question_id,title,body,link,score,view_count,answer_count,comment_count,favorite_count,creation_date,last_activity_date,last_edit_date,closed_date,closed_reason,tags,owner_name,owner_reputation,owner_user_id,owner_type,is_answered,accepted_answer_id,bounty_amount,content_license,protected_date,body_length,body_text_length,code_block_count,link_count,image_count,tag_count,has_accepted_answer,is_closed,has_bounty,has_body,has_owner,has_edit,title_length,title_word_count,is_title_question,answer_rate,score_per_view,age_days,year,month,hour,day_of_week,is_weekend,is_python,is_javascript,is_java,is_csharp,is_sql,is_php 231767,What does the "yield" keyword do in Python?,"
What functionality does the yield keyword in Python provide?
For example, I'm trying to understand this code1:
def _get_child_candidates(self, distance, min_dist, max_dist):
if self._leftchild and distance - max_dist < self._median:
yield self._leftchild
if self._rightchild and distance + max_dist >= self._median:
yield self._rightchild
And this is the caller:
result, candidates = [], [self]
while candidates:
node = candidates.pop()
distance = node._get_dist(obj)
if distance <= max_dist and distance >= min_dist:
result.extend(node._values)
candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))
return result
What happens when the method _get_child_candidates is called?
Is a list returned? A single element? Is it called again? When will subsequent calls stop?
What does this do, and why should one include the if statement?
if __name__ == "__main__":
print("Hello, World!")
If you are trying to close a question where someone should be using this idiom and isn't, consider closing as a duplicate of Why is Python running my module when I import it, and how do I stop it? instead. For questions where someone simply hasn't called any functions, or incorrectly expects a function named main to be used as an entry point automatically, use Why doesn't the main() function run when I start a Python script? Where does the script start running?.
Is there a ternary conditional operator in Python?
",https://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator,8130,3144666.0,32.0,,,2008-12-27 08:32:18,2025-08-22 12:22:53,2022-06-06 02:52:42,,,python;operators;conditional-operator,Devoted,185101,51518,registered,true,394814,,CC BY-SA 4.0,2013-06-10 05:15:42,131,51,0,1,0,3,true,false,false,true,true,true,48,7,true,0.01,0.0026,6538,2008,12,8,Saturday,true,true,false,false,false,false,false 100003,What are metaclasses in Python?,"What are metaclasses? What are they used for?
",https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python,7535,1267480.0,28.0,,,2008-09-19 06:10:46,2026-09-23 12:53:02,2023-02-08 04:49:19,,,python;oop;metaclass;python-class;python-datamodel,Bite code,602069,9951,registered,true,100146,,CC BY-SA 4.0,2012-10-18 18:42:40,147,46,0,1,0,5,true,false,false,true,true,true,31,5,true,0.022,0.0059,6637,2008,9,6,Friday,false,true,false,false,false,false,false 82831,How do I check whether a file exists without exceptions?,"How do I check whether a file exists or not, without using the try statement?
I want to merge two dictionaries into a new dictionary.
x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = merge(x, y)
>>> z
{'a': 1, 'b': 3, 'c': 4}
Whenever a key k is present in both dictionaries, only the value y[k] should be kept.
How do I call an external command within Python as if I had typed it in a shell or command prompt?
",https://stackoverflow.com/questions/89228/how-do-i-execute-a-program-or-call-a-system-command,6299,5265203.0,66.0,,,2008-09-18 01:35:30,2026-04-24 13:04:42,2022-12-15 01:06:05,,,python;shell;terminal;subprocess;command,freshWoWer,64759,17085,registered,true,89243,,CC BY-SA 4.0,2013-04-16 20:23:20,106,99,0,0,0,5,true,false,false,true,true,true,52,11,true,0.013,0.0012,6638,2008,9,1,Thursday,false,true,false,false,false,false,false 273192,"How do I create a directory, and any missing parent directories?","How do I create a directory at a given path, and also create any missing parent directories along that path? For example, the Bash command mkdir -p /path/to/nested/directory does this.
How do I access the index while iterating over a sequence with a for loop?
xs = [8, 23, 45]
for x in xs:
print("item #{} = {}".format(index, x))
Desired output:
item #1 = 8
item #2 = 23
item #3 = 45
",https://stackoverflow.com/questions/522563/how-can-i-access-the-index-value-in-a-for-loop,5685,5127037.0,28.0,,,2009-02-06 22:47:54,2025-06-24 15:40:40,2025-04-08 19:23:12,,,python;loops;list,Joan Venge,334947,51816,registered,true,522578,,CC BY-SA 4.0,2016-03-18 09:03:59,367,216,3,0,0,3,true,false,false,true,true,true,57,11,true,0.005,0.0011,6497,2009,2,22,Friday,false,true,false,false,false,false,false
952914,How do I make a flat list out of a list of lists?,"I have a list of lists like
[
[1, 2, 3],
[4, 5, 6],
[7],
[8, 9]
]
How can I flatten it to get [1, 2, 3, 4, 5, 6, 7, 8, 9]?
Editor's notes:
If your list of lists comes from a nested list comprehension, the problem can be solved more simply/directly by fixing the comprehension; please see How can I get a flat result from a list comprehension instead of a nested list?.
The most popular solutions here generally only flatten one "level" of the nested list. See Flatten an irregular (arbitrarily nested) list of lists for solutions that completely flatten a deeply nested structure (recursively, in general).
",https://stackoverflow.com/questions/952914/how-do-i-make-a-flat-list-out-of-a-list-of-lists,5521,4714654.0,32.0,,,2009-06-04 20:30:05,2026-10-12 09:18:45,2026-03-13 16:31:17,,,python;list;multidimensional-array;flatten,Emma,56021,110527,registered,true,952952,,CC BY-SA 4.0,2013-01-11 13:22:54,860,635,2,2,0,4,true,false,false,true,true,true,49,13,true,0.007,0.0012,6379,2009,6,20,Thursday,false,true,false,false,false,false,false 136097,What is the difference between @staticmethod and @classmethod in Python?,"What is the difference between a method decorated with @staticmethod and one decorated with @classmethod?
How does Python's slice notation work? That is: when I write code like a[x:y:z], a[:], a[::2] etc., how can I understand which elements end up in the slice?
See Why are slice and range upper-bound exclusive? to learn why xs[0:2] == [xs[0], xs[1]], not [..., xs[2]].
See Make a new list containing every Nth item in the original list for xs[::N].
See How does assignment work with list slices? to learn what xs[0:2] = ["a", "b"] does.
Given a list ["foo", "bar", "baz"] and an item in the list "bar", how do I get its index 1?
d = {'x': 1, 'y': 2, 'z': 3}
for key in d:
print(key, 'corresponds to', d[key])
How does Python recognize that it needs only to read the key from the dictionary? Is key a special keyword, or is it simply a variable?
I have a pandas dataframe, df:
c1 c2
0 10 100
1 11 110
2 12 120
How do I iterate over the rows of this dataframe? For every row, I want to access its elements (values in cells) by the name of the columns. For example:
for row in df.rows:
print(row['c1'], row['c2'])
I found a similar question, which suggests using either of these:
for date, row in df.T.iteritems():
for row in df.iterrows():
But I do not understand what the row object is and how I can work with it.
How do I create or use a global variable inside a function?
How do I use a global variable that was defined in one function inside other functions?
Failing to use the global keyword where appropriate often causes UnboundLocalError. The precise rules for this are explained at UnboundLocalError on local variable when reassigned after first use. Generally, please close other questions as a duplicate of that question when an explanation is sought, and this question when someone simply needs to know the global keyword.
How do I get the current time in Python?
",https://stackoverflow.com/questions/415511/how-do-i-get-the-current-time-in-python,4002,4847333.0,54.0,,,2009-01-06 04:54:23,2026-01-06 17:34:20,2024-01-08 06:02:45,,,python;datetime;time,user46646,160945,46646,registered,true,415519,,CC BY-SA 4.0,2012-04-26 12:03:40,48,41,0,0,0,3,true,false,false,true,true,true,40,9,true,0.011,0.0008,6528,2009,1,4,Tuesday,false,true,false,false,false,false,false 123198,How do I copy a file?,"How do I copy a file in Python?
",https://stackoverflow.com/questions/123198/how-do-i-copy-a-file,3967,4143995.0,21.0,,,2008-09-23 19:23:48,2025-03-02 21:30:03,2025-03-02 21:30:03,,,python;file;copy;filesystems;file-copying,Matt,89117,17693,registered,true,123212,,CC BY-SA 4.0,2016-03-16 11:40:22,39,32,0,0,0,5,true,false,false,true,true,true,21,6,true,0.005,0.001,6633,2008,9,19,Tuesday,false,true,false,false,false,false,false 6470428,How can I catch multiple exceptions in one line? (in the "except" block),"I know that I can do:
try:
# do something that may fail
except:
# do this if ANYTHING goes wrong
I can also do this:
try:
# do something that may fail
except IDontLikeYouException:
# say please
except YouAreTooShortException:
# stand on a ladder
But if I want to do the same thing inside two different exceptions, the best I can think of right now is to do this:
try:
# do something that may fail
except IDontLikeYouException:
# say please
except YouAreBeingMeanException:
# say please
Is there a way that I can do something like this (since the action to take in both exceptions is to say please):
try:
# do something that may fail
except IDontLikeYouException, YouAreBeingMeanException:
# say please
Now this really won't work, as it matches the syntax for:
try:
# do something that may fail
except Exception, e:
# say please
So, my effort to catch the two distinct exceptions doesn't exactly come through.
Is there a way to do this?
",https://stackoverflow.com/questions/6470428/how-can-i-catch-multiple-exceptions-in-one-line-in-the-except-block,3967,1672246.0,6.0,,,2011-06-24 15:55:08,2026-07-04 23:10:27,2025-04-08 20:32:52,,,python;exception,inspectorG4dget,114974,198633,registered,true,6470452,,CC BY-SA 4.0,2015-11-19 17:09:57,1171,989,6,0,0,2,true,false,false,true,true,true,82,13,false,0.004,0.0024,5629,2011,6,15,Friday,false,true,false,false,false,false,false 448271,What is __init__.py for?,"What is __init__.py for in a Python source directory?
I captured the standard output of an external program into a bytes object:
>>> from subprocess import *
>>> stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0]
>>> stdout
b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n'
I want to convert that to a normal Python string, so that I can print it like this:
>>> print(stdout)
-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1
-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2
How do I convert the bytes object to a str with Python 3?
See Best way to convert string to bytes in Python 3? for the other way around.
",https://stackoverflow.com/questions/606191/convert-bytes-to-a-string-in-python-3,3888,5423268.0,23.0,,,2009-03-03 12:23:01,2025-01-06 01:58:20,2023-08-02 23:01:51,,,python;string;python-3.x,Tomas Sedovic,44803,2239,registered,true,606199,,CC BY-SA 4.0,2017-01-22 14:29:04,853,663,5,1,0,3,true,false,false,true,true,true,37,8,false,0.004,0.0007,6472,2009,3,12,Tuesday,false,true,false,false,false,false,false 1436703,What is the difference between __str__ and __repr__?,"What is the difference between __str__ and __repr__ in Python?
How can I select rows from a DataFrame based on values in some column in Pandas?
In SQL, I would use:
SELECT *
FROM table
WHERE column_name = some_value
",https://stackoverflow.com/questions/17071871/how-do-i-select-rows-from-a-dataframe-based-on-column-values,3635,6901742.0,20.0,,,2013-06-12 17:42:05,2025-05-14 01:53:58,2025-04-02 19:11:44,,,python;pandas;dataframe;indexing;filter,szli,39429,458429,registered,true,17071908,,CC BY-SA 4.0,2018-02-24 18:33:59,230,154,1,0,0,5,true,false,false,true,true,true,61,12,true,0.003,0.0005,4910,2013,6,17,Wednesday,false,true,false,false,false,false,false
1024847,How can I add new keys to a dictionary?,"How do I add a new key to an existing dictionary? It doesn't have an .add() method.
I'm looking for a string.contains or string.indexof method in Python.
I want to do:
if not somestring.contains(""blah""):
continue
",https://stackoverflow.com/questions/3437059/does-python-have-a-string-contains-substring-method,3585,7567945.0,10.0,,,2010-08-09 02:52:50,2025-01-17 16:59:58,2017-05-26 18:02:52,,,python;string;substring;contains,Blankman,269014,39677,registered,true,3437070,,CC BY-SA 3.0,2015-10-13 12:20:15,199,135,3,0,0,4,true,false,false,true,true,true,62,8,true,0.001,0.0005,5948,2010,8,2,Monday,false,true,false,false,false,false,false
6996603,How can I delete a file or folder in Python?,"How can I delete a file or folder in Python?
",https://stackoverflow.com/questions/6996603/how-can-i-delete-a-file-or-folder-in-python,3556,4069329.0,18.0,,,2011-08-09 13:05:42,2024-04-29 09:36:08,2023-07-27 06:00:02,,,python;file-io;directory;delete-file,Zygimantas,35891,854002,registered,true,6996628,,CC BY-SA 4.0,2020-11-03 23:48:20,52,45,0,0,0,4,true,false,false,true,true,true,44,10,true,0.004,0.0009,5583,2011,8,13,Tuesday,false,true,false,false,false,false,false 1132941,"Least Astonishment" and the Mutable Default Argument,"def foo(a=[]):
a.append(5)
return a
Python novices expect this function called with no parameter to always return a list with only one element: [5]. The result is different and astonishing:
>>> foo()
[5]
>>> foo()
[5, 5]
>>> foo()
[5, 5, 5]
>>> foo()
[5, 5, 5, 5]
>>> foo()
The behavior has an underlying explanation, but it is unexpected if you don't understand internals. What is the reason for binding the default argument at function definition, and not at function execution? I doubt the experienced behavior has a practical use (who really used static variables in C, without breeding bugs?)
Edit:
Baczek made an interesting example. Together with your comments and Utaal's in particular, I elaborated:
def a():
print("a executed")
return []
def b(x=a()):
x.append(5)
print(x)
a executed
>>> b()
[5]
>>> b()
[5, 5]
It seems that the design decision was relative to where to put the scope of parameters: inside the function, or "together" with it?
Doing the binding inside the function would mean that x is effectively bound to the specified default when the function is called, not defined, something that would present a deep flaw: the def line would be "hybrid" in the sense that part of the binding (of the function object) would happen at definition, and part (assignment of default parameters) at function invocation time.
The actual behavior is more consistent: everything of that line gets evaluated when that line is executed, meaning at function definition.
",https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument,3513,302551.0,34.0,,,2009-07-15 18:00:37,2025-08-12 22:31:16,2025-08-12 22:31:16,,,python;language-design;default-parameters;least-astonishment,Stefano Borini,145448,78374,registered,true,1145781,,CC BY-SA 4.0,2012-01-13 16:13:22,1901,1608,6,2,0,4,true,false,false,true,true,true,63,7,false,0.112,0.0116,6338,2009,7,18,Wednesday,false,true,false,false,false,false,false 36901,What does ** (double star/asterisk) and * (star/asterisk) do for parameters?,"What do *args and **kwargs mean in these function definitions?
def foo(x, y, *args):
pass
def bar(x, y, **kwargs):
pass
See What do ** (double star/asterisk) and * (star/asterisk) mean in a function call? for the complementary question about arguments.
",https://stackoverflow.com/questions/36901/what-does-double-star-asterisk-and-star-asterisk-do-for-parameters,3505,1564871.0,28.0,,,2008-08-31 15:04:35,2026-06-03 04:41:03,2023-02-27 07:29:27,,,python;syntax;parameter-passing;variadic-functions;argument-unpacking,Todd,36410,2572,registered,true,36908,,CC BY-SA 4.0,2017-01-22 14:33:24,403,264,3,1,0,5,true,false,false,true,true,true,76,11,true,0.018,0.0022,6656,2008,8,15,Sunday,true,true,false,false,false,false,false 4906977,How can I access environment variables in Python?,"How can I get the value of an environment variable in Python?
",https://stackoverflow.com/questions/4906977/how-can-i-access-environment-variables-in-python,3480,3530599.0,17.0,,,2011-02-05 13:03:35,2024-02-12 16:18:05,2022-12-14 19:45:55,,,python;environment-variables,Amit Yadav,35916,601738,registered,true,4907053,,CC BY-SA 4.0,2018-12-20 04:45:55,69,62,0,0,0,2,true,false,false,true,true,true,49,8,true,0.005,0.001,5768,2011,2,13,Saturday,true,true,false,false,false,false,false 3207219,How do I list all files of a directory?,"How can I list all files of a directory in Python and add them to a list?
I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.
I can sort on the keys, but how can I sort based on the values?
Note: I have read Stack Overflow question here How do I sort a list of dictionaries by a value of the dictionary? and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution to sort either in ascending or descending order.
",https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value,3413,5857516.0,34.0,,,2009-03-05 00:49:05,2025-07-16 09:04:20,2019-03-20 22:50:51,,,python;sorting;dictionary,Gern Blanston,42680,2786,registered,true,613218,,CC BY-SA 4.0,2012-06-23 15:31:18,651,565,0,1,0,3,true,false,false,true,true,true,36,8,true,0.006,0.0006,6470,2009,3,0,Thursday,false,true,false,false,false,false,false 2612802,How do I clone a list so that it doesn't change unexpectedly after assignment?,"While using new_list = my_list, any modifications to new_list changes my_list every time. Why is this, and how can I clone or copy the list to prevent it? For example:
>>> my_list = [1, 2, 3]
>>> new_list = my_list
>>> new_list.append(4)
>>> my_list
[1, 2, 3, 4]
",https://stackoverflow.com/questions/2612802/how-do-i-clone-a-list-so-that-it-doesnt-change-unexpectedly-after-assignment,3371,2307744.0,25.0,,,2010-04-10 08:49:46,2025-12-21 05:36:37,2024-06-01 02:57:32,,,python;list;clone;mutable,aF.,67113,187730,registered,true,2612815,,CC BY-SA 4.0,2014-12-05 17:10:28,370,300,4,0,0,4,true,false,false,true,true,true,82,14,true,0.011,0.0015,6069,2010,4,8,Saturday,true,true,false,false,false,false,false
986006,How do I pass a variable by reference?,"I wrote this class for testing:
class PassByReference:
def __init__(self):
self.variable = 'Original'
self.change(self.variable)
print(self.variable)
def change(self, var):
var = 'Changed'
When I tried creating an instance, the output was Original. So it seems like parameters in Python are passed by value. Is that correct? How can I modify the code to get the effect of pass-by-reference, so that the output is Changed?
Sometimes people are surprised that code like x = 1, where x is a parameter name, doesn't impact on the caller's argument, but code like x[0] = 1 does. This happens because item assignment and slice assignment are ways to mutate an existing object, rather than reassign a variable, despite the = syntax. See Why can a function modify some arguments as perceived by the caller, but not others? for details.
See also What's the difference between passing by reference vs. passing by value? for important, language-agnostic terminology discussion.
",https://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference,3366,2222220.0,44.0,,,2009-06-12 10:23:51,2025-10-14 23:11:08,2023-07-12 16:23:18,,,python;reference;parameter-passing;pass-by-reference,David Sykes,50142,259,registered,true,986145,,CC BY-SA 4.0,2012-04-19 22:49:48,1323,1014,7,2,0,4,true,false,false,true,true,true,38,8,true,0.02,0.0015,6371,2009,6,10,Friday,false,true,false,false,false,false,false 287871,How do I print colored text to the terminal?,"How do I output colored text to the terminal in Python?
",https://stackoverflow.com/questions/287871/how-do-i-print-colored-text-to-the-terminal,3334,2816800.0,68.0,,,2008-11-13 18:58:10,2025-11-30 14:05:15,2022-07-10 22:35:13,,,python;terminal;output;ansi-colors,aboSamoor,33491,35062,registered,true,,,CC BY-SA 4.0,2015-06-01 09:25:28,63,56,0,0,0,4,false,false,false,true,true,true,44,9,true,0.024,0.0012,6582,2008,11,18,Thursday,false,true,false,false,false,false,false 2052390,Manually raising (throwing) an exception in Python,"How do I raise an exception in Python so that it can later be caught via an except block?
Why is super() used?
Is there a difference between using Base.__init__ and super().__init__?
class Base(object):
def __init__(self):
print "Base created"
class ChildA(Base):
def __init__(self):
Base.__init__(self)
class ChildB(Base):
def __init__(self):
super(ChildB, self).__init__()
ChildA()
ChildB()
",https://stackoverflow.com/questions/576169/understanding-python-super-with-init-methods,3302,2989347.0,7.0,,,2009-02-23 00:30:08,2024-04-02 17:51:25,2022-04-01 11:47:58,2015-11-02 00:55:26,Duplicate,python;class;oop;inheritance;super,Mizipzor,52779,56763,registered,true,576183,,,2014-01-29 11:46:27,455,378,4,0,0,5,true,true,false,true,true,true,52,6,false,0.002,0.0011,6480,2009,2,0,Monday,false,true,false,false,false,false,false
510348,How do I make a time delay?,"How do I put a time delay in a Python script?
",https://stackoverflow.com/questions/510348/how-do-i-make-a-time-delay,3287,4006370.0,13.0,,,2009-02-04 07:04:09,2023-09-21 14:21:35,2022-06-13 00:08:58,2019-09-26 06:00:40,Duplicate,python;delay;sleep;timedelay,user46646,160945,46646,registered,true,,,,2015-03-10 20:32:25,53,46,0,0,0,4,false,true,false,true,true,true,27,7,true,0.003,0.0008,6499,2009,2,7,Wednesday,false,true,false,false,false,false,false 332289,How do I change the size of figures drawn with Matplotlib?,"How do I change the size of figure drawn with Matplotlib?
",https://stackoverflow.com/questions/332289/how-do-i-change-the-size-of-figures-drawn-with-matplotlib,3267,6439585.0,16.0,,,2008-12-01 21:24:44,2025-05-14 01:09:44,2025-05-14 01:09:44,,,python;pandas;matplotlib;seaborn;figsize,tatwright,38707,40849,unregistered,true,,,CC BY-SA 4.0,2015-06-07 19:37:13,65,58,0,0,0,5,false,false,false,true,true,true,58,11,true,0.002,0.0005,6564,2008,12,21,Monday,false,true,false,false,false,false,false 1720421,How do I concatenate two lists in Python?,"How do I concatenate two lists in Python?
Example:
listone = [1, 2, 3]
listtwo = [4, 5, 6]
Expected outcome:
>>> joinedlist
[1, 2, 3, 4, 5, 6]
",https://stackoverflow.com/questions/1720421/how-do-i-concatenate-two-lists-in-python,3237,4923419.0,31.0,,,2009-11-12 07:04:09,2024-01-10 20:15:51,2019-03-17 09:15:29,,,python;list;concatenation,y2k,66264,206504,registered,true,1720432,,CC BY-SA 4.0,2013-04-14 10:35:38,227,158,2,0,0,3,true,false,false,true,true,true,41,8,true,0.006,0.0007,6218,2009,11,7,Thursday,false,true,false,false,false,false,false
53513,How do I check if a list is empty?,"For example, if passed the following:
a = []
How do I check to see if a is empty?
How do I make two decorators in Python that would do the following?
@make_bold
@make_italic
def say():
return "Hello"
Calling say() should return:
"<b><i>Hello</i></b>"
",https://stackoverflow.com/questions/739654/how-do-i-make-function-decorators-and-chain-them-together,3203,700440.0,22.0,,,2009-04-11 07:05:31,2023-10-08 00:52:58,2022-12-30 10:10:48,,,python;function;decorator;python-decorators;chain,Imran,91925,1897,registered,true,739665,,CC BY-SA 4.0,2013-04-10 11:33:49,293,218,3,0,0,5,true,false,false,true,true,true,58,10,true,0.031,0.0046,6433,2009,4,7,Saturday,true,true,false,false,false,false,false
312443,How do I split a list into equally-sized chunks?,"How do I split a list of arbitrary length into equal sized chunks?
See also: How to iterate over a list in chunks.
To chunk strings, see Split string every nth character?.
How do I determine:
What's the difference between the list methods append() and extend()?
I want to change the column labels of a Pandas DataFrame from
['$a', '$b', '$c', '$d', '$e']
to
['a', 'b', 'c', 'd', 'e']
",https://stackoverflow.com/questions/11346283/renaming-column-names-in-pandas,3074,7045644.0,33.0,,,2012-07-05 14:21:15,2025-05-23 08:56:42,2022-07-28 09:10:19,,,python;pandas;replace;dataframe;rename,user1504276,30835,1504276,registered,true,11346337,,CC BY-SA 4.0,2018-03-17 09:14:45,186,124,2,0,0,5,true,false,false,true,true,true,31,5,false,0.005,0.0004,5252,2012,7,14,Thursday,false,true,false,false,false,false,false
30081275,Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3?,"It is my understanding that the range() function, which is actually an object type in Python 3, generates its contents on the fly, similar to a generator.
This being the case, I would have expected the following line to take an inordinate amount of time because, in order to determine whether 1 quadrillion is in the range, a quadrillion values would have to be generated:
1_000_000_000_000_000 in range(1_000_000_000_000_001)
Furthermore: it seems that no matter how many zeroes I add on, the calculation more or less takes the same amount of time (basically instantaneous).
I have also tried things like this, but the calculation is still almost instant:
# count by tens
1_000_000_000_000_000_000_000 in range(0,1_000_000_000_000_000_000_001,10)
If I try to implement my own range function, the result is not so nice!
def my_crappy_range(N):
i = 0
while i < N:
yield i
i += 1
return
What is the range() object doing under the hood that makes it so fast?
Martijn Pieters's answer was chosen for its completeness, but also see abarnert's first answer for a good discussion of what it means for range to be a full-fledged sequence in Python 3, and some information/warning regarding potential inconsistency for __contains__ function optimization across Python implementations. abarnert's other answer goes into some more detail and provides links for those interested in the history behind the optimization in Python 3 (and lack of optimization of xrange in Python 2). Answers by poke and by wim provide the relevant C source code and explanations for those who are interested.
I want to remove a key from a dictionary if it is present. I currently use this code:
if key in my_dict:
del my_dict[key]
Without the if statement, the code will raise KeyError if the key is not present. How can I handle this more simply?
See Delete an element from a dictionary for more general approaches to the problem of removing a key from a dict (including ones which produce a modified copy).
",https://stackoverflow.com/questions/11277432/how-can-i-remove-a-key-from-a-python-dictionary,3026,3144243.0,11.0,,,2012-06-30 20:27:59,2024-11-02 13:47:58,2023-02-23 08:25:54,,,python;dictionary;unset,Tony,38831,692499,registered,true,11277439,,CC BY-SA 4.0,2019-07-22 08:40:34,598,406,3,1,0,3,true,false,false,true,true,true,48,10,true,0.003,0.001,5257,2012,6,20,Saturday,true,true,false,false,false,false,false 466345,Convert string "Jun 1 2005 1:33PM" into datetime,"I have a huge list of datetime strings like the following
["Jun 1 2005 1:33PM", "Aug 28 1999 12:00AM"]
How do I convert them into datetime objects?
Is it possible to upgrade all Python packages at one time with pip?
Note: that there is a feature request for this on the official issue tracker.
",https://stackoverflow.com/questions/2720014/how-to-upgrade-all-python-packages-with-pip,2901,2147822.0,67.0,,,2010-04-27 09:23:25,2026-05-11 05:59:35,2024-09-28 05:20:27,,,python;pip;pypi,thedjpetersen,29725,324085,registered,true,3452888,,CC BY-SA 4.0,2019-04-09 10:17:59,342,146,1,2,0,3,true,false,false,true,true,true,43,8,false,0.031,0.0014,6052,2010,4,9,Tuesday,false,true,false,false,false,false,false 990754,How to leave/exit/deactivate a Python virtualenv,"I'm using virtualenv and the virtualenvwrapper. I can switch between virtualenv's just fine using the workon command.
me@mymachine:~$ workon env1
(env1)me@mymachine:~$ workon env2
(env2)me@mymachine:~$ workon env1
(env1)me@mymachine:~$
How do I exit all virtual environments and work on my system environment again? Right now, the only way I have of getting back to me@mymachine:~$ is to exit the shell and start a new one. That's kind of annoying. Is there a command to work on "nothing", and if so, what is it? If such a command does not exist, how would I go about creating it?
How do I sort a list of dictionaries by a specific key's value? Given:
[{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]
When sorted by name, it should become:
[{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}]
",https://stackoverflow.com/questions/72899/how-can-i-sort-a-list-of-dictionaries-by-a-value-of-the-dictionary-in-python,2859,1497079.0,22.0,,,2008-09-16 14:27:47,2025-07-23 17:11:37,2025-07-23 17:04:29,,,python;list;sorting;dictionary;data-structures,masi,118,12398,registered,true,73050,,CC BY-SA 4.0,2014-06-11 16:04:57,381,232,3,0,0,5,true,false,false,true,true,true,77,16,true,0.015,0.0019,6640,2008,9,14,Tuesday,false,true,false,false,false,false,false
930397,How do I get the last element of a list?,"How do I get the last element of a list in Python? I tried:
alist[::-1]
but I got
",https://stackoverflow.com/questions/930397/how-do-i-get-the-last-element-of-a-list,2814,3399526.0,19.0,,,2009-05-30 19:28:53,2026-05-23 08:12:06,2026-05-23 08:12:06,,,python;list,Janusz,190109,114066,registered,true,930398,,CC BY-SA 4.0,2016-12-14 17:06:17,269,162,1,0,0,2,true,false,false,true,true,true,40,10,true,0.006,0.0008,6384,2009,5,19,Saturday,true,true,false,false,false,false,false 379906,How do I parse a string to a float or int?,"ValueError: attempt to assign sequence of size 6 to extended slice of size 5
How can I convert an str to a float?
"545.2222" -> 545.2222
Or an str to a int?
"31" -> 31
For the reverse, see Convert integer to string in Python and Converting a float to a string without rounding it.
Please instead use How can I read inputs as numbers? to close duplicate questions where OP received a string from user input and immediately wants to convert it, or was hoping for input (in 3.x) to convert the type automatically.
pip is a replacement for easy_install. But should I install pip using easy_install on Windows? Is there a better way?
I want to get a new string from the third character to the end of the string, e.g. myString[2:end]. If omitting the second part means 'to the end', and if you omit the first part, does it start from the start?
Non-working example:
print(" \{ Hello \} {0} ".format(42))
Desired output:
{Hello} 42
",https://stackoverflow.com/questions/5466451/how-do-i-escape-curly-brace-characters-characters-in-a-string-while-using,2725,1319012.0,24.0,,,2011-03-29 00:04:53,2026-04-02 16:13:24,2024-09-12 15:26:03,,,python;string;format;string-formatting;curly-braces,Schitti,28479,242670,registered,true,5466478,,CC BY-SA 4.0,2022-08-05 16:58:14,201,100,2,0,0,5,true,false,false,true,true,true,87,14,true,0.018,0.0021,5716,2011,3,0,Tuesday,false,true,false,false,false,false,false
1602934,Check if a given key already exists in a dictionary,"I wanted to test if a key exists in a dictionary before updating the value for the key. I wrote the following code:
if 'key1' in dict.keys():
print ""blah""
else:
print ""boo""
I think this is not the best way to accomplish this task. Is there a better way to test for a key in the dictionary?
",https://stackoverflow.com/questions/1602934/check-if-a-given-key-already-exists-in-a-dictionary,2675,7356931.0,16.0,,,2009-10-21 19:05:09,2023-03-07 14:12:21,2013-05-02 06:45:00,,,python;dictionary,Mohan Gulati,28219,112850,registered,true,1602964,,CC BY-SA 3.0,2015-09-09 04:47:11,335,297,1,0,0,2,true,false,false,true,true,true,51,10,false,0.002,0.0004,6240,2009,10,19,Wednesday,false,true,false,false,false,false,false 4383571,Importing files from different folder,"I have this folder structure:
application
├── app
│ └── folder
│ └── file.py
└── app2
└── some_folder
└── some_file.py
How can I import a function from file.py, from within some_file.py? I tried:
from application.app.folder.file import func_name
but it doesn't work.
",https://stackoverflow.com/questions/4383571/importing-files-from-different-folder,2672,4008963.0,41.0,,,2010-12-08 02:07:15,2025-02-18 13:05:22,2022-08-28 02:26:55,,,python;importerror;python-import,Ivan,31489,340453,registered,true,,,CC BY-SA 4.0,2017-04-19 04:58:38,421,289,4,0,0,3,false,false,false,true,true,true,37,5,false,0.01,0.0007,5827,2010,12,2,Wednesday,false,true,false,false,false,false,false 68645,Class (static) variables and methods,"How do I create class (i.e. static) variables or methods in Python?
",https://stackoverflow.com/questions/68645/class-static-variables-and-methods,2638,1845560.0,27.0,,,2008-09-16 01:46:36,2024-01-30 14:39:08,2022-12-03 07:36:13,,,python;class;static;class-variables,Andrew Walker,42830,2246,registered,true,68672,,CC BY-SA 4.0,2016-10-01 12:43:57,181,68,0,1,0,4,true,false,false,true,true,true,36,5,false,0.015,0.0014,6640,2008,9,1,Tuesday,false,true,false,false,false,false,false 6797984,How do I lowercase a string in Python?,"Is there a way to convert a string to lowercase?
"Kilometers" → "kilometers"
See How to change a string into uppercase? for the opposite.
",https://stackoverflow.com/questions/6797984/how-do-i-lowercase-a-string-in-python,2589,3232137.0,10.0,,,2011-07-23 03:08:53,2025-03-19 22:13:07,2023-03-07 22:19:38,,,python;string;uppercase;lowercase,Benjamin Didur,26091,858922,unregistered,true,6797990,,CC BY-SA 4.0,2016-03-09 01:56:27,275,162,1,1,0,4,true,false,false,true,true,true,38,8,true,0.003,0.0008,5600,2011,7,3,Saturday,true,true,false,false,false,false,false 610883,How can I check if an object has an attribute?,"How do I check if an object has some attribute? For example:
>>> a = SomeClass()
>>> a.property
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: SomeClass instance has no attribute 'property'
How do I tell if a has the attribute property before using it?
Consider these examples using print in Python:
>>> for i in range(4): print('.')
.
.
.
.
>>> print('.', '.', '.', '.')
. . . .
Either a newline or a space is added between each value. How can I avoid that, so that the output is .... instead? In other words, how can I "append" strings to the standard output stream?
How do I call a function, using a string with the function's name? For example:
import foo
func_name = "bar"
call(foo, func_name) # calls foo.bar()
",https://stackoverflow.com/questions/3061/calling-a-function-of-a-module-by-using-its-name-a-string,2496,1264363.0,19.0,,,2008-08-06 03:36:08,2024-08-23 17:41:09,2022-06-04 21:43:08,,,python;object;reflection,ricree,36982,121,registered,true,3071,,CC BY-SA 4.0,2013-01-06 23:06:18,191,160,1,0,0,3,true,false,false,true,true,true,59,12,false,0.015,0.002,6681,2008,8,3,Wednesday,false,true,false,false,false,false,false
455612,Limiting floats to two decimal points,"I want a to be rounded to 13.95. I tried using round, but I get:
>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999
Editor's note: For the analogous issue with the standard library Decimal class, see How can I format a decimal to always show 2 decimal places?
",https://stackoverflow.com/questions/455612/limiting-floats-to-two-decimal-points,2462,6117278.0,36.0,,,2009-01-18 18:16:41,2026-03-16 02:39:57,2026-03-16 02:34:22,,,python;floating-point;rounding;precision,kevin,,,does_not_exist,true,,,CC BY-SA 4.0,2014-04-25 05:36:39,549,289,3,2,0,4,false,false,false,true,false,true,37,6,false,0.006,0.0004,6516,2009,1,18,Sunday,true,true,false,false,false,false,false 306400,How can I randomly select (choose) an item from a list (get a random element)?,"How do I retrieve an item at random from the following list?
foo = ['a', 'b', 'c', 'd', 'e']
",https://stackoverflow.com/questions/306400/how-can-i-randomly-select-choose-an-item-from-a-list-get-a-random-element,2447,2500543.0,18.0,,,2008-11-20 18:42:21,2023-08-31 22:53:30,2023-08-31 22:53:30,,,python;list;random,Ray,194116,4872,registered,true,306417,,CC BY-SA 4.0,2015-05-26 11:13:57,162,94,1,0,0,3,true,false,false,true,true,true,78,15,true,0.007,0.001,6575,2008,11,18,Thursday,false,true,false,false,false,false,false
627435,How to remove an element from a list by index,"How do I remove an element from a list by index?
I found list.remove(), but this slowly scans the list for an item by value.
To delete a column in a DataFrame, I can successfully use:
del df['column_name']
But why can't I use the following?
del df.column_name
Since it is possible to access the Series via df.column_name, I expected this to work.
How do I get the number of elements in the list items?
items = ["apple", "orange", "banana"]
# There are 3 items.
",https://stackoverflow.com/questions/1712227/how-do-i-get-the-number-of-elements-in-a-list-length-of-a-list-in-python,2309,4072999.0,11.0,,,2009-11-11 00:30:54,2024-07-02 12:05:02,2022-10-13 18:05:54,,,python;list,y2k,66264,206504,registered,true,1712236,,CC BY-SA 4.0,2013-09-20 20:25:01,190,146,2,0,0,2,true,false,false,true,true,true,75,17,true,0.003,0.0006,6219,2009,11,0,Wednesday,false,true,false,false,false,false,false
41573587,"What is the difference between venv, pyvenv, pyenv, virtualenv, virtualenvwrapper, pipenv, etc.?","Python 3.3 includes the new package venv in its standard library. What does it do, and how does it differ from all the other packages that match the regex (py)?(v|virtual|pip)?env?
How do I pad a numeric string with zeroes to the left, so that the string has a specific length?
",https://stackoverflow.com/questions/339007/how-do-i-pad-a-string-with-zeros,2266,1746405.0,19.0,,,2008-12-03 22:39:51,2026-03-04 22:54:12,2024-01-29 21:56:47,,,python;string;zero-padding,Faisal,,,does_not_exist,true,339013,,CC BY-SA 4.0,2016-08-30 13:56:22,104,97,0,0,0,3,true,false,false,true,false,true,33,8,true,0.011,0.0013,6562,2008,12,22,Wednesday,false,true,false,false,false,false,false 402504,How can I determine a Python variable's type?,"How do I see the type of a variable? (e.g., unsigned 32 bit)
",https://stackoverflow.com/questions/402504/how-can-i-determine-a-python-variables-type,2259,4259858.0,22.0,,,2008-12-31 07:58:57,2025-04-25 12:38:10,2025-04-25 11:15:02,,,python;types,user46646,160945,46646,registered,true,,,CC BY-SA 4.0,2014-03-20 01:12:16,68,61,0,0,0,2,false,false,false,true,true,true,49,8,true,0.005,0.0005,6534,2008,12,7,Wednesday,false,true,false,false,false,false,false 5844672,Delete an element from a dictionary,"See also How can I remove a key from a Python dictionary? for the specific issue of removing an item (by key) that may not already be present.
",https://stackoverflow.com/questions/5844672/delete-an-element-from-a-dictionary,2249,2966672.0,20.0,,,2011-04-30 21:20:57,2025-03-24 16:45:10,2025-03-24 16:45:10,,,python;dictionary;del,richzilla,42378,301032,registered,true,5844692,,CC BY-SA 4.0,2015-09-11 03:09:02,444,300,0,1,0,3,true,false,false,true,true,true,35,6,false,0.007,0.0008,5684,2011,4,21,Saturday,true,true,false,false,false,false,false 9573244,How to check if the string is empty in Python?,"Does Python have something like an empty string variable where you can do:
if myString == string.empty:
Regardless, what's the most elegant way to check for empty string values? I find hard coding "" every time for checking an empty string not as good.
Is there a simple way to determine if a variable is a list, dictionary, or something else?
",https://stackoverflow.com/questions/2225038/determine-the-type-of-an-object,2232,2526859.0,15.0,,,2010-02-08 21:37:20,2022-08-29 20:14:36,2022-06-06 03:59:45,2022-09-09 07:18:44,Duplicate,python;dictionary;types;typeof,Justin Ethier,134991,101258,registered,true,2225066,,,2013-10-27 16:21:56,98,91,0,0,0,4,true,true,false,true,true,true,32,6,true,0.006,0.0009,6130,2010,2,21,Monday,false,true,false,false,false,false,false 2600191,How do I count the occurrences of a list item?,"Given a single item, how do I count occurrences of it in a list, in Python?
A related but different problem is counting occurrences of each different element in a collection, getting a dictionary or list as a histogram result instead of a single integer. For that problem, see Using a dictionary to count the items in a list.
",https://stackoverflow.com/questions/2600191/how-do-i-count-the-occurrences-of-a-list-item,2229,3175906.0,30.0,,,2010-04-08 13:30:00,2026-01-01 18:03:01,2022-07-30 20:57:11,,,python;list;count,weakish,30320,222893,registered,true,2600208,,CC BY-SA 4.0,2016-04-13 15:24:14,433,327,0,1,0,3,true,false,false,true,true,true,46,10,true,0.009,0.0007,6071,2010,4,13,Thursday,false,true,false,false,false,false,false 7370801,How do I measure elapsed time in Python?,"I want to measure the time it took to execute a function. I couldn't get timeit to work:
import timeit
start = timeit.timeit()
print("hello")
end = timeit.timeit()
print(end - start)
",https://stackoverflow.com/questions/7370801/how-do-i-measure-elapsed-time-in-python,2205,3168589.0,42.0,,,2011-09-10 09:21:02,2026-03-03 12:01:54,2022-06-13 01:03:25,,,python;performance;measure;timeit,gilbert8,22061,938033,unregistered,true,,,CC BY-SA 4.0,2019-12-14 21:13:47,238,194,2,0,0,4,false,false,false,true,true,true,40,8,true,0.013,0.0007,5551,2011,9,9,Saturday,true,true,false,false,false,false,false
9371238,Why is reading lines from stdin much slower in C++ than Python?,"I wanted to compare reading lines of string input from stdin using Python and C++ and was shocked to see my C++ code run an order of magnitude slower than the equivalent Python code. Since my C++ is rusty and I'm not yet an expert Pythonista, please tell me if I'm doing something wrong or if I'm misunderstanding something.
(TLDR answer: include the statement: cin.sync_with_stdio(false) or just use fgets instead.
TLDR results: scroll all the way down to the bottom of my question and look at the table.)
C++ code:
#include <iostream>
#include <time.h>
using namespace std;
int main() {
string input_line;
long line_count = 0;
time_t start = time(NULL);
int sec;
int lps;
while (cin) {
getline(cin, input_line);
if (!cin.eof())
line_count++;
};
sec = (int) time(NULL) - start;
cerr << "Read " << line_count << " lines in " << sec << " seconds.";
if (sec > 0) {
lps = line_count / sec;
cerr << " LPS: " << lps << endl;
} else
cerr << endl;
return 0;
}
// Compiled with:
// g++ -O3 -o readline_test_cpp foo.cpp
Python Equivalent:
#!/usr/bin/env python
import time
import sys
count = 0
start = time.time()
for line in sys.stdin:
count += 1
delta_sec = int(time.time() - start_time)
if delta_sec >= 0:
lines_per_sec = int(round(count/delta_sec))
print("Read {0} lines in {1} seconds. LPS: {2}".format(count, delta_sec,
lines_per_sec))
Here are my results:
$ cat test_lines | ./readline_test_cpp
Read 5570000 lines in 9 seconds. LPS: 618889
$ cat test_lines | ./readline_test.py
Read 5570000 lines in 1 seconds. LPS: 5570000
I should note that I tried this both under Mac OS X v10.6.8 (Snow Leopard) and Linux 2.6.32 (Red Hat Linux 6.2). The former is a MacBook Pro, and the latter is a very beefy server, not that this is too pertinent.
$ for i in {1..5}; do echo "Test run $i at `date`"; echo -n "CPP:"; cat test_lines | ./readline_test_cpp ; echo -n "Python:"; cat test_lines | ./readline_test.py ; done
Test run 1 at Mon Feb 20 21:29:28 EST 2012
CPP: Read 5570001 lines in 9 seconds. LPS: 618889
Python:Read 5570000 lines in 1 seconds. LPS: 5570000
Test run 2 at Mon Feb 20 21:29:39 EST 2012
CPP: Read 5570001 lines in 9 seconds. LPS: 618889
Python:Read 5570000 lines in 1 seconds. LPS: 5570000
Test run 3 at Mon Feb 20 21:29:50 EST 2012
CPP: Read 5570001 lines in 9 seconds. LPS: 618889
Python:Read 5570000 lines in 1 seconds. LPS: 5570000
Test run 4 at Mon Feb 20 21:30:01 EST 2012
CPP: Read 5570001 lines in 9 seconds. LPS: 618889
Python:Read 5570000 lines in 1 seconds. LPS: 5570000
Test run 5 at Mon Feb 20 21:30:11 EST 2012
CPP: Read 5570001 lines in 10 seconds. LPS: 557000
Python:Read 5570000 lines in 1 seconds. LPS: 5570000
Tiny benchmark addendum and recap
For completeness, I thought I'd update the read speed for the same file on the same box with the original (synced) C++ code. Again, this is for a 100M line file on a fast disk. Here's the comparison, with several solutions/approaches:
| Implementation | Lines per second |
|---|---|
| python (default) | 3,571,428 |
| cin (default/naive) | 819,672 |
| cin (no sync) | 12,500,000 |
| fgets | 14,285,714 |
| wc (not fair comparison) | 54,644,808 |
This has always confused me. It seems like this would be nicer:
["Hello", "world"].join("-")
Than this:
"-".join(["Hello", "world"])
Is there a specific reason it is like this?
",https://stackoverflow.com/questions/493819/why-is-it-string-joinlist-instead-of-list-joinstring,2168,1582238.0,10.0,,,2009-01-29 22:45:13,2026-07-10 05:16:54,2022-04-01 02:51:16,,,python;string;list,Evan Fosmark,102757,49701,registered,true,493842,,CC BY-SA 4.0,2018-04-27 06:45:44,308,239,2,0,0,3,true,false,false,true,true,true,57,7,true,0.006,0.0014,6505,2009,1,22,Thursday,false,true,false,false,false,false,false 4706499,How do I append to a file?,"How do I append to a file instead of overwriting it?
",https://stackoverflow.com/questions/4706499/how-do-i-append-to-a-file,2140,2386146.0,12.0,,,2011-01-16 16:20:33,2022-10-19 00:55:58,2022-06-13 00:23:12,,,python;file;append,user502039,,,does_not_exist,true,4706520,,CC BY-SA 4.0,2017-12-22 13:08:28,60,53,0,0,0,3,true,false,false,true,false,true,26,7,true,0.005,0.0009,5788,2011,1,16,Sunday,true,true,false,false,false,false,false 101754,Is there a way to run Python on Android?,"We are working on an S60 version and this platform has a nice Python API..
However, there is nothing official about Python on Android, but since Jython exists, is there a way to let the snake and the robot work together??
",https://stackoverflow.com/questions/101754/is-there-a-way-to-run-python-on-android,2081,782969.0,23.0,,,2008-09-19 13:21:12,2025-12-08 13:21:21,2018-11-08 19:09:14,,,android;python;jython;ase;android-scripting,Bite code,602069,9951,registered,true,8189603,,CC BY-SA 4.0,2012-07-10 03:47:27,392,223,0,2,0,5,true,false,false,true,true,true,40,9,true,0.029,0.0027,6637,2008,9,13,Friday,false,true,false,false,false,false,false 275018,How can I remove a trailing newline?,"How can I remove the last character of a string if it is a newline?
"abc\n" --> "abc"
",https://stackoverflow.com/questions/275018/how-can-i-remove-a-trailing-newline,2077,2535574.0,28.0,,,2008-11-08 18:25:24,2023-11-08 17:02:25,2022-12-15 23:21:18,,,python;newline;trailing,RidingThisToTheTop,,,does_not_exist,true,,,CC BY-SA 4.0,2016-10-01 12:45:28,143,112,1,0,0,3,false,false,false,true,false,true,36,7,true,0.011,0.0008,6587,2008,11,18,Saturday,true,true,false,false,false,false,false
735975,Static methods in Python?,"Can I define a static method which I can call directly on the class instance? e.g.,
MyClass.the_static_method()
",https://stackoverflow.com/questions/735975/static-methods-in-python,2077,1338339.0,12.0,,,2009-04-09 21:23:19,2023-01-22 01:42:44,2022-11-29 00:11:40,,,python;static-methods,Joan Venge,334947,51816,registered,true,735978,,CC BY-SA 4.0,2018-12-20 04:45:49,250,113,1,1,0,2,true,false,false,true,true,true,25,4,true,0.009,0.0016,6435,2009,4,21,Thursday,false,true,false,false,false,false,false
10660435,How do I split the definition of a long string over multiple lines?,"I have a very long query. I would like to split it in several lines in Python. A way to do it in JavaScript would be using several sentences and joining them with a + operator (I know, maybe it's not the most efficient way to do it, but I'm not really concerned about performance in this stage, just code readability). Example:
var long_string = 'some text not important. just garbage to' +
'illustrate my example';
I tried doing something similar in Python, but it didn't work, so I used \ to split the long string. However, I'm not sure if this is the only/best/pythonicest way of doing it. It looks awkward.
Actual code:
query = 'SELECT action.descr as "action", '\
'role.id as role_id,'\
'role.descr as role'\
'FROM '\
'public.role_action_def,'\
'public.role,'\
'public.record_def, '\
'public.action'\
'WHERE role.id = role_action_def.role_id AND'\
'record_def.id = role_action_def.def_id AND'\
'action.id = role_action_def.action_id AND'\
'role_action_def.account_id = ' + account_id + ' AND'\
'record_def.account_id=' + account_id + ' AND'\
'def_id=' + def_id
See also: How can I do a line break (line continuation) in Python (split up a long line of source code)? when the overall line of code is long but doesn't contain a long string literal.
",https://stackoverflow.com/questions/10660435/how-do-i-split-the-definition-of-a-long-string-over-multiple-lines,2075,2144440.0,31.0,,,2012-05-18 22:21:09,2026-08-04 21:30:46,2024-04-22 20:45:01,,,python;string;multiline;multilinestring,Pablo Mescher,27797,1231428,registered,true,10660443,,CC BY-SA 4.0,,1581,1339,4,1,0,4,true,false,false,true,true,true,67,13,true,0.014,0.001,5300,2012,5,22,Friday,false,true,false,false,false,false,false 5226311,Installing specific package version with pip,"I am trying to install version 1.2.2 of MySQL_python, using a fresh virtualenv created with the --no-site-packages option. The current version shown in PyPi is 1.2.3. Is there a way to install the older version? I have tried:
pip install MySQL_python==1.2.2
However, when installed, it still shows MySQL_python-1.2.3-py2.6.egg-info in the site packages. Is this a problem specific to this package, or am I doing something wrong?
How do I pretty-print a JSON file in Python?
",https://stackoverflow.com/questions/12943819/how-to-prettyprint-a-json-file,2063,2589850.0,15.0,,,2012-10-17 21:38:43,2023-10-22 10:53:24,2022-04-10 10:24:34,,,python;json;formatting;pretty-print,Colleen,25977,892387,registered,true,12944035,,CC BY-SA 4.0,2020-06-19 07:17:02,52,45,0,0,0,4,true,false,false,true,true,true,31,6,true,0.006,0.0008,5148,2012,10,21,Wednesday,false,true,false,false,false,false,false 15943769,How do I get the row count of a Pandas DataFrame?,"How do I get the number of rows of a pandas dataframe df?
How do I find out the name of the class used to create an instance of an object in Python?
I'm not sure if I should use the inspect module or parse the __class__ attribute.
How do I check if a string represents a numeric value in Python?
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
The above works, but it seems clunky.
Editor's note: If what you are testing comes from user input, it is still a string even if it represents an int or a float. For converting the input, see How can I read inputs as numbers? For ensuring that the input represents an int or float (or other requirements) before proceeding, see Asking the user for input until they give a valid response
How do I check if an object is of a given type, or if it inherits from a given type?
How do I check if the object o is of type str?
Editor's note: Beginners often wrongly expect a string to already be "a number" – either expecting Python 3.x input to convert type, or expecting that a string like '1' is also simultaneously an integer. This question does not address those types of questions. Instead, see How do I check if a string represents a number (float or int)?, How can I read inputs as numbers? and/or Asking the user for input until they give a valid response as appropriate.
How do I read every line of a file in Python and store each line as an element in a list?
I want to read the file line by line and append each line to the end of the list.
",https://stackoverflow.com/questions/3277503/how-to-read-a-file-line-by-line-into-a-list,2023,5212225.0,28.0,,,2010-07-18 22:25:01,2024-12-19 00:16:03,2018-11-16 00:14:30,,,python;string;file;readlines,Julie Raswick,20383,395371,unregistered,true,,,CC BY-SA 4.0,2016-05-02 06:52:42,188,174,0,0,0,4,false,false,false,true,true,true,44,9,true,0.005,0.0004,5970,2010,7,22,Sunday,true,true,false,false,false,false,false 12179271,Meaning of @classmethod and @staticmethod for a beginner,"What do @classmethod and @staticmethod mean in Python, and how are they different? When should I use them, why should I use them, and how should I use them?
As far as I understand, @classmethod tells a class that it's a method which should be inherited into subclasses, or... something. However, what's the point of that? Why not just define the class method without adding @classmethod or @staticmethod or any @ definitions?
Here is the problem:
I have a requirements.txt file that looks like:
BeautifulSoup==3.2.0
Django==1.3
Fabric==1.2.0
Jinja2==2.5.5
PyYAML==3.09
Pygments==1.4
SQLAlchemy==0.7.1
South==0.7.3
amqplib==0.6.1
anyjson==0.3
...
I have a local archive directory containing all the packages + others.
I have created a new virtualenv with
bin/virtualenv testing
Upon activating it, I tried to install the packages according to requirements.txt from the local archive directory.
source bin/activate
pip install -r /path/to/requirements.txt -f file:///path/to/archive/
I got some output that seems to indicate that the installation is fine:
Downloading/unpacking Fabric==1.2.0 (from -r ../testing/requirements.txt (line 3))
Running setup.py egg_info for package Fabric
warning: no previously-included files matching '*' found under directory 'docs/_build'
warning: no files found matching 'fabfile.py'
Downloading/unpacking South==0.7.3 (from -r ../testing/requirements.txt (line 8))
Running setup.py egg_info for package South
....
But a later check revealed that none of the packages are installed properly. I cannot import the packages, and none are found in the site-packages directory of my virtualenv. So what went wrong?
",https://stackoverflow.com/questions/7225900/how-can-i-install-packages-using-pip-according-to-the-requirements-txt-file-from,2003,3915894.0,18.0,,,2011-08-29 03:53:04,2026-01-06 02:15:41,2025-11-05 16:45:38,,,python;pip;virtualenv;requirements.txt,kakarukeys,24361,496852,registered,true,10429168,,CC BY-SA 4.0,2015-10-24 16:39:45,1628,1231,6,1,0,4,true,false,false,true,true,true,99,16,true,0.005,0.0005,5563,2011,8,3,Monday,false,true,false,false,false,false,false 1319615,How do I declare custom exceptions in modern Python?,"How do I declare custom exception classes in modern Python? My primary goal is to follow whatever standard other exception classes have, so that (for instance) any extra string I include in the exception is printed out by whatever tool caught the exception.
By "modern Python" I mean something that will run in Python 2.5 but be 'correct' for the Python 2.6 and Python 3.* way of doing things. And by "custom" I mean an Exception object that can include extra data about the cause of the error: a string, maybe also some other arbitrary object relevant to the exception.
I was tripped up by the following deprecation warning in Python 2.6.2:
>>> class MyError(Exception):
... def __init__(self, message):
... self.message = message
...
>>> MyError("foo")
_sandbox.py:3: DeprecationWarning: BaseException.message has been deprecated as of Python 2.6
It seems crazy that BaseException has a special meaning for attributes named message. I gather from PEP-352 that attribute did have a special meaning in 2.5 they're trying to deprecate away, so I guess that name (and that one alone) is now forbidden? Ugh.
I'm also fuzzily aware that Exception has some magic parameter args, but I've never known how to use it. Nor am I sure it's the right way to do things going forward; a lot of the discussion I found online suggested they were trying to do away with args in Python 3.
I am trying to build a shared library using a C extension file but first I have to generate the output file using the command below:
gcc -Wall utilsmodule.c -o Utilc
After executing the command, I get this error message:
> utilsmodule.c:1:20: fatal error: Python.h: No such file or directory
compilation terminated.
I have tried all the suggested solutions over the internet but the problem still exists. I have no problem with Python.h. I managed to locate the file on my machine.
How can I generate random integers between 0 and 9 (inclusive) in Python?
For example, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
What do single and double leading underscores before an object's name represent in Python?
",https://stackoverflow.com/questions/1301346/what-is-the-meaning-of-single-and-double-underscore-before-an-object-name,1927,901283.0,19.0,,,2009-08-19 17:11:57,2025-05-12 10:24:37,2022-06-13 01:28:06,,,python;oop;naming-conventions;identifier,Ram Rachum,90035,76701,registered,true,1301369,,CC BY-SA 4.0,2017-08-23 08:56:20,98,91,0,0,0,4,true,false,false,true,true,true,74,13,true,0.021,0.0021,6303,2009,8,17,Wednesday,false,true,false,false,false,false,false 14132789,How to resolve the Python error 'attempted relative import',"I've been here:
and plenty of URLs that I did not copy, some on SO, some on other sites, back when I thought I'd have the solution quickly.
The forever-recurring question is this: how do I solve this "Attempted relative import in non-package" message?
ImportError: attempted relative import with no known parent package
I built an exact replica of the package on pep-0328:
package/
__init__.py
subpackage1/
__init__.py
moduleX.py
moduleY.py
subpackage2/
__init__.py
moduleZ.py
moduleA.py
The imports were done from the console.
I did make functions named spam and eggs in their appropriate modules. Naturally, it didn't work. The answer is apparently in the 4th URL I listed, but it's all alumni to me. There was this response on one of the URLs I visited:
Relative imports use a module's name attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to 'main') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.
The above response looks promising, but it's all hieroglyphs to me. How do I make Python not return to me "Attempted relative import in non-package"? It has an answer that involves -m, supposedly.
Why does Python give that error message? What does by "non-package" mean? Why and how do you define a 'package'?
",https://stackoverflow.com/questions/14132789/how-to-resolve-the-python-error-attempted-relative-import,1907,786794.0,16.0,,,2013-01-03 03:50:40,2026-10-09 23:04:07,2026-09-24 12:10:20,,,python;python-import;relative-path;python-packaging;relative-import,user1881400,,,does_not_exist,true,14132912,,CC BY-SA 4.0,2019-07-14 12:30:00,2677,1754,2,7,0,5,true,false,false,true,false,true,67,9,false,0.02,0.0024,5070,2013,1,3,Thursday,false,true,false,false,false,false,false 16981921,Relative imports in Python 3,"I want to import a function from another file in the same directory.
Usually, one of the following works:
from .mymodule import myfunction
from mymodule import myfunction
...but the other one gives me one of these errors:
ImportError: attempted relative import with no known parent package
ModuleNotFoundError: No module named 'mymodule'
SystemError: Parent module '' not loaded, cannot perform relative import
Why is this?
",https://stackoverflow.com/questions/16981921/relative-imports-in-python-3,1894,2228066.0,36.0,,,2013-06-07 10:26:50,2025-05-11 14:17:43,2022-08-29 12:04:53,,,python;python-3.x;python-import,John Smith Optional,25596,1126971,registered,true,16985066,,CC BY-SA 4.0,2022-11-01 09:16:34,694,429,5,0,0,3,true,false,false,true,true,true,28,5,false,0.016,0.0009,4915,2013,6,10,Friday,false,true,false,false,false,false,false 12309269,How do I write JSON data to a file?,"How do I write JSON data stored in the dictionary data to a file?
f = open('data.json', 'wb')
f.write(data)
This gives the error:
",https://stackoverflow.com/questions/12309269/how-do-i-write-json-data-to-a-file,1887,3217381.0,19.0,,,2012-09-06 22:21:21,2025-04-27 17:24:47,2022-03-30 05:49:52,,,python;json,user1530318,28137,1530318,registered,true,12309296,,CC BY-SA 4.0,2018-11-06 18:55:02,262,179,2,0,0,2,true,false,false,true,true,true,35,9,true,0.006,0.0006,5189,2012,9,22,Thursday,false,true,false,false,false,false,false 1534210,Use a different Python version with virtualenv,"TypeError: must be string or buffer, not dict
How do I create a virtual environment for a specified version of Python?
",https://stackoverflow.com/questions/1534210/use-a-different-python-version-with-virtualenv,1886,2590233.0,44.0,,,2009-10-07 21:11:22,2026-07-03 19:04:35,2026-07-03 13:43:09,,,python;virtualenv;virtualenvwrapper,Ulf,19570,51208,registered,true,1534343,,CC BY-SA 4.0,2014-06-22 19:41:38,80,73,0,0,0,3,true,false,false,true,true,true,46,7,false,0.017,0.0007,6254,2009,10,21,Wednesday,false,true,false,false,false,false,false 541390,Extracting extension from filename,"Is there a function to extract the extension from a filename?
",https://stackoverflow.com/questions/541390/extracting-extension-from-filename,1882,1695648.0,33.0,,,2009-02-12 14:11:50,2025-05-07 12:20:53,2024-11-19 17:29:11,,,python;filenames;file-extension,Alex,45141,85185,registered,true,541394,,CC BY-SA 4.0,2018-08-11 19:58:50,69,62,0,0,0,3,true,false,false,true,true,true,34,4,false,0.019,0.0011,6491,2009,2,14,Thursday,false,true,false,false,false,false,false 67631,How can I import a module dynamically given the full path?,"How do I load a Python module given its full path?
Note that the file can be anywhere in the filesystem where the user has access rights.
See also: How to import a module given its name as string?
",https://stackoverflow.com/questions/67631/how-can-i-import-a-module-dynamically-given-the-full-path,1879,1622144.0,38.0,,,2008-09-15 22:30:55,2024-02-17 17:55:58,2022-11-30 11:42:29,,,python;python-import;python-module,derfred,20221,10286,registered,true,67692,,CC BY-SA 4.0,2015-07-11 12:01:11,310,198,0,1,0,3,true,false,false,true,true,true,58,11,true,0.023,0.0012,6641,2008,9,22,Monday,false,true,false,false,false,false,false 1557571,How do I get time of a Python program's execution?,"I have a command line program in Python that takes a while to finish. I want to know the exact time it takes to finish running.
I've looked at the timeit module, but it seems it's only for small snippets of code. I want to time the whole program.
There are several ways to write to stderr:
print >> sys.stderr, "spam" # Python 2 only.
sys.stderr.write("spam\n")
os.write(2, b"spam\n")
from __future__ import print_function
print("spam", file=sys.stderr)
What are the differences between these methods? Which method should be preferred?
",https://stackoverflow.com/questions/5574702/how-do-i-print-to-stderr-in-python,1826,1379883.0,17.0,,,2011-04-07 00:59:10,2022-10-03 09:36:11,2022-09-20 03:48:01,,,python;printing;stderr,wim,370725,674039,registered,true,14981125,,CC BY-SA 4.0,2018-05-29 16:57:00,378,340,1,0,0,3,true,false,false,true,true,true,35,8,true,0.012,0.0013,5707,2011,4,0,Thursday,false,true,false,false,false,false,false 2257441,Random string generation with upper case letters and digits,"How do I generate a string of size N, made of numbers and uppercase English letters such as:
How do I read from standard input (stdin)?
I have multiple classes which would become singletons (my use case is for a logger, but this is not important). I do not wish to clutter several classes with added gumph when I can simply inherit or decorate.
Best methods:
def singleton(class_):
instances = {}
def getinstance(*args, **kwargs):
if class_ not in instances:
instances[class_] = class_(*args, **kwargs)
return instances[class_]
return getinstance
@singleton
class MyClass(BaseClass):
pass
Pros
Cons
While objects created using MyClass() would be true singleton objects, MyClass itself is a function, not a class, so you cannot call class methods from it. Also for
x = MyClass();
y = MyClass();
t = type(n)();
then x == y but x != t && y != t
class Singleton(object):
_instance = None
def __new__(class_, *args, **kwargs):
if not isinstance(class_._instance, class_):
class_._instance = object.__new__(class_, *args, **kwargs)
return class_._instance
class MyClass(Singleton, BaseClass):
pass
Pros
Cons
__new__ could be overwritten during inheritance from a second base class? One has to think more than is necessary.class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
#Python2
class MyClass(BaseClass):
__metaclass__ = Singleton
#Python3
class MyClass(BaseClass, metaclass=Singleton):
pass
Pros
__metaclass__ for its proper purpose (and made me aware of it)Cons
def singleton(class_):
class class_w(class_):
_instance = None
def __new__(class_, *args, **kwargs):
if class_w._instance is None:
class_w._instance = super(class_w,
class_).__new__(class_,
*args,
**kwargs)
class_w._instance._sealed = False
return class_w._instance
def __init__(self, *args, **kwargs):
if self._sealed:
return
super(class_w, self).__init__(*args, **kwargs)
self._sealed = True
class_w.__name__ = class_.__name__
return class_w
@singleton
class MyClass(BaseClass):
pass
Pros
Cons
_sealed attributesuper() because they will recurse. This means you can't customize __new__ and can't subclass a class that needs you to call up to __init__.a module file singleton.py
Pros
Cons
This question is not for the discussion of whether or not the singleton design pattern is desirable, is an anti-pattern, or for any religious wars, but to discuss how this pattern is best implemented in Python in such a way that is most Pythonic. In this instance I define 'most Pythonic' to mean that it follows the 'principle of least astonishment'.
",https://stackoverflow.com/questions/6760685/what-is-the-best-way-of-implementing-a-singleton-in-python,1816,859735.0,44.0,,,2011-07-20 10:47:57,2026-07-13 12:59:40,2026-07-11 22:36:42,,,best-practices;python;singleton;metaclass;base-class,theheadofabroom,22605,655372,registered,true,73988733,,CC BY-SA 4.0,2015-02-25 00:55:43,4707,3819,16,2,0,5,true,false,false,true,true,true,59,11,true,0.051,0.0021,5603,2011,7,10,Wednesday,false,true,false,false,false,false,false 44834,What does __all__ mean in Python?,"I see __all__ in __init__.py files. What does it do?
This displays the figure in a GUI:
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [1, 4, 9])
plt.show()
But how do I instead save the figure to a file (e.g. foo.png)?
",https://stackoverflow.com/questions/9622163/save-plot-to-image-file-instead-of-displaying-it,1809,3280843.0,25.0,,,2012-03-08 17:38:10,2024-08-14 16:36:23,2023-12-04 21:49:31,,,python;matplotlib;savefig,Homunculus Reticulli,69294,962891,registered,true,9890599,,CC BY-SA 4.0,2018-07-27 10:44:06,211,173,1,0,0,3,true,false,false,true,true,true,48,9,false,0.008,0.0006,5371,2012,3,17,Thursday,false,true,false,false,false,false,false 11285613,Selecting multiple columns in a Pandas dataframe,"How do I select columns a and b from df, and save them into a new dataframe df1?
index a b c
1 2 3 4
2 3 4 5
Unsuccessful attempt:
df1 = df['a':'b']
df1 = df.ix[:, 'a':'b']
",https://stackoverflow.com/questions/11285613/selecting-multiple-columns-in-a-pandas-dataframe,1801,4281829.0,22.0,,,2012-07-01 21:03:16,2023-11-03 23:33:47,2023-04-10 06:22:54,,,python;pandas;dataframe;select;indexing,user1234440,23777,1610626,registered,true,11287278,,CC BY-SA 4.0,2018-01-03 08:01:28,388,198,6,0,0,5,true,false,false,true,true,true,48,7,false,0.005,0.0004,5256,2012,7,21,Sunday,true,true,false,false,false,false,false
209840,Make a dictionary (dict) from separate lists of keys and values,"I want to combine these:
keys = ['name', 'age', 'food']
values = ['Monty', 42, 'spam']
into a single dictionary:
{'name': 'Monty', 'age': 42, 'food': 'spam'}
How can I do this?
",https://stackoverflow.com/questions/209840/make-a-dictionary-dict-from-separate-lists-of-keys-and-values,1798,1430447.0,22.0,,,2008-10-16 19:05:47,2025-03-25 19:53:42,2025-03-24 18:24:56,,,python;list;dictionary;key,Guido,47945,12388,registered,true,209854,,CC BY-SA 4.0,2019-07-22 08:41:36,322,179,2,0,0,4,true,false,false,true,true,true,63,11,false,0.015,0.0013,6610,2008,10,19,Thursday,false,true,false,false,false,false,false 678236,How do I get the filename without the extension from a path in Python?,"How do I get the filename without the extension from a path in Python?
"/path/to/some/file.txt" → "file"
",https://stackoverflow.com/questions/678236/how-do-i-get-the-filename-without-the-extension-from-a-path-in-python,1795,2416665.0,33.0,,,2009-03-24 16:41:03,2025-05-07 15:31:47,2022-04-09 08:10:25,,,python;string;path,Joan Venge,334947,51816,registered,true,678242,,CC BY-SA 4.0,2019-01-24 00:16:02,159,128,1,0,0,3,true,false,false,true,true,true,70,14,true,0.014,0.0007,6451,2009,3,16,Tuesday,false,true,false,false,false,false,false
582336,How do I profile a Python script?,"Project Euler and other coding contests often have a maximum time to run or people boast of how fast their particular solution runs. With Python, sometimes the approaches are somewhat kludgey - i.e., adding timing code to __main__.
What is a good way to profile how long a Python program takes to run?
",https://stackoverflow.com/questions/582336/how-do-i-profile-a-python-script,1762,966372.0,34.0,,,2009-02-24 16:01:26,2024-07-17 07:12:07,2022-04-09 07:20:40,,,python;performance;optimization;time-complexity;profiling,Chris Lawlor,49662,21245,registered,true,582337,,CC BY-SA 4.0,2018-08-01 15:33:21,404,303,1,1,0,5,true,false,false,true,true,true,33,7,true,0.035,0.0018,6479,2009,2,16,Tuesday,false,true,false,false,false,false,false 4260280,if/else in a list comprehension,"How do I convert the following for-loop containing an if/else into a list comprehension?
results = []
for x in xs:
results.append(f(x) if x is not None else '')
It should yield '' if x is None, and otherwise f(x).
I tried:
[f(x) for x in xs if x is not None else '']
but it gives a SyntaxError. What is the correct syntax?
See Does Python have a ternary conditional operator? for info on ... if ... else ....
See List comprehension with condition for omitting values based on a condition: [... for x in xs if x cond].
See `elif` in list comprehension conditionals for elif.
I have a series of 20 plots (not subplots) to be made in a single figure. I want the legend to be outside of the box. At the same time, I do not want to change the axes, as the size of the figure gets reduced.
float('nan') represents NaN (not a number). But how do I check for it?
There is no built in reverse method for Python's str object. How can I reverse a string?
Why does the following class declaration inherit from object?
class MyClass(object):
...
",https://stackoverflow.com/questions/4015417/why-do-python-classes-inherit-object,1718,469566.0,6.0,,,2010-10-25 14:15:26,2022-04-09 07:21:43,2022-04-09 07:21:43,,,python;class;oop;object;inheritance,tjvr,18081,359640,registered,true,45062077,,CC BY-SA 4.0,2019-05-06 08:05:01,138,94,2,0,0,5,true,false,false,true,true,true,37,6,true,0.013,0.0037,5871,2010,10,14,Monday,false,true,false,false,false,false,false
60208,Replacements for switch statement in Python?,"I want to write a function in Python that returns different fixed values based on the value of an input index.
In other languages I would use a switch or case statement, but Python does not appear to have a switch statement. What are the recommended Python solutions in this scenario?
I have the following DataFrame (df):
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.rand(10, 5))
I add more column(s) by assignment:
df['mean'] = df.mean(1)
How can I move the column mean to the front, i.e. set it as first column leaving the order of the other columns untouched?
How do I check if a directory exists in Python?
",https://stackoverflow.com/questions/8933237/how-do-i-check-if-a-directory-exists-in-python,1684,1803110.0,16.0,,,2012-01-19 21:03:20,2026-05-12 09:45:02,2023-03-20 00:53:22,,,python;directory,David542,113050,651174,registered,true,8933290,,CC BY-SA 4.0,,55,48,0,0,0,2,true,false,false,true,true,true,47,10,true,0.009,0.0009,5420,2012,1,21,Thursday,false,true,false,false,false,false,false 17271319,How do I install pip on macOS or OS X?,"I spent most of the day yesterday searching for a clear answer for installing pip (package manager for Python). I can't find a good solution.
How do I install it?
",https://stackoverflow.com/questions/17271319/how-do-i-install-pip-on-macos-or-os-x,1671,3246198.0,21.0,,,2013-06-24 08:44:30,2025-03-03 13:23:19,2017-04-08 16:21:27,,,python;macos;pip;installation,The System,16751,2513263,registered,true,,,CC BY-SA 3.0,2015-04-23 18:03:18,191,164,1,0,0,4,false,false,false,true,true,true,38,10,true,0.006,0.0005,4898,2013,6,8,Monday,false,true,false,false,false,false,false 1471994,What is setup.py?,"What is setup.py and how can it be configured or used?
What is the Python 3 equivalent of python -m SimpleHTTPServer?
How do I force Python's print function to flush the buffered output to the screen?
See also: Disable output buffering if the goal is to change the buffering behaviour generally. This question is about explicitly flushing output after a specific print call, even though output is still being buffered.
For duplicate closers: if a beginner is asking a question about trying to make output appear immediately while not using a newline at the end, please instead use Why doesn't print output show up immediately in the terminal when there is no newline at the end? to close the question. The current question isn't good enough because the person asking will likely not have a concept of buffering or flushing; the other question is intended to explain those concepts first, whereas this question is about the technical details.
",https://stackoverflow.com/questions/230751/how-can-i-flush-the-output-of-the-print-function,1647,1212352.0,14.0,,,2008-10-23 17:59:39,2024-03-21 09:13:14,2023-01-01 23:30:48,,,python;printing;flush;output-buffering,Walter Nissen,17247,8835,registered,true,230774,,CC BY-SA 4.0,2018-12-20 06:37:14,1088,829,2,2,0,4,true,false,false,true,true,true,49,10,true,0.012,0.0014,6603,2008,10,17,Thursday,false,true,false,false,false,false,false 3702675,Catch and print full Python exception traceback without halting/exiting the program,"I want to catch and log exceptions without exiting, e.g.,
try:
do_stuff()
except Exception as err:
print(Exception, err)
# I want to print the entire traceback here,
# not just the exception name and details
I want to print the exact same output that is printed when the exception is raised without the try/except intercepting the exception, and I do not want it to exit my program.
",https://stackoverflow.com/questions/3702675/catch-and-print-full-python-exception-traceback-without-halting-exiting-the-prog,1629,1868000.0,19.0,,,2010-09-13 17:03:30,2024-12-05 09:33:21,2023-05-24 16:53:42,,,python;exception;try-catch;traceback,chriscauley,21711,266564,registered,true,16946886,,CC BY-SA 4.0,2017-09-21 06:15:56,447,400,1,0,0,4,true,false,false,true,true,true,83,11,false,0.01,0.0009,5913,2010,9,17,Monday,false,true,false,false,false,false,false 1747817,Create a dictionary with comprehension,"Can I use list comprehension syntax to create a dictionary?
For example, by iterating over pairs of keys and values:
d = {... for k, v in zip(keys, values)}
",https://stackoverflow.com/questions/1747817/create-a-dictionary-with-comprehension,1615,1256948.0,17.0,,,2009-11-17 10:07:53,2023-09-12 13:26:51,2022-04-09 07:41:50,,,python;dictionary;list-comprehension;dictionary-comprehension,flybywire,277882,63051,registered,true,1747827,,CC BY-SA 4.0,,196,158,1,0,0,4,true,false,false,true,true,true,38,5,false,0.014,0.0013,6213,2009,11,10,Tuesday,false,true,false,false,false,false,false
11618898,pg_config executable not found,"I am having trouble installing psycopg2. I get the following error when I try to pip install psycopg2:
Error: pg_config executable not found.
Please add the directory containing pg_config to the PATH
or specify the full executable path with the option:
python setup.py build_ext --pg-config /path/to/pg_config build ...
or with the pg_config option in 'setup.cfg'.
----------------------------------------
Command python setup.py egg_info failed with error code 1 in /tmp/pip-build/psycopg2
But the problem is pg_config is actually in my PATH; it runs without any problem:
$ which pg_config
/usr/pgsql-9.1/bin/pg_config
I tried adding the pg_config path to the setup.cfg file and building it using the source files I downloaded from their website (http://initd.org/psycopg/) and I get the following error message!
Error: Unable to find 'pg_config' file in '/usr/pgsql-9.1/bin/'
But it is actually THERE!!!
I am baffled by these errors. Can anyone help please?
By the way, I sudo all the commands. Also I am on RHEL 5.5.
So I have difficulty with the concept of *args and **kwargs.
So far I have learned that:
*args = list of arguments - as positional arguments**kwargs = dictionary - whose keys become separate keyword arguments and the values become values of these arguments.I don't understand what programming task this would be helpful for.
Maybe:
I think to enter lists and dictionaries as arguments of a function AND at the same time as a wildcard, so I can pass ANY argument?
Is there a simple example to explain how *args and **kwargs are used?
Also the tutorial I found used just the ""*"" and a variable name.
Are *args and **kwargs just placeholders or do you use exactly *args and **kwargs in the code?
How do I convert an integer to a string?
42 ⟶ "42"
For the reverse, see How do I parse a string to a float or int?. Floats can be handled similarly, but handling the decimal points can be tricky because floating-point values are not precise. See Converting a float to a string without rounding it for more specific advice.
",https://stackoverflow.com/questions/961632/convert-integer-to-string-in-python,1596,3903990.0,14.0,,,2009-06-07 10:22:38,2024-12-17 14:48:15,2023-02-18 17:18:58,,,python;string;integer,Hick,36634,105167,registered,true,961638,,CC BY-SA 4.0,2015-04-05 18:15:02,568,339,1,3,0,3,true,false,false,true,true,true,35,6,false,0.004,0.0004,6376,2009,6,10,Sunday,true,true,false,false,false,false,false 9001509,How do I sort a dictionary by key?,"How do I sort a dictionary by its keys?
Example input:
{2:3, 1:89, 4:5, 3:0}
Desired output:
{1:89, 2:3, 3:0, 4:5}
",https://stackoverflow.com/questions/9001509/how-do-i-sort-a-dictionary-by-key,1588,2458681.0,33.0,,,2012-01-25 10:54:29,2026-03-09 08:42:57,2022-07-17 04:19:31,,,python;sorting;dictionary,Antony,16507,1069533,registered,true,9001529,,CC BY-SA 4.0,2017-09-24 11:41:58,186,117,2,0,0,3,true,false,false,true,true,true,34,8,true,0.013,0.0006,5414,2012,1,10,Wednesday,false,true,false,false,false,false,false
15891038,Change column type in pandas,"I created a DataFrame from a list of lists:
table = [
['a', '1.2', '4.2' ],
['b', '70', '0.03'],
['x', '5', '0' ],
]
df = pd.DataFrame(table)
How do I convert the columns to specific types? In this case, I want to convert columns 2 and 3 into floats.
Is there a way to specify the types while converting the list to DataFrame? Or is it better to create the DataFrame first and then loop through the columns to change the dtype for each column? Ideally I would like to do this in a dynamic way because there can be hundreds of columns, and I don't want to specify exactly which columns are of which type. All I can guarantee is that each column contains values of the same type.
",https://stackoverflow.com/questions/15891038/change-column-type-in-pandas,1586,4257812.0,16.0,,,2013-04-08 23:53:30,2024-07-09 21:49:17,2024-07-09 21:49:17,,,python;pandas;dataframe;types;type-conversion,user1642513,,,does_not_exist,true,28648923,,CC BY-SA 4.0,2020-10-04 17:41:52,785,703,1,0,0,5,true,false,false,true,false,true,28,5,false,0.004,0.0004,4975,2013,4,23,Monday,false,true,false,false,false,false,false 1549801,What are the differences between type() and isinstance()?,"What are the differences between these two code snippets?
Using type:
import types
if type(a) is types.DictType:
do_something()
if type(b) in types.StringTypes:
do_something_else()
Using isinstance:
if isinstance(a, dict):
do_something()
if isinstance(b, str) or isinstance(b, unicode):
do_something_else()
",https://stackoverflow.com/questions/1549801/what-are-the-differences-between-type-and-isinstance,1578,923808.0,8.0,,,2009-10-11 03:50:54,2023-09-13 08:33:28,2022-06-20 06:45:34,2023-09-13 08:33:17,Duplicate,python;oop;inheritance;types,abbot,27986,4001,registered,true,1549854,,,2016-12-12 10:21:27,597,326,4,2,0,4,true,true,false,true,true,true,57,8,true,0.009,0.0017,6250,2009,10,3,Sunday,true,true,false,false,false,false,false
2465921,How to copy a dictionary and only edit the copy,"I set dict2 = dict1. When I edit dict2, the original dict1 also changes. How can I avoid this?
>>> dict1 = {"key1": "value1", "key2": "value2"}
>>> dict2 = dict1
>>> dict2["key2"] = "WHY?!"
>>> dict1
{'key2': 'WHY?!', 'key1': 'value1'}
",https://stackoverflow.com/questions/2465921/how-to-copy-a-dictionary-and-only-edit-the-copy,1552,1352504.0,23.0,,,2010-03-17 21:07:06,2026-01-06 21:04:35,2024-05-02 23:05:08,,,python;dictionary;reference,MadSc13ntist,21780,193237,unregistered,true,,,CC BY-SA 4.0,2019-01-02 14:41:04,461,333,4,1,0,3,false,false,false,true,true,true,47,10,false,0.017,0.0011,6093,2010,3,21,Wednesday,false,true,false,false,false,false,false
7585435,How to convert string to bytes in Python 3,"TypeError: 'str' does not support the buffer interface suggests two possible methods to convert a string to bytes:
b = bytes(mystring, 'utf-8')
b = mystring.encode('utf-8')
What are the differences between them? Which one should I opt for and why?
See Convert bytes to a string in Python 3 for the other way around.
",https://stackoverflow.com/questions/7585435/how-to-convert-string-to-bytes-in-python-3,1542,3012262.0,5.0,,,2011-09-28 15:14:07,2025-08-22 23:21:40,2025-01-23 17:52:09,,,python;string;character-encoding;python-3.x,Mark Ransom,310707,5987,registered,true,7585619,,CC BY-SA 4.0,2019-03-26 22:29:45,556,327,1,2,0,4,true,false,false,true,true,true,42,9,false,0.002,0.0005,5533,2011,9,15,Wednesday,false,true,false,false,false,false,false 8858008,How do I move a file in Python?,"How can I do the equivalent of mv in Python?
mv "path/to/current/file.foo" "path/to/new/destination/for/file.foo"
",https://stackoverflow.com/questions/8858008/how-do-i-move-a-file-in-python,1540,2147124.0,12.0,,,2012-01-13 22:17:58,2024-04-28 06:05:52,2023-02-23 08:19:48,,,python;file;file-handling;python-os,David542,113050,651174,registered,true,8858026,,CC BY-SA 4.0,2018-06-29 11:23:20,279,135,2,1,0,4,true,false,false,true,true,true,31,8,true,0.006,0.0007,5426,2012,1,22,Friday,false,true,false,false,false,false,false
192109,Is there a built-in function to print all the current properties and values of an object?,"So what I'm looking for here is something like PHP's print_r function.
This is so I can debug my scripts by seeing what's the state of the object in question.
",https://stackoverflow.com/questions/192109/is-there-a-built-in-function-to-print-all-the-current-properties-and-values-of-a,1539,1467969.0,32.0,,,2008-10-10 16:19:27,2026-03-22 04:29:42,2023-11-17 20:38:18,,,python;debugging;introspection;pretty-print;python-datamodel,fuentesjr,52664,10708,registered,true,192365,,CC BY-SA 4.0,2021-09-05 01:39:05,232,159,0,1,0,5,true,false,false,true,true,true,89,16,true,0.022,0.001,6616,2008,10,16,Friday,false,true,false,false,false,false,false 5142418,What is the use of "assert" in Python?,"What does assert mean? How is it used?
How can I check if a list has any duplicates and return a new list without duplicates?
",https://stackoverflow.com/questions/7961363/removing-duplicates-in-lists,1528,2347864.0,58.0,,,2011-11-01 00:45:24,2026-03-04 20:16:19,2022-10-11 03:18:40,,,python;algorithm;list;duplicates;intersection,Neemaximo,21189,1022857,registered,true,7961390,,CC BY-SA 4.0,2014-07-31 16:07:22,94,87,0,0,0,5,true,false,false,true,true,true,28,4,false,0.025,0.0007,5499,2011,11,0,Tuesday,false,true,false,false,false,false,false 31684375,Automatically create file 'requirements.txt',"Sometimes I download the Python source code from GitHub and don't know how to install all the dependencies. If there isn't any requirements.txt file I have to create it by hand.
Given the Python source code directory, is it possible to create requirements.txt automatically from the import section?
",https://stackoverflow.com/questions/31684375/automatically-create-file-requirements-txt,1527,2759158.0,29.0,,,2015-07-28 18:29:03,2026-01-04 22:32:56,2023-09-02 15:39:57,,,python;dependencies;python-import;requirements.txt,Igor Barinov,26360,1268964,registered,true,33468993,,CC BY-SA 4.0,2023-07-02 01:26:50,399,299,0,1,0,4,true,false,false,true,true,true,52,4,false,0.011,0.0006,4134,2015,7,18,Tuesday,false,true,false,false,false,false,false 3430372,How do I get the full path of the current file's directory?,"How do I get the current file's directory path? I tried:
>>> os.path.abspath(__file__)
'C:\\python27\\test.py'
But I want:
'C:\\python27\\'
",https://stackoverflow.com/questions/3430372/how-do-i-get-the-full-path-of-the-current-files-directory,1525,2849355.0,12.0,,,2010-08-07 12:17:52,2023-09-07 15:57:19,2022-06-05 19:47:10,2023-03-15 07:28:04,Duplicate,python;directory,Shubham,22604,388350,registered,true,3430395,,,2019-07-13 13:32:52,213,151,2,0,0,2,true,true,false,true,true,true,63,12,true,0.004,0.0005,5950,2010,8,12,Saturday,true,true,false,false,false,false,false
2846653,How do I use threading in Python?,"I would like a clear example showing tasks being divided across multiple threads.
",https://stackoverflow.com/questions/2846653/how-do-i-use-threading-in-python,1524,1202477.0,25.0,,,2010-05-17 04:24:00,2024-10-13 17:29:42,2023-06-03 23:54:06,,,python;multithreading;concurrency;python-multithreading,albruno,15345,342728,registered,true,,,CC BY-SA 4.0,2018-02-10 20:17:25,89,82,0,0,0,4,false,false,false,true,true,true,33,7,true,0.021,0.0013,6032,2010,5,4,Monday,false,true,false,false,false,false,false 1483429,How do I print an exception in Python?,"How do I print the error/exception in the except: block?
try:
...
except:
print(exception)
",https://stackoverflow.com/questions/1483429/how-do-i-print-an-exception-in-python,1521,2332239.0,11.0,,,2009-09-27 11:48:19,2024-04-27 19:25:22,2022-06-20 06:52:27,2025-05-14 00:47:47,Duplicate,python;exception;error-handling,TIMEX,275634,179736,registered,true,1483488,,,2020-04-16 07:39:58,144,100,2,0,0,3,true,true,false,true,true,true,38,8,true,0.005,0.0007,6264,2009,9,11,Sunday,true,true,false,false,false,false,false
3768895,How to make a class JSON serializable,"How to make a Python class serializable?
class FileItem:
def __init__(self, fname):
self.fname = fname
Attempt to serialize to JSON:
>>> import json
>>> x = FileItem('/foo/bar')
>>> json.dumps(x)
TypeError: Object of type 'FileItem' is not JSON serializable
",https://stackoverflow.com/questions/3768895/how-to-make-a-class-json-serializable,1519,1710371.0,46.0,,,2010-09-22 11:52:19,2025-08-21 07:10:36,2022-04-09 10:18:54,,,python;json;serialization,Sergey,21599,388427,registered,true,3768975,,CC BY-SA 4.0,2019-07-13 13:10:38,361,299,2,0,0,3,true,false,false,true,true,true,37,7,false,0.027,0.0009,5904,2010,9,11,Wednesday,false,true,false,false,false,false,false
9942594,UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128),"I'm having problems dealing with unicode characters from text fetched from different web pages (on different sites). I am using BeautifulSoup.
The problem is that the error is not always reproducible; it sometimes works with some pages, and sometimes, it barfs by throwing a UnicodeEncodeError. I have tried just about everything I can think of, and yet I have not found anything that works consistently without throwing some kind of Unicode-related error.
One of the sections of code that is causing problems is shown below:
agent_telno = agent.find('div', 'agent_contact_number')
agent_telno = '' if agent_telno is None else agent_telno.contents[0]
p.agent_info = str(agent_contact + ' ' + agent_telno).strip()
Here is a stack trace produced on SOME strings when the snippet above is run:
Traceback (most recent call last):
File ""foobar.py"", line 792, in <module>
p.agent_info = str(agent_contact + ' ' + agent_telno).strip()
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)
I suspect that this is because some pages (or more specifically, pages from some of the sites) may be encoded, whilst others may be unencoded. All the sites are based in the UK and provide data meant for UK consumption - so there are no issues relating to internalization or dealing with text written in anything other than English.
Does anyone have any ideas as to how to solve this so that I can CONSISTENTLY fix this problem?
",https://stackoverflow.com/questions/9942594/unicodeencodeerror-ascii-codec-cant-encode-character-u-xa0-in-position-20,1517,2321386.0,35.0,,,2012-03-30 12:06:41,2024-08-08 07:49:44,2016-03-22 13:59:47,,,python;unicode;beautifulsoup;python-2.x;python-unicode,Homunculus Reticulli,69294,962891,registered,true,9942822,,CC BY-SA 3.0,2015-11-30 21:27:59,1589,1486,3,0,0,5,true,false,false,true,true,true,126,14,false,0.015,0.0007,5349,2012,3,12,Friday,false,true,false,false,false,false,false 3289601,Null object in Python,"How do I refer to the null object in Python?
",https://stackoverflow.com/questions/3289601/null-object-in-python,1513,2572887.0,11.0,,,2010-07-20 11:53:41,2025-02-21 16:32:37,2022-08-23 07:20:02,,,python;object;null,Lizard,45397,123140,registered,true,3289606,,CC BY-SA 4.0,,126,45,0,1,0,3,true,false,false,true,true,true,21,4,false,0.004,0.0006,5968,2010,7,11,Tuesday,false,true,false,false,false,false,false 1093322,How do I check which version of Python is running my script?,"How do I check which version of the Python interpreter is running my script?
See Find full path of the Python interpreter (Python executable)? if you are looking to find exactly which interpreter is being used - for example, to debug a Pip installation problem, or to check which virtual environment (if any) is active.
",https://stackoverflow.com/questions/1093322/how-do-i-check-which-version-of-python-is-running-my-script,1506,1886276.0,26.0,,,2009-07-07 16:17:49,2024-10-14 14:20:49,2024-03-10 16:31:30,,,python;version,carrier,33306,20498,registered,true,1093331,,CC BY-SA 4.0,2014-06-11 19:44:42,421,323,0,1,0,2,true,false,false,true,true,true,60,12,true,0.014,0.0008,6346,2009,7,16,Tuesday,false,true,false,false,false,false,false 2835559,Why can't Python parse this JSON data?,"I have this JSON in a file:
{
"maps": [
{
"id": "blabla",
"iscategorical": "0"
},
{
"id": "blabla",
"iscategorical": "0"
}
],
"masks": [
"id": "valore"
],
"om_points": "value",
"parameters": [
"id": "valore"
]
}
I wrote this script to print all of the JSON data:
import json
from pprint import pprint
with open('data.json') as f:
data = json.load(f)
pprint(data)
This program raises an exception, though:
Traceback (most recent call last):
File "<pyshell#1>", line 5, in <module>
data = json.load(f)
File "/usr/lib/python3.5/json/__init__.py", line 319, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.5/json/decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.5/json/decoder.py", line 355, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 13 column 13 (char 213)
How can I parse the JSON and extract its values?
",https://stackoverflow.com/questions/2835559/why-cant-python-parse-this-json-data,1503,2701990.0,3.0,,,2010-05-14 15:54:20,2022-07-02 05:29:08,2022-07-01 21:31:24,2022-07-02 08:20:21,Not suitable for this site,python;json;parsing,michele,26698,453712,registered,true,2835672,,,2014-01-26 10:24:44,1538,1323,3,0,0,3,true,true,false,true,true,true,42,7,true,0.001,0.0006,6035,2010,5,15,Friday,false,true,false,false,false,false,false 4760215,Running shell command and capturing the output,"I want to write a function that will execute a shell command and return its output as a string, no matter, is it an error or success message. I just want to get the same result that I would have gotten with the command line.
What would be a code example that would do such a thing?
For example:
def run_command(cmd):
# ??????
print run_command('mysqladmin create test -uroot -pmysqladmin12')
# Should output something like:
# mysqladmin: CREATE DATABASE failed; error: 'Can't create database 'test'; database exists'
",https://stackoverflow.com/questions/4760215/running-shell-command-and-capturing-the-output,1498,2054157.0,25.0,,,2011-01-21 14:55:44,2025-05-30 19:46:28,2018-10-25 17:30:00,,,python;shell;subprocess,Silver Light,46480,303513,registered,true,4760517,,CC BY-SA 4.0,2014-12-28 12:47:23,588,526,1,0,0,3,true,false,false,true,true,true,46,7,false,0.012,0.0007,5783,2011,1,14,Friday,false,true,false,false,false,false,false
11875770,How can I overcome "datetime.datetime not JSON serializable"?,"sample = {}
sample['title'] = "String"
sample['somedate'] = somedatetimehere
jsonify(sample) on that dict gets:
TypeError: datetime.datetime(2012, 8, 8, 21, 46, 24, 862000) is not JSON serializable
What can I do to overcome that error?
Note: the dictionaries are generated from the retrieval of records out of mongodb where when I print out str(sample['somedate']), the output is 2012-08-08 21:46:24.862000.
I just upgraded my Pandas from 0.11 to 0.13.0rc1. Now, the application is popping out many new warnings. One of them like this:
E:\FinReporter\FM_EXT.py:449: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_index,col_indexer] = value instead
quote_df['TVol'] = quote_df['TVol']/TVOL_SCALE
What exactly does it mean? Do I need to change something?
How should I suspend the warning if I insist on using quote_df['TVol'] = quote_df['TVol']/TVOL_SCALE?
def _decode_stock_quote(list_of_150_stk_str):
"""decode the webpage and return dataframe"""
from cStringIO import StringIO
str_of_all = "".join(list_of_150_stk_str)
quote_df = pd.read_csv(
StringIO(str_of_all),
sep=',',
names=list('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefg'))
#dtype={'A': object, 'B': object, 'C': np.float64}
quote_df.rename(
columns={
'A':'STK', 'B':'TOpen', 'C':'TPCLOSE', 'D':'TPrice',
'E':'THigh', 'F':'TLow', 'I':'TVol', 'J':'TAmt',
'e':'TDate', 'f':'TTime'},
inplace=True)
quote_df = quote_df.ix[:,[0,3,2,1,4,5,8,9,30,31]]
quote_df['TClose'] = quote_df['TPrice']
quote_df['RT'] = 100 * (quote_df['TPrice']/quote_df['TPCLOSE'] - 1)
quote_df['TVol'] = quote_df['TVol']/TVOL_SCALE
quote_df['TAmt'] = quote_df['TAmt']/TAMT_SCALE
quote_df['STK_ID'] = quote_df['STK'].str.slice(13,19)
quote_df['STK_Name'] = quote_df['STK'].str.slice(21,30)#.decode('gb2312')
quote_df['TDate'] = quote_df.TDate.map(lambda x: x[0:4]+x[5:7]+x[8:10])
return quote_df
E:\FinReporter\FM_EXT.py:449: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_index,col_indexer] = value instead
quote_df['TVol'] = quote_df['TVol']/TVOL_SCALE
E:\FinReporter\FM_EXT.py:450: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_index,col_indexer] = value instead
quote_df['TAmt'] = quote_df['TAmt']/TAMT_SCALE
E:\FinReporter\FM_EXT.py:453: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_index,col_indexer] = value instead
quote_df['TDate'] = quote_df.TDate.map(lambda x: x[0:4]+x[5:7]+x[8:10])
",https://stackoverflow.com/questions/20625582/how-to-deal-with-settingwithcopywarning-in-pandas,1495,2589615.0,27.0,,,2013-12-17 03:48:02,2025-06-15 02:38:25,2025-06-15 02:38:25,,,python;pandas;dataframe;chained-assignment;pandas-settingwithcopy-warning,bigbug,60024,1072888,registered,true,20627316,,CC BY-SA 4.0,2018-04-19 09:47:07,2635,2433,4,0,0,5,true,false,false,true,true,true,49,7,false,0.01,0.0006,4722,2013,12,3,Tuesday,false,true,false,false,false,false,false
7696924,How do I create multiline comments in Python?,"How do I make multi-line comments? Most languages have block comment symbols like:
/*
*/
",https://stackoverflow.com/questions/7696924/how-do-i-create-multiline-comments-in-python,1487,2364813.0,27.0,,,2011-10-08 12:51:13,2026-02-13 14:03:20,2022-04-09 08:05:41,,,python;comments;documentation,Pavan Kumar,20873,639891,registered,true,7696966,,CC BY-SA 4.0,2015-05-31 17:06:15,122,91,1,0,0,3,true,false,false,true,true,true,45,8,true,0.011,0.0006,5523,2011,10,12,Saturday,true,true,false,false,false,false,false
122327,How do I find the location of my Python site-packages directory?,"How do I find the location of my site-packages directory?
How do I display a leading zero for all numbers with less than two digits?
1 → 01
10 → 10
100 → 100
",https://stackoverflow.com/questions/134934/display-number-with-leading-zeros,1480,1735027.0,19.0,,,2008-09-25 18:06:06,2022-11-09 15:44:56,2022-04-09 09:44:19,2023-01-22 10:15:11,Duplicate,python;integer;string-formatting,ashchristopher,26511,22306,registered,true,134951,,,,180,110,1,0,0,3,true,true,false,true,true,true,33,5,false,0.011,0.0009,6631,2008,9,18,Thursday,false,true,false,false,false,false,false
13413590,How to drop rows of Pandas DataFrame whose value in a certain column is NaN,"I have this DataFrame and want only the records whose EPS column is not NaN:
STK_ID EPS cash
STK_ID RPT_Date
601166 20111231 601166 NaN NaN
600036 20111231 600036 NaN 12
600016 20111231 600016 4.3 NaN
601009 20111231 601009 NaN NaN
601939 20111231 601939 2.5 NaN
000001 20111231 000001 NaN NaN
...i.e. something like df.drop(....) to get this resulting dataframe:
STK_ID EPS cash
STK_ID RPT_Date
600016 20111231 600016 4.3 NaN
601939 20111231 601939 2.5 NaN
How do I do that?
",https://stackoverflow.com/questions/13413590/how-to-drop-rows-of-pandas-dataframe-whose-value-in-a-certain-column-is-nan,1479,2322471.0,17.0,,,2012-11-16 09:17:22,2024-03-08 15:47:42,2023-11-29 00:38:52,,,python;pandas;dataframe;indexing;nan,bigbug,60024,1072888,registered,true,13413845,,CC BY-SA 4.0,2016-03-16 11:53:00,748,588,3,0,0,5,true,false,false,true,true,true,75,15,false,0.007,0.0006,5118,2012,11,9,Friday,false,true,false,false,false,false,false 268272,Getting key with maximum value in dictionary?,"I have a dictionary where keys are strings, and values are integers.
stats = {'a': 1, 'b': 3000, 'c': 0}
How do I get the key with the maximum value? In this case, it is 'b'.
Is there a nicer approach than using an intermediate list with reversed key-value tuples?
inverse = [(value, key) for key, value in stats.items()]
print(max(inverse)[1])
",https://stackoverflow.com/questions/268272/getting-key-with-maximum-value-in-dictionary,1474,1820680.0,29.0,,,2008-11-06 10:49:58,2024-03-08 03:53:33,2022-04-09 09:53:24,,,python;dictionary;max,ricafeal,15169,34598,registered,true,268285,,CC BY-SA 4.0,2013-04-11 05:14:02,436,348,3,0,0,3,true,false,false,true,true,true,45,7,true,0.016,0.0008,6589,2008,11,10,Thursday,false,true,false,false,false,false,false
1952464,Python: how to determine if an object is iterable?,"Is there a method like isiterable? The only solution I have found so far is to call:
hasattr(myObj, '__iter__')
but I am not sure how foolproof this is.
",https://stackoverflow.com/questions/1952464/python-how-to-determine-if-an-object-is-iterable,1472,853607.0,25.0,,,2009-12-23 12:13:55,2024-07-31 18:59:36,2024-07-31 18:59:36,,,python;iterable,willem,27287,22702,registered,true,1952481,,CC BY-SA 4.0,2013-04-10 11:35:13,242,154,2,0,0,2,true,false,false,true,true,true,50,9,true,0.029,0.0017,6177,2009,12,12,Wednesday,false,true,false,false,false,false,false 5082452,String formatting: % vs. .format vs. f-string literal,"There are various string formatting methods:
"Hello %s" % name"Hello {}".format(name) (uses str.format)f"{name}" (uses f-strings)Which is better, and for what situations?
The following methods have the same outcome, so what is the difference?
name = "Alice"
"Hello %s" % name
"Hello {0}".format(name)
f"Hello {name}"
# Using named arguments:
"Hello %(kwarg)s" % {'kwarg': name}
"Hello {kwarg}".format(kwarg=name)
f"Hello {name}"
When does string formatting run, and how do I avoid a runtime performance penalty?
If you are trying to close a duplicate question that is just looking for a way to format a string, please use How do I put a variable’s value inside a string?.
",https://stackoverflow.com/questions/5082452/string-formatting-vs-format-vs-f-string-literal,1471,1080815.0,16.0,,,2011-02-22 18:46:42,2024-07-10 10:34:49,2022-08-17 07:09:46,,,python;performance;string-formatting;f-string,NorthIsUp,17925,231463,registered,true,5082482,,CC BY-SA 4.0,2017-01-31 21:55:30,1177,832,5,2,0,4,true,false,false,true,true,true,53,8,false,0.015,0.0014,5751,2011,2,18,Tuesday,false,true,false,false,false,false,false 6269765,What does the 'b' character do in front of a string literal?,"Apparently, the following is the valid syntax:
b'The string'
I would like to know:
b character in front of the string mean?I found a related question right here on SO, but that question is about PHP though, and it states the b is used to indicate the string is binary, as opposed to Unicode, which was needed for code to be compatible from version of PHP < 6, when migrating to PHP 6. I don't think this applies to Python.
I did find this documentation on the Python site about using a u character in the same syntax to specify a string as Unicode. Unfortunately, it doesn't mention the b character anywhere in that document.
Also, just out of curiosity, are there more symbols than the b and u that do other things?
How do I declare a constant in Python?
In Java, we do:
public static final String CONST_NAME = "Name";
",https://stackoverflow.com/questions/2682745/how-do-i-create-a-constant-in-python,1459,1623361.0,45.0,,,2010-04-21 12:20:18,2026-07-24 15:23:06,2022-04-09 08:55:35,,,python;constants,zfranciscus,17321,166264,registered,true,2682752,,CC BY-SA 4.0,2021-11-04 00:27:00,191,114,1,0,0,2,true,false,false,true,true,true,37,8,true,0.028,0.0009,6058,2010,4,12,Wednesday,false,true,false,false,false,false,false
73663,How do I terminate a script?,"How do I exit a script early, like the die() command in PHP?
I would like to understand how the built-in function property works. What confuses me is that property can also be used as a decorator, but it only takes arguments when used as a built-in function and not when used as a decorator.
This example is from the documentation:
class C:
def __init__(self):
self._x = None
def getx(self):
return self._x
def setx(self, value):
self._x = value
def delx(self):
del self._x
x = property(getx, setx, delx, "I'm the 'x' property.")
property's arguments are getx, setx, delx and a doc string.
In the code below property is used as a decorator. The object of it is the x function, but in the code above there is no place for an object function in the arguments.
class C:
def __init__(self):
self._x = None
@property
def x(self):
"""I'm the 'x' property."""
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._x
How are the x.setter and x.deleter decorators created in this case?
When we add a model field in Django we generally write:
models.CharField(max_length=100, null=True, blank=True)
The same is done with ForeignKey, DecimalField etc. What is the basic difference between:
null=True onlyblank=True onlynull=True and blank=Truein respect to different (CharField, ForeignKey, ManyToManyField, DateTimeField) fields? What are the advantages/disadvantages of using option 1, 2, or 3?
How do I create an empty DataFrame, then add rows, one by one?
I created an empty DataFrame:
df = pd.DataFrame(columns=('lib', 'qty1', 'qty2'))
Then I can add a new row at the end and fill a single field with:
df = df._set_value(index=len(df), col='qty1', value=10.0)
It works for only one field at a time. What is a better way to add new row to df?
I want to check if a variable exists. Now I'm doing something like this:
try:
myVar
except NameError:
# Do something.
Are there other ways without exceptions?
",https://stackoverflow.com/questions/843277/how-do-i-check-if-a-variable-exists,1428,1941563.0,16.0,,,2009-05-09 13:10:31,2025-06-03 06:53:11,2022-04-09 09:48:20,,,python;exception;variables,Max Frai,64832,87152,registered,true,843293,,CC BY-SA 4.0,2018-08-01 05:21:55,206,168,1,0,0,3,true,false,false,true,true,true,36,8,true,0.008,0.0007,6405,2009,5,13,Saturday,true,true,false,false,false,false,false 11248073,How do I remove all packages installed by pip?,"How do I uninstall all packages installed by pip from my currently activated virtual environment?
",https://stackoverflow.com/questions/11248073/how-do-i-remove-all-packages-installed-by-pip,1421,1867735.0,34.0,,,2012-06-28 15:36:44,2024-03-31 18:02:12,2023-02-10 05:04:15,,,python;pip;virtualenv;python-packaging,blueberryfields,51766,173773,registered,true,11250821,,CC BY-SA 4.0,2022-01-31 10:11:50,105,98,0,0,0,4,true,false,false,true,true,true,46,9,true,0.018,0.0008,5259,2012,6,15,Thursday,false,true,false,false,false,false,false 53162,How can I do a line break (line continuation) in Python (split up a long line of source code)?,"Given:
e = 'a' + 'b' + 'c' + 'd'
How do I write the above in two lines?
e = 'a' + 'b' +
'c' + 'd'
See also: How do I split the definition of a long string over multiple lines? if there is a long string literal in the code that needs to be broken up to wrap the line nicely.
",https://stackoverflow.com/questions/53162/how-can-i-do-a-line-break-line-continuation-in-python-split-up-a-long-line-of,1416,2767446.0,11.0,,,2008-09-09 23:45:30,2025-03-28 15:26:04,2024-04-22 20:45:51,,,python;syntax;line-breaks;long-lines,Ray,194116,4872,registered,true,53180,,CC BY-SA 4.0,2013-10-10 08:04:18,435,281,2,1,0,4,true,false,false,true,true,true,94,19,true,0.004,0.0005,6647,2008,9,23,Tuesday,false,true,false,false,false,false,false 533631,What is a mixin and why is it useful?,"In Programming Python, Mark Lutz mentions the term mixin. I am from a C/C++/C# background and I have not heard the term before. What is a mixin?
Reading between the lines of this example (which I have linked to because it is quite long), I am presuming it is a case of using multiple inheritance to extend a class as opposed to proper subclassing. Is this right?
Why would I want to do that rather than put the new functionality into a subclass? For that matter, why would a mixin/multiple inheritance approach be better than using composition?
What separates a mixin from multiple inheritance? Is it just a matter of semantics?
",https://stackoverflow.com/questions/533631/what-is-a-mixin-and-why-is-it-useful,1416,587762.0,17.0,,,2009-02-10 18:50:42,2025-09-08 15:40:47,2022-11-29 16:05:02,,,python;oop;multiple-inheritance;mixins;python-class,TarkaDaal,19856,55155,registered,true,547714,,CC BY-SA 4.0,,1100,629,0,2,0,5,true,false,false,true,true,true,37,9,true,0.029,0.0024,6493,2009,2,18,Tuesday,false,true,false,false,false,false,false 101268,Hidden features of Python,"What are the lesser-known but useful features of the Python programming language?
.get valueimport this__missing__ items.pth filestry/except/elseprint() functionwith statementHow do I iterate over a list in reverse in Python?
I have a text file that looks like:
ABC
DEF
How can I read the file into a single-line string without newlines, in this case creating a string 'ABCDEF'?
For reading the file into a list of lines, but removing the trailing newline character from each line, see How to read a file without newlines?.
",https://stackoverflow.com/questions/8369219/how-can-i-read-a-text-file-into-a-string-variable-and-strip-newlines,1411,2470821.0,27.0,,,2011-12-03 16:47:54,2026-04-19 05:09:10,2023-08-08 14:19:31,,,python;string,klijo,16601,963489,registered,true,8369345,,CC BY-SA 4.0,,479,300,2,1,0,2,true,false,false,true,true,true,69,14,true,0.011,0.0006,5467,2011,12,16,Saturday,true,true,false,false,false,false,false 2802726,Putting a simple if-then-else statement on one line,"How do I write an if-then-else statement in Python so that it fits on one line?
For example, I want a one line version of:
if count == N:
count = 0
else:
count = N + 1
In Objective-C, I would write this as:
count = count == N ? 0 : count + 1;
",https://stackoverflow.com/questions/2802726/putting-a-simple-if-then-else-statement-on-one-line,1405,2790494.0,5.0,,,2010-05-10 12:58:04,2023-07-25 14:50:07,2023-06-03 23:48:20,2020-01-31 06:43:20,Duplicate,python;if-statement;syntax;conditional-operator,Abizern,152047,41116,registered,true,2802748,,,,361,253,5,0,0,4,true,true,false,true,true,true,51,8,false,0.002,0.0005,6039,2010,5,12,Monday,false,true,false,false,false,false,false
19482970,Get a list from Pandas DataFrame column headers,"I want to get a list of the column headers from a Pandas DataFrame. The DataFrame will come from user input, so I won't know how many columns there will be or what they will be called.
For example, if I'm given a DataFrame like this:
y gdp cap
0 1 2 5
1 2 3 9
2 8 7 2
3 3 4 7
4 6 7 7
5 4 8 3
6 8 2 8
7 9 9 10
8 6 6 4
9 10 10 7
I would get a list like this:
['y', 'gdp', 'cap']
",https://stackoverflow.com/questions/19482970/get-a-list-from-pandas-dataframe-column-headers,1397,2461421.0,25.0,,,2013-10-20 21:18:37,2023-09-16 19:35:57,2023-04-12 06:39:52,,,python;pandas;dataframe;list;header,natsuki_2002,25639,2428549,registered,true,19483025,,CC BY-SA 4.0,2017-10-04 06:00:30,610,463,2,0,0,5,true,false,false,true,true,true,47,8,false,0.01,0.0006,4780,2013,10,21,Sunday,true,true,false,false,false,false,false
8384737,"Extract file name from path, no matter what the os/path format","Which Python library can I use to extract filenames from paths, no matter what the operating system or path format could be?
For example, I'd like all of these paths to return me c:
a/b/c/
a/b/c
\a\b\c
\a\b\c\
a\b\c
a/b/../../a/b/c/
a/b/../../a/b/c
",https://stackoverflow.com/questions/8384737/extract-file-name-from-path-no-matter-what-the-os-path-format,1395,2546106.0,23.0,,,2011-12-05 11:39:49,2024-12-12 20:36:43,2023-04-11 04:09:23,,,python;path,BuZz,17695,1029944,registered,true,8384788,,CC BY-SA 4.0,2023-03-17 10:53:38,303,252,2,0,0,2,true,false,false,true,true,true,62,11,false,0.009,0.0005,5465,2011,12,11,Monday,false,true,false,false,false,false,false
12096252,Use a list of values to select rows from a Pandas dataframe,"Let’s say I have the following Pandas dataframe:
df = DataFrame({'A': [5,6,3,4], 'B': [1,2,3,5]})
df
A B
0 5 1
1 6 2
2 3 3
3 4 5
I can subset based on a specific value:
x = df[df['A'] == 3]
x
A B
2 3 3
But how can I subset based on a list of values? - something like this:
list_of_values = [3, 6]
y = df[df['A'] in list_of_values]
To get:
A B
1 6 2
2 3 3
",https://stackoverflow.com/questions/12096252/use-a-list-of-values-to-select-rows-from-a-pandas-dataframe,1395,1831675.0,9.0,,,2012-08-23 16:31:12,2025-03-19 13:29:16,2025-01-13 21:58:49,,,python;pandas;dataframe;indexing;filter,zach,31483,983191,registered,true,12098586,,CC BY-SA 4.0,2021-01-02 08:54:19,545,421,4,0,0,5,true,false,false,true,true,true,59,12,false,0.005,0.0008,5203,2012,8,16,Thursday,false,true,false,false,false,false,false
2429511,Why do people write "#!/usr/bin/env python" on the first line of a Python script?,"I see these at the top of Python files:
#!/usr/bin/env python
#!/usr/bin/env python3
It seems to me that the files run the same without that line.
",https://stackoverflow.com/questions/2429511/why-do-people-write-usr-bin-env-python-on-the-first-line-of-a-python-script,1394,1092864.0,22.0,,,2010-03-11 23:50:54,2026-08-07 10:12:20,2023-03-25 17:36:34,,,python;shell;shebang,john garcias,14055,291988,unregistered,true,,,CC BY-SA 4.0,2015-03-13 13:00:01,285,149,2,0,0,3,false,false,false,true,true,true,91,14,true,0.02,0.0013,6099,2010,3,23,Thursday,false,true,false,false,false,false,false 6159900,Correct way to write line to file?,"How do I write a line to a file in modern Python? I heard that this is deprecated:
print >>f, "hi there"
Also, does "\n" work on all platforms, or should I use "\r\n" on Windows?
How do I remove leading and trailing whitespace from a string in Python?
" Hello world " --> "Hello world"
" Hello world" --> "Hello world"
"Hello world " --> "Hello world"
"Hello world" --> "Hello world"
",https://stackoverflow.com/questions/761804/how-do-i-trim-whitespace-from-a-string,1389,1467335.0,14.0,,,2009-04-17 19:16:06,2023-12-10 03:40:46,2022-04-09 08:15:35,,,python;string;trim,robert,,,does_not_exist,true,761825,,CC BY-SA 4.0,2022-12-06 11:19:45,333,302,1,0,0,3,true,false,false,true,false,true,39,8,true,0.01,0.0009,6427,2009,4,19,Friday,false,true,false,false,false,false,false
3277367,How does Python's super() work with multiple inheritance?,"How does super() work with multiple inheritance? For example, given:
class First(object):
def __init__(self):
print "first"
class Second(object):
def __init__(self):
print "second"
class Third(First, Second):
def __init__(self):
super(Third, self).__init__()
print "that's it"
Which parent method of Third does super().__init__ refer to? Can I choose which runs?
I know it has something to do with method resolution order (MRO).
",https://stackoverflow.com/questions/3277367/how-does-pythons-super-work-with-multiple-inheritance,1389,708052.0,18.0,,,2010-07-18 21:40:25,2023-06-23 16:16:08,2022-04-17 02:00:16,,,python;multiple-inheritance,Callisto,13911,395354,unregistered,true,3277407,,CC BY-SA 4.0,2016-12-09 17:53:12,667,506,4,1,0,2,true,false,false,true,true,true,61,8,true,0.025,0.002,5970,2010,7,21,Sunday,true,true,false,false,false,false,false 33533148,How do I type hint a method with the type of the enclosing class?,"I have the following code in Python 3:
class Position:
def __init__(self, x: int, y: int):
self.x = x
self.y = y
def __add__(self, other: Position) -> Position:
return Position(self.x + other.x, self.y + other.y)
But my editor (PyCharm) says that the reference Position can not be resolved (in the __add__ method). How should I specify that I expect the return type to be of type Position?
I think this is actually a PyCharm issue. It actually uses the information in its warnings, and code completion.
But correct me if I'm wrong, and need to use some other syntax.
",https://stackoverflow.com/questions/33533148/how-do-i-type-hint-a-method-with-the-type-of-the-enclosing-class,1387,415753.0,9.0,,,2015-11-04 22:17:54,2025-04-07 03:53:54,2024-05-28 15:04:46,,,python;pycharm;python-typing,Michael van Gerwen,13981,4665133,registered,true,33533514,,CC BY-SA 4.0,,756,606,4,0,1,3,true,false,false,true,true,true,65,14,true,0.022,0.0033,4035,2015,11,22,Wednesday,false,true,false,false,false,false,false 237079,How do I get file creation and modification date/times?,"What's the best cross-platform way to get file creation and modification dates/times, that works on both Linux and Windows?
",https://stackoverflow.com/questions/237079/how-do-i-get-file-creation-and-modification-date-times,1385,1361730.0,13.0,,,2008-10-25 21:54:56,2026-02-05 10:02:58,2022-04-09 09:57:16,,,python;file,Mark Biek,152519,305,registered,true,52858040,,CC BY-SA 4.0,2021-04-14 21:14:53,131,124,0,0,0,2,true,false,false,true,true,true,55,9,true,0.01,0.001,6601,2008,10,21,Saturday,true,true,false,false,false,false,false 16819222,How do I return dictionary keys as a list in Python?,"With Python 2.7, I can get dictionary keys, values, or items as a list:
>>> newdict = {1:0, 2:0, 3:0}
>>> newdict.keys()
[1, 2, 3]
With Python >= 3.3, I get:
>>> newdict.keys()
dict_keys([1, 2, 3])
How do I get a plain list of keys with Python 3?
How do I get the ASCII value of a character as an int in Python?
Python is an interpreted language. But why does my source directory contain .pyc files, which are identified by Windows as "Compiled Python Files"?
How do I convert a string into a boolean in Python? This attempt returns True:
>>> bool("False")
True
",https://stackoverflow.com/questions/715417/converting-from-a-string-to-boolean-in-python,1363,1539884.0,43.0,,,2009-04-03 19:44:20,2025-10-15 07:17:49,2022-06-13 02:49:32,,,python;string;boolean,Joan Venge,334947,51816,registered,true,715455,,CC BY-SA 4.0,2018-08-22 21:35:39,166,122,2,0,0,3,true,false,false,true,true,true,45,8,false,0.028,0.0009,6441,2009,4,19,Friday,false,true,false,false,false,false,false
2709821,What is the purpose of the `self` parameter? Why is it needed?,"Consider this example:
class MyClass:
def func(self, name):
self.name = name
I know that self refers to the specific instance of MyClass. But why must func explicitly include self as a parameter? Why do we need to use self in the method's code? Some other languages make this implicit, or use special syntax instead.
For a language-agnostic consideration of the design decision, see What is the advantage of having this/self pointer mandatory explicit?.
To close debugging questions where OP omitted a self parameter for a method and got a TypeError, use TypeError: method() takes 1 positional argument but 2 were given instead. If OP omitted self. in the body of the method and got a NameError, consider How can I call a function within a class?.
How do I count the number of occurrences of a character in a string?
e.g. 'a' appears in 'Mary had a little lamb' 4 times.
How do I create a GUID/UUID in Python that is platform independent? I hear there is a method using ActivePython on Windows but it's Windows only because it uses COM. Is there a method using plain Python?
",https://stackoverflow.com/questions/534839/how-to-create-a-guid-uuid-in-python,1350,1396906.0,8.0,,,2009-02-10 23:51:21,2024-06-05 23:59:13,2022-08-06 10:15:09,,,python;uuid;guid;uniqueidentifier,Jonathon Watney,22488,59180,registered,true,534847,,CC BY-SA 4.0,2023-02-24 08:13:47,211,204,0,0,0,4,true,false,false,true,true,true,35,7,false,0.006,0.001,6493,2009,2,23,Tuesday,false,true,false,false,false,false,false 12555323,How to add a new column to an existing DataFrame,"I have the following indexed DataFrame with named columns and rows not- continuous numbers:
a b c d
2 0.671399 0.101208 -0.181532 0.241273
3 0.446172 -0.243316 0.051767 1.577318
5 0.614758 0.075793 -0.451460 -0.012493
I would like to add a new column, 'e', to the existing data frame and do not want to change anything in the data frame (i.e., the new column always has the same length as the DataFrame).
0 -0.335485
1 -1.166658
2 -0.385571
dtype: float64
I tried different versions of join, append, merge, but I did not get the result I wanted, only errors at most.
How can I add column e to the above example?
How do I get a list of Python modules installed on my computer?
",https://stackoverflow.com/questions/739993/how-do-i-get-a-list-of-locally-installed-python-modules,1339,2160728.0,34.0,,,2009-04-11 12:34:18,2026-04-21 13:03:58,2022-04-09 10:22:21,,,python;module;pip,Léo Léopold Hertz 준영,143822,54964,registered,true,23885252,,CC BY-SA 4.0,2013-11-24 07:53:09,71,64,0,0,0,3,true,false,false,true,true,true,56,11,true,0.016,0.0006,6433,2009,4,12,Saturday,true,true,false,false,false,false,false 1504717,Why does comparing strings using either '==' or 'is' sometimes produce a different result?,"Two string variables are set to the same value. s1 == s2 always returns True, but s1 is s2 sometimes returns False.
If I open my Python interpreter and do the same is comparison, it succeeds:
>>> s1 = 'text'
>>> s2 = 'text'
>>> s1 is s2
True
Why is this?
",https://stackoverflow.com/questions/1504717/why-does-comparing-strings-using-either-or-is-sometimes-produce-a-differe,1333,1714863.0,15.0,,,2009-10-01 15:40:14,2025-06-19 07:47:42,2022-04-09 09:21:50,2025-06-18 18:02:14,Duplicate,python;string;comparison;identity;equality,jottos,20484,14555,registered,true,1504742,,,,393,283,6,0,0,5,true,true,false,true,true,true,106,14,true,0.009,0.0008,6260,2009,10,15,Thursday,false,true,false,false,false,false,false 7604966,Maximum and Minimum values for ints,"How do I represent minimum and maximum values for integers in Python? In Java, we have Integer.MIN_VALUE and Integer.MAX_VALUE.
See also: What is the maximum float in Python?.
",https://stackoverflow.com/questions/7604966/maximum-and-minimum-values-for-ints,1325,2330514.0,12.0,,,2011-09-30 01:01:06,2023-11-07 07:30:43,2023-01-29 11:51:19,,,python;integer,bdhar,23471,139909,registered,true,7604981,,CC BY-SA 4.0,2019-07-14 12:11:06,292,177,2,1,0,2,true,false,false,true,true,true,35,6,false,0.005,0.0006,5531,2011,9,1,Friday,false,true,false,false,false,false,false 5971312,How to set environment variables in Python?,"I need to set some environment variables in the Python script and I want all the other scripts that are called from Python to see the environment variables' set.
If I do,
os.environ["DEBUSSY"] = 1
it complains saying that 1 has to be a string.
I also want to know how to read the environment variables in Python (in the latter part of the script) once I set it.
",https://stackoverflow.com/questions/5971312/how-to-set-environment-variables-in-python,1323,2391349.0,20.0,,,2011-05-11 22:25:11,2023-08-01 14:40:28,2020-09-06 13:43:21,,,python;environment-variables,prahallada,13497,742061,unregistered,true,,,CC BY-SA 4.0,,438,373,2,0,0,2,false,false,false,true,true,true,43,7,true,0.008,0.0006,5673,2011,5,22,Wednesday,false,true,false,false,false,false,false 845058,How to get the line count of a large file cheaply in Python,"How do I get a line count of a large file in the most memory- and time-efficient manner?
def file_len(filename):
with open(filename) as f:
for i, _ in enumerate(f):
pass
return i + 1
",https://stackoverflow.com/questions/845058/how-to-get-the-line-count-of-a-large-file-cheaply-in-python,1323,1175288.0,44.0,,,2009-05-10 10:22:05,2023-11-03 21:19:20,2023-11-02 04:37:09,,,python;text-files;line-count,SilentGhost,323181,12855,registered,true,845081,,CC BY-SA 4.0,2012-11-03 16:49:34,243,212,1,0,0,3,true,false,false,true,true,true,59,13,false,0.037,0.0011,6404,2009,5,10,Sunday,true,true,false,false,false,false,false
2349991,How do I import other Python files?,"How do I import files in Python? I want to import:
file.py)What is the purpose of __slots__ in Python — especially with respect to when I would want to use it, and when not?
I have two iterables, and I want to go over them in pairs:
foo = [1, 2, 3]
bar = [4, 5, 6]
for (f, b) in iterate_together(foo, bar):
print("f:", f, " | b:", b)
That should result in:
f: 1 | b: 4
f: 2 | b: 5
f: 3 | b: 6
One way to do it is to iterate over the indices:
for i in range(len(foo)):
print("f:", foo[i], " | b:", bar[i])
But that seems somewhat unpythonic to me. Is there a better way to do it?
Related tasks:
* How to merge lists into a list of tuples? - given the above foo and bar, create the list [(1, 4), (2, 5), (3, 6)].
* How can I make a dictionary (dict) from separate lists of keys and values? - create the dict {1: 4, 2: 5, 3: 6}.
* Create a dictionary with comprehension - constructing dict using zip in a dict comprehension.
I'm trying to install a Python package on Windows, using Christoph Gohlke's Windows binaries here:
http://www.lfd.uci.edu/~gohlke/pythonlibs/#jpype
The package is made available here as a .whl file. How do I install that?
How do I print an integer with commas as thousands separators?
1234567 ⟶ 1,234,567
It does not need to be locale-specific to decide between periods and commas.
",https://stackoverflow.com/questions/1823058/how-to-print-a-number-using-commas-as-thousands-separators,1311,1056775.0,26.0,,,2009-11-30 23:11:43,2025-09-17 14:14:06,2022-06-04 22:27:38,,,python;number-formatting,Elias Zamaria,101994,28324,registered,true,10742904,,CC BY-SA 4.0,2017-08-05 03:17:10,203,165,1,0,0,2,true,false,false,true,true,true,58,10,false,0.025,0.0012,6200,2009,11,23,Monday,false,true,false,false,false,false,false 10434599,Get the data received in a Flask request,"I want to be able to get the data sent to my Flask app. I've tried accessing request.data but it is an empty string. How do you access request data?
from flask import request
@app.route('/', methods=['GET', 'POST'])
def parse_request():
data = request.data # data is empty
# need posted data here
The answer to this question led me to ask Get raw POST body in Python Flask regardless of Content-Type header next, which is about getting the raw data rather than the parsed data.
",https://stackoverflow.com/questions/10434599/get-the-data-received-in-a-flask-request,1303,1970759.0,26.0,,,2012-05-03 15:31:26,2024-10-15 18:31:08,2020-04-07 22:44:46,,,python;flask;werkzeug,ddinchev,34903,762886,registered,true,16664376,,CC BY-SA 4.0,2018-08-21 22:53:31,636,493,2,1,0,3,true,false,false,true,true,true,40,8,false,0.013,0.0007,5315,2012,5,15,Thursday,false,true,false,false,false,false,false 6908143,"Should I put #! (shebang) in Python scripts, and what form should it take?","Should I put the shebang in my Python scripts? In what form?
#!/usr/bin/env python
or
#!/usr/local/bin/python
Are these equally portable? Which form is used most?
Note: the tornado project uses the shebang. On the other hand the Django project doesn't.
",https://stackoverflow.com/questions/6908143/should-i-put-shebang-in-python-scripts-and-what-form-should-it-take,1299,972784.0,15.0,,,2011-08-02 06:35:42,2023-10-21 19:39:37,2017-11-01 01:20:48,,,python;shell;python-3.x;shebang,treecoder,45669,1206051,registered,true,19305076,,CC BY-SA 3.0,2018-08-02 19:07:49,570,261,2,2,0,4,true,false,false,true,true,true,74,14,true,0.015,0.0013,5590,2011,8,6,Tuesday,false,true,false,false,false,false,false 7571635,Fastest way to check if a value exists in a list,"What is the fastest way to check if a value exists in a very large list (with millions of values) and what its index is?
",https://stackoverflow.com/questions/7571635/fastest-way-to-check-if-a-value-exists-in-a-list,1293,3085659.0,12.0,,,2011-09-27 15:23:26,2026-02-10 19:06:53,2023-09-01 07:17:04,,,python;list;performance;membership,Jean-Francois Gallant,14193,967334,registered,true,7571665,,CC BY-SA 4.0,2018-04-09 00:35:45,128,121,0,0,0,4,true,false,false,true,true,true,48,11,false,0.004,0.0004,5534,2011,9,15,Tuesday,false,true,false,false,false,false,false 403421,How do I sort a list of objects based on an attribute of the objects?,"I have a list of Python objects that I want to sort by a specific attribute of each object:
[Tag(name="toe", count=10), Tag(name="leg", count=2), ...]
How do I sort the list by .count in descending order?
How do I connect to a MySQL database using a python program?
",https://stackoverflow.com/questions/372885/how-do-i-connect-to-a-mysql-database-in-python,1291,1491773.0,27.0,,,2008-12-16 21:49:09,2023-11-27 00:11:19,2011-07-28 17:48:49,,,python;mysql,Marc Lincoln,,,does_not_exist,true,,,CC BY-SA 3.0,2014-02-27 13:40:07,68,61,0,0,0,2,false,false,false,true,false,true,47,10,true,0.018,0.0009,6549,2008,12,21,Tuesday,false,true,false,false,false,false,false 8270092,Remove all whitespace in a string,"I want to eliminate all the whitespace from a string, on both ends, and in between words.
I have this Python code:
def my_handle(self):
sentence = ' hello apple '
sentence.strip()
But that only eliminates the whitespace on both sides of the string. How do I remove all whitespace?
",https://stackoverflow.com/questions/8270092/remove-all-whitespace-in-a-string,1287,3112367.0,16.0,,,2011-11-25 13:51:21,2024-09-25 02:42:06,2023-08-31 04:50:49,,,python;string;trim;removing-whitespace,Kalanamith,20953,1004875,registered,true,8270146,,CC BY-SA 4.0,2019-07-13 13:08:12,374,292,1,0,0,4,true,false,false,true,true,true,33,6,false,0.005,0.0004,5475,2011,11,13,Friday,false,true,false,false,false,false,false 129507,How do you test that a Python function throws an exception?,"How does one write a unit test that fails only if a function doesn't throw an expected exception?
",https://stackoverflow.com/questions/129507/how-do-you-test-that-a-python-function-throws-an-exception,1279,1028977.0,20.0,,,2008-09-24 20:00:35,2025-03-02 13:38:31,2023-01-06 22:13:21,,,python;unit-testing;exception,Daryl Spitzer,151362,4766,registered,true,129522,,CC BY-SA 4.0,,105,98,0,0,0,3,true,false,false,true,true,true,59,11,true,0.019,0.0012,6632,2008,9,20,Wednesday,false,true,false,false,false,false,false 19124601,Pretty-print an entire Pandas Series / DataFrame,"I work with Series and DataFrames on the terminal a lot. The default __repr__ for a Series returns a reduced sample, with some head and tail values, but the rest missing.
Is there a builtin way to pretty-print the entire Series / DataFrame? Ideally, it would support proper alignment, perhaps borders between columns, and maybe even color-coding for the different columns.
",https://stackoverflow.com/questions/19124601/pretty-print-an-entire-pandas-series-dataframe,1271,1708373.0,15.0,,,2013-10-01 19:46:07,2025-04-07 04:01:41,2018-10-03 02:53:10,,,python;pandas;dataframe,Dun Peal,18059,916907,registered,true,30691921,,CC BY-SA 4.0,2018-08-02 10:18:28,402,375,1,0,0,3,true,false,false,true,true,true,48,7,false,0.009,0.0007,4799,2013,10,19,Tuesday,false,true,false,false,false,false,false 3462143,Get difference between two lists with Unique Entries,"I have two lists in Python:
temp1 = ['One', 'Two', 'Three', 'Four']
temp2 = ['One', 'Two']
Assuming the elements in each list are unique, I want to create a third list with items from the first list which are not in the second list:
temp3 = ['Three', 'Four']
Are there any fast ways without cycles and checking?
",https://stackoverflow.com/questions/3462143/get-difference-between-two-lists-with-unique-entries,1270,1571678.0,33.0,,,2010-08-11 19:38:10,2023-08-15 08:27:33,2022-12-20 15:35:29,,,python;performance;list;set;set-difference,Max Frai,64832,87152,registered,true,3462160,,CC BY-SA 4.0,2019-06-15 14:29:27,383,314,2,0,0,5,true,false,false,true,true,true,52,8,false,0.021,0.0008,5946,2010,8,19,Wednesday,false,true,false,false,false,false,false 12453580,How to concatenate (join) items in a list to a single string,"How do I concatenate a list of strings into a single string?
For example, given ['this', 'is', 'a', 'sentence'], how do I get "this-is-a-sentence"?
For handling a few strings in separate variables, see How do I append one string to another in Python?.
For the opposite process - creating a list from a string - see How do I split a string into a list of characters? or How do I split a string into a list of words? as appropriate.
",https://stackoverflow.com/questions/12453580/how-to-concatenate-join-items-in-a-list-to-a-single-string,1266,2440509.0,12.0,,,2012-09-17 05:32:25,2024-03-23 22:45:15,2022-09-11 06:47:09,2025-04-01 22:20:09,Duplicate,python;string;list;concatenation,alvas,123759,610569,registered,true,12453584,,,2022-01-21 18:11:42,699,442,2,3,0,4,true,true,false,true,true,true,60,12,false,0.005,0.0005,5178,2012,9,5,Monday,false,true,false,false,false,false,false 4028904,What is a cross-platform way to get the home directory?,"I need to get the location of the home directory of the current logged-on user. Currently, I've been using the following on Linux:
os.getenv("HOME")
However, this does not work on Windows. What is the correct cross-platform way to do this ?
",https://stackoverflow.com/questions/4028904/what-is-a-cross-platform-way-to-get-the-home-directory,1263,730175.0,5.0,,,2010-10-26 23:43:19,2025-10-03 14:19:01,2022-07-29 04:26:12,,,python;cross-platform;home-directory,Nathan Osman,73789,193619,registered,true,4028943,,CC BY-SA 4.0,,327,252,1,0,0,3,true,false,false,true,true,true,55,10,true,0.007,0.0017,5870,2010,10,23,Tuesday,false,true,false,false,false,false,false 5618878,How to convert list to string,"How can I convert a list to a string using Python?
",https://stackoverflow.com/questions/5618878/how-to-convert-list-to-string,1261,4180185.0,3.0,,,2011-04-11 08:51:08,2024-12-14 09:46:24,2024-12-14 09:46:24,2019-09-14 19:41:31,Duplicate,python;string;list;join,Nm3,12697,701825,unregistered,true,,,,,58,51,0,0,0,4,false,true,false,true,true,true,29,6,false,0.001,0.0003,5703,2011,4,8,Monday,false,true,false,false,false,false,false 2970608,What are "named tuples" in Python?,"For the last question specifically, see also Existence of mutable named tuple in Python?.
",https://stackoverflow.com/questions/2970608/what-are-named-tuples-in-python,1256,716639.0,14.0,,,2010-06-03 23:50:16,2024-08-25 01:46:25,2023-05-18 09:50:45,,,python;types;tuples;terminology;namedtuple,Denilson Sá Maia,50097,124946,registered,true,2970722,,CC BY-SA 4.0,2018-09-24 17:35:55,396,277,0,1,0,5,true,false,false,true,true,true,44,6,true,0.02,0.0018,6015,2010,6,23,Thursday,false,true,false,false,false,false,false 1185524,How do I trim whitespace?,"Is there a Python function that will trim whitespace (spaces and tabs) from a string?
So that given input " \t example string\t " becomes "example string".
I want to get the unique values from the following list:
['nowplaying', 'PBS', 'PBS', 'nowplaying', 'job', 'debate', 'thenandnow']
The output which I require is:
['nowplaying', 'PBS', 'job', 'debate', 'thenandnow']
This code works:
output = []
for x in trends:
if x not in output:
output.append(x)
print(output)
is there a better solution I should use?
",https://stackoverflow.com/questions/12897374/get-unique-values-from-a-list-in-python,1252,3113692.0,30.0,,,2012-10-15 14:05:37,2023-07-05 07:29:44,2020-10-02 13:09:45,2018-07-09 18:30:50,Duplicate,python;list,savitha,12799,128112,registered,true,,,,2017-01-27 20:42:03,474,374,3,0,0,2,false,true,false,true,true,true,39,8,false,0.01,0.0004,5150,2012,10,14,Monday,false,true,false,false,false,false,false 10214827,Find which version of package is installed with pip,"Using pip, is it possible to figure out which version of a package is currently installed?
I know about pip install XYZ --upgrade but I am wondering if there is anything like pip info XYZ. If not what would be the best way to tell what version I am currently using.
The canonical way to return multiple values in languages that support it is often tupling.
Consider this trivial example:
def f(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y3
return (y0, y1, y2)
However, this quickly gets problematic as the number of values returned increases. What if you want to return four or five values? Sure, you could keep tupling them, but it gets easy to forget which value is where. It's also rather ugly to unpack them wherever you want to receive them.
The next logical step seems to be to introduce some sort of 'record notation'. In Python, the obvious way to do this is by means of a dict.
Consider the following:
def g(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y3
return {'y0': y0, 'y1': y1 ,'y2': y2}
(Just to be clear, y0, y1, and y2 are just meant as abstract identifiers. As pointed out, in practice you'd use meaningful identifiers.)
Now, we have a mechanism whereby we can project out a particular member of the returned object. For example,
result['y0']
However, there is another option. We could instead return a specialized structure. I've framed this in the context of Python, but I'm sure it applies to other languages as well. Indeed, if you were working in C this might very well be your only option. Here goes:
class ReturnValue:
def __init__(self, y0, y1, y2):
self.y0 = y0
self.y1 = y1
self.y2 = y2
def g(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y3
return ReturnValue(y0, y1, y2)
In Python the previous two are perhaps very similar in terms of plumbing - after all { y0, y1, y2 } just end up being entries in the internal __dict__ of the ReturnValue.
There is one additional feature provided by Python though for tiny objects, the __slots__ attribute. The class could be expressed as:
class ReturnValue(object):
__slots__ = ["y0", "y1", "y2"]
def __init__(self, y0, y1, y2):
self.y0 = y0
self.y1 = y1
self.y2 = y2
From the Python Reference Manual:
The
__slots__declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a value for each variable. Space is saved because__dict__is not created for each instance.
Using Python 3.7's new dataclasses, return a class with automatically added special methods, typing and other useful tools:
@dataclass
class Returnvalue:
y0: int
y1: float
y3: int
def total_cost(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y3
return ReturnValue(y0, y1, y2)
Another suggestion which I'd overlooked comes from Bill the Lizard:
def h(x):
result = [x + 1]
result.append(x * 3)
result.append(y0 ** y3)
return result
This is my least favorite method though. I suppose I'm tainted by exposure to Haskell, but the idea of mixed-type lists has always felt uncomfortable to me. In this particular example the list is -not- mixed type, but it conceivably could be.
A list used in this way really doesn't gain anything with respect to the tuple as far as I can tell. The only real difference between lists and tuples in Python is that lists are mutable, whereas tuples are not.
I personally tend to carry over the conventions from functional programming: use lists for any number of elements of the same type, and tuples for a fixed number of elements of predetermined types.
After the lengthy preamble, comes the inevitable question. Which method (do you think) is best?
",https://stackoverflow.com/questions/354883/alternatives-for-returning-multiple-values-from-a-python-function,1237,1410337.0,14.0,,,2008-12-10 01:55:50,2023-05-15 17:32:00,2023-05-15 17:32:00,2018-09-12 01:19:35,Opinion-based,python;return;return-value,saffsd,24410,37984,registered,true,,,,2013-11-19 01:21:29,4398,3542,14,4,0,3,false,true,false,true,true,true,65,9,false,0.01,0.0009,6555,2008,12,1,Wednesday,false,true,false,false,false,false,false 20101834,pip install from git repo branch,"Trying to pip install a repo's specific branch. Google tells me to
pip install https://github.com/user/repo.git@branch
The branch's name is issue/34/oscar-0.6 so I did pip install https://github.com/tangentlabs/django-oscar-paypal.git@/issue/34/oscar-0.6 but its returning a 404.
How do I install this branch?
",https://stackoverflow.com/questions/20101834/pip-install-from-git-repo-branch,1231,1159310.0,12.0,,,2013-11-20 16:46:42,2026-09-02 14:45:31,2021-06-19 18:54:22,,,python;git;pip,goh,29939,357236,registered,true,20101940,,CC BY-SA 4.0,,396,312,4,0,0,3,true,false,false,true,true,true,32,6,false,0.01,0.0011,4749,2013,11,16,Wednesday,false,true,false,false,false,false,false 441147,How to subtract a day from a date?,"I have a Python datetime.datetime object. What is the best way to subtract one day?
How can I convert the str representation of a dictionary, such as the following string, into a dict?
s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
I prefer not to use eval. What else can I use?
I'm building a web application with Django. The reasons I chose Django were:
Now that I'm getting closer to thinking about publishing my work, I start being concerned about scale. The only information I found about the scaling capabilities of Django is provided by the Django team (I'm not saying anything to disregard them, but this is clearly not objective information...).
Has an independent development team reported building a Django-based site that reliably handles an excess of 100k daily visits?
",https://stackoverflow.com/questions/886221/has-django-served-an-excess-of-100k-daily-visits,1220,211468.0,29.0,,,2009-05-20 05:07:55,2026-11-16 19:35:07,2026-11-16 19:35:07,2016-06-09 06:13:16,Needs more focus,python;django;scalability,Roee Adler,34132,103532,registered,true,886645,,,2019-07-21 01:25:06,1078,969,0,0,0,3,true,true,false,true,true,true,49,9,true,0.137,0.0058,6394,2009,5,5,Wednesday,false,true,false,false,false,false,false 20638006,Convert list of dictionaries to a pandas DataFrame,"How can I convert a list of dictionaries into a DataFrame? I want to turn
[{'points': 50, 'time': '5:00', 'year': 2010},
{'points': 25, 'time': '6:00', 'month': "february"},
{'points':90, 'time': '9:00', 'month': 'january'},
{'points_h1':20, 'month': 'june'}]
into
month points points_h1 time year
0 NaN 50 NaN 5:00 2010
1 february 25 NaN 6:00 NaN
2 january 90 NaN 9:00 NaN
3 june NaN 20 NaN NaN
",https://stackoverflow.com/questions/20638006/convert-list-of-dictionaries-to-a-pandas-dataframe,1219,1036466.0,8.0,,,2013-12-17 15:24:51,2024-02-24 15:54:59,2023-10-31 23:38:48,,,python;dictionary;pandas;dataframe,appleLover,15839,1560517,registered,true,20638258,,CC BY-SA 4.0,2020-07-20 17:38:14,636,498,2,0,0,4,true,false,false,true,true,true,50,8,false,0.008,0.0012,4722,2013,12,15,Tuesday,false,true,false,false,false,false,false
2793324,Is there a simple way to delete a list element by value?,"I want to remove a value from a list if it exists in the list (which it may not).
a = [1, 2, 3, 4]
b = a.index(6)
del a[b]
print(a)
The above gives the error:
ValueError: list.index(x): x not in list
So I have to do this:
a = [1, 2, 3, 4]
try:
b = a.index(6)
del a[b]
except:
pass
print(a)
But is there not a simpler way to do this?
",https://stackoverflow.com/questions/2793324/is-there-a-simple-way-to-delete-a-list-element-by-value,1217,2048614.0,27.0,,,2010-05-08 07:48:28,2025-03-18 13:32:10,2022-04-10 11:02:08,,,python;list,zjm1126,67717,234322,registered,true,2793341,,CC BY-SA 4.0,,490,351,3,0,0,2,true,false,false,true,true,true,56,12,true,0.013,0.0006,6041,2010,5,7,Saturday,true,true,false,false,false,false,false 2104080,How do I check file size in Python?,"How do I get the size of a file in Python?
",https://stackoverflow.com/questions/2104080/how-do-i-check-file-size-in-python,1216,1141019.0,11.0,,,2010-01-20 18:58:29,2025-01-02 18:06:38,2022-04-17 02:14:17,,,python;file,5YrsLaterDBA,35156,117039,registered,true,2104107,,CC BY-SA 4.0,2018-08-17 18:18:07,50,43,0,0,0,2,true,false,false,true,true,true,35,8,true,0.01,0.0011,6149,2010,1,18,Wednesday,false,true,false,false,false,false,false 11520492,"Difference between del, remove, and pop on lists in Python","Is there any difference between these three methods to remove an element from a list in Python?
a = [1, 2, 3]
a.remove(2)
a # [1, 3]
a = [1, 2, 3]
del a[1]
a # [1, 3]
a = [1, 2, 3]
a.pop(1) # 2
a # [1, 3]
",https://stackoverflow.com/questions/11520492/difference-between-del-remove-and-pop-on-lists-in-python,1214,2070120.0,15.0,,,2012-07-17 10:21:41,2024-02-21 07:50:54,2024-02-21 07:50:54,,,python;list,sachin irukula,13059,1477714,registered,true,11520540,,CC BY-SA 4.0,2016-05-23 06:45:18,325,257,1,0,0,2,true,false,false,true,true,true,58,10,false,0.007,0.0006,5240,2012,7,10,Tuesday,false,true,false,false,false,false,false
4990718,How can I write a `try`/`except` block that catches all exceptions?,"How can I write a try/except block that catches all exceptions?
How do I check whether a variable is an integer?
",https://stackoverflow.com/questions/3501382/checking-whether-a-variable-is-an-integer-or-not,1190,2263320.0,41.0,,,2010-08-17 10:15:08,2026-06-14 17:42:20,2021-01-12 14:28:38,2020-01-13 18:18:07,Duplicate,python;integer,Hulk,34520,221149,registered,true,3501408,,,,56,49,0,0,0,2,true,true,false,true,true,true,48,9,false,0.018,0.0005,5940,2010,8,10,Tuesday,false,true,false,false,false,false,false 14262433,"Large data" workflows using pandas,"I have tried to puzzle out an answer to this question for many months while learning pandas. I use SAS for my day-to-day work and it is great for it's out-of-core support. However, SAS is horrible as a piece of software for numerous other reasons.
One day I hope to replace my use of SAS with python and pandas, but I currently lack an out-of-core workflow for large datasets. I'm not talking about ""big data"" that requires a distributed network, but rather files too large to fit in memory but small enough to fit on a hard-drive.
My first thought is to use HDFStore to hold large datasets on disk and pull only the pieces I need into dataframes for analysis. Others have mentioned MongoDB as an easier to use alternative. My question is this:
What are some best-practice workflows for accomplishing the following:
Real-world examples would be much appreciated, especially from anyone who uses pandas on ""large data"".
Edit -- an example of how I would like this to work:
I am trying to find a best-practice way of performing these steps. Reading links about pandas and pytables it seems that appending a new column could be a problem.
Edit -- Responding to Jeff's questions specifically:
if var1 > 2 then newvar = 'A' elif var2 = 4 then newvar = 'B'. The result of these operations is a new column for every record in my dataset.It is rare that I would ever add rows to the dataset. I will nearly always be creating new columns (variables or features in statistics/machine learning parlance).
",https://stackoverflow.com/questions/14262433/large-data-workflows-using-pandas,1190,358347.0,16.0,,,2013-01-10 16:20:32,2024-04-28 17:47:11,2020-12-07 19:53:31,2021-12-31 21:27:07,Not suitable for this site,python;mongodb;pandas;hdf5;large-data,Zelazny7,40758,919872,registered,true,14268804,,,2015-12-24 12:01:56,4736,4503,2,0,0,5,true,true,false,true,true,true,45,5,false,0.045,0.0033,5063,2013,1,16,Thursday,false,true,false,false,false,false,false 11041405,Why dict.get(key) instead of dict[key]?,"I came across the dict method get which, given a key in the dictionary, returns the associated value.
For what purpose is this function useful? If I wanted to find a value associated with a key in a dictionary, I can just do dict[key], and it returns the same thing:
dictionary = {"Name": "Harry", "Age": 17}
dictionary["Name"] == dictionary.get("Name") # True
See also: Return a default value if a dictionary key is not available
",https://stackoverflow.com/questions/11041405/why-dict-getkey-instead-of-dictkey,1183,1041341.0,17.0,,,2012-06-14 21:10:39,2026-10-13 21:42:23,2023-08-24 17:45:14,,,python;dictionary;lookup,stensootla,15205,1204054,registered,true,11041421,,CC BY-SA 4.0,2021-12-18 01:39:57,695,490,4,1,0,3,true,false,false,true,true,true,39,5,true,0.016,0.0011,5273,2012,6,21,Thursday,false,true,false,false,false,false,false 22676,How to download a file over HTTP?,"I have a small utility that I use to download an MP3 file from a website on a schedule and then builds/updates a podcast XML file which I've added to iTunes.
The text processing that creates/updates the XML file is written in Python. However, I use wget inside a Windows .bat file to download the actual MP3 file. I would prefer to have the entire utility written in Python.
I struggled to find a way to actually download the file in Python, thus why I resorted to using wget.
So, how do I download the file using Python?
",https://stackoverflow.com/questions/22676/how-to-download-a-file-over-http,1182,1719400.0,31.0,,,2008-08-22 15:34:13,2025-06-09 19:57:11,2021-02-25 21:56:26,,,python;http;urllib,Owen,22967,2109,registered,true,22682,,CC BY-SA 4.0,2014-09-04 04:42:50,579,525,2,0,0,3,true,false,false,true,true,true,33,7,true,0.018,0.0007,6665,2008,8,15,Friday,false,true,false,false,false,false,false 15008758,Parsing boolean values with argparse,"I would like to use argparse to parse boolean command-line arguments written as ""--foo True"" or ""--foo False"". For example:
my_program --my_boolean_flag False
However, the following test code does not do what I would like:
import argparse
parser = argparse.ArgumentParser(description=""My parser"")
parser.add_argument(""--my_bool"", type=bool)
cmd_line = [""--my_bool"", ""False""]
parsed_args = parser.parse(cmd_line)
Sadly, parsed_args.my_bool evaluates to True. This is the case even when I change cmd_line to be [""--my_bool"", """"], which is surprising, since bool("""") evalutates to False.
How can I get argparse to parse ""False"", ""F"", and their lower-case variants to be False?
I have a list that I want to filter by an attribute of the items.
Which of the following is preferred (readability, performance, other reasons)?
xs = [x for x in xs if x.attribute == value]
xs = filter(lambda x: x.attribute == value, xs)
",https://stackoverflow.com/questions/3013449/list-comprehension-vs-lambda-filter,1171,971343.0,19.0,,,2010-06-10 10:14:00,2024-07-09 06:32:18,2022-04-10 13:07:25,2025-01-10 17:22:06,Opinion-based,python;list;functional-programming;filter;lambda,Agos,19633,107613,registered,true,3013686,,,,302,240,2,0,0,5,true,true,false,true,true,true,38,6,false,0.02,0.0012,6008,2010,6,10,Thursday,false,true,false,false,false,false,false
1912434,How can I parse XML and get instances of a particular node attribute?,"I have many rows in XML and I'm trying to get instances of a particular node attribute.
<foo>
<bar>
<type foobar="1"/>
<type foobar="2"/>
</bar>
</foo>
How do I access the values of the attribute foobar? In this example, I want "1" and "2".
I have a string representing a Unix timestamp (i.e. "1284101485") in Python, and I'd like to convert it to a readable date. When I use time.strftime, I get TypeError:
import time
print time.strftime("%B %d %Y", "1284101485")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: argument must be 9-item sequence, not str
",https://stackoverflow.com/questions/3682748/converting-unix-timestamp-string-to-readable-date,1169,1771799.0,20.0,,,2010-09-10 06:56:58,2026-01-03 11:18:14,2026-01-03 11:18:14,,,python;datetime;unix-timestamp;strftime,VeryNewToPython,11723,444083,unregistered,true,,,CC BY-SA 4.0,,563,406,4,0,0,4,false,false,false,true,true,true,49,7,false,0.011,0.0007,5916,2010,9,6,Friday,false,true,false,false,false,false,false
16923281,Writing a pandas DataFrame to CSV file,"I have a dataframe in pandas which I would like to write to a CSV file.
I am doing this using:
df.to_csv('out.csv')
And getting the following error:
UnicodeEncodeError: 'ascii' codec can't encode character u'\u03b1' in position 20: ordinal not in range(128)
I am running Python 2.5.
This is my folder tree:
ptdraft/
nib.py
simulations/
life/
life.py
(I also have __init__.py in each folder, omitted here for readability)
How do I import the nib module from inside the life module? I am hoping it is possible to do without tinkering with sys.path.
Note: The main module being run is in the ptdraft folder.
I'm building a Python application and don't want to force my clients to install Python and modules.
So, is there a way to compile a Python script to be a standalone executable?
",https://stackoverflow.com/questions/5458048/how-can-i-make-a-python-script-standalone-executable-to-run-without-any-dependen,1166,2078047.0,19.0,,,2011-03-28 11:04:09,2024-01-08 10:27:16,2024-01-08 10:27:16,2021-04-07 02:09:18,Duplicate,python;executable,Jeff,15713,498574,registered,true,5458807,,,2017-03-05 03:12:41,191,177,0,0,0,2,true,true,false,true,true,true,83,14,true,0.009,0.0006,5717,2011,3,11,Monday,false,true,false,false,false,false,false 626759,What's the difference between lists and tuples?,"What are the differences between lists and tuples, and what are their respective advantages and disadvantages?
",https://stackoverflow.com/questions/626759/whats-the-difference-between-lists-and-tuples,1165,474709.0,22.0,,,2009-03-09 15:41:25,2025-07-05 14:40:50,2024-12-09 06:39:58,,,python;list;tuples,Lucas Gabriel Sánchez,42045,20601,registered,true,626871,,CC BY-SA 4.0,2018-09-23 04:30:03,118,111,0,0,0,3,true,false,false,true,true,true,51,7,true,0.046,0.0025,6466,2009,3,15,Monday,false,true,false,false,false,false,false 1773805,How can I parse a YAML file in Python,"How can I parse a YAML file in Python?
",https://stackoverflow.com/questions/1773805/how-can-i-parse-a-yaml-file-in-python,1164,1620758.0,10.0,,,2009-11-20 23:16:16,2025-08-15 02:49:17,2015-11-23 12:27:06,,,python;yaml,Szymon Lipiński,28932,191332,registered,true,1774043,,CC BY-SA 3.0,2019-06-15 09:04:08,46,39,0,0,0,2,true,false,false,true,true,true,37,9,false,0.006,0.0007,6210,2009,11,23,Friday,false,true,false,false,false,false,false 247770,How can I retrieve a module's path?,"I want to detect whether a module has changed. Now, using inotify is simple; you just need to know the directory you want to get notifications from.
How do I retrieve a module's path in Python?
",https://stackoverflow.com/questions/247770/how-can-i-retrieve-a-modules-path,1158,1296211.0,26.0,,,2008-10-29 17:52:40,2026-08-03 17:34:50,2026-08-03 17:13:54,,,python;module;inotify,Cheery,25662,21711,registered,true,248862,,CC BY-SA 4.0,2019-07-13 13:13:34,286,194,0,1,0,3,true,false,false,true,true,true,39,7,true,0.02,0.0009,6597,2008,10,17,Wednesday,false,true,false,false,false,false,false 9233027,UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to <undefined>,"I'm trying to get a Python 3 program to do some manipulations with a text file filled with information. However, when trying to read the file I get the following error:
Traceback (most recent call last):
File "SCRIPT LOCATION", line NUMBER, in <module>
text = file.read()
File "C:\Python31\lib\encodings\cp1252.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 2907500: character maps to `<undefined>`
Editor's note: After reading this Q&A, see How to determine the encoding of text if you need help figuring out the encoding of the file you are trying to open.
",https://stackoverflow.com/questions/9233027/unicodedecodeerror-charmap-codec-cant-decode-byte-x-in-position-y-character,1156,2053541.0,16.0,,,2012-02-10 18:43:57,2026-05-26 21:18:13,2026-01-21 15:42:26,,,python;python-3.x;unicode;file-io;decode,Eden Crow,16454,1066850,registered,true,9233174,,CC BY-SA 4.0,2018-10-14 02:56:22,899,731,1,1,0,5,true,false,false,true,true,true,118,14,false,0.008,0.0006,5398,2012,2,18,Friday,false,true,false,false,false,false,false 16869024,What is __pycache__?,"From what I understand, a cache is an encrypted file of similar files.
What do we do with the __pycache__ folder? Is it what we give to people instead of our source code? Is it just my input data? This folder keeps getting created, what it is for?
I have a long-running Python server and would like to be able to upgrade a service without restarting the server. What's the best way do do this?
if foo.py has changed:
unimport foo <-- How do I do this?
import foo
myfoo = foo.Foo()
",https://stackoverflow.com/questions/437589/how-do-i-unload-reload-a-python-module,1152,1017319.0,24.0,,,2009-01-13 00:33:36,2025-05-08 14:43:15,2020-06-14 06:04:12,,,python;module;reload;python-import,Mark Harrison,306839,116,registered,true,437591,,CC BY-SA 4.0,,282,251,1,0,0,4,true,false,false,true,true,true,41,8,true,0.024,0.0011,6521,2009,1,0,Tuesday,false,true,false,false,false,false,false
20180543,How do I check the versions of Python modules?,"I installed the Python modules construct and statlib using setuptools:
sudo apt-get install python-setuptools
sudo easy_install statlib
sudo easy_install construct
How do I check their versions from the command line?
",https://stackoverflow.com/questions/20180543/how-do-i-check-the-versions-of-python-modules,1146,2478964.0,32.0,,,2013-11-24 20:25:01,2025-05-01 11:32:05,2022-07-17 04:21:47,,,python,tarabyte,19562,476410,registered,true,20180597,,CC BY-SA 4.0,2020-06-02 06:39:50,296,219,4,0,0,1,true,false,false,true,true,true,46,9,true,0.013,0.0005,4745,2013,11,20,Sunday,true,true,false,false,false,false,false 303200,How do I remove/delete/replace a folder that is not empty?,"I am getting an "access is denied" error when I attempt to delete a folder that is not empty. Newer versions of Python may also report a "directory not empty" error.
I used the following command in my attempt:
os.remove("/folder_name")
How can I remove, delete, or replace a directory that is not empty?
",https://stackoverflow.com/questions/303200/how-do-i-remove-delete-replace-a-folder-that-is-not-empty,1146,1097767.0,24.0,,,2008-11-19 20:15:38,2025-07-19 14:14:08,2025-06-23 21:56:31,,,python;file,Amara,14439,37804,registered,true,303225,,CC BY-SA 4.0,2023-12-13 08:44:49,417,335,1,0,0,2,true,false,false,true,true,true,58,10,true,0.022,0.001,6576,2008,11,20,Wednesday,false,true,false,false,false,false,false 36932,How can I represent an 'Enum' in Python?,"I'm mainly a C# developer, but I'm currently working on a project in Python.
How can I represent the equivalent of an Enum in Python?
",https://stackoverflow.com/questions/36932/how-can-i-represent-an-enum-in-python,1140,1329847.0,43.0,,,2008-08-31 15:55:47,2022-01-24 15:43:14,2014-09-22 16:03:16,,,python;python-3.x;enums,John Rutherford,10702,3880,registered,true,1695250,,CC BY-SA 3.0,2012-04-30 20:51:16,151,137,0,0,0,3,true,false,false,true,true,true,48,8,true,0.032,0.0009,6656,2008,8,15,Sunday,true,true,false,false,false,false,false 1323410,Should I use 'has_key()' or 'in' on Python dicts?,"Given:
>>> d = {'a': 1, 'b': 2}
Which of the following is the best way to check if 'a' is in d?
>>> 'a' in d
True
>>> d.has_key('a')
True
",https://stackoverflow.com/questions/1323410/should-i-use-has-key-or-in-on-python-dicts,1136,922690.0,9.0,,,2009-08-24 16:30:15,2022-11-23 08:30:50,2022-04-10 12:20:03,2023-01-15 06:49:37,Duplicate,python;dictionary,igorgue,18322,29253,registered,true,1323426,,,2019-01-12 18:27:57,280,168,5,0,0,2,true,true,false,true,true,true,65,9,true,0.01,0.0012,6298,2009,8,16,Monday,false,true,false,false,false,false,false
20994716,What is the difference between pip and Conda?,"I know pip is a package manager for Python packages. However, I saw the installation on IPython's website use conda to install IPython.
Can I use pip to install IPython?
Why should I use conda as another Python package manager when I already have pip?
What is the difference between pip and conda?
I have seen a few different styles of writing docstrings in Python, what are the most popular styles?
",https://stackoverflow.com/questions/3898572/what-are-the-most-common-python-docstring-formats,1135,832973.0,6.0,,,2010-10-10 01:10:44,2021-11-27 23:49:14,2021-11-27 23:49:14,2018-01-10 19:50:44,Opinion-based,python;coding-style;documentation;docstring,Noah McIlraith,14322,255344,registered,true,24385103,,,,109,102,0,0,0,4,true,true,false,true,true,true,50,8,true,0.007,0.0014,5886,2010,10,1,Sunday,true,true,false,false,false,false,false 159720,What is the naming convention in Python for variables and functions?,"Coming from a C# background the naming convention for variables and methods are usually either camelCase or PascalCase:
// C# example
string thisIsMyVariable = "a"
public void ThisIsMyMethod()
In Python, I have seen the above but I have also seen snake_case being used:
# python example
this_is_my_variable = 'a'
def this_is_my_function():
Is there a more preferable, definitive coding style for Python?
",https://stackoverflow.com/questions/159720/what-is-the-naming-convention-in-python-for-variables-and-functions,1134,943444.0,16.0,,,2008-10-01 21:01:16,2024-10-11 13:30:32,2023-06-10 21:09:57,,,python;naming-conventions;camelcasing;pascalcasing;snakecasing,Ray,194116,4872,registered,true,159745,,CC BY-SA 4.0,2013-09-17 16:17:25,559,416,2,0,0,5,true,false,false,true,true,true,68,11,true,0.017,0.0012,6625,2008,10,21,Wednesday,false,true,false,false,false,false,false 251464,How to get a function name as a string?,"How do I get a function's name as a string?
def foo():
pass
>>> name_of(foo)
"foo"
",https://stackoverflow.com/questions/251464/how-to-get-a-function-name-as-a-string,1133,961079.0,14.0,,,2008-10-30 19:38:24,2022-04-17 02:06:55,2022-04-17 02:06:55,,,python;string;function,X10,18253,11452,registered,true,255297,,CC BY-SA 4.0,2019-07-13 13:28:43,139,108,1,0,0,3,true,false,false,true,true,true,39,9,true,0.015,0.0012,6596,2008,10,19,Thursday,false,true,false,false,false,false,false
54867,What is the difference between old style and new style classes in Python?,"What is the difference between old style and new style classes in Python? When should I use one or the other?
",https://stackoverflow.com/questions/54867/what-is-the-difference-between-old-style-and-new-style-classes-in-python,1133,279691.0,8.0,,,2008-09-10 18:01:27,2020-02-02 11:31:19,2018-10-29 14:02:48,,,python;class;oop;types;new-style-class,readonly,359184,4883,registered,true,54873,,CC BY-SA 4.0,2017-02-01 20:08:30,118,111,0,0,0,5,true,false,false,true,true,true,73,13,true,0.029,0.0041,6646,2008,9,18,Wednesday,false,true,false,false,false,false,false 743164,How to emulate a do-while loop?,"I need to emulate a do-while loop in a Python program. Unfortunately, the following straightforward code does not work:
list_of_ints = [ 1, 2, 3 ]
iterator = list_of_ints.__iter__()
element = None
while True:
if element:
print element
try:
element = iterator.next()
except StopIteration:
break
print ""done""
Instead of ""1,2,3,done"", it prints the following output:
[stdout:]1
[stdout:]2
[stdout:]3
None['Traceback (most recent call last):
', ' File ""test_python.py"", line 8, in <module>
s = i.next()
', 'StopIteration
']
What can I do in order to catch the 'stop iteration' exception and break a while loop properly?
An example of why such a thing may be needed is shown below as pseudocode.
State machine:
s = """"
while True :
if state is STATE_CODE :
if ""//"" in s :
tokens.add( TOKEN_COMMENT, s.split( ""//"" )[1] )
state = STATE_COMMENT
else :
tokens.add( TOKEN_CODE, s )
if state is STATE_COMMENT :
if ""//"" in s :
tokens.append( TOKEN_COMMENT, s.split( ""//"" )[1] )
else
state = STATE_CODE
# Re-evaluate same line
continue
try :
s = i.next()
except StopIteration :
break
",https://stackoverflow.com/questions/743164/how-to-emulate-a-do-while-loop,1131,1855351.0,22.0,,,2009-04-13 06:18:42,2023-09-27 15:23:53,2021-03-13 18:11:33,,,python;while-loop;do-while,grigoryvp,43191,69882,registered,true,743186,,CC BY-SA 4.0,2016-05-12 21:02:27,1293,1186,3,0,0,3,true,false,false,true,true,true,31,6,true,0.012,0.0006,6431,2009,4,6,Monday,false,true,false,false,false,false,false
9733638,How can I POST JSON data with Python's Requests library?,"I need to POST JSON content from a client to a server. I'm using Python 2.7.1 and simplejson. The client is using Requests. The server is CherryPy. I can GET hard-coded JSON content from the server (the code is not shown), but when I try to POST JSON content to the server, I get "400 Bad Request".
Here is my client code:
data = {'sender': 'Alice',
'receiver': 'Bob',
'message': 'We did it!'}
data_json = simplejson.dumps(data)
payload = {'json_payload': data_json}
r = requests.post("http://localhost:8080", data=payload)
Here is the server code.
class Root(object):
def __init__(self, content):
self.content = content
print self.content # This works
exposed = True
def GET(self):
cherrypy.response.headers['Content-Type'] = 'application/json'
return simplejson.dumps(self.content)
def POST(self):
self.content = simplejson.loads(cherrypy.request.body.read())
How can I fix this problem?
",https://stackoverflow.com/questions/9733638/how-can-i-post-json-data-with-pythons-requests-library,1130,1937204.0,10.0,,,2012-03-16 07:46:49,2025-12-02 08:39:00,2025-11-22 11:46:53,,,python;json;python-requests;cherrypy,Charles R,19289,1273455,registered,true,26344315,,CC BY-SA 4.0,2018-11-24 23:43:39,1454,984,2,5,0,4,true,false,false,true,true,true,60,10,true,0.005,0.0006,5363,2012,3,7,Friday,false,true,false,false,false,false,false 529424,Traverse a list in reverse order in Python,"How do I traverse a list in reverse order in Python? So I can start from collection[len(collection)-1] and end in collection[0].
I also want to be able to access the loop index.
",https://stackoverflow.com/questions/529424/traverse-a-list-in-reverse-order-in-python,1122,1511088.0,28.0,,,2009-02-09 19:04:58,2022-09-26 22:27:38,2022-09-06 10:26:29,2022-08-04 00:19:23,Duplicate,python;loops;reverse,Joan Venge,334947,51816,registered,true,529427,,,2017-10-24 07:57:17,218,178,2,0,0,3,true,true,false,true,true,true,42,8,false,0.019,0.0007,6494,2009,2,19,Monday,false,true,false,false,false,false,false 2485466,What is Python's equivalent of && (logical-and) in an if-statement?,"This doesn't work:
if cond1 && cond2:
",https://stackoverflow.com/questions/2485466/what-is-pythons-equivalent-of-logical-and-in-an-if-statement,1115,3080688.0,9.0,,,2010-03-21 01:23:03,2023-09-13 11:28:25,2023-09-13 11:28:25,,,python;logical-and,delete,,,does_not_exist,true,2485471,,CC BY-SA 4.0,2019-05-29 02:53:35,78,47,1,0,0,2,true,false,false,true,false,true,79,10,true,0.003,0.0004,6089,2010,3,1,Sunday,true,true,false,false,false,false,false
483666,Reverse / invert a dictionary mapping,"Given a dictionary like so:
my_map = {'a': 1, 'b': 2}
How can one invert this map to get:
inv_map = {1: 'a', 2: 'b'}
",https://stackoverflow.com/questions/483666/reverse-invert-a-dictionary-mapping,1107,949964.0,35.0,,,2009-01-27 14:46:09,2025-04-25 07:09:50,2019-10-06 03:59:15,,,python;dictionary;mapping;reverse,Brian M. Hunt,84612,19212,registered,true,483833,,CC BY-SA 4.0,2019-07-14 12:17:43,184,122,2,0,0,4,true,false,false,true,true,true,37,6,false,0.037,0.0012,6507,2009,1,14,Tuesday,false,true,false,false,false,false,false
4843173,How to check if type of a variable is string?,"Is there a way to check if the type of a variable in python is a string, like:
isinstance(x,int);
for integer values?
",https://stackoverflow.com/questions/4843173/how-to-check-if-type-of-a-variable-is-string,1099,1555749.0,22.0,,,2011-01-30 13:32:19,2024-05-29 17:43:34,2020-04-19 17:47:44,2022-09-09 07:19:26,Duplicate,python;string;variables;types,c_pleaseUpvote,11023,592450,registered,true,,,,2015-06-13 08:20:25,172,121,2,0,0,4,false,true,false,true,true,true,45,10,true,0.014,0.0007,5774,2011,1,13,Sunday,true,true,false,false,false,false,false 4426663,How do I remove the first item from a list?,"How do I remove the first item from a list?
[0, 1, 2, 3] → [1, 2, 3]
",https://stackoverflow.com/questions/4426663/how-do-i-remove-the-first-item-from-a-list,1097,1390353.0,14.0,,,2010-12-13 07:38:38,2025-01-19 15:25:53,2022-04-10 13:13:53,,,python;list,rectangletangle,53607,433417,registered,true,4426727,,CC BY-SA 4.0,2016-01-12 03:58:23,105,74,1,0,0,2,true,false,false,true,true,true,43,10,true,0.01,0.0008,5822,2010,12,7,Monday,false,true,false,false,false,false,false
449560,How do I determine the size of an object in Python?,"How do I get the size occupied in memory by an object in Python?
",https://stackoverflow.com/questions/449560/how-do-i-determine-the-size-of-an-object-in-python,1097,1252879.0,17.0,,,2009-01-16 05:07:12,2024-03-05 01:15:10,2022-10-18 06:21:06,,,python;object;memory;memory-management;sizeof,user46646,160945,46646,registered,true,,,CC BY-SA 4.0,2014-12-25 00:03:47,72,65,0,0,0,5,false,false,false,true,true,true,51,11,true,0.014,0.0009,6518,2009,1,5,Friday,false,true,false,false,false,false,false 480214,"How do I remove duplicates from a list, while preserving order?","How do I remove duplicates from a list, while preserving order? Using a set to remove duplicates destroys the original order. Is there a built-in or a Pythonic idiom?
",https://stackoverflow.com/questions/480214/how-do-i-remove-duplicates-from-a-list-while-preserving-order,1090,775014.0,31.0,,,2009-01-26 15:43:58,2025-03-01 17:50:58,2022-10-16 15:42:53,,,python;list;duplicates;list-comprehension;unique,Josh Glover,26430,58994,registered,true,480227,,CC BY-SA 4.0,2016-10-12 23:16:27,174,167,0,0,0,5,true,false,false,true,true,true,63,11,true,0.04,0.0014,6508,2009,1,15,Monday,false,true,false,false,false,false,false 51520,How to get an absolute file path in Python,"Given a path such as "mydir/myfile.txt", how do I find the file's absolute path in Python? E.g. on Windows, I might end up with:
"C:/example/cwd/mydir/myfile.txt"
",https://stackoverflow.com/questions/51520/how-to-get-an-absolute-file-path-in-python,1083,1603128.0,12.0,,,2008-09-09 10:19:32,2024-08-29 10:46:37,2022-07-05 15:51:01,,,python;path;relative-path;absolute-path,izb,52420,974,registered,true,51523,,CC BY-SA 4.0,2019-07-13 13:37:44,228,184,2,0,0,4,true,false,false,true,true,true,42,9,false,0.007,0.0007,6647,2008,9,10,Tuesday,false,true,false,false,false,false,false
1485841,Behaviour of increment and decrement operators in Python,"How do I use pre-increment/decrement operators (++, --), just like in C++?
Why does ++count run, but not change the value of the variable?
In Python, what are the differences between the urllib, urllib2, urllib3 and Requests modules? Why are there three? They seem to do the same thing...
Is there a nicer way than the following to return today's date in the YYYY-MM-DD format?
str(datetime.datetime.today()).split()[0]
",https://stackoverflow.com/questions/32490629/getting-todays-date-in-yyyy-mm-dd-in-python,1076,1916208.0,14.0,,,2015-09-09 23:20:25,2025-11-27 02:08:14,2025-04-24 19:52:08,,,python;date;datetime;formatting;python-datetime,Pyderman,16647,1389110,registered,true,32490661,,CC BY-SA 4.0,,176,132,2,0,0,5,true,false,false,true,true,true,49,7,true,0.007,0.0006,4091,2015,9,23,Wednesday,false,true,false,false,false,false,false
308999,What does functools.wraps do?,"In a comment on this answer to another question, someone said that they weren't sure what functools.wraps was doing. So, I'm asking this question so that there will be a record of it on StackOverflow for future reference: what does functools.wraps do, exactly?
I am trying to understand the advantages of multiprocessing over threading. I know that multiprocessing gets around the Global Interpreter Lock, but what other advantages are there, and can threading not do the same thing?
",https://stackoverflow.com/questions/3044580/multiprocessing-vs-threading-python,1059,648287.0,12.0,,,2010-06-15 11:12:45,2023-02-15 15:02:10,2014-01-27 03:05:30,2020-02-08 22:57:41,Duplicate,python;multithreading;multiprocessing,John,11389,356354,registered,true,3044626,,,2019-06-19 21:01:50,414,223,0,2,0,3,true,true,false,true,true,true,35,4,false,0.019,0.0016,6003,2010,6,11,Tuesday,false,true,false,false,false,false,false 18172851,Deleting DataFrame row in Pandas based on column value,"I have the following DataFrame:
daysago line_race rating rw wrating
line_date
2007-03-31 62 11 56 1.000000 56.000000
2007-03-10 83 11 67 1.000000 67.000000
2007-02-10 111 9 66 1.000000 66.000000
2007-01-13 139 10 83 0.880678 73.096278
2006-12-23 160 10 88 0.793033 69.786942
2006-11-09 204 9 52 0.636655 33.106077
2006-10-22 222 8 66 0.581946 38.408408
2006-09-29 245 9 70 0.518825 36.317752
2006-09-16 258 11 68 0.486226 33.063381
2006-08-30 275 8 72 0.446667 32.160051
2006-02-11 475 5 65 0.164591 10.698423
2006-01-13 504 0 70 0.142409 9.968634
2006-01-02 515 0 64 0.134800 8.627219
2005-12-06 542 0 70 0.117803 8.246238
2005-11-29 549 0 70 0.113758 7.963072
2005-11-22 556 0 -1 0.109852 -0.109852
2005-11-01 577 0 -1 0.098919 -0.098919
2005-10-20 589 0 -1 0.093168 -0.093168
2005-09-27 612 0 -1 0.083063 -0.083063
2005-09-07 632 0 -1 0.075171 -0.075171
2005-06-12 719 0 69 0.048690 3.359623
2005-05-29 733 0 -1 0.045404 -0.045404
2005-05-02 760 0 -1 0.039679 -0.039679
2005-04-02 790 0 -1 0.034160 -0.034160
2005-03-13 810 0 -1 0.030915 -0.030915
2004-11-09 934 0 -1 0.016647 -0.016647
I need to remove the rows where line_race is equal to 0. What's the most efficient way to do this?
When I run pip install xyz on a Linux machine (using Debian or Ubuntu or a derived Linux distribution), I get this error:
error: externally-managed-environment × This environment is externally managed ╰─> To install Python packages system-wide, try apt install python3-xyz, where xyz is the package you are trying to install. If you wish to install a non-Debian-packaged Python package, create a virtual environment using python3 -m venv path/to/venv. Then use path/to/venv/bin/python and path/to/venv/bin/pip. Make sure you have python3-full installed. If you wish to install a non-Debian packaged Python application, it may be easiest to use pipx install xyz, which will manage a virtual environment for you. Make sure you have pipx installed. See /usr/share/doc/python3.11/README.venv for more information. note: If you believe this is a mistake, please contact your Python installation or OS distribution provider. You can override this, at the risk of breaking your Python installation or OS, by passing --break-system-packages. hint: See PEP 668 for the detailed specification.
What does this error mean? How do I avoid it? Why doesn't pip install xyz work like it did before I upgraded my system using sudo apt upgrade?
Is there a way to get functionality similar to mkdir -p on the shell from within Python. I am looking for a solution other than a system call. I am sure the code is less than 20 lines, and I am wondering if someone has already written it?
I would like to list all files recursively in a directory. I currently have a directory structure like this:
src/main.csrc/dir/file1.csrc/another-dir/file2.csrc/another-dir/nested/files/file3.cI've tried to do the following:
from glob import glob
glob(os.path.join('src','*.c'))
But this will only get be files directly in the src subfolder, e.g. I get main.c but I will not get file1.c, file2.c etc.
from glob import glob
glob(os.path.join('src','*.c'))
glob(os.path.join('src','*','*.c'))
glob(os.path.join('src','*','*','*.c'))
glob(os.path.join('src','*','*','*','*.c'))
But this is obviously limited and clunky, how can I do this properly?
",https://stackoverflow.com/questions/2186525/how-to-use-glob-to-find-files-recursively,1057,1130065.0,28.0,,,2010-02-02 18:19:50,2026-01-06 10:46:28,2026-01-06 10:46:28,,,python;path;filesystems;glob;fnmatch,Ben Gartner,15023,169175,registered,true,2186565,,CC BY-SA 4.0,2020-02-12 12:49:33,880,655,10,0,0,5,true,false,false,true,true,true,44,8,true,0.025,0.0009,6136,2010,2,18,Tuesday,false,true,false,false,false,false,false 3743222,How do I convert a datetime to date?,"How do I convert a datetime.datetime object (e.g., the return value of datetime.datetime.now()) to a datetime.date object in Python?
I've always thought of the if not x is None version to be more clear, but Google's style guide and PEP-8 both use if x is not None. Are there any minor performance differences (I'm assuming not), and is there any case where one really doesn't fit (making the other a clear winner for my convention)?*
*I'm referring to any singleton, rather than just None.
",https://stackoverflow.com/questions/2710940/python-if-x-is-not-none-or-if-not-x-is-none,1052,1569605.0,9.0,,,2010-04-26 03:10:30,2025-08-19 01:09:52,2023-05-15 17:32:37,,,python;nonetype;boolean-expression;pep8,orokusaki,57606,128463,registered,true,2711073,,CC BY-SA 4.0,2019-01-10 17:39:11,734,414,3,2,0,4,true,false,false,true,true,true,48,12,true,0.006,0.0007,6053,2010,4,3,Monday,false,true,false,false,false,false,false 11707586,How do I expand the output display to see more columns of a Pandas DataFrame?,"...to compare singletons like None. Use is or is not.
Is there a way to widen the display of output in either interactive or script-execution mode?
Specifically, I am using the describe() function on a Pandas DataFrame. When the DataFrame is five columns (labels) wide, I get the descriptive statistics that I want. However, if the DataFrame has any more columns, the statistics are suppressed and something like this is returned:
>> Index: 8 entries, count to max
>> Data columns:
>> x1 8 non-null values
>> x2 8 non-null values
>> x3 8 non-null values
>> x4 8 non-null values
>> x5 8 non-null values
>> x6 8 non-null values
>> x7 8 non-null values
The "8" value is given whether there are 6 or 7 columns. What does the "8" refer to?
I have already tried dragging the IDLE window larger, as well as increasing the "Configure IDLE" width options, to no avail.
",https://stackoverflow.com/questions/11707586/how-do-i-expand-the-output-display-to-see-more-columns-of-a-pandas-dataframe,1051,1815006.0,23.0,,,2012-07-29 07:44:51,2024-09-17 15:36:23,2022-08-18 19:34:16,,,python;pandas;printing;column-width,beets,11071,1560238,registered,true,11711637,,CC BY-SA 4.0,2019-07-17 09:18:44,1173,964,5,1,0,4,true,false,false,true,true,true,77,15,true,0.013,0.0006,5228,2012,7,7,Sunday,true,true,false,false,false,false,false 1937622,Convert date to datetime in Python,"Is there a built-in method for converting a date to a datetime in Python, for example getting the datetime for the midnight of the given date? The opposite conversion is easy: datetime has a .date() method.
Do I really have to manually call datetime(d.year, d.month, d.day)?
How can I find all the files in a directory having the extension .txt in python?
The very common directory structure for even a simple Python module seems to be to separate the unit tests into their own test directory:
new_project/
antigravity/
antigravity.py
test/
test_antigravity.py
setup.py
etc.
My question is simply What's the usual way of actually running the tests? I suspect this is obvious to everyone except me, but you can't just run python test_antigravity.py from the test directory as its import antigravity will fail as the module is not on the path.
I know I could modify PYTHONPATH and other search path related tricks, but I can't believe that's the simplest way - it's fine if you're the developer but not realistic to expect your users to use if they just want to check the tests are passing.
The other alternative is just to copy the test file into the other directory, but it seems a bit dumb and misses the point of having them in a separate directory to start with.
So, if you had just downloaded the source to my new project how would you run the unit tests? I'd prefer an answer that would let me say to my users: "To run the unit tests do X."
",https://stackoverflow.com/questions/1896918/running-unittest-with-typical-test-directory-structure,1040,479204.0,28.0,,,2009-12-13 16:10:23,2025-03-07 17:10:50,2022-06-08 01:27:10,,,python;unit-testing,Major Major,10926,164747,registered,true,24266885,,CC BY-SA 4.0,,1248,1133,4,0,0,2,true,false,false,true,true,true,54,7,false,0.058,0.0022,6187,2009,12,16,Sunday,true,true,false,false,false,false,false 2632677,Python integer incrementing with ++,"number++
I can't find anything about this in the Python docs. Must I subject myself to number = number + 1? Don't people use ++ / -- notation?
How do you get the logical xor of two variables in Python?
For example, I have two variables that I expect to be strings. I want to test that only one of them contains a True value (is not None or an empty string):
str1 = raw_input("Enter string one:")
str2 = raw_input("Enter string two:")
if logical_xor(str1, str2):
print "ok"
else:
print "bad"
The ^ operator is bitwise, and not defined on all objects:
>>> 1 ^ 1
0
>>> 2 ^ 1
3
>>> "abc" ^ ""
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for ^: 'str' and 'str'
",https://stackoverflow.com/questions/432842/how-do-you-get-the-logical-xor-of-two-variables-in-python,1038,1456196.0,29.0,,,2009-01-11 12:34:43,2024-06-11 08:14:49,2023-08-24 19:12:58,,,python;logical-operators,Zach Hirsch,26689,50773,registered,true,433161,,CC BY-SA 4.0,2019-07-14 12:18:50,892,700,3,1,0,2,true,false,false,true,true,true,58,12,true,0.02,0.0007,6523,2009,1,12,Sunday,true,true,false,false,false,false,false
323972,Is there any way to kill a Thread?,"Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?
",https://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread,1035,1389206.0,31.0,,,2008-11-27 14:55:53,2025-08-24 16:32:38,2022-11-21 15:55:24,,,python;multithreading;python-multithreading;kill;terminate,Sudden Def,10611,28121,registered,true,325528,,CC BY-SA 4.0,2018-04-20 00:16:37,104,97,0,0,0,5,true,false,false,true,true,true,34,8,true,0.022,0.0007,6568,2008,11,14,Thursday,false,true,false,false,false,false,false 477486,How do I use a decimal step value for range()?,"How do I iterate between 0 and 1 by a step of 0.1?
This says that the step argument cannot be zero:
for i in range(0, 1, 0.1):
print(i)
",https://stackoverflow.com/questions/477486/how-do-i-use-a-decimal-step-value-for-range,1029,1235367.0,36.0,,,2009-01-25 10:20:43,2024-07-19 05:50:43,2022-07-17 04:32:41,,,python;floating-point;range,Evan Fosmark,102757,49701,registered,true,477635,,CC BY-SA 4.0,2016-04-27 14:56:00,179,141,1,0,0,3,true,false,false,true,true,true,46,10,true,0.029,0.0008,6509,2009,1,10,Sunday,true,true,false,false,false,false,false
81584,What IDE to use for Python?,"What IDEs (""GUIs/editors"") do others use for Python coding?
",https://stackoverflow.com/questions/81584/what-ide-to-use-for-python,1022,1686389.0,1.0,,,2008-09-17 09:53:15,2018-09-24 10:56:48,2014-11-11 01:57:55,2016-09-13 19:45:13,Not suitable for this site,python;ide;editor,husayt,15331,15461,registered,true,,,,2014-11-11 02:00:07,67,60,0,0,0,3,false,true,false,true,true,true,27,6,true,0.001,0.0006,6639,2008,9,9,Wednesday,false,true,false,false,false,false,false 209513,Convert hex string to integer in Python,"How do I convert a hex string to an integer?
"0xffff" ⟶ 65535
"ffff" ⟶ 65535
",https://stackoverflow.com/questions/209513/convert-hex-string-to-integer-in-python,1019,1511872.0,11.0,,,2008-10-16 17:28:03,2024-07-19 09:52:44,2022-07-30 09:39:14,,,python;string;hex,Matt,89117,17693,registered,true,209550,,CC BY-SA 4.0,2017-01-31 22:30:35,139,108,1,0,0,3,true,false,false,true,true,true,39,7,false,0.007,0.0007,6610,2008,10,17,Thursday,false,true,false,false,false,false,false
973473,Getting a list of all subdirectories in the current directory,"Is there a way to return a list of all the subdirectories in the current directory in Python?
I know you can do this with files, but I need to get the list of directories instead.
",https://stackoverflow.com/questions/973473/getting-a-list-of-all-subdirectories-in-the-current-directory,1018,1741459.0,36.0,,,2009-06-10 02:48:21,2024-10-15 12:24:48,2016-06-16 21:45:55,,,python;directory;subdirectory,Brad Zeis,11005,120258,registered,true,973488,,CC BY-SA 3.0,2020-09-18 05:33:32,195,181,0,0,0,3,true,false,false,true,true,true,61,10,false,0.021,0.0006,6373,2009,6,2,Wednesday,false,true,false,false,false,false,false 687295,How do I do a not equal in Django queryset filtering?,"In Django model QuerySets, I see that there is a __gt and __lt for comparative values, but is there a __ne or != (not equals)? I want to filter out using a not equals. For example, for
Model:
bool a;
int x;
I want to do
results = Model.objects.exclude(a=True, x!=5)
The != is not correct syntax. I also tried __ne.
I ended up using:
results = Model.objects.exclude(a=True, x__lt=5).exclude(a=True, x__gt=5)
",https://stackoverflow.com/questions/687295/how-do-i-do-a-not-equal-in-django-queryset-filtering,1014,766666.0,17.0,,,2009-03-26 19:47:45,2022-03-06 14:41:06,2020-11-12 06:47:22,,,python;django;django-models;django-queryset,MikeN,46627,36680,registered,true,1154977,,CC BY-SA 4.0,2019-07-21 01:26:32,613,418,9,0,0,4,true,false,false,true,true,true,53,11,true,0.022,0.0013,6449,2009,3,19,Thursday,false,true,false,false,false,false,false
45310254,Fixed digits after decimal with f-strings,"Is there an easy way with Python f-strings to fix the number of digits after the decimal point? (Specifically f-strings, not other string formatting options like .format or %)
For example, let's say I want to display 2 digits after the decimal place.
How do I do that? Let's say that
a = 10.1234
",https://stackoverflow.com/questions/45310254/fixed-digits-after-decimal-with-f-strings,1012,846508.0,10.0,,,2017-07-25 17:41:20,2025-12-09 10:06:14,2020-04-19 16:07:08,,,python;python-3.x;f-string,GafferMan2112,10439,6432812,registered,true,45310389,,CC BY-SA 4.0,,346,301,1,0,0,3,true,false,false,true,true,true,41,6,false,0.012,0.0012,3406,2017,7,17,Tuesday,false,true,false,false,false,false,false
19377969,Combine two columns of text in pandas dataframe,"I have a dataframe that looks like
Year quarter
2000 q2
2001 q3
How do I add a new column by combining these columns to get the following dataframe?
Year quarter period
2000 q2 2000q2
2001 q3 2001q3
",https://stackoverflow.com/questions/19377969/combine-two-columns-of-text-in-pandas-dataframe,1010,1999836.0,23.0,,,2013-10-15 09:42:52,2024-12-12 17:09:27,2023-12-06 03:49:52,,,python;pandas;string;dataframe;string-concatenation,user2866103,10655,2866103,registered,true,,,CC BY-SA 4.0,,370,230,2,0,0,5,false,false,false,true,true,true,47,8,false,0.012,0.0005,4785,2013,10,9,Tuesday,false,true,false,false,false,false,false
3845423,Remove empty strings from a list of strings,"I want to remove all empty strings from a list of strings in python.
My idea looks like this:
while '' in str_list:
str_list.remove('')
Is there any more pythonic way to do this?
",https://stackoverflow.com/questions/3845423/remove-empty-strings-from-a-list-of-strings,1010,1227463.0,14.0,,,2010-10-02 11:21:10,2024-03-20 18:18:15,2020-01-12 16:45:10,,,python;string;list,zerodx,10121,337249,registered,true,3845453,,CC BY-SA 4.0,2020-01-31 14:33:39,232,187,1,0,0,3,true,false,false,true,true,true,43,8,false,0.011,0.0008,5894,2010,10,11,Saturday,true,true,false,false,false,false,false 1854,How to identify which OS Python is running on,"What do I need to look at to see whether I'm on Windows or Unix, etc.?
",https://stackoverflow.com/questions/1854/how-to-identify-which-os-python-is-running-on,1010,584131.0,28.0,,,2008-08-05 03:23:18,2024-04-19 15:30:47,2023-03-25 14:52:36,,,python;operating-system;cross-platform;platform-agnostic,Mark Harrison,306839,116,registered,true,1857,,CC BY-SA 4.0,2019-07-08 07:35:09,78,71,0,0,0,4,true,false,false,true,true,true,45,9,false,0.048,0.0017,6682,2008,8,3,Tuesday,false,true,false,false,false,false,false 899103,"Writing a list to a file with Python, with newlines","How do I write a list to a file? writelines() doesn't insert newline characters, so I need to do:
f.writelines([f"{line}\n" for line in lines])
",https://stackoverflow.com/questions/899103/writing-a-list-to-a-file-with-python-with-newlines,1008,2435045.0,27.0,,,2009-05-22 17:52:18,2025-02-24 10:35:32,2022-07-10 23:56:51,,,python;file;list;file-io;newline,Josh Arenberg,10628,40909,registered,true,899176,,CC BY-SA 4.0,2016-01-18 02:06:18,199,155,2,0,0,5,true,false,false,true,true,true,51,10,false,0.011,0.0004,6392,2009,5,17,Friday,false,true,false,false,false,false,false
31593201,How are iloc and loc different?,"Can someone explain how these two methods of slicing are different? I've seen the docs and I've seen previous similar questions (1, 2), but I still find myself unable to understand how they are different. To me, they seem interchangeable in large part, because they are at the lower levels of slicing.
For example, say we want to get the first five rows of a DataFrame. How is it that these two work?
df.loc[:5]
df.iloc[:5]
Can someone present cases where the distinction in uses are clearer?
Once upon a time, I also wanted to know how these two functions differed from df.ix[:5] but ix has been removed from pandas 1.0, so I don't care anymore.
I'm able to update pip-managed packages, but how do I update pip itself? According to pip --version, I currently have pip 1.1 installed in my virtualenv and I want to update to the latest version.
What's the command for that? Do I need to use distribute or is there a native pip or virtualenv command? I've already tried pip update and pip update pip with no success.
I would like to know what are all the possible values for the timezone argument in the Python library pytz. How to do it?
",https://stackoverflow.com/questions/13866926/is-there-a-list-of-pytz-timezones,1006,781986.0,10.0,,,2012-12-13 19:24:37,2025-08-06 02:07:08,2023-04-05 07:08:54,,,python;django;datetime;timezone;pytz,ipegasus,15328,1112656,registered,true,13867319,,CC BY-SA 4.0,2019-07-21 01:27:50,129,122,0,0,0,5,true,false,false,true,true,true,34,7,true,0.013,0.0013,5091,2012,12,19,Thursday,false,true,false,false,false,false,false 3684484,Peak detection in a 2D array,"I'm helping a veterinary clinic measuring pressure under a dogs paw. I use Python for my data analysis and now I'm stuck trying to divide the paws into (anatomical) subregions.
I made a 2D array of each paw, that consists of the maximal values for each sensor that has been loaded by the paw over time. Here's an example of one paw, where I used Excel to draw the areas I want to 'detect'. These are 2 by 2 boxes around the sensor with local maxima's, that together have the largest sum.
So I tried some experimenting and decide to simply look for the maximums of each column and row (can't look in one direction due to the shape of the paw). This seems to 'detect' the location of the separate toes fairly well, but it also marks neighboring sensors.
So what would be the best way to tell Python which of these maximums are the ones I want?
Note: The 2x2 squares can't overlap, since they have to be separate toes!
Also I took 2x2 as a convenience, any more advanced solution is welcome, but I'm simply a human movement scientist, so I'm neither a real programmer or a mathematician, so please keep it 'simple'.
Here's a version that can be loaded with np.loadtxt
So I tried @jextee's solution (see the results below). As you can see, it works very on the front paws, but it works less well for the hind legs.
More specifically, it can't recognize the small peak that's the fourth toe. This is obviously inherent to the fact that the loop looks top down towards the lowest value, without taking into account where this is.
Would anyone know how to tweak @jextee's algorithm, so that it might be able to find the 4th toe too?
Since I haven't processed any other trials yet, I can't supply any other samples. But the data I gave before were the averages of each paw. This file is an array with the maximal data of 9 paws in the order they made contact with the plate.
This image shows how they were spatially spread out over the plate.
I have set up a blog for anyone interested and I have setup a OneDrive with all the raw measurements. So to anyone requesting more data: more power to you!
So after the help I got with my questions regarding paw detection and paw sorting, I was finally able to check the toe detection for every paw! Turns out, it doesn't work so well in anything but paws sized like the one in my own example. Off course in hindsight, it's my own fault for choosing the 2x2 so arbitrarily.
Here's a nice example of where it goes wrong: a nail is being recognized as a toe and the 'heel' is so wide, it gets recognized twice!
The paw is too large, so taking a 2x2 size with no overlap, causes some toes to be detected twice. The other way around, in small dogs it often fails to find a 5th toe, which I suspect is being caused by the 2x2 area being too large.
After trying the current solution on all my measurements I came to the staggering conclusion that for nearly all my small dogs it didn't find a 5th toe and that in over 50% of the impacts for the large dogs it would find more!
So clearly I need to change it. My own guess was changing the size of the neighborhood to something smaller for small dogs and larger for large dogs. But generate_binary_structure wouldn't let me change the size of the array.
Anyone has a better suggestion for locating the toes, perhaps having the toe area scale with the paw size?
",https://stackoverflow.com/questions/3684484/peak-detection-in-a-2d-array,1005,163056.0,17.0,,,2010-09-10 12:12:25,2023-08-11 17:32:42,2023-08-08 23:49:05,,,python;image-processing,Ivo Flipse,10282,77595,registered,true,3689710,,CC BY-SA 4.0,2014-04-05 00:00:40,4405,3373,3,6,5,2,true,false,false,true,true,true,28,6,false,0.104,0.0062,5916,2010,9,12,Friday,false,true,false,false,false,false,false 8023306,Get key by value in dictionary,"I made a function which will look up ages in a Dictionary and show the matching name:
dictionary = {'george' : 16, 'amber' : 19}
search_age = raw_input(""Provide age"")
for age in dictionary.values():
if age == search_age:
name = dictionary[age]
print name
I know how to compare and find the age I just don't know how to show the name of the person. Additionally, I am getting a KeyError because of line 5. I know it's not correct but I can't figure out how to make it search backwards.
Is there a reason to prefer using map() over list comprehension or vice versa? Is either of them generally more efficient or considered generally more Pythonic than the other?
",https://stackoverflow.com/questions/1247486/list-comprehension-vs-map,1000,363122.0,14.0,,,2009-08-07 23:43:31,2023-01-16 00:38:57,2023-01-16 00:21:13,,,python;list-comprehension;map-function,TimothyAWiseman,15023,43818,registered,true,1247490,,CC BY-SA 4.0,,270,177,0,1,0,3,true,false,false,true,true,true,25,4,false,0.039,0.0028,6315,2009,8,23,Friday,false,true,false,false,false,false,false 4271740,How can I use Python to get the system hostname?,"I'm writing a chat program for a local network. I would like be able to identify computers and get the user-set computer name with Python.
",https://stackoverflow.com/questions/4271740/how-can-i-use-python-to-get-the-system-hostname,996,927404.0,12.0,,,2010-11-24 21:33:23,2020-11-11 02:57:09,2016-09-13 16:00:53,,,python;hostname,John,16208,467090,registered,true,4271755,,CC BY-SA 3.0,2019-07-14 12:12:21,146,139,0,0,0,2,true,false,false,true,true,true,48,10,true,0.013,0.0011,5841,2010,11,21,Wednesday,false,true,false,false,false,false,false 624926,How do I detect whether a variable is a function?,"I have a variable, x, and I want to know whether it is pointing to a function or not.
I had hoped I could do something like:
>>> isinstance(x, function)
But that gives me:
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'function' is not defined
The reason I picked that is because
>>> type(x)
<type 'function'>
",https://stackoverflow.com/questions/624926/how-do-i-detect-whether-a-variable-is-a-function,994,424618.0,32.0,,,2009-03-09 03:31:30,2026-03-14 18:15:07,2022-11-29 00:12:55,,,python,Daniel H,10295,14799,registered,true,624939,,CC BY-SA 4.0,,541,389,4,0,0,1,true,false,false,true,true,true,49,10,true,0.075,0.0023,6466,2009,3,3,Monday,false,true,false,false,false,false,false
14379753,What does -> mean in Python function definitions?,"I've recently noticed something interesting when looking at Python 3.3 grammar specification:
funcdef: 'def' NAME parameters ['->' test] ':' suite
The optional 'arrow' block was absent in Python 2 and I couldn't find any information regarding its meaning in Python 3. It turns out this is correct Python and it's accepted by the interpreter:
def f(x) -> 123:
return x
I thought that this might be some kind of a precondition syntax, but:
x here, as it is still undefined,2 < 1), it doesn't affect the function behavior.Could anyone familiar with this syntax style explain it?
",https://stackoverflow.com/questions/14379753/what-does-mean-in-python-function-definitions,994,921815.0,12.0,,,2013-01-17 13:03:35,2025-02-17 16:33:11,2025-02-17 16:33:11,,,python;python-typing;grammar;function-definition,Krotton,10189,1311262,registered,true,14379780,,CC BY-SA 4.0,2024-02-13 15:57:03,862,652,4,1,0,4,true,false,false,true,true,true,52,8,true,0.013,0.0011,5056,2013,1,13,Thursday,false,true,false,false,false,false,false 6392739,What does the "at" (@) symbol do in Python?,"What does the @ symbol do in Python?
Is there a Python equivalent for the switch statement?
How do I remove a specific value from an array? Something like:
array.remove(value);
Constraints: I have to use core JavaScript. Frameworks are not allowed.
",https://stackoverflow.com/questions/5767325/how-can-i-remove-a-specific-item-from-an-array-in-javascript,12260,13647685.0,51.0,,,2011-04-23 22:17:18,2026-03-01 02:48:12,2023-02-06 14:23:52,,,javascript;arrays,Walker,135691,364969,registered,true,5767357,,CC BY-SA 4.0,2014-12-15 20:00:00,250,158,1,0,0,2,true,false,false,true,true,true,61,12,true,0.004,0.0009,5691,2011,4,22,Saturday,true,false,true,false,false,false,false 178325,How do I check if an element is hidden in jQuery?,"How do I toggle the visibility of an element using .hide(), .show(), or .toggle()?
How do I test if an element is visible or hidden?
Recently, I ran some of my JavaScript code through Crockford's JSLint, and it gave the following error:
Problem at line 1 character 1: Missing "use strict" statement.
Doing some searching, I realized that some people add "use strict"; into their JavaScript code. Once I added the statement, the error stopped appearing. Unfortunately, Google did not reveal much of the history behind this string statement. Certainly it must have something to do with how the JavaScript is interpreted by the browser, but I have no idea what the effect would be.
So what is "use strict"; all about, what does it imply, and is it still relevant?
Do any of the current browsers respond to the "use strict"; string or is it for future use?
How can I redirect the user from one page to another using jQuery or pure JavaScript?
",https://stackoverflow.com/questions/503093/how-do-i-redirect-to-another-webpage,7693,8190456.0,58.0,,,2009-02-02 12:54:16,2025-06-13 08:52:11,2018-02-06 12:40:14,,,javascript;jquery;http-redirect,venkatachalam,102407,44984,registered,true,506004,,CC BY-SA 3.0,2015-11-12 13:11:22,93,86,0,0,0,3,true,false,false,true,true,true,37,7,true,0.007,0.0009,6501,2009,2,12,Monday,false,false,true,false,false,false,false 336859,var functionName = function() {} vs function functionName() {},"I've recently started maintaining someone else's JavaScript code. I'm fixing bugs, adding features and also trying to tidy up the code and make it more consistent.
The previous developer used two ways of declaring functions and I can't work out if there is a reason behind it or not.
The two ways are:
var functionOne = function() {
// Some code
};
And,
function functionTwo() {
// Some code
}
What are the reasons for using these two different methods and what are the pros and cons of each? Is there anything that can be done with one method that can't be done with the other?
",https://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname,7669,1247026.0,42.0,,,2008-12-03 11:31:07,2024-04-23 15:08:21,2023-02-14 07:44:35,,,javascript;function;methods;syntax,Richard Garside,89575,31569,registered,true,336868,,CC BY-SA 4.0,2013-06-10 05:05:53,672,589,2,0,0,4,true,false,false,true,true,true,62,9,false,0.034,0.0061,6562,2008,12,11,Wednesday,false,false,true,false,false,false,false 111102,How do JavaScript closures work?,"How would you explain JavaScript closures to someone with a knowledge of the concepts they consist of (for example functions, variables and the like), but does not understand closures themselves?
I have seen the Scheme example given on Wikipedia, but unfortunately it did not help.
",https://stackoverflow.com/questions/111102/how-do-javascript-closures-work,7608,1638914.0,85.0,,,2008-09-21 14:12:07,2023-07-16 17:04:37,2017-04-09 13:55:17,,,javascript;function;variables;scope;closures,Bite code,602069,9951,registered,true,111111,,CC BY-SA 3.0,2011-09-19 16:35:31,391,283,0,1,0,5,true,false,false,true,true,true,32,5,true,0.052,0.0046,6635,2008,9,14,Sunday,true,false,true,false,false,false,false 208105,How do I remove a property from a JavaScript object?,"Given an object:
let myObject = {
"ircEvent": "PRIVMSG",
"method": "newURI",
"regex": "^http://.*"
};
How do I remove the property regex to end up with the following myObject?
let myObject = {
"ircEvent": "PRIVMSG",
"method": "newURI"
};
",https://stackoverflow.com/questions/208105/how-do-i-remove-a-property-from-a-javascript-object,7584,3408018.0,40.0,,,2008-10-16 10:57:45,2026-07-13 11:41:22,2022-08-29 10:25:21,,,javascript;object;properties,johnstok,98570,27929,registered,true,208106,,CC BY-SA 4.0,2011-10-20 18:27:07,438,350,4,0,0,3,true,false,false,true,true,true,52,10,true,0.012,0.0022,6610,2008,10,10,Thursday,false,false,true,false,false,false,false
1789945,How to check whether a string contains a substring in JavaScript?,"Usually I would expect a String.contains() method, but there doesn't seem to be one.
What is a reasonable way to check for this?
",https://stackoverflow.com/questions/1789945/how-to-check-whether-a-string-contains-a-substring-in-javascript,7402,8388948.0,3.0,,,2009-11-24 13:04:29,2022-10-18 06:47:43,2019-04-03 13:17:08,,,javascript;string;substring;string-matching,gramm,18824,131679,registered,true,1789952,,CC BY-SA 4.0,2012-11-02 12:31:07,158,131,1,0,0,4,true,false,false,true,true,true,65,11,true,0.0,0.0009,6206,2009,11,13,Tuesday,false,false,true,false,false,false,false 14220321,How do I return the response from an asynchronous call?,"How do I return the response/result from a function foo that makes an asynchronous request?
I am trying to return the value from the callback, as well as assigning the result to a local variable inside the function and returning that one, but none of those ways actually return the response — they all return undefined or whatever the initial value of the variable result is.
Example of an asynchronous function that accepts a callback (using jQuery's ajax function):
function foo() {
var result;
$.ajax({
url: '...',
success: function(response) {
result = response;
// return response; // <- I tried that one as well
}
});
return result; // It always returns `undefined`
}
Example using Node.js:
function foo() {
var result;
fs.readFile("path/to/file", function(err, data) {
result = data;
// return data; // <- I tried that one as well
});
return result; // It always returns `undefined`
}
Example using the then block of a promise:
function foo() {
var result;
fetch(url).then(function(response) {
result = response;
// return response; // <- I tried that one as well
});
return result; // It always returns `undefined`
}
",https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call,6744,2188785.0,44.0,,,2013-01-08 17:06:14,2025-03-04 19:20:50,2022-07-06 21:29:59,,,javascript;ajax;asynchronous,Felix Kling,821480,218196,registered,true,14220323,,CC BY-SA 4.0,2019-04-08 04:43:23,1504,1281,8,0,0,3,true,false,false,true,true,true,55,10,true,0.02,0.0031,5065,2013,1,17,Tuesday,false,false,true,false,false,false,false
762011,What is the difference between "let" and "var"?,"ECMAScript 6 introduced the let declaration keyword.
I've heard that it's described as a local variable, but I'm still not quite sure how it behaves differently than the var keyword.
What are the differences? When should let be used instead of var?
How do I include a JavaScript file inside another JavaScript file, similar to @import in CSS?
How can I loop through all the entries in an array using JavaScript?
",https://stackoverflow.com/questions/9329446/loop-for-each-over-an-array-in-javascript,5814,5557561.0,41.0,,,2012-02-17 13:51:48,2025-01-23 12:43:23,2023-01-21 12:16:12,,,javascript;arrays;loops;foreach;iteration,Dante1986,60373,1140876,registered,true,9329476,,CC BY-SA 4.0,2014-04-03 15:03:15,76,69,0,0,0,5,true,false,false,true,true,true,43,8,false,0.007,0.001,5391,2012,2,13,Friday,false,false,true,false,false,false,false 359494,Which equals operator (== vs ===) should be used in JavaScript comparisons?,"I'm using JSLint to go through JavaScript, and it's returning many suggestions to replace == (two equals signs) with === (three equals signs) when doing things like comparing idSele_UNVEHtype.value.length == 0 inside of an if statement.
Is there a performance benefit to replacing == with ===?
Any performance improvement would be welcomed as many comparison operators exist.
If no type conversion takes place, would there be a performance gain over ==?
Given a string:
string = "Test abc test test abc test test test abc test test abc";
This seems to only remove the first occurrence of abc in the string above:
string = string.replace('abc', '');
How do I replace all occurrences of it?
",https://stackoverflow.com/questions/1144783/how-do-i-replace-all-occurrences-of-a-string,5519,4640456.0,50.0,,,2009-07-17 17:53:46,2025-01-29 13:39:20,2025-01-29 13:39:20,,,javascript;string;replace,Ali,268320,49153,registered,true,1145525,,CC BY-SA 4.0,2015-09-01 10:41:22,338,247,3,0,0,3,true,false,false,true,true,true,45,9,true,0.011,0.0012,6336,2009,7,17,Friday,false,false,true,false,false,false,false 105034,How do I create a GUID / UUID?,"How do I create GUIDs (globally-unique identifiers) in JavaScript? The GUID / UUID should be at least 32 characters and should stay in the ASCII range to avoid trouble when passing them around.
I'm not sure what routines are available on all browsers, how "random" and seeded the built-in random number generator is, etc.
",https://stackoverflow.com/questions/105034/how-do-i-create-a-guid-uuid,5503,3341206.0,77.0,,,2008-09-19 20:01:00,2025-10-17 08:33:07,2022-07-24 23:56:45,,,javascript;guid;uuid,Jason Cohen,83753,4926,registered,true,105074,,CC BY-SA 4.0,2013-06-10 05:10:35,346,332,0,0,0,3,true,false,false,true,true,true,30,8,true,0.023,0.0016,6637,2008,9,20,Friday,false,false,true,false,false,false,false 46155,How can I validate an email address in JavaScript?,"I'd like to check if the user input is an email address in JavaScript, before sending it to a server or attempting to send an email to it, to prevent the most basic mistyping. How could I achieve this?
",https://stackoverflow.com/questions/46155/how-can-i-validate-an-email-address-in-javascript,5466,4940660.0,78.0,,,2008-09-05 16:10:11,2025-01-03 21:51:06,2022-07-28 07:55:26,,,javascript;html;regex;email-validation,pix0r,31338,72,registered,true,46181,,CC BY-SA 4.0,2011-03-02 11:31:02,209,202,0,0,0,4,true,false,false,true,true,true,50,9,true,0.016,0.0011,6651,2008,9,16,Friday,false,false,true,false,false,false,false 1026069,How do I make the first letter of a string uppercase in JavaScript?,"How do I make the first character of a string uppercase if it's a letter, but not change the case of any of the other letters?
For example:
"this is a test" → "This is a test""the Eiffel Tower" → "The Eiffel Tower""/index.html" → "/index.html"I need to check the checked property of a checkbox and perform an action based on the checked property using jQuery.
For example, if the age checkbox is checked, then I need to show a textbox to enter age, else hide the textbox.
But the following code returns false by default:
if ($('#isAgeSelected').attr('checked')) {
$(""#txtAge"").show();
} else {
$(""#txtAge"").hide();
}
<script src=""https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js""></script>
<input type=""checkbox"" id=""isAgeSelected""/>
<div id=""txtAge"" style=""display:none"">
Age is selected
</div>
How do I successfully query the checked property?
What is the most efficient way to clone a JavaScript object? I've seen obj = eval(uneval(o)); being used, but that's non-standard and only supported by Firefox.
I've done things like obj = JSON.parse(JSON.stringify(o)); but question the efficiency.
I've also seen recursive copying functions with various flaws.
I'm surprised no canonical solution exists.
What is the most concise and efficient way to find out if a JavaScript array contains a value?
This is the only way I know to do it:
function contains(a, obj) {
for (var i = 0; i < a.length; i++) {
if (a[i] === obj) {
return true;
}
}
return false;
}
Is there a better and more concise way to accomplish this?
This is very closely related to Stack Overflow question Best way to find an item in a JavaScript Array? which addresses finding objects in an array using indexOf.
I want a single number that represents the current date and time, like a Unix timestamp.
",https://stackoverflow.com/questions/221294/how-do-i-get-a-timestamp-in-javascript,4937,4665000.0,36.0,,,2008-10-21 09:29:33,2025-06-11 10:39:01,2022-08-07 21:40:43,,,javascript;datetime;timestamp;date-arithmetic,Pablo Fernandez,290260,6068,registered,true,221297,,CC BY-SA 4.0,2010-11-18 15:45:59,167,89,0,1,0,4,true,false,false,true,true,true,39,8,true,0.008,0.0011,6605,2008,10,9,Tuesday,false,false,true,false,false,false,false 426258,Setting "checked" for a checkbox with jQuery,"I'd like to do something like this to tick a checkbox using jQuery:
$("".myCheckBox"").checked(true);
or
$("".myCheckBox"").selected(true);
Does such a thing exist?
",https://stackoverflow.com/questions/426258/setting-checked-for-a-checkbox-with-jquery,4609,3911528.0,44.0,,,2009-01-08 22:20:24,2023-08-02 12:29:21,2020-03-08 23:08:46,,,javascript;jquery;checkbox;selected;checked,tpower,57016,18107,registered,true,426276,,CC BY-SA 4.0,2013-06-10 05:05:03,266,167,3,0,0,5,true,false,false,true,true,true,54,7,false,0.011,0.0012,6526,2009,1,22,Thursday,false,false,true,false,false,false,false 2669690,Why does Google prepend while(1); to their JSON responses?,"Why does Google prepend while(1); to their (private) JSON responses?
For example, here's a response while turning a calendar on and off in Google Calendar:
while (1);
[
['u', [
['smsSentFlag', 'false'],
['hideInvitations', 'false'],
['remindOnRespondedEventsOnly', 'true'],
['hideInvitations_remindOnRespondedEventsOnly', 'false_true'],
['Calendar ID stripped for privacy', 'false'],
['smsVerifiedFlag', 'true']
]]
]
I would assume this is to prevent people from doing an eval() on it, but all you'd really have to do is replace the while and then you'd be set. I would assume the eval prevention is to make sure people write safe JSON parsing code.
I've seen this used in a couple of other places, too, but a lot more so with Google (Mail, Calendar, Contacts, etc.) Strangely enough, Google Docs starts with &&&START&&& instead, and Google Contacts seems to start with while(1); &&&START&&&.
What's going on here?
",https://stackoverflow.com/questions/2669690/why-does-google-prepend-while1-to-their-json-responses,4510,612268.0,8.0,,,2010-04-19 18:00:09,2025-11-08 19:00:20,2020-01-03 22:03:52,,,javascript;json;ajax;security,Jess,43058,151495,registered,true,2669766,,CC BY-SA 4.0,2017-10-25 16:09:05,1262,997,6,2,0,4,true,false,false,true,true,true,58,9,true,0.013,0.0074,6060,2010,4,18,Monday,false,false,true,false,false,false,false 14994391,"Thinking in AngularJS" if I have a jQuery background?,"Suppose I'm familiar with developing client-side applications in jQuery, but now I'd like to start using AngularJS. Can you describe the paradigm shift that is necessary? Here are a few questions that might help you frame an answer:
I'm not looking for a detailed comparison between jQuery and AngularJS.
The following are two methods of building a link that has the sole purpose of running JavaScript code. Which is better, in terms of functionality, page load speed, validation purposes, etc.?
function myJsFunc() {
alert(""myJsFunc"");
}
<a href=""#"" onclick=""myJsFunc();"">Run JavaScript Code</a>
or
function myJsFunc() {
alert(""myJsFunc"");
}
<a href=""javascript:void(0)"" onclick=""myJsFunc();"">Run JavaScript Code</a>
I am looking for a JavaScript array insert method, in the style of:
arr.insert(index, item)
It should preferably be in jQuery, but any JavaScript implementation will do at this point.
",https://stackoverflow.com/questions/586182/how-can-i-insert-an-item-into-an-array-at-a-specific-index,4355,3698994.0,34.0,,,2009-02-25 14:29:30,2025-11-02 02:06:08,2025-11-02 01:09:59,,,javascript;arrays,tags2k,84775,192,registered,true,586189,,CC BY-SA 4.0,2014-09-14 19:26:59,223,185,1,0,0,2,true,false,false,true,true,true,59,13,true,0.009,0.0012,6478,2009,2,14,Wednesday,false,false,true,false,false,false,false 400212,How do I copy to the clipboard in JavaScript?,"How do I copy text to the clipboard (multi-browser)?
Related: How does Trello access the user's clipboard?
",https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript,4342,3115236.0,27.0,,,2008-12-30 13:09:05,2023-02-01 07:16:11,2022-07-17 00:28:25,,,javascript;clipboard;copy-paste,Santiago Corredoira,47296,4264,registered,true,30810322,,CC BY-SA 4.0,2013-05-11 21:46:59,236,111,0,1,0,3,true,false,false,true,true,true,45,9,true,0.009,0.0014,6535,2008,12,13,Tuesday,false,false,true,false,false,false,false 11832914,"How to round to at most 2 decimal places, if necessary","I'd like to round at most two decimal places, but only if necessary.
Input:
10
1.7777777
9.1
Output:
10
1.78
9.1
How can I do this in JavaScript?
",https://stackoverflow.com/questions/11832914/how-to-round-to-at-most-2-decimal-places-if-necessary,4337,4966651.0,95.0,,,2012-08-06 17:17:48,2026-08-06 12:15:24,2026-08-06 12:06:46,,,javascript;rounding;decimal-point,stinkycheeseman,46157,360705,registered,true,11832950,,CC BY-SA 4.0,2013-08-17 15:11:09,311,148,2,0,0,3,true,false,false,true,true,true,54,11,false,0.019,0.0009,5220,2012,8,17,Monday,false,false,true,false,false,false,false 1129216,Sort array of objects by string property value,"I have an array of JavaScript objects:
var objs = [
{ first_nom: 'Laszlo', last_nom: 'Jamf' },
{ first_nom: 'Pig', last_nom: 'Bodine' },
{ first_nom: 'Pirate', last_nom: 'Prentice' }
];
How can I sort them by the value of last_nom in JavaScript?
I know about sort(a,b), but that only seems to work on strings and numbers. Do I need to add a toString() method to my objects?
I saw this code:
this.vertical = vertical !== undefined ? !!vertical : this.vertical;
It seems to be using !! as an operator, which I don't recognize. What does it do?
Is there a string.Empty in JavaScript, or is it just a case of checking for ""?
How do I check if a particular key exists in a JavaScript object or array?
If a key doesn't exist, and I try to access it, will it return false? Or throw an error?
",https://stackoverflow.com/questions/1098040/checking-if-a-key-exists-in-a-javascript-object,4141,3852274.0,33.0,,,2009-07-08 13:21:32,2024-08-04 11:47:09,2020-01-30 09:24:38,,,javascript;arrays;object,Adam Ernst,54318,79,registered,true,1098955,,CC BY-SA 4.0,2013-12-05 20:21:55,179,165,0,0,0,3,true,false,false,true,true,true,48,9,true,0.009,0.0011,6345,2009,7,13,Wednesday,false,false,true,false,false,false,false 3010840,How to loop through the items of an array in JavaScript?,"In Java, you can use a for loop to traverse objects in an array as follows:
String[] myStringArray = {"Hello", "World"};
for (String s : myStringArray) {
// Do something
}
Can I do the same in JavaScript?
",https://stackoverflow.com/questions/3010840/how-to-loop-through-the-items-of-an-array-in-javascript,4097,5588326.0,46.0,,,2010-06-10 00:04:27,2026-04-12 07:59:59,2026-04-12 07:59:59,,,javascript;arrays;loops;for-loop,Mark Szymanski,58420,304725,registered,true,,,CC BY-SA 4.0,2014-03-17 02:31:46,320,230,2,0,0,4,false,false,false,true,true,true,56,11,true,0.008,0.0007,6008,2010,6,0,Thursday,false,false,true,false,false,false,false 951021,What is the JavaScript version of sleep()?,"Is there a better way to engineer a sleep in JavaScript than the following pausecomp function?
function pausecomp(millis)
{
var date = new Date();
var curDate = null;
do { curDate = new Date(); }
while(curDate-date < millis);
}
Unlike Sleep in JavaScript - delay between actions, I want a real sleep in the middle of a function, and not a delay before a piece of code executes.
",https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep,3982,5417348.0,97.0,,,2009-06-04 14:41:10,2025-10-22 19:19:24,2025-10-22 19:19:24,,,javascript;sleep,fmsf,37261,26004,registered,true,39914235,,CC BY-SA 4.0,2018-05-23 15:01:07,656,398,3,2,0,2,true,false,false,true,true,true,42,7,true,0.018,0.0007,6379,2009,6,14,Thursday,false,false,true,false,false,false,false 679915,How do I test for an empty JavaScript object?,"After an AJAX request, sometimes my application may return an empty object, like:
var a = {};
How can I check whether that's the case?
",https://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object,3888,4460078.0,41.0,,,2009-03-25 01:39:45,2023-05-23 22:44:12,2020-01-17 13:22:02,,,javascript;javascript-objects,falmp,39307,64784,registered,true,32108184,,CC BY-SA 4.0,2018-04-25 13:59:12,176,138,1,0,0,2,true,false,false,true,true,true,45,9,true,0.009,0.0009,6450,2009,3,1,Wednesday,false,false,true,false,false,false,false 1034621,Get the current URL with JavaScript?,"All I want is to get the website URL. Not the URL as taken from a link. On the page loading I need to be able to grab the full, current URL of the website and set it as a variable to do with as I please.
",https://stackoverflow.com/questions/1034621/get-the-current-url-with-javascript,3847,3998118.0,26.0,,,2009-06-23 19:26:45,2026-03-12 17:52:17,2017-09-23 23:41:54,,,javascript;url,dougoftheabaci,,,does_not_exist,true,1034642,,CC BY-SA 3.0,2013-05-30 02:56:32,211,204,0,0,0,2,true,false,false,true,false,true,36,6,true,0.007,0.001,6360,2009,6,19,Tuesday,false,false,true,false,false,false,false 728360,How do I correctly clone a JavaScript object?,"I have an object x. I'd like to copy it as object y, such that changes to y do not modify x. I realized that copying objects derived from built-in JavaScript objects will result in extra, unwanted properties. This isn't a problem, since I'm copying one of my own literal-constructed objects.
How do I correctly clone a JavaScript object?
",https://stackoverflow.com/questions/728360/how-do-i-correctly-clone-a-javascript-object,3830,2554188.0,83.0,,,2009-04-08 03:01:06,2024-09-14 22:59:13,2020-04-30 19:52:26,2025-11-11 11:48:28,Duplicate,javascript;clone;javascript-objects,soundly_typed,40662,49695,registered,true,728694,,,2014-04-05 12:41:45,405,339,4,0,0,3,true,true,false,true,true,true,45,8,true,0.032,0.0015,6436,2009,4,3,Wednesday,false,false,true,false,false,false,false 684672,How do I loop through or enumerate a JavaScript object?,"I have a JavaScript object like the following:
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
How do I loop through all of p's elements (p1, p2, p3...) and get their keys and values?
Can I convert a string representing a boolean value (e.g., 'true', 'false') into an intrinsic type in JavaScript?
I have a hidden form in HTML that is updated based on a user's selection within a list. This form contains some fields which represent boolean values and are dynamically populated with an intrinsic boolean value. However, once this value is placed into the hidden input field it becomes a string.
The only way I could find to determine the field's boolean value, once it was converted into a string, was to depend upon the literal value of its string representation.
var myValue = document.myForm.IS_TRUE.value;
var isTrueSet = myValue == 'true';
Is there a better way to accomplish this?
",https://stackoverflow.com/questions/263965/how-can-i-convert-a-string-to-boolean-in-javascript,3624,3657746.0,111.0,,,2008-11-05 00:13:08,2025-07-20 08:49:01,2024-02-29 21:29:12,,,javascript;boolean-expression;boolean-operations;string-conversion,Kevin,7956,4599,registered,true,264037,,CC BY-SA 4.0,2014-04-28 12:56:20,756,704,1,0,0,4,true,false,false,true,true,true,52,10,true,0.03,0.001,6590,2008,11,0,Wednesday,false,false,true,false,false,false,false 3552461,How do I format a date in JavaScript?,"How do I format a Javascript Date object as a string? (Preferable format: 10-Aug-2010)
How can I display JSON in an easy-to-read (for human readers) format? I'm looking primarily for indentation and whitespace, with perhaps even colors / font-styles / etc.
",https://stackoverflow.com/questions/4810841/pretty-print-json-using-javascript,3557,2019715.0,32.0,,,2011-01-26 22:33:53,2026-11-13 18:55:43,2020-02-24 00:04:40,,,javascript;json;pretty-print,Mark,70538,298406,registered,true,7220510,,CC BY-SA 4.0,2017-06-14 18:41:04,177,170,0,0,0,3,true,false,false,true,true,true,34,4,false,0.016,0.0018,5778,2011,1,22,Wednesday,false,false,true,false,false,false,false 805107,How can I assign a multiline string literal to a variable?,"How do I convert this Ruby code with a multiline string into JavaScript?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
",https://stackoverflow.com/questions/805107/how-can-i-assign-a-multiline-string-literal-to-a-variable,3523,2473301.0,41.0,,,2009-04-30 02:11:55,2024-11-30 20:59:45,2024-11-30 18:41:45,,,javascript;string;multiline;heredoc,Newy,40337,95956,registered,true,805113,,CC BY-SA 4.0,2013-12-12 03:03:13,208,138,1,0,0,4,true,false,false,true,true,true,58,11,true,0.017,0.0014,6414,2009,4,2,Thursday,false,false,true,false,false,false,false
1986896,What is the difference between call and apply?,"What is the difference between using Function.prototype.apply() and Function.prototype.call() to invoke a function?
const func = function() {
alert("Hello world!");
};
func.apply() vs. func.call()
Are there performance differences between the two aforementioned methods? When is it best to use call over apply and vice versa?
How can I change the class of an HTML element in response to an onclick or any other events using JavaScript?
I need to be able to merge two (very simple) JavaScript objects at runtime. For example I'd like to:
var obj1 = { food: 'pizza', car: 'ford' }
var obj2 = { animal: 'dog' }
obj1.merge(obj2);
//obj1 now has three properties: food, car, and animal
Is there a built in way to do this? I do not need recursion, and I do not need to merge functions, just methods on flat objects.
",https://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects,3376,2121548.0,69.0,,,2008-10-05 00:30:54,2024-09-17 04:16:14,2024-02-21 17:14:37,,,javascript;javascript-objects,JC Grubbs,40641,4541,registered,true,171256,,CC BY-SA 4.0,2014-06-11 17:50:12,415,377,1,0,0,2,true,false,false,true,true,true,53,9,true,0.033,0.0016,6621,2008,10,0,Sunday,true,false,true,false,false,false,false 20035101,"Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?","Mod note: This question is about why
XMLHttpRequest/fetch/etc. on the browser are subject to the Same Access Policy restrictions (you get errors mentioning CORB or CORS) while Postman is not. This question is not about how to fix a "No 'Access-Control-Allow-Origin'..." error. It's about why they happen.
Please stop posting:
- CORS configurations for every language/framework under the sun. Instead find your relevant language/framework's question.
- 3rd party services that allow a request to circumvent CORS
- Command line options for turning off CORS for various browsers
I am trying to do authorization using JavaScript by connecting to the RESTful API built-in Flask. However, when I make the request, I get the following error:
XMLHttpRequest cannot load http://myApiUrl/login.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'null' is therefore not allowed access.
I know that the API or remote resource must set the header, but why did it work when I made the request via the Chrome extension Postman?
This is the request code:
$.ajax({
type: 'POST',
dataType: 'text',
url: api,
username: 'user',
password: 'pass',
crossDomain: true,
xhrFields: {
withCredentials: true,
},
})
.done(function (data) {
console.log('done');
})
.fail(function (xhr, textStatus, errorThrown) {
alert(xhr.responseText);
alert(textStatus);
});
",https://stackoverflow.com/questions/20035101/why-does-my-javascript-code-receive-a-no-access-control-allow-origin-header-i,3369,6595838.0,9.0,,,2013-11-17 19:29:06,2024-12-13 09:23:49,2023-03-28 15:50:48,,,javascript;jquery;cors;postman;same-origin-policy,Mr Jedi,34835,2140160,registered,true,20035319,,CC BY-SA 4.0,2015-04-17 16:02:57,2320,1421,4,6,0,5,true,false,false,true,true,true,165,21,true,0.001,0.0005,4752,2013,11,19,Sunday,true,false,true,false,false,false,false
4775722,How can I check if an object is an array?,"I'm trying to write a function that either accepts a list of strings, or a single string. If it's a string, then I want to convert it to an array with just the one item so I can loop over it without fear of an error.
So how do I check if the variable is an array?
",https://stackoverflow.com/questions/4775722/how-can-i-check-if-an-object-is-an-array,3361,2121813.0,51.0,,,2011-01-23 18:53:04,2021-08-30 20:18:06,2021-08-14 07:41:03,2021-10-26 13:53:09,Duplicate,javascript;arrays;javascript-objects,mpen,285759,65387,registered,true,20956445,,,2015-09-23 18:27:55,278,264,0,0,0,3,true,true,false,true,true,true,41,10,true,0.024,0.0016,5781,2011,1,18,Sunday,true,false,true,false,false,false,false 37576685,Using async/await with a forEach loop,"Are there any issues with using async/await in a forEach loop? I'm trying to loop through an array of files and await on the contents of each file.
import fs from 'fs-promise'
async function printFiles () {
const files = await getFilePaths() // Assume this works fine
files.forEach(async (file) => {
const contents = await fs.readFile(file, 'utf8')
console.log(contents)
})
}
printFiles()
This code does work, but could something go wrong with this? I had someone tell me that you're not supposed to use async/await in a higher-order function like this, so I just wanted to ask if there was any issue with this.
When I want to prevent other event handlers from executing after a certain event is fired, I can use one of two techniques. I'll use jQuery in the examples, but this applies to plain-JS as well:
event.preventDefault()$('a').click(function (e) {
// custom handling here
e.preventDefault();
});
return false$('a').click(function () {
// custom handling here
return false;
});
Is there any significant difference between those two methods of stopping event propagation?
For me, return false; is simpler, shorter and probably less error prone than executing a method. With the method, you have to remember about correct casing, parenthesis, etc.
Also, I have to define the first parameter in callback to be able to call the method. Perhaps, there are some reasons why I should avoid doing it like this and use preventDefault instead? What's the better way?
var funcs = [];
// let's create 3 functions
for (var i = 0; i < 3; i++) {
// and store them in funcs
funcs[i] = function() {
// each should log its value.
console.log(""My value:"", i);
};
}
for (var j = 0; j < 3; j++) {
// and now let's run each one to see
funcs[j]();
}
It outputs this:
My value: 3
My value: 3
My value: 3
Whereas I'd like it to output:
My value: 0
My value: 1
My value: 2
The same problem occurs when the delay in running the function is caused by using event listeners:
var buttons = document.getElementsByTagName(""button"");
// let's create 3 functions
for (var i = 0; i < buttons.length; i++) {
// as event listeners
buttons[i].addEventListener(""click"", function() {
// each should log its value.
console.log(""My value:"", i);
});
}
<button>0</button>
<br />
<button>1</button>
<br />
<button>2</button>
… or asynchronous code, e.g. using Promises:
// Some async wait function
const wait = (ms) => new Promise((resolve, reject) => setTimeout(resolve, ms));
for (var i = 0; i < 3; i++) {
// Log `i` as soon as each promise resolves.
wait(i * 100).then(() => console.log(i));
}
It is also apparent in for in and for of loops:
const arr = [1,2,3];
const fns = [];
for (var i in arr){
fns.push(() => console.log(""index:"", i));
}
for (var v of arr){
fns.push(() => console.log(""value:"", v));
}
for (const n of arr) {
var obj = { number: n }; // or new MyLibObject({ ... })
fns.push(() => console.log(""n:"", n, ""|"", ""obj:"", JSON.stringify(obj)));
}
for(var f of fns){
f();
}
What’s the solution to this basic problem?
",https://stackoverflow.com/questions/750486/how-to-ensure-closures-created-in-a-loop-capture-the-value-of-the-loop-variable,3264,500403.0,45.0,,,2009-04-15 06:06:20,2026-03-07 08:12:31,2026-03-07 08:12:31,,,javascript;loops;closures,nickf,548426,9021,registered,true,750506,,CC BY-SA 4.0,2014-05-11 03:11:13,2808,1705,7,0,0,3,true,false,false,true,true,true,112,19,true,0.09,0.0065,6429,2009,4,6,Wednesday,false,false,true,false,false,false,false 27509,Detecting an undefined object property,"How do I check if an object property in JavaScript is undefined?
",https://stackoverflow.com/questions/27509/detecting-an-undefined-object-property,3247,1531591.0,49.0,,,2008-08-26 07:25:08,2023-08-21 11:42:18,2022-08-16 15:34:01,,,javascript;object;undefined;object-property,Matt Sheppard,118363,797,registered,true,416327,,CC BY-SA 4.0,2012-04-25 08:45:21,72,65,0,0,0,4,true,false,false,true,true,true,38,5,false,0.032,0.0021,6661,2008,8,7,Tuesday,false,false,true,false,false,false,false 23569441,Is it possible to apply CSS to half of a character?,"What I am looking for:
A way to style one HALF of a character. (In this case, half the letter being transparent)
What I have currently searched for and tried (With no luck):
Below is an example of what I am trying to obtain.
Does a CSS or JavaScript solution exist for this, or am I going to have to resort to images? I would prefer not to go the image route as this text will end up being generated dynamically.
",https://stackoverflow.com/questions/23569441/is-it-possible-to-apply-css-to-half-of-a-character,3194,301192.0,20.0,,,2014-05-09 16:16:57,2025-10-13 13:30:39,2024-03-17 19:44:15,,,javascript;html;css,SimplyAzuma,25654,3009513,registered,true,23569891,,CC BY-SA 4.0,2014-05-13 16:05:22,728,546,0,0,1,3,true,false,false,true,true,true,51,11,true,0.066,0.0106,4579,2014,5,16,Friday,false,false,true,false,false,false,false 31044,Is there an "exists" function for jQuery?,"How can I check the existence of an element in jQuery?
The current code that I have is this:
if ($(selector).length > 0) {
// Do something
}
Is there a more elegant way to approach this? Perhaps a plugin or a function?
",https://stackoverflow.com/questions/31044/is-there-an-exists-function-for-jquery,3166,880030.0,17.0,,,2008-08-27 19:49:41,2024-10-05 06:32:55,2017-12-16 11:29:03,,,javascript;jquery,Jake McGraw,56216,302,registered,true,587408,,CC BY-SA 3.0,2013-04-08 03:55:15,275,230,1,0,0,2,true,false,false,true,true,true,51,7,true,0.019,0.0036,6660,2008,8,19,Wednesday,false,false,true,false,false,false,false 166221,How can I upload files asynchronously with jQuery?,"I would like to upload a file asynchronously with jQuery.
$(document).ready(function () {
$(""#uploadbutton"").click(function () {
var filename = $(""#file"").val();
$.ajax({
type: ""POST"",
url: ""addFile.do"",
enctype: 'multipart/form-data',
data: {
file: filename
},
success: function () {
alert(""Data Uploaded: "");
}
});
});
});
<script src=""https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js""></script>
<span>File</span>
<input type=""file"" id=""file"" name=""file"" size=""10""/>
<input id=""uploadbutton"" type=""button"" value=""Upload""/>
Instead of the file being uploaded, I am only getting the filename. What can I do to fix this problem?
",https://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously-with-jquery,3163,1519643.0,34.0,,,2008-10-03 10:22:17,2023-05-22 08:51:36,2021-06-03 07:58:52,,,javascript;jquery;ajax;asynchronous;xmlhttprequest,Sergio del Amo,78326,2138,registered,true,,,CC BY-SA 4.0,2010-08-30 11:41:16,1173,863,2,0,0,5,false,false,false,true,true,true,50,8,true,0.022,0.0021,6623,2008,10,10,Friday,false,false,true,false,false,false,false 5515310,"Is there a standard function to check for null, undefined, or blank variables in JavaScript?","Is there a universal JavaScript function that checks that a variable has a value and ensures that it's not undefined or null? I've got this code, but I'm not sure if it covers all cases:
function isEmpty(val){
return (val === undefined || val == null || val.length <= 0) ? true : false;
}
",https://stackoverflow.com/questions/5515310/is-there-a-standard-function-to-check-for-null-undefined-or-blank-variables-in,3150,3152633.0,47.0,,,2011-04-01 15:14:24,2024-03-07 12:44:58,2023-05-30 18:39:09,2023-05-26 20:13:23,Duplicate,javascript;null;comparison;undefined,Alex,36119,177416,registered,true,5515349,,,2018-03-29 07:53:11,354,297,3,0,0,4,true,true,false,true,true,true,92,15,true,0.015,0.001,5713,2011,4,15,Friday,false,false,true,false,false,false,false
4351521,How do I pass command line arguments to a Node.js program and receive them?,"I have a web server written in Node.js and I would like to launch with a specific folder. I'm not sure how to access arguments in JavaScript. I'm running node like this:
$ node server.js folder
here server.js is my server code. Node.js help says this is possible:
$ node -h
Usage: node [options] script.js [arguments]
How would I access those arguments in JavaScript? Somehow I was not able to find this information on the web.
",https://stackoverflow.com/questions/4351521/how-do-i-pass-command-line-arguments-to-a-node-js-program-and-receive-them,3147,1982484.0,42.0,,,2010-12-04 01:56:46,2025-03-04 17:54:34,2023-08-25 21:04:22,,,javascript;node.js;arguments;command-line-arguments,milkplus,34575,245777,registered,true,4351548,,CC BY-SA 4.0,2018-12-20 04:44:57,584,434,3,1,0,4,true,false,false,true,true,true,75,14,true,0.021,0.0016,5831,2010,12,1,Saturday,true,false,true,false,false,false,false 3390396,How can I check for "undefined" in JavaScript?,"What is the most appropriate way to test if a variable is undefined in JavaScript?
I've seen several possible ways:
if (window.myVariable)
Or
if (typeof(myVariable) != "undefined")
Or
if (myVariable) // This throws an error if undefined. Should this be in Try/Catch?
",https://stackoverflow.com/questions/3390396/how-can-i-check-for-undefined-in-javascript,3108,3818447.0,16.0,,,2010-08-02 17:53:29,2020-07-24 23:25:26,2020-07-24 23:25:26,2014-10-10 13:59:07,Duplicate,javascript;undefined,makerofthings7,61859,328397,registered,true,3390426,,,2013-10-15 23:34:50,380,280,3,0,0,2,true,true,false,true,true,true,56,8,true,0.004,0.0008,5955,2010,8,17,Monday,false,false,true,false,false,false,false
2010892,How to store objects in HTML5 localStorage/sessionStorage,"I'd like to store a JavaScript object in HTML5 localStorage, but my object is apparently being converted to a string.
I can store and retrieve primitive JavaScript types and arrays using localStorage, but objects don't seem to work. Should they?
Here's my code:
var testObject = { 'one': 1, 'two': 2, 'three': 3 };
console.log('typeof testObject: ' + typeof testObject);
console.log('testObject properties:');
for (var prop in testObject) {
console.log(' ' + prop + ': ' + testObject[prop]);
}
// Put the object into storage
localStorage.setItem('testObject', testObject);
// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');
console.log('typeof retrievedObject: ' + typeof retrievedObject);
console.log('Value of retrievedObject: ' + retrievedObject);
The console output is
typeof testObject: object
testObject properties:
one: 1
two: 2
three: 3
typeof retrievedObject: string
Value of retrievedObject: [object Object]
It looks to me like the setItem method is converting the input to a string before storing it.
I see this behavior in Safari, Chrome, and Firefox, so I assume it's my misunderstanding of the HTML5 Web Storage specification, not a browser-specific bug or limitation.
I've tried to make sense of the structured clone algorithm described in 2 Common infrastructure. I don't fully understand what it's saying, but maybe my problem has to do with my object's properties not being enumerable (???).
Is there an easy workaround?
Update: The W3C eventually changed their minds about the structured-clone specification, and decided to change the spec to match the implementations. See 12111 – spec for Storage object getItem(key) method does not match implementation behavior. So this question is no longer 100% valid, but the answers still may be of interest.
",https://stackoverflow.com/questions/2010892/how-to-store-objects-in-html5-localstorage-sessionstorage,3103,1500491.0,24.0,,,2010-01-06 04:05:51,2023-10-11 19:44:18,2022-09-13 08:02:56,,,javascript;html;local-storage,Kristopher Johnson,82804,1175,registered,true,2010948,,CC BY-SA 4.0,2013-06-23 10:10:37,2307,1832,5,3,0,3,true,false,false,true,true,true,57,7,false,0.016,0.0021,6163,2010,1,4,Wednesday,false,false,true,false,false,false,false 824349,How do I modify the URL without reloading the page?,"Is there a way I can modify the URL of the current page without reloading the page?
I would like to access the portion before the # hash if possible.
I only need to change the portion after the domain, so it's not like I'm violating cross-domain policies.
window.location.href = "www.mysite.com/page2.php"; // this reloads
",https://stackoverflow.com/questions/824349/how-do-i-modify-the-url-without-reloading-the-page,3085,2209461.0,22.0,,,2009-05-05 10:54:05,2025-08-04 09:15:58,2022-04-29 20:16:48,,,javascript;html;url;url-rewriting;friendly-url,Robin Rodricks,114780,41021,registered,true,3354511,,CC BY-SA 4.0,2014-03-12 20:04:37,415,336,1,0,0,5,true,false,false,true,true,true,51,10,true,0.01,0.0014,6409,2009,5,10,Tuesday,false,false,true,false,false,false,false
5223,Length of a JavaScript object,"I have a JavaScript object. Is there a built-in or accepted best practice way to get the length of this object?
const myObject = new Object();
myObject["firstname"] = "Gareth";
myObject["lastname"] = "Simpson";
myObject["age"] = 21;
",https://stackoverflow.com/questions/5223/length-of-a-javascript-object,3083,3114058.0,43.0,,,2008-08-07 19:42:21,2025-02-01 19:20:27,2023-04-03 06:42:52,,,javascript;object;javascript-objects,Gareth Simpson,37861,147,registered,true,6700,,CC BY-SA 4.0,2013-04-04 17:18:05,315,284,1,0,0,3,true,false,false,true,true,true,29,5,false,0.014,0.001,6680,2008,8,19,Thursday,false,false,true,false,false,false,false
596351,How can I know which radio button is selected via jQuery?,"I have two radio buttons and want to post the value of the selected one. How can I get the value with jQuery?
I can get all of them like this:
$(""form :radio"")
How do I know which one is selected?
",https://stackoverflow.com/questions/596351/how-can-i-know-which-radio-button-is-selected-via-jquery,3080,2558171.0,39.0,,,2009-02-27 19:53:27,2022-09-13 05:12:25,2020-01-10 15:06:37,,,javascript;jquery;html;jquery-selectors;radio-button,juan,82342,1782,registered,true,596369,,CC BY-SA 4.0,2014-03-25 19:25:23,246,201,1,0,0,5,true,false,false,true,true,true,57,11,true,0.015,0.0012,6476,2009,2,19,Friday,false,false,true,false,false,false,false 1531093,How do I get the current date in JavaScript?,"How do I get the current date in JavaScript?
",https://stackoverflow.com/questions/1531093/how-do-i-get-the-current-date-in-javascript,3049,4383411.0,64.0,,,2009-10-07 11:39:02,2026-03-27 21:23:24,2021-01-14 23:51:10,,,javascript;date;date-formatting,Suresh,39657,96180,registered,true,4929629,,CC BY-SA 4.0,2012-02-12 07:54:33,52,45,0,0,0,3,true,false,false,true,true,true,44,9,true,0.015,0.0007,6254,2009,10,11,Wednesday,false,false,true,false,false,false,false 152975,How do I detect a click outside an element?,"I have some HTML menus, which I show completely when a user clicks on the head of these menus. I would like to hide these elements when the user clicks outside the menus' area.
Is something like this possible with jQuery?
$(""#menuscontainer"").clickOutsideThisElement(function() {
// Hide the menus
});
",https://stackoverflow.com/questions/152975/how-do-i-detect-a-click-outside-an-element,2975,1846258.0,91.0,,,2008-09-30 13:17:12,2023-03-27 23:51:46,2020-01-04 19:07:46,,,javascript;jquery;click,Sergio del Amo,78326,2138,registered,true,153047,,CC BY-SA 4.0,2013-06-24 20:59:56,347,309,1,0,0,3,true,false,false,true,true,true,43,9,true,0.049,0.0016,6626,2008,9,13,Tuesday,false,false,true,false,false,false,false
4907843,Open a URL in a new tab (and not a new window),"I'm trying to open a URL in a new tab, as opposed to a popup window.
I've seen related questions where the responses would look something like:
window.open(url,'_blank');
window.open(url);
But none of them worked for me, the browser still tried to open a popup window.
",https://stackoverflow.com/questions/4907843/open-a-url-in-a-new-tab-and-not-a-new-window,2952,4070046.0,32.0,,,2011-02-05 15:52:13,2024-12-20 11:10:45,2021-11-29 07:19:06,,,javascript;tabs;href,Mark,41533,137100,registered,true,4907854,,CC BY-SA 4.0,2013-08-27 14:40:13,383,273,1,1,0,3,true,false,false,true,true,true,46,12,false,0.008,0.0007,5768,2011,2,15,Saturday,true,false,true,false,false,false,false 332872,Encode URL in JavaScript,"How do you safely encode a URL using JavaScript such that it can be put into a GET string?
var myUrl = ""http://example.com/index.html?param=1&anotherParam=2"";
var myOtherUrl = ""http://example.com/index.html?url="" + myUrl;
I assume that you need to encode the myUrl variable on that second line?
I have an array of numbers that I need to make sure are unique. I found the code snippet below on the Internet, and it works great until the array has a zero in it. I found this other script here on Stack Overflow that looks almost exactly like it, but it doesn't fail.
How can I determine where the prototype script is going wrong?
Array.prototype.getUnique = function() {
var o = {}, a = [], i, e;
for (i = 0; e = this[i]; i++) {o[e] = 1};
for (e in o) {a.push (e)};
return a;
}
",https://stackoverflow.com/questions/1960473/get-all-unique-values-in-a-javascript-array-remove-duplicates,2927,3765728.0,94.0,,,2009-12-25 04:28:23,2025-08-05 16:57:20,2025-08-05 16:57:20,2024-04-10 08:54:43,Duplicate,javascript;unique;arrays,Mottie,86817,145346,registered,true,14438954,,,,586,490,1,1,0,3,true,true,false,true,true,true,63,10,false,0.025,0.0008,6175,2009,12,4,Friday,false,false,true,false,false,false,false
1349404,Generate a string of random characters,"I want a string of fixed length, composed of characters picked randomly from a set of characters e.g. [a-zA-Z0-9].
How can I do this with JavaScript?
",https://stackoverflow.com/questions/1349404/generate-a-string-of-random-characters,2915,3166046.0,94.0,,,2009-08-28 21:14:41,2025-10-28 16:37:44,2025-03-13 21:29:26,,,javascript;string;random,Tom Lehman,89939,25068,registered,true,1349426,,CC BY-SA 4.0,2013-11-03 04:41:37,177,150,1,0,0,3,true,false,false,true,true,true,38,6,false,0.03,0.0009,6294,2009,8,21,Friday,false,false,true,false,false,false,false 351409,How to append something to an array?,"How do I append an object (such as a string or number) to an array in JavaScript?
",https://stackoverflow.com/questions/351409/how-to-append-something-to-an-array,2889,5524673.0,30.0,,,2008-12-09 00:20:05,2024-09-25 10:42:20,2017-09-10 19:21:27,,,javascript;arrays;append,interstar,27626,8482,registered,true,351421,,CC BY-SA 3.0,,99,92,0,0,0,3,true,false,false,true,true,true,36,7,true,0.005,0.0005,6556,2008,12,0,Tuesday,false,false,true,false,false,false,false 4059147,Check if a variable is a string in JavaScript,"How can I determine whether a variable is a string or something else in JavaScript?
",https://stackoverflow.com/questions/4059147/check-if-a-variable-is-a-string-in-javascript,2882,3102861.0,34.0,,,2010-10-30 14:36:34,2026-10-07 06:41:13,2021-03-13 20:37:09,,,javascript;string,Olical,41742,455137,registered,true,4059166,,CC BY-SA 4.0,2018-12-20 04:51:25,91,84,0,0,0,2,true,false,false,true,true,true,45,9,false,0.011,0.0009,5866,2010,10,14,Saturday,true,false,true,false,false,false,false 492994,Compare two dates with JavaScript,"Can someone suggest a way to compare the values of two dates greater than, less than, and not in the past using JavaScript? The values will be coming from text boxes.
",https://stackoverflow.com/questions/492994/compare-two-dates-with-javascript,2867,3605271.0,47.0,,,2009-01-29 19:14:06,2026-08-13 18:51:43,2020-02-27 19:37:15,,,javascript;date;datetime;compare,Alex,40715,41508,registered,true,493018,,CC BY-SA 4.0,2015-10-05 09:21:28,191,167,0,0,0,4,true,false,false,true,true,true,33,5,false,0.013,0.0008,6505,2009,1,19,Thursday,false,false,true,false,false,false,false 2901102,How can I format a number with commas as thousands separators?,"I am trying to print an integer in JavaScript with commas as thousands separators. For example, I want to show the number 1234567 as "1,234,567". How would I go about doing this?
Here is how I am doing it:
function numberWithCommas(x) {
x = x.toString();
var pattern = /(-?\d+)(\d{3})/;
while (pattern.test(x))
x = x.replace(pattern, ""$1,$2"");
return x;
}
console.log(numberWithCommas(1000))
Is there a simpler or more elegant way to do it? It would be nice if it works with floats also, but that is not necessary. It does not need to be locale-specific to decide between periods and commas.
",https://stackoverflow.com/questions/2901102/how-can-i-format-a-number-with-commas-as-thousands-separators,2782,2343650.0,53.0,,,2010-05-24 23:42:31,2026-10-24 07:18:13,2025-12-19 14:14:38,,,javascript;formatting;numbers,Elias Zamaria,101994,28324,registered,true,2901298,,CC BY-SA 4.0,2015-05-25 21:56:39,929,632,1,0,0,3,true,false,false,true,true,true,62,11,true,0.023,0.0012,6025,2010,5,23,Monday,false,false,true,false,false,false,false 5404839,How do I refresh a page using JavaScript?,"How do I refresh a page using JavaScript?
",https://stackoverflow.com/questions/5404839/how-do-i-refresh-a-page-using-javascript,2763,3227834.0,20.0,,,2011-03-23 11:55:31,2026-04-28 08:57:51,2022-07-17 06:23:26,,,javascript;jquery;refresh;reload,luca,37232,505762,registered,true,5404869,,CC BY-SA 4.0,2014-05-07 09:06:51,49,42,0,0,0,4,true,false,false,true,true,true,41,8,true,0.006,0.0009,5722,2011,3,11,Wednesday,false,false,true,false,false,false,false 6677035,Scroll to an element with jQuery,"I have this input element:
<input type="text" class="textfield" value="" id="subject" name="subject">
Then I have some other elements, like other tag's & <textarea> tag's, etc...
When the user clicks on the <input id="#subject">, the page should scroll to the page's last element, and it should do so with a nice animation (It should be a scroll to bottom and not to top).
The last item of the page is a submit button with #submit:
<input type="submit" class="submit" id="submit" name="submit" value="Ok, Done.">
The animation should not be too fast and should be fluid.
I am running the latest jQuery version. I prefer to not install any plugin but to use the default jQuery features to achieve this.
",https://stackoverflow.com/questions/6677035/scroll-to-an-element-with-jquery,2732,3249858.0,33.0,,,2011-07-13 09:49:44,2023-08-15 10:19:38,2022-06-14 23:32:41,,,javascript;jquery;scroll,DiegoP.,45865,735997,registered,true,6677069,,CC BY-SA 4.0,2012-08-21 15:41:34,1009,845,7,0,0,3,true,false,false,true,true,true,32,6,false,0.01,0.0008,5610,2011,7,9,Wednesday,false,false,true,false,false,false,false 2647867,How can I determine if a variable is 'undefined' or 'null'?,"How do I determine if a variable is undefined or null?
My code is as follows:
var EmpName = $("div#esd-names div#name").attr('class');
if(EmpName == 'undefined'){
// DO SOMETHING
};
<div id="esd-names">
<div id="name"></div>
</div>
But when I do this, the JavaScript interpreter halts execution.
",https://stackoverflow.com/questions/2647867/how-can-i-determine-if-a-variable-is-undefined-or-null,2718,3557949.0,33.0,,,2010-04-15 18:12:16,2023-12-04 17:15:49,2023-03-16 17:13:59,,,javascript;jquery;variables;null;undefined,sadmicrowave,41100,281488,registered,true,2647888,,CC BY-SA 4.0,2013-10-23 21:42:30,528,357,4,0,0,5,true,false,false,true,true,true,75,11,true,0.009,0.0008,6064,2010,4,18,Thursday,false,false,true,false,false,false,false 48270127,Can (a== 1 && a ==2 && a==3) ever evaluate to true?,"Moderator note: Please resist the urge to edit the code or remove this notice. The pattern of whitespace may be part of the question and therefore should not be tampered with unnecessarily. If you are in the "whitespace is insignificant" camp, you should be able to accept the code as is.
How is it ever possible that (a== 1 && a ==2 && a==3) could evaluate to true in JavaScript?
This is an interview question asked by a major tech company. We never write such code in our day-to-day job.
",https://stackoverflow.com/questions/48270127/can-a-1-a-2-a-3-ever-evaluate-to-true,2703,435717.0,28.0,,,2018-01-15 20:20:47,2026-01-27 22:01:28,2026-01-27 22:01:28,,,javascript;ecmascript-6,Dimpu Aravind Buddha,9895,1165332,registered,true,48270314,,CC BY-SA 4.0,2018-01-16 16:45:21,607,518,2,0,0,2,true,false,false,true,true,true,67,12,true,0.064,0.0062,3232,2018,1,20,Monday,false,false,true,false,false,false,false 901115,How can I get query string values in JavaScript?,"Is there a plugin-less way of retrieving query string values via jQuery (or without)?
If so, how? If not, is there a plugin which can do so?
",https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript,2693,5525828.0,73.0,,,2009-05-23 08:10:48,2023-06-06 10:08:34,2015-04-07 00:55:08,,,javascript;url;plugins;query-string,Subliminal Hash,13772,49742,registered,true,901144,,CC BY-SA 3.0,2011-10-23 15:27:31,239,143,0,1,0,4,true,false,false,true,true,true,48,9,true,0.013,0.0005,6391,2009,5,8,Saturday,true,false,true,false,false,false,false 894860,Set a default parameter value for a JavaScript function,"I would like a JavaScript function to have optional arguments which I set a default on, which get used if the value isn't defined (and ignored if the value is passed). In Ruby you can do it like this:
def read_file(file, delete_after = false)
# code
end
Does this work in JavaScript?
function read_file(file, delete_after = false) {
// Code
}
",https://stackoverflow.com/questions/894860/set-a-default-parameter-value-for-a-javascript-function,2690,1500922.0,30.0,,,2009-05-21 20:07:17,2025-08-14 03:36:04,2020-06-30 14:30:47,,,javascript;function;parameters;arguments;default-parameters,Tilendor,49013,1470,registered,true,894877,,CC BY-SA 4.0,2015-10-05 09:18:20,414,352,2,0,0,5,true,false,false,true,true,true,55,9,false,0.02,0.0018,6393,2009,5,20,Thursday,false,false,true,false,false,false,false
171027,Adding a table row in jQuery,"I'm using jQuery to add an additional row to a table as the last row.
I have done it this way:
$('#myTable').append('<tr><td>my data</td><td>more data</td></tr>');
Are there limitations to what you can add to a table like this (such as inputs, selects, number of rows)? Is there a different way to do it?
",https://stackoverflow.com/questions/171027/adding-a-table-row-in-jquery,2675,2060131.0,42.0,,,2008-10-04 21:33:10,2022-08-16 15:48:14,2022-08-16 15:48:14,,,javascript;jquery;html-table,Darryl Hein,145615,5441,registered,true,171049,,CC BY-SA 4.0,2011-01-23 10:07:15,387,342,1,0,0,3,true,false,false,true,true,true,28,6,false,0.02,0.0013,6622,2008,10,21,Saturday,true,false,true,false,false,false,false 952924,How do I chop/slice/trim off last character in string using Javascript?,"I have a string, 12345.00, and I would like it to return 12345.0.
I have looked at trim, but it looks like it is only trimming whitespace and slice which I don't see how this would work. Any suggestions?
Is there a way to generate a random number in a specified range with JavaScript ?
For example: a specified range from 1 to 6 were the random number could be either 1, 2, 3, 4, 5, or 6.
",https://stackoverflow.com/questions/4959975/generate-random-number-between-two-numbers-in-javascript,2619,2732568.0,34.0,,,2011-02-10 16:41:22,2024-06-03 13:50:18,2022-04-30 08:13:46,,,javascript;random,Mirgorod,32957,568975,registered,true,4960020,,CC BY-SA 4.0,2018-02-04 01:31:17,252,185,0,0,0,2,true,false,false,true,true,true,56,8,false,0.012,0.001,5763,2011,2,16,Thursday,false,false,true,false,false,false,false 1133770,How can I convert a string to an integer in JavaScript?,"How do I convert a string to an integer in JavaScript?
",https://stackoverflow.com/questions/1133770/how-can-i-convert-a-string-to-an-integer-in-javascript,2601,2915869.0,32.0,,,2009-07-15 20:22:48,2026-08-20 21:38:35,2025-08-05 17:12:10,,,javascript;string;integer;data-conversion,,,,does_not_exist,true,1133814,,CC BY-SA 4.0,2014-06-18 09:16:06,62,55,0,0,0,4,true,false,false,true,false,true,55,11,true,0.011,0.0009,6338,2009,7,20,Wednesday,false,false,true,false,false,false,false 1414365,Disable/enable an input with jQuery?,"$input.disabled = true;
or
$input.disabled = ""disabled"";
Which is the standard way? And, conversely, how do you enable a disabled input?
",https://stackoverflow.com/questions/1414365/disable-enable-an-input-with-jquery,2596,2745952.0,19.0,,,2009-09-12 05:21:54,2023-03-29 18:57:52,2020-01-09 18:55:00,,,javascript;jquery;html-input;disabled-input,omg,141172,104015,registered,true,1414366,,CC BY-SA 4.0,2015-06-30 13:22:48,205,143,2,0,0,4,true,false,false,true,true,true,36,5,true,0.007,0.0009,6279,2009,9,5,Saturday,true,false,true,false,false,false,false 18082,Validate decimal numbers in JavaScript - IsNumeric(),"What's the cleanest, most effective way to validate decimal numbers in JavaScript?
Bonus points for:
Test cases:
01. IsNumeric('-1') => true
02. IsNumeric('-1.5') => true
03. IsNumeric('0') => true
04. IsNumeric('0.42') => true
05. IsNumeric('.42') => true
06. IsNumeric('99,999') => false
07. IsNumeric('0x89f') => false
08. IsNumeric('#abcdef') => false
09. IsNumeric('1.2.3') => false
10. IsNumeric('') => false
11. IsNumeric('blah') => false
",https://stackoverflow.com/questions/18082/validate-decimal-numbers-in-javascript-isnumeric,2575,1591141.0,53.0,,,2008-08-20 14:21:13,2026-09-23 06:07:11,2016-12-07 03:57:31,,,javascript;validation;numbers,Michael Haren,108788,29,registered,true,1830844,,CC BY-SA 3.0,2013-01-06 20:57:32,656,584,1,0,0,3,true,false,false,true,true,true,52,7,false,0.033,0.0016,6667,2008,8,14,Wednesday,false,false,true,false,false,false,false
1527803,Generating random whole numbers in JavaScript in a specific range,"How can I generate random whole numbers between two specified variables in JavaScript, e.g. x = 4 and y = 8 would output any of 4, 5, 6, 7, 8?
I have a very simple JavaScript array that may or may not contain duplicates.
var names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];
I need to remove the duplicates and put the unique values in a new array.
I could point to all the code that I've tried but I think it's useless because they don't work. I accept jQuery solutions too.
How can I get the selected text (not the selected value) from a drop-down list in jQuery?
",https://stackoverflow.com/questions/1643227/get-selected-text-from-a-drop-down-list-select-box-using-jquery,2550,2422578.0,35.0,,,2009-10-29 12:02:09,2021-10-20 14:48:08,2021-01-30 15:25:01,,,javascript;jquery;dom;drop-down-menu;jquery-selectors,haddar,25715,170231,unregistered,true,1643247,,CC BY-SA 4.0,2012-03-03 17:55:49,114,90,0,0,0,5,true,false,false,true,true,true,65,11,false,0.014,0.0011,6232,2009,10,12,Thursday,false,false,true,false,false,false,false 149055,How to format numbers as currency strings?,"I would like to format a price in JavaScript. I'd like a function which takes a float as an argument and returns a string formatted like this:
$ 2,500.00
How can I do this?
",https://stackoverflow.com/questions/149055/how-to-format-numbers-as-currency-strings,2528,2965024.0,67.0,,,2008-09-29 15:00:28,2025-09-26 17:14:08,2025-07-25 18:16:05,,,javascript;formatting;currency;number-formatting,Daniel Magliola,32812,3314,registered,true,149150,,CC BY-SA 4.0,2013-02-11 09:46:45,238,174,3,0,0,4,true,false,false,true,true,true,42,7,true,0.023,0.0009,6627,2008,9,15,Monday,false,false,true,false,false,false,false 5874652,.prop() vs .attr(),"So jQuery 1.6 has the new function prop().
$(selector).click(function(){
//instead of:
this.getAttribute('style');
//do i use:
$(this).prop('style');
//or:
$(this).attr('style');
})
or in this case do they do the same thing?
And if I do have to switch to using prop(), all the old attr() calls will break if i switch to 1.6?
UPDATE
selector = '#id'
$(selector).click(function() {
//instead of:
var getAtt = this.getAttribute('style');
//do i use:
var thisProp = $(this).prop('style');
//or:
var thisAttr = $(this).attr('style');
console.log(getAtt, thisProp, thisAttr);
});
<script src=""https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js""></script>
<div id='id' style=""color: red;background: orange;"">test</div>
(see also this fiddle: http://jsfiddle.net/maniator/JpUF2/)
The console logs the getAttribute as a string, and the attr as a string, but the prop as a CSSStyleDeclaration, Why? And how does that affect my coding in the future?
I understand JSON, but not JSONP. Wikipedia's document on JSON is (was) the top search result for JSONP. It says this:
JSONP or ""JSON with padding"" is a JSON extension wherein a prefix is specified as an input argument of the call itself.
Huh? What call? That doesn't make any sense to me. JSON is a data format. There's no call.
The 2nd search result is from some guy named Remy, who writes this about JSONP:
JSONP is script tag injection, passing the response from the server in to a user specified function.
I can sort of understand that, but it's still not making any sense.
So what is JSONP? Why was it created (what problem does it solve)? And why would I use it?
Addendum: I've just created a new page for JSONP on Wikipedia; it now has a clear and thorough description of JSONP, based on jvenema's answer.
",https://stackoverflow.com/questions/2067472/what-is-jsonp-and-why-was-it-created,2494,632320.0,10.0,,,2010-01-14 20:53:48,2023-06-16 19:22:45,2019-02-27 14:26:58,,,javascript;json;jsonp;terminology,Cheeso,193593,48082,registered,true,2067584,,CC BY-SA 4.0,2015-10-05 09:01:36,1297,834,0,5,0,4,true,false,false,true,true,true,38,8,true,0.016,0.0039,6155,2010,1,20,Thursday,false,false,true,false,false,false,false 3746725,How to create an array containing 1...N,"I'm looking for any alternatives to the below for creating a JavaScript array containing 1 through to N where N is only known at runtime.
var foo = [];
for (var i = 1; i <= N; i++) {
foo.push(i);
}
To me it feels like there should be a way of doing this without the loop.
",https://stackoverflow.com/questions/3746725/how-to-create-an-array-containing-1-n,2484,2853347.0,82.0,,,2010-09-19 17:34:17,2026-04-15 06:43:09,2022-05-26 08:19:49,,,javascript;arrays;range,Godders,25306,305844,registered,true,3746797,,CC BY-SA 4.0,2014-10-06 14:03:38,318,280,1,0,0,3,true,false,false,true,true,true,39,7,false,0.029,0.0009,5907,2010,9,17,Sunday,true,false,true,false,false,false,false 5113374,JavaScript check if variable exists (is defined/initialized),"Which method of checking if a variable has been initialized is better/correct? (Assuming the variable could hold anything (string, int, object, function, etc.))
if (elem) { // or !elem
or
if (typeof elem !== 'undefined') {
or
if (elem != null) {
",https://stackoverflow.com/questions/5113374/javascript-check-if-variable-exists-is-defined-initialized,2479,2734894.0,31.0,,,2011-02-25 03:44:47,2022-12-11 14:00:19,2022-04-12 01:07:20,,,javascript;function;variables;initialization;undefined,samliew,79615,584192,registered,true,6509422,,CC BY-SA 4.0,2014-07-06 00:19:18,342,249,3,0,0,5,true,false,false,true,true,true,60,7,false,0.011,0.0009,5748,2011,2,3,Friday,false,false,true,false,false,false,false
610406,JavaScript equivalent to printf/String.Format,"I'm looking for a good JavaScript equivalent of the C/PHP printf() or for C#/Java programmers, String.Format() (IFormatProvider for .NET).
My basic requirement is a thousand separator format for numbers for now, but something that handles lots of combinations (including dates) would be good.
I realize Microsoft's Ajax library provides a version of String.Format(), but we don't want the entire overhead of that framework.
How can I get windowWidth, windowHeight, pageWidth, pageHeight, screenWidth, screenHeight, pageX, pageY, screenX, screenY which will work in all major browsers?
I have a script that uses $(document).ready, but it doesn't use anything else from jQuery. I'd like to lighten it up by removing the jQuery dependency.
How can I implement my own $(document).ready functionality without using jQuery? I know that using window.onload will not be the same, as window.onload fires after all images, frames, etc. have been loaded.
How do I get the selected value from a dropdown list using JavaScript?
<form>
<select id=""ddlViewBy"">
<option value=""1"">test1</option>
<option value=""2"" selected=""selected"">test2</option>
<option value=""3"">test3</option>
</select>
</form>
I have a need to add or prepend elements at the beginning of an array.
For example, if my array looks like below:
[23, 45, 12, 67]
And the response from my AJAX call is 34, I want the updated array to be like the following:
[34, 23, 45, 12, 67]
Currently I am planning to do it like this:
var newArray = [];
newArray.push(response);
for (var i = 0; i < theArray.length; i++) {
newArray.push(theArray[i]);
}
theArray = newArray;
delete newArray;
Is there a better way to do this? Does JavaScript have any built-in functionality that does this?
The complexity of my method is O(n) and it would be really interesting to see better implementations.
I have a layout similar to this, and would like to use a jQuery selector to select the child img inside the div on click.
<div id="...">
<img src="...">
</div>
To get the div, I've got this selector:
$(this)
How can I get the child img using a selector?
var obj = {
name: ""Simon"",
age: ""20"",
clothing: {
style: ""simple"",
hipster: false
}
}
for(var propt in obj){
console.log(propt + ': ' + obj[propt]);
}
How does the variable propt represent the properties of the object? It's not a built-in method or property. Why does it come up with every property in the object?
What is the preferred syntax for defining enums in JavaScript? Something like:
my.namespace.ColorEnum = {
RED : 0,
GREEN : 1,
BLUE : 2
}
// later on
if(currentColor == my.namespace.ColorEnum.RED) {
// whatever
}
Or is there a more preferable idiom?
",https://stackoverflow.com/questions/287903/what-is-the-preferred-syntax-for-defining-enums-in-javascript,2396,1289853.0,50.0,,,2008-11-13 19:09:06,2026-10-21 07:29:34,2026-10-20 15:02:31,,,javascript;syntax;enums,David Citron,43669,5309,registered,true,5040502,,CC BY-SA 4.0,2015-10-05 09:19:02,305,267,1,0,0,3,true,false,false,true,true,true,62,10,true,0.039,0.0019,6582,2008,11,19,Thursday,false,false,true,false,false,false,false 442404,"Retrieve the position (X,Y) of an HTML element","I want to know how to get the X and Y position of HTML elements such as img and div in JavaScript.
With React Router, I can use the Link element to create links which are natively handled by React Router.
I see internally it calls this.context.transitionTo(...).
I want to do navigation. Not from a link, but from a dropdown selection (as an example). How can I do this in code? What is this.context?
I saw the Navigation mixin, but can I do this without mixins?
How do you check if a value is an object in JavaScript?
",https://stackoverflow.com/questions/8511281/check-if-a-value-is-an-object-in-javascript,2340,2532655.0,55.0,,,2011-12-14 20:35:47,2026-11-15 20:20:30,2020-09-25 22:52:57,,,javascript;types;javascript-objects,Danny Fox,41199,1091828,registered,true,8511332,,CC BY-SA 4.0,2016-09-03 15:56:39,63,56,0,0,0,3,true,false,false,true,true,true,43,9,false,0.022,0.0009,5456,2011,12,20,Wednesday,false,false,true,false,false,false,false 242813,Are double quotes and single quotes interchangeable for string literals in JavaScript?,"Consider the following two alternatives:
console.log("double");console.log('single');The former uses double quotes around the string, whereas the latter uses single quotes around the string.
I see more and more JavaScript libraries out there using single quotes when handling strings.
Are these two usages interchangeable? If not, is there an advantage in using one over the other?
",https://stackoverflow.com/questions/242813/are-double-quotes-and-single-quotes-interchangeable-for-string-literals-in-javas,2332,762671.0,24.0,,,2008-10-28 10:34:35,2025-11-01 04:02:18,2024-07-05 22:37:16,,,javascript;string,aemkei,11235,28150,registered,true,242833,,CC BY-SA 4.0,2014-12-16 06:56:43,477,396,2,0,0,2,true,false,false,true,true,true,86,12,true,0.031,0.0031,6598,2008,10,10,Tuesday,false,false,true,false,false,false,false 2641347,Short circuit Array.forEach like calling break,"[1,2,3].forEach(function(el) {
if(el === 1) break;
});
How can I do this using the new forEach method in JavaScript? I've tried return;, return false; and break. break crashes and return does nothing but continue iteration.
I'd like to tell the difference between valid and invalid date objects in JS, but couldn't figure out how:
var d = new Date(""foo"");
console.log(d.toString()); // shows 'Invalid Date'
console.log(typeof d); // shows 'object'
console.log(d instanceof Date); // shows 'true'
Any ideas for writing an isValidDate function?
Date.parse for parsing date strings, which gives an authoritative way to check if the date string is valid.Date instances at all, this would be easiest to validate.Date instance, and then testing for the Date's time value. If the date is invalid, the time value is NaN. I checked with ECMA-262 and this behavior is in the standard, which is exactly what I'm looking for.What is the scope of variables in javascript? Do they have the same scope inside as opposed to outside a function? Or does it even matter? Also, where are the variables stored if they are defined globally?
",https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript,2222,586219.0,27.0,,,2009-02-01 08:27:19,2021-06-28 11:13:30,2018-05-01 10:15:07,,,javascript;function;variables;scope;var,lYriCAlsSH,58197,60102,registered,true,500459,,CC BY-SA 3.0,2014-03-03 19:06:43,213,206,0,0,0,5,true,false,false,true,true,true,45,8,true,0.046,0.0038,6502,2009,2,8,Sunday,true,false,true,false,false,false,false 3102819,Disable same origin policy in Chrome,"Is there any way to disable the Same-origin policy on Google's Chrome browser?
",https://stackoverflow.com/questions/3102819/disable-same-origin-policy-in-chrome,2220,3859321.0,39.0,,,2010-06-23 15:00:21,2026-09-23 22:05:33,2019-05-15 16:11:44,,,javascript;ajax;google-chrome,Landon Kuhn,79121,1785,registered,true,3177718,,CC BY-SA 4.0,2015-10-05 09:21:40,240,79,0,2,0,3,true,false,false,true,true,true,36,6,false,0.01,0.0006,5995,2010,6,15,Wednesday,false,false,true,false,false,false,false 1232040,How do I empty an array in JavaScript?,"Is there a way to empty an array and if so possibly with .remove()?
For instance,
A = [1,2,3,4];
How can I empty that?
",https://stackoverflow.com/questions/1232040/how-do-i-empty-an-array-in-javascript,2192,4418288.0,17.0,,,2009-08-05 09:08:39,2024-09-18 07:00:21,2015-11-11 19:22:52,,,javascript;arrays,akano1,41952,149738,registered,true,1232046,,CC BY-SA 3.0,2014-07-08 18:19:31,182,124,2,0,0,2,true,false,false,true,true,true,38,8,true,0.004,0.0005,6317,2009,8,9,Wednesday,false,false,true,false,false,false,false 5062614,How to decide when to use Node.js?,"I am new to this kind of stuff, but lately I've been hearing a lot about how good Node.js is. Considering how much I love working with jQuery and JavaScript in general, I can't help but wonder how to decide when to use Node.js. The web application I have in mind is something like Bitly - takes some content, archives it.
From all the homework I have been doing in the last few days, I obtained the following information. Node.js
Some of the sources that I have come across are:
Considering that Node.js can be run almost out-of-the-box on Amazon's EC2 instances, I am trying to understand what type of problems require Node.js as opposed to any of the mighty kings out there like PHP, Python and Ruby. I understand that it really depends on the expertise one has on a language, but my question falls more into the general category of: When to use a particular framework and what type of problems is it particularly suited for?
",https://stackoverflow.com/questions/5062614/how-to-decide-when-to-use-node-js,2190,590584.0,17.0,,,2011-02-21 05:20:51,2026-07-06 17:30:02,2026-07-06 17:30:02,,,javascript;node.js;web-applications,Legend,117858,184046,registered,true,5062670,,CC BY-SA 4.0,,2872,1436,0,13,0,3,true,false,false,true,true,true,34,7,true,0.029,0.0037,5752,2011,2,5,Monday,false,false,true,false,false,false,false 3216013,Get the last item in an array,"Here is my JavaScript code so far:
var linkElement = document.getElementById(""BackButton"");
var loc_array = document.location.href.split('/');
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-2])));
linkElement.appendChild(newT);
Currently it takes the second to last item in the array from the URL. However, I want to do a check for the last item in the array to be ""index.html"" and if so, grab the third to last item instead.
How do I check if a variable is an array in JavaScript?
if (variable.constructor == Array)
",https://stackoverflow.com/questions/767486/how-do-i-check-if-a-variable-is-an-array-in-javascript,2185,1382497.0,26.0,,,2009-04-20 09:02:59,2024-07-11 04:04:35,2022-04-10 12:59:04,,,javascript;arrays;list;variables,Andy McCluggage,38978,3362,registered,true,26633883,,CC BY-SA 4.0,2014-03-26 10:47:12,123,92,1,0,0,4,true,false,false,true,true,true,55,12,true,0.019,0.0016,6424,2009,4,9,Monday,false,false,true,false,false,false,false
572897,How does JavaScript .prototype work?,"I'm not that into dynamic programming languages but I've written my fair share of JavaScript code. I never really got my head around this prototype-based programming, does any one know how this works?
var obj = new Object();
obj.prototype.test = function() { alert('Hello?'); };
var obj2 = new obj();
obj2.test();
I remember a lot discussion I had with people a while back (I'm not exactly sure what I'm doing) but as I understand it, there's no concept of a class. It's just an object, and instances of those objects are clones of the original, right?
But what is the exact purpose of this ".prototype" property in JavaScript? How does it relate to instantiating objects?
var obj = new Object(); // not a functional object
obj.prototype.test = function() { alert('Hello?'); }; // this is wrong!
function MyObject() {} // a first class functional object
MyObject.prototype.test = function() { alert('OK'); } // OK
Also these slides really helped a lot.
",https://stackoverflow.com/questions/572897/how-does-javascript-prototype-work,2185,521997.0,26.0,,,2009-02-21 12:31:18,2024-05-17 05:14:24,2023-10-25 15:37:38,,,javascript;dynamic-languages;prototype-oriented,John Leidegren,61422,58961,registered,true,572996,,CC BY-SA 4.0,2013-07-12 22:29:24,1134,986,2,1,0,3,true,false,false,true,true,true,36,5,true,0.05,0.0042,6482,2009,2,12,Saturday,true,false,true,false,false,false,false 4459379,Preview an image before it is uploaded,"I want to be able to preview a file (image) before it is uploaded. The preview action should be executed all in the browser without using Ajax to upload the image.
How can I do this?
",https://stackoverflow.com/questions/4459379/preview-an-image-before-it-is-uploaded,2175,1891400.0,30.0,,,2010-12-16 09:51:32,2024-08-20 12:09:16,2011-09-06 10:49:25,,,javascript;jquery;file-upload,Simbian,21953,518838,registered,true,4459419,,CC BY-SA 3.0,2013-02-11 14:44:35,199,185,0,0,0,3,true,false,false,true,true,true,38,7,false,0.016,0.0011,5819,2010,12,9,Thursday,false,false,true,false,false,false,false 7486085,How to create a copy of a JavaScript array instead of a reference?,"When copying an array in JavaScript to another array:
var arr1 = ['a','b','c'];
var arr2 = arr1;
arr2.push('d');
console.log(arr1); //= ['a','b','c','d']
I realized that arr2 refers to the same array as arr1, rather than a new, independent array. How can I copy the array to get two independent arrays?
I've got an array:
myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}, etc.]
I'm unable to change the structure of the array. I'm being passed an id of 45, and I want to get 'bar' for that object in the array.
How do I do this in JavaScript or using jQuery?
",https://stackoverflow.com/questions/7364150/search-an-array-of-javascript-objects-for-an-object-with-a-matching-value,2161,2543932.0,37.0,,,2011-09-09 15:42:29,2024-09-02 17:18:01,2024-09-02 17:18:01,,,javascript;arrays;javascript-objects,thugsb,23496,614566,registered,true,35398031,,CC BY-SA 4.0,2016-10-24 08:50:38,342,271,3,0,0,3,true,false,false,true,true,true,73,13,false,0.015,0.0008,5552,2011,9,15,Friday,false,false,true,false,false,false,false 957537,How can I display a JavaScript object?,"How do I display the content of a JavaScript object in a string format like when we alert a variable?
The same formatted way I want to display an object.
",https://stackoverflow.com/questions/957537/how-can-i-display-a-javascript-object,2152,2642534.0,40.0,,,2009-06-05 19:01:59,2024-11-07 11:17:08,2020-05-10 11:21:04,,,javascript;serialization;javascript-objects,maxjackie,23492,118061,registered,true,957633,,CC BY-SA 4.0,2012-01-03 21:23:43,182,155,1,0,0,3,true,false,false,true,true,true,38,7,true,0.015,0.0008,6378,2009,6,19,Friday,false,false,true,false,false,false,false 2496710,Writing to files in Node.js,"I've been trying to find a way to write to a file when using Node.js, but with no success. How can I do that?
",https://stackoverflow.com/questions/2496710/writing-to-files-in-node-js,2128,2190390.0,19.0,,,2010-03-23 00:25:02,2024-12-06 15:31:07,2022-03-08 09:36:44,,,javascript;node.js;file;express;fs,Gjorgji,23164,282329,registered,true,2497040,,CC BY-SA 4.0,2016-10-20 05:43:40,117,110,0,0,0,5,true,false,false,true,true,true,27,5,false,0.009,0.001,6087,2010,3,0,Tuesday,false,false,true,false,false,false,false 22876978,Loop inside React JSX,"I'm trying to do something like the following in React JSX (where ObjectRow is a separate component):
<tbody>
for (var i=0; i < numrows; i++) {
<ObjectRow/>
}
</tbody>
I realize and understand why this isn't valid JSX, since JSX maps to function calls. However, coming from template land and being new to JSX, I am unsure how I would achieve the above (adding a component multiple times).
",https://stackoverflow.com/questions/22876978/loop-inside-react-jsx,2104,2215599.0,88.0,,,2014-04-05 05:29:28,2025-02-11 12:26:59,2021-02-14 15:36:11,,,javascript;reactjs;jsx,B Robster,42213,652693,registered,true,22877049,,CC BY-SA 4.0,2019-10-14 13:01:16,466,428,1,0,0,3,true,false,false,true,true,true,21,4,false,0.04,0.0009,4613,2014,4,5,Saturday,true,false,true,false,false,false,false 500504,Why is using "for...in" for array iteration a bad idea?,"I've been told not to use for...in with arrays in JavaScript. Why not?
How do I scroll to the top of the page using JavaScript? The scrollbar instantly jumping to the top of the page is desirable too as I'm not looking to achieve smooth scrolling.
",https://stackoverflow.com/questions/1144805/scroll-to-the-top-of-the-page-using-javascript,2091,2589154.0,50.0,,,2009-07-17 17:59:09,2023-10-06 20:55:14,2020-09-30 05:51:14,,,javascript;scroll,KingNestor,68540,64878,registered,true,1145012,,CC BY-SA 4.0,2018-12-20 04:50:58,184,177,0,0,0,2,true,false,false,true,true,true,47,9,true,0.019,0.0008,6336,2009,7,17,Friday,false,false,true,false,false,false,false 27732209,Turning off an ESLint rule for a specific line,"In order to turn off a linting rule for a particular line in JSHint, we use the following rule:
/* jshint ignore:start*/
$scope.someVar = ConstructorFunction();
/* jshint ignore:end */
Is there an equivalent of the above for ESLint?
",https://stackoverflow.com/questions/27732209/turning-off-an-eslint-rule-for-a-specific-line,2071,1869835.0,15.0,,,2015-01-01 15:47:47,2026-03-04 03:52:43,2026-01-27 04:34:51,,,javascript;jshint;eslint,runtimeZero,28486,2117019,registered,true,29592334,,CC BY-SA 4.0,,272,234,1,0,0,3,true,false,false,true,true,true,46,9,false,0.008,0.0011,4342,2015,1,15,Thursday,false,false,true,false,false,false,false 2450954,How to randomize (shuffle) a JavaScript array?,"I have an array like this:
var arr1 = [""a"", ""b"", ""c"", ""d""];
How can I randomize / shuffle it?
",https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array,2068,1799745.0,58.0,,,2010-03-15 22:37:11,2025-03-21 07:11:59,2020-04-06 13:10:05,,,javascript;arrays;random;shuffle,Ali,268320,49153,registered,true,2450976,,CC BY-SA 4.0,2014-10-30 06:12:54,135,97,1,0,0,4,true,false,false,true,true,true,46,7,true,0.032,0.0011,6095,2010,3,22,Monday,false,false,true,false,false,false,false 175739,How can I check if a string is a valid number?,"I'm hoping there's something in the same conceptual space as the old VB6 IsNumeric() function?
How does data binding work in the AngularJS framework?
I haven't found technical details on their site. It's more or less clear how it works when data is propagated from view to model. But how does AngularJS track changes of model properties without setters and getters?
I found that there are JavaScript watchers that may do this work. But they are not supported in Internet Explorer 6 and Internet Explorer 7. So how does AngularJS know that I changed for example the following and reflected this change on a view?
myobject.myproperty=""new value"";
",https://stackoverflow.com/questions/9682092/how-does-data-binding-work-in-angularjs,2050,366430.0,14.0,,,2012-03-13 10:16:37,2018-11-05 12:56:41,2017-05-23 12:34:53,,,javascript;angularjs;data-binding,Pashec,23279,168367,registered,true,9693933,,CC BY-SA 3.0,2015-06-25 09:18:47,943,574,2,4,0,3,true,false,false,true,true,true,40,7,true,0.038,0.0056,5366,2012,3,10,Tuesday,false,false,true,false,false,false,false
126100,How to efficiently count the number of keys/properties of an object in JavaScript,"What’s the fastest way to count the number of keys/properties of an object? Is it possible to do this without iterating over the object, i.e., without doing:
var count = 0;
for (k in myobj) if (myobj.hasOwnProperty(k)) ++count;
(Firefox did provide a magic __count__ property, but this was removed somewhere around version 4.)
I have two JavaScript arrays:
var array1 = [""Vijendra"",""Singh""];
var array2 = [""Singh"", ""Shakya""];
I want the output to be:
var array3 = [""Vijendra"",""Singh"",""Shakya""];
The output array should have repeated words removed.
How do I merge two arrays in JavaScript so that I get only the unique items from each array in the same order they were inserted into the original arrays?
",https://stackoverflow.com/questions/1584370/how-to-merge-two-arrays-in-javascript-and-de-duplicate-items,2033,2259991.0,93.0,,,2009-10-18 08:34:57,2025-05-20 15:58:46,2017-10-18 06:29:39,,,javascript;arrays;merge,Vijjendra,25311,165873,registered,true,1584377,,CC BY-SA 3.0,2018-01-04 09:48:51,459,383,2,0,0,3,true,false,false,true,true,true,60,10,false,0.041,0.0009,6243,2009,10,8,Sunday,true,false,true,false,false,false,false 455338,How do I check if an object has a key in JavaScript?,"Which is the right thing to do?
if (myObj['key'] == undefined)
or
if (myObj['key'] == null)
or
if (myObj['key'])
",https://stackoverflow.com/questions/455338/how-do-i-check-if-an-object-has-a-key-in-javascript,2031,2343366.0,2.0,,,2009-01-18 15:42:58,2020-01-09 10:52:24,2017-01-23 15:46:20,2014-02-05 18:32:57,Duplicate,javascript;object,kevin,,,does_not_exist,true,455366,,,2014-06-04 06:57:49,214,121,3,0,0,2,true,true,false,true,false,true,52,12,true,0.001,0.0009,6516,2009,1,15,Sunday,true,false,true,false,false,false,false
446594,Abort Ajax requests using jQuery,"Is it possible that using jQuery, I cancel/abort an Ajax request that I have not yet received the response from?
",https://stackoverflow.com/questions/446594/abort-ajax-requests-using-jquery,2006,733037.0,18.0,,,2009-01-15 12:45:18,2024-04-09 01:03:07,2020-07-08 00:24:40,,,javascript;jquery;ajax,lukewm,21753,47831,registered,true,446626,,CC BY-SA 4.0,2013-12-31 17:54:29,137,113,0,0,0,3,true,false,false,true,true,true,32,5,false,0.025,0.0027,6519,2009,1,12,Thursday,false,false,true,false,false,false,false 1168807,How can I add a key/value pair to a JavaScript object?,"Here is my object literal:
var obj = {key1: value1, key2: value2};
How can I add field key3 with value3 to the object?
I would like to create a String.replaceAll() method in JavaScript and think using a regex would be the most terse way to do it. However, I can't figure out how to pass a variable into a regex. I can do this already which will replace all the instances of "B" with "A".
"ABABAB".replace(/B/g, "A");
But I want to do something like this:
String.prototype.replaceAll = function(replaceThis, withThis) {
this.replace(/replaceThis/g, withThis);
};
But obviously, this will only replace the text "replaceThis"...so how do I pass this variable into my regex string?
I have JavaScript object array with the following structure:
objArray = [ { foo: 1, bar: 2}, { foo: 3, bar: 4}, { foo: 5, bar: 6} ];
I want to extract a field from each object, and get an array containing the values, for example field foo would give array [ 1, 3, 5 ].
I can do this with this trivial approach:
function getFields(input, field) {
var output = [];
for (var i=0; i < input.length ; ++i)
output.push(input[i][field]);
return output;
}
var result = getFields(objArray, ""foo""); // returns [ 1, 3, 5 ]
Is there a more elegant or idiomatic way to do this, so that a custom utility function would be unnecessary?
Note about suggested duplicate, it covers how to convert a single object to an array.
",https://stackoverflow.com/questions/19590865/from-an-array-of-objects-extract-value-of-a-property-as-array,1975,2038871.0,26.0,,,2013-10-25 13:13:03,2025-02-15 16:44:54,2019-03-21 10:01:36,,,javascript;javascript-objects,hyde,63311,1717300,registered,true,46694321,,CC BY-SA 4.0,2019-06-10 03:14:27,921,741,4,1,0,2,true,false,false,true,true,true,62,12,false,0.013,0.001,4775,2013,10,13,Friday,false,false,true,false,false,false,false 57803,How to convert decimal to hexadecimal in JavaScript,"How do you convert decimal values to their hexadecimal equivalent in JavaScript?
",https://stackoverflow.com/questions/57803/how-to-convert-decimal-to-hexadecimal-in-javascript,1973,1551826.0,31.0,,,2008-09-11 22:26:58,2024-10-08 08:44:52,2021-02-09 21:06:12,,,javascript;hex;number-formatting;radix,Luke Smith,24394,5556,registered,true,57805,,CC BY-SA 4.0,2013-07-29 11:38:12,88,81,0,0,0,4,true,false,false,true,true,true,51,8,false,0.02,0.0013,6645,2008,9,22,Thursday,false,false,true,false,false,false,false 3514784,How to detect a mobile device using jQuery,"Is there a way to detect whether or not a user is using a mobile device in jQuery? Something similar to the CSS @media attribute? I would like to run a different script if the browser is on a handheld device.
The jQuery $.browser function is not what I am looking for.
When embedding JavaScript in an HTML document, where is the proper place to put the <script> tags and included JavaScript? I seem to recall that you are not supposed to place these in the <head> section, but placing at the beginning of the <body> section is bad, too, since the JavaScript will have to be parsed before the page is rendered completely (or something like that). This seems to leave the end of the <body> section as a logical place for <script> tags.
So, where is the right place to put the <script> tags?
(This question references this question, in which it was suggested that JavaScript function calls should be moved from <a> tags to <script> tags. I'm specifically using jQuery, but more general answers are also appropriate.)
What is the TypeScript language? What can it do that JavaScript or available libraries cannot do, that would give me reason to consider it?
",https://stackoverflow.com/questions/12694530/what-is-typescript-and-why-should-i-use-it-instead-of-javascript,1941,698418.0,5.0,,,2012-10-02 16:37:58,2026-07-14 10:29:05,2026-07-14 10:29:05,,,javascript;typescript,Mohammed Thabet,21719,353953,registered,true,12694578,,CC BY-SA 4.0,2019-06-20 07:16:35,147,140,0,0,0,2,true,false,false,true,true,true,65,12,true,0.007,0.0028,5163,2012,10,16,Tuesday,false,false,true,false,false,false,false 1279957,How to move an element into another element,"I would like to move one DIV element inside another. For example, I want to move this (including all children):
<div id="source">
...
</div>
into this:
<div id="destination">
...
</div>
so that I have this:
<div id="destination">
<div id="source">
...
</div>
</div>
",https://stackoverflow.com/questions/1279957/how-to-move-an-element-into-another-element,1938,1465694.0,16.0,,,2009-08-14 20:14:45,2024-10-08 08:21:47,2022-11-12 05:03:12,,,javascript;jquery;html,Mark Richman,29830,134484,registered,true,1279963,,CC BY-SA 4.0,2014-03-16 08:27:08,579,369,3,0,0,3,true,false,false,true,true,true,43,8,false,0.011,0.0013,6308,2009,8,20,Friday,false,false,true,false,false,false,false
1646698,What is the 'new' keyword in JavaScript?,"The new keyword in JavaScript can be quite confusing when it is first encountered, as people tend to think that JavaScript is not an object-oriented programming language.
I have a constructor function which registers an event handler:
function MyConstructor(data, transport) {
this.data = data;
transport.on('data', function () {
alert(this.data);
});
}
// Mock transport object
var transport = {
on: function(event, callback) {
setTimeout(callback, 1000);
}
};
// called as
var obj = new MyConstructor('foo', transport);
However, I'm not able to access the data property of the created object inside the callback. It looks like this does not refer to the object that was created, but to another one.
I also tried to use an object method instead of an anonymous function:
function MyConstructor(data, transport) {
this.data = data;
transport.on('data', this.alert);
}
MyConstructor.prototype.alert = function() {
alert(this.name);
};
but it exhibits the same problems.
How can I access the correct object?
",https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback,1924,659930.0,16.0,,,2013-11-29 06:13:11,2025-10-22 20:14:45,2021-07-25 20:19:56,,,javascript;callback;this,Felix Kling,821480,218196,registered,true,20279485,,CC BY-SA 4.0,2015-10-05 08:59:54,1198,897,4,0,0,3,true,false,false,true,true,true,50,9,false,0.024,0.0029,4740,2013,11,6,Friday,false,false,true,false,false,false,false 9899372,Vanilla JavaScript equivalent of jQuery's $.ready() - how to call a function when the page/DOM is ready for it,"With jQuery, we all know the wonderful .ready() function:
$('document').ready(function(){});
However, let's say I want to run a function that is written in standard JavaScript with no library backing it, and that I want to launch a function as soon as the page is ready to handle it. What's the proper way to approach this?
I know I can do:
window.onload=""myFunction()"";
Or I can use the body tag:
<body onload=""myFunction()"">
Or I can even try at the bottom of the page after everything, but the end body or html tag like:
<script type=""text/javascript"">
myFunction();
</script>
What is a cross-browser(old/new)-compliant method of issuing one or more functions in a manner like jQuery's $.ready()?
How do I check if an object has a specific property in JavaScript?
Consider:
x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
//Do this
}
Is there another way to do it?
",https://stackoverflow.com/questions/135448/how-do-i-check-if-an-object-has-a-specific-property-in-javascript,1913,1508575.0,33.0,,,2008-09-25 19:27:06,2024-08-18 04:44:04,2024-04-11 15:02:53,,,javascript,sheats,35062,4915,registered,true,136411,,CC BY-SA 4.0,2014-05-31 12:08:32,219,174,1,0,0,1,true,false,false,true,true,true,66,13,true,0.022,0.0013,6631,2008,9,19,Thursday,false,false,true,false,false,false,false 18641899,What is the difference between Bower and npm?,"What is the fundamental difference between bower and npm? Just want something plain and simple. I've seen some of my colleagues use bower and npm interchangeably in their projects.
Let's say we have an object with this format:
var thisIsObject= {
'Cow' : 'Moo',
'Cat' : 'Meow',
'Dog' : 'Bark'
};
I wanted to do a function that removes by key:
removeFromObjectByKey('Cow');
",https://stackoverflow.com/questions/3455405/how-do-i-remove-a-key-from-a-javascript-object,1905,2132801.0,3.0,,,2010-08-11 04:59:03,2022-08-05 15:14:45,2017-03-11 13:50:00,2015-12-14 21:32:02,Duplicate,javascript,Martin Ongtangco,23625,162381,registered,true,3455416,,,,268,206,2,0,0,1,true,true,false,true,true,true,47,10,true,0.001,0.0009,5946,2010,8,4,Wednesday,false,false,true,false,false,false,false
7202157,Why does ++[[]][+[]]+[+[]] return the string "10"?,"This is valid and returns the string ""10"" in JavaScript (more examples here):
console.log(++[[]][+[]]+[+[]])
Why? What is happening here?
",https://stackoverflow.com/questions/7202157/why-does-return-the-string-10,1896,238476.0,10.0,,,2011-08-26 08:46:14,2024-01-29 15:25:02,2024-01-29 15:25:02,,,javascript;syntax;jsfuck,JohnJohnGa,15725,324853,registered,true,7202287,,CC BY-SA 4.0,2015-10-05 09:18:35,474,150,2,1,0,3,true,false,false,true,true,true,60,7,true,0.042,0.008,5566,2011,8,8,Friday,false,false,true,false,false,false,false 14810506,'map' function for objects (instead of arrays),"I have an object:
myObject = { 'a': 1, 'b': 2, 'c': 3 }
I am looking for a native method, similar to Array.prototype.map that would be used as follows:
newObject = myObject.map(function (value, label) {
return value * value;
});
// newObject is now { 'a': 1, 'b': 4, 'c': 9 }
Does JavaScript have such a map function for objects? (I want this for Node.JS, so I don't care about cross-browser issues.)
How can I loop through all members in a JavaScript object, including values that are objects?
For example, how could I loop through this (accessing the "your_name" and "your_message" for each)?
var validation_messages = {
"key_1": {
"your_name": "jimmy",
"your_msg": "hello world"
},
"key_2": {
"your_name": "billy",
"your_msg": "foo equals bar"
}
}
",https://stackoverflow.com/questions/921789/how-to-loop-through-a-plain-javascript-object-with-the-objects-as-members,1840,2136697.0,30.0,,,2009-05-28 16:18:14,2023-12-15 03:26:59,2021-07-19 11:36:05,,,javascript;loops,edt,22490,32242,registered,true,921808,,CC BY-SA 4.0,2015-12-14 13:25:08,557,519,1,0,0,2,true,false,false,true,true,true,73,13,false,0.014,0.0009,6386,2009,5,16,Thursday,false,false,true,false,false,false,false
646628,How to check if a string "StartsWith" another string?,"How would I write the equivalent of C#'s String.StartsWith in JavaScript?
var haystack = 'hello world';
var needle = 'he';
haystack.startsWith(needle) == true
Note: This is an old question, and as pointed out in the comments ECMAScript 2015 (ES6) introduced the .startsWith method. However, at the time of writing this update (2015) browser support is far from complete.
I need to get execution time in milliseconds.
Note: I originally asked this question back in 2008. The accepted answer then was to use new Date().getTime() However, we can all agree now that using the standard performance.now() API is more appropriate. I am therefore changing the accepted answer to this one.
The primitive types (number, string, etc.) are passed by value. Still, objects are unknown because they can be both passed by value (in which case we consider that a variable holding an object is a reference to the object) and passed-by-reference (when we consider that the variable to the object holds the object itself).
Although it doesn't matter in the end, I want to know what is the correct way to present the arguments passing conventions. Is there an excerpt from the JavaScript specification, which defines what should be the semantics regarding this?
",https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language,1812,598204.0,36.0,,,2009-02-05 21:23:56,2025-06-10 08:29:08,2024-03-23 09:42:33,,,javascript;pass-by-reference;pass-by-value,Danail Nachev,19941,3219,registered,true,,,CC BY-SA 4.0,2015-06-14 08:35:04,575,561,0,0,0,3,false,false,false,true,true,true,60,7,true,0.06,0.003,6498,2009,2,21,Thursday,false,false,true,false,false,false,false 1291942,What does "javascript:void(0)" mean?,"<a href="javascript:void(0)" id="loginlink">login</a>
I've seen such hrefs many times, but I don't know what exactly that means.
I am using setInterval(fname, 10000); to call a function every 10 seconds in JavaScript. Is it possible to stop calling it on some event?
I want the user to be able to stop the repeated refresh of data.
",https://stackoverflow.com/questions/109086/stop-setinterval-call-in-javascript,1802,1524059.0,9.0,,,2008-09-20 19:29:55,2023-05-13 13:21:56,2020-09-08 20:35:21,,,javascript;dom-events;setinterval,cnu,37385,1448,registered,true,109091,,CC BY-SA 4.0,2013-09-23 04:47:47,232,205,1,0,0,3,true,false,false,true,true,true,35,5,false,0.006,0.0012,6636,2008,9,19,Saturday,true,false,true,false,false,false,false 563406,How to add days to Date?,"How to add days to current Date using JavaScript? Does JavaScript have a built in function like .NET's AddDay()?
My version of node is always v0.6.1-pre even after I install brew node and NVM install v0.6.19.
My node version is:
node -v
v0.6.1-pre
NVM says this (after I install a version of node for the first time in one bash terminal):
nvm ls
v0.6.19
current: v0.6.19
But when I restart bash, this is what I see:
nvm ls
v0.6.19
current: v0.6.1-pre
default -> 0.6.19 (-> v0.6.19)
So where is this phantom node 0.6.1-pre version and how can I get rid of it? I'm trying to install libraries via NPM so that I can work on a project.
I tried using BREW to update before NVM, using brew update and brew install node.
I've tried deleting the ""node"" directory in my /usr/local/include and the ""node"" and ""node_modules"" in my /usr/local/lib.
I've tried uninstalling npm and reinstalling it following these instructions.
All of this because I was trying to update an older version of node to install the ""zipstream"" library. Now there's folders in my users directory, and the node version STILL isn't up to date, even though NVM says it's using 0.6.19.
Ideally, I'd like to uninstall nodejs, npm, and nvm, and just reinstall the entire thing from scratch on my system.
",https://stackoverflow.com/questions/11177954/how-do-i-completely-uninstall-node-js-and-reinstall-from-beginning-mac-os-x,1799,3108465.0,35.0,,,2012-06-24 13:40:56,2026-02-06 09:31:54,2020-05-14 10:49:27,,,javascript;node.js;npm,Dominic Tancredi,42430,1247659,registered,true,11178106,,CC BY-SA 4.0,2016-06-09 04:23:43,1562,1177,7,1,0,3,true,false,false,true,true,true,78,13,false,0.011,0.0006,5263,2012,6,13,Sunday,true,false,true,false,false,false,false 21692646,How does Facebook disable the browser's integrated Developer Tools?,"So apparently because of the recent scams, the developer tools are exploited by people to post spam and even used to "hack" accounts. Facebook has blocked the developer tools, and I can't even use the console.
How did they do that?? One Stack Overflow post claimed it is impossible, but Facebook has proven them wrong.
Just go to Facebook and open up the developer tools, type one character into the console, and this warning pops up. No matter what you put in, it will not get executed.
How is this possible?
They even blocked auto-complete in the console:
How do I convert all elements of my form to a JavaScript object?
I'd like to have some way of automatically building a JavaScript object from my form, without having to loop over each element. I do not want a string, as returned by $('#formid').serialize();, nor do I want the map returned by $('#formid').serializeArray();
I'm trying to direct a browser to a different page. If I wanted a GET request, I might say
document.location.href = 'http://example.com/q=a';
But the resource I'm trying to access won't respond properly unless I use a POST request. If this were not dynamically generated, I might use the HTML
<form action="http://example.com/" method="POST">
<input type="hidden" name="q" value="a">
</form>
Then I would just submit the form from the DOM.
But really I would like JavaScript code that allows me to say
post_to_url('http://example.com/', {'q':'a'});
What's the best cross browser implementation?
I need a solution that changes the location of the browser, just like submitting a form. If this is possible with XMLHttpRequest, it is not obvious. And this should not be asynchronous, nor use XML, so Ajax is not the answer.
",https://stackoverflow.com/questions/133925/javascript-post-request-like-a-form-submit,1767,1895045.0,32.0,,,2008-09-25 15:15:43,2024-06-12 14:27:44,2022-12-27 19:51:44,,,javascript;forms;post;submit,Joseph Holsten,20946,16981,registered,true,133997,,CC BY-SA 4.0,2012-05-29 19:11:28,1198,896,3,1,0,4,true,false,false,true,true,true,42,7,false,0.017,0.0009,6631,2008,9,15,Thursday,false,false,true,false,false,false,false 432493,How do you access the matched groups in a JavaScript regular expression?,"I want to match a portion of a string using a regular expression and then access that parenthesized substring:
var myString = ""something format_abc""; // I want ""abc""
var arr = /(?:^|\s)format_(.*?)(?:\s|$)/.exec(myString);
console.log(arr); // Prints: ["" format_abc"", ""abc""] .. so far so good.
console.log(arr[1]); // Prints: undefined (???)
console.log(arr[0]); // Prints: format_undefined (!!!)
What am I doing wrong?
I've discovered that there was nothing wrong with the regular expression code above: the actual string which I was testing against was this:
"date format_%A"
Reporting that "%A" is undefined seems a very strange behaviour, but it is not directly related to this question, so I've opened a new one, Why is a matched substring returning "undefined" in JavaScript?.
The issue was that console.log takes its parameters like a printf statement, and since the string I was logging ("%A") had a special value, it was trying to find the value of the next parameter.
I want to parse a JSON string in JavaScript. The response is something like
var response = '{""result"":true,""count"":1}';
How can I get the values result and count from this?
In PHP, you can do...
range(1, 3); // Array(1, 2, 3)
range(""A"", ""C""); // Array(""A"", ""B"", ""C"")
That is, there is a function that lets you get a range of numbers or characters by passing the upper and lower bounds.
Is there anything built-in to JavaScript natively for this? If not, how would I implement it?
",https://stackoverflow.com/questions/3895478/does-javascript-have-a-method-like-range-to-generate-a-range-within-the-supp,1759,1727627.0,92.0,,,2010-10-09 02:37:29,2024-10-20 10:21:31,2019-12-01 18:05:38,,,javascript;arrays;functional-programming,alex,492880,31671,registered,true,3895521,,CC BY-SA 4.0,2018-08-11 11:34:13,356,311,1,0,0,3,true,false,false,true,true,true,102,15,true,0.053,0.001,5887,2010,10,2,Saturday,true,false,true,false,false,false,false 979975,Get the values from the "GET" parameters (JavaScript),"I have a URL with some GET parameters as follows:
www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5
I need to get the whole value of c. I tried to read the URL, but I got only m2. How do I do this using JavaScript?
I have an element that already has a class:
<div class="someclass">
...
</div>
How can i add a class to the div (not replace, but add) with JavaScript?
What is the difference between null and undefined in JavaScript?
I am building some objects in JavaScript and pushing those objects into an array, I am storing the key I want to use in a variable then creating my objects like so:
var key = ""happyCount"";
myArray.push( { key : someValueArray } );
but when I try to examine my array of objects for every object the key is ""key"" instead of the value of the variable key. Is there any way to set the value of the key from a variable?
Fiddle for better explanation: http://jsfiddle.net/Fr6eY/3/
",https://stackoverflow.com/questions/11508463/javascript-set-object-key-by-variable,1748,1488106.0,9.0,,,2012-07-16 16:24:23,2026-04-09 00:53:22,2018-10-08 10:10:38,2024-05-23 13:47:11,Duplicate,javascript,Hunter McMillen,61854,702638,registered,true,11508490,,,2023-03-07 22:07:11,598,480,2,1,0,1,true,true,false,true,true,true,37,6,false,0.006,0.0012,5241,2012,7,16,Monday,false,false,true,false,false,false,false 979256,Sorting an array of objects by property values,"I've got the following objects using AJAX and stored them in an array:
var homes = [
{
""h_id"": ""3"",
""city"": ""Dallas"",
""state"": ""TX"",
""zip"": ""75201"",
""price"": ""162500""
}, {
""h_id"": ""4"",
""city"": ""Bevery Hills"",
""state"": ""CA"",
""zip"": ""90210"",
""price"": ""319250""
}, {
""h_id"": ""5"",
""city"": ""New York"",
""state"": ""NY"",
""zip"": ""00010"",
""price"": ""962500""
}
];
How do I create a function to sort the objects by the price property in ascending or descending order using JavaScript only?
Why would someone prefer either the Lodash or Underscore.js utility library over the other?
Lodash seems to be a drop-in replacement for underscore, the latter having been around longer.
I think both are brilliant, but I do not know enough about how they work to make an educated comparison, and I would like to know more about the differences.
",https://stackoverflow.com/questions/13789618/differences-between-lodash-and-underscore-js,1727,374182.0,12.0,,,2012-12-09 17:08:36,2022-10-14 19:08:01,2022-10-14 19:08:01,2019-01-20 23:25:37,Opinion-based,underscore.js;javascript;lodash,Brian M. Hunt,84612,19212,registered,true,13898916,,,,472,345,0,2,0,3,true,true,false,true,true,true,44,5,false,0.032,0.0046,5095,2012,12,17,Sunday,true,false,true,false,false,false,false 1911015,How do I debug Node.js applications?,"How do I debug a Node.js server application?
Right now I'm mostly using alert debugging with print statements like this:
sys.puts(sys.inspect(someVariable));
There must be a better way to debug. I know that Google Chrome has a command-line debugger. Is this debugger available for Node.js as well?
",https://stackoverflow.com/questions/1911015/how-do-i-debug-node-js-applications,1715,568732.0,42.0,,,2009-12-15 22:50:07,2023-06-25 18:29:01,2015-12-20 10:19:03,,,javascript;node.js;debugging;google-chrome-devtools,Fabian Jakobs,29183,129322,registered,true,2536734,,CC BY-SA 3.0,2014-07-31 12:21:17,430,302,1,1,0,4,true,false,false,true,true,true,36,6,true,0.074,0.003,6185,2009,12,22,Tuesday,false,false,true,false,false,false,false 523643,Difference between == and === in JavaScript,"What is the difference between == and === in JavaScript? I have also seen != and !== operators. Are there more such operators?
Given a string representation of a number, how can I convert it to number type in TypeScript?
var numberString: string = ""1234"";
var numberValue: number = /* what should I do with `numberString`? */;
",https://stackoverflow.com/questions/14667713/how-to-convert-a-string-to-number-in-typescript,1709,2811445.0,22.0,,,2013-02-02 23:34:18,2025-09-26 09:44:15,2024-07-15 20:53:41,,,javascript;typescript,Paul0515,25755,1627079,registered,true,14668510,,CC BY-SA 4.0,2019-06-20 07:16:29,246,202,2,0,0,2,true,false,false,true,true,true,48,9,true,0.008,0.0006,5040,2013,2,23,Saturday,true,false,true,false,false,false,false
497094,How do I find out which DOM element has the focus?,"I would like to find out, in JavaScript, which element currently has focus. I've been looking through the DOM and haven't found what I need, yet. Is there a way to do this, and how?
The reason I was looking for this:
I'm trying to make keys like the arrows and enter navigate through a table of input elements. Tab works now, but enter, and arrows do not by default it seems. I've got the key handling part set up but now I need to figure out how to move the focus over in the event handling functions.
I am storing time in a MySQL database as a Unix timestamp and that gets sent to some JavaScript code. How would I get just the time out of it?
For example, in HH/MM/SS format.
I have a bit of code where I am looping through all the select boxes on a page and binding a .hover event to them to do a bit of twiddling with their width on mouse on/off.
This happens on page ready and works just fine.
The problem I have is that any select boxes I add via Ajax or DOM after the initial loop won't have the event bound.
I have found this plugin (jQuery Live Query Plugin), but before I add another 5k to my pages with a plugin, I want to see if anyone knows a way to do this, either with jQuery directly or by another option.
",https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements,1673,1104848.0,23.0,,,2008-10-14 23:25:19,2025-06-17 11:10:39,2016-12-02 10:27:40,,,javascript;jquery;events;unobtrusive-javascript,Eli,100368,27580,registered,true,1207393,,CC BY-SA 3.0,2014-03-24 10:09:10,688,547,2,1,0,4,true,false,false,true,true,true,46,6,true,0.021,0.0015,6612,2008,10,23,Tuesday,false,false,true,false,false,false,false 281264,Remove empty elements from an array in Javascript,"How do I remove empty elements from an array in JavaScript?
Is there a straightforward way, or do I need to loop through it and remove them manually?
",https://stackoverflow.com/questions/281264/remove-empty-elements-from-an-array-in-javascript,1665,1871126.0,52.0,,,2008-11-11 15:48:54,2024-11-19 21:23:03,2020-08-24 20:58:11,,,javascript;arrays,Mkkt Bkkt,122065,8954,registered,true,281335,,CC BY-SA 4.0,2018-05-10 06:50:52,166,152,0,0,0,2,true,false,false,true,true,true,49,8,false,0.028,0.0009,6584,2008,11,15,Tuesday,false,false,true,false,false,false,false 10636611,How does the 'Access-Control-Allow-Origin' header work?,"Apparently, I have completely misunderstood its semantics. I thought of something like this:
http://siteA - the origin.http://siteB, which I thought meant that MyCode.js was allowed to make cross-origin references to the site B.http://siteB, which should be fine, despite being cross-origin requests.Well, I am wrong. It does not work like this at all. So, I have read Cross-origin resource sharing and attempted to read Cross-Origin Resource Sharing in w3c recommendation.
One thing is sure - I still do not understand how I am supposed to use this header.
I have full control of both site A and site B. How do I enable the JavaScript code downloaded from the site A to access resources on the site B using this header?
P.S.: I do not want to utilize JSONP.
",https://stackoverflow.com/questions/10636611/how-does-the-access-control-allow-origin-header-work,1665,2829464.0,21.0,,,2012-05-17 13:23:54,2025-02-01 10:08:58,2022-09-18 11:45:46,,,javascript;cross-domain;cors,mark,64054,80002,registered,true,10636765,,CC BY-SA 4.0,2017-05-16 19:30:52,1346,969,3,3,0,3,true,false,false,true,true,true,63,6,true,0.007,0.0006,5301,2012,5,13,Thursday,false,false,true,false,false,false,false 1470488,What is the purpose of the var keyword and when should I use it (or omit it)?,"NOTE: This question was asked from the viewpoint of ECMAScript version 3 or 5. The answers might become outdated with the introduction of new features in the release of ECMAScript 6.
What exactly is the function of the var keyword in JavaScript, and what is the difference between
var someNumber = 2;
var someFunction = function() { doSomething; }
var someObject = { }
var someObject.someProperty = 5;
and
someNumber = 2;
someFunction = function() { doSomething; }
someObject = { }
someObject.someProperty = 5;
?
When would you use either one, and why/what does it do?
",https://stackoverflow.com/questions/1470488/what-is-the-purpose-of-the-var-keyword-and-when-should-i-use-it-or-omit-it,1664,341995.0,19.0,,,2009-09-24 08:54:04,2021-08-25 15:14:00,2018-02-07 18:26:43,,,javascript;keyword;ecmascript-5,Alex,77739,114916,registered,true,1470494,,CC BY-SA 3.0,2014-05-21 21:53:02,728,581,3,0,0,3,true,false,false,true,true,true,77,17,true,0.056,0.0049,6267,2009,9,8,Thursday,false,false,true,false,false,false,false 1230233,How to find the sum of an array of numbers,"Given an array [1, 2, 3, 4], how can I find the sum of its elements? (In this case, the sum would be 10.)
I thought $.each might be useful, but I'm not sure how to implement it.
I'm trying to get a list of the names of all the files present in a directory using Node.js. I want output that is an array of filenames. How can I do this?
",https://stackoverflow.com/questions/2727167/how-do-you-get-a-list-of-the-names-of-all-files-present-in-a-directory-in-node-j,1655,1727992.0,33.0,,,2010-04-28 06:10:16,2025-06-28 12:58:20,2017-02-03 14:06:43,,,javascript;node.js;directory-listing,resopollution,20440,76969,registered,true,2727191,,CC BY-SA 3.0,2015-07-14 10:51:20,165,158,0,0,0,3,true,false,false,true,true,true,82,18,true,0.019,0.001,6051,2010,4,6,Wednesday,false,false,true,false,false,false,false 867916,Creating a div element in jQuery,"How do I create a div element in jQuery?
How do I get the current year in JavaScript?
",https://stackoverflow.com/questions/6002254/get-the-current-year-in-javascript,1641,1405321.0,13.0,,,2011-05-14 13:53:05,2025-04-05 07:30:54,2017-03-26 15:44:50,,,javascript;date,Satch3000,49758,683553,registered,true,6002276,,CC BY-SA 3.0,2015-02-07 23:37:05,52,45,0,0,0,2,true,false,false,true,true,true,34,6,false,0.009,0.0012,5670,2011,5,13,Saturday,true,false,true,false,false,false,false 10865025,Merge/flatten an array of arrays,"I have a JavaScript array like:
[[""$6""], [""$12""], [""$25""], [""$25""], [""$18""], [""$22""], [""$10""]]
How would I go about merging the separate inner arrays into one like:
[""$6"", ""$12"", ""$25"", ...]
",https://stackoverflow.com/questions/10865025/merge-flatten-an-array-of-arrays,1583,1340678.0,90.0,,,2012-06-02 18:53:46,2026-06-03 10:52:07,2023-10-09 08:08:49,,,javascript;arrays;multidimensional-array;merge;flatten,Andy,19319,109407,registered,true,10865042,,CC BY-SA 4.0,2018-01-02 20:04:07,258,196,2,0,0,5,true,false,false,true,true,true,32,5,false,0.067,0.0012,5285,2012,6,18,Saturday,true,false,true,false,false,false,false
10286204,What is the "right" JSON date format?,"I've seen so many different standards for the JSON date format:
""\""\\/Date(1335205592410)\\/\"""" .NET JavaScriptSerializer
""\""\\/Date(1335205592410-0500)\\/\"""" .NET DataContractJsonSerializer
""2012-04-23T18:25:43.511Z"" JavaScript built-in JSON object
""2012-04-21T18:25:43-05:00"" ISO 8601
Which one is the right one? Or best? Is there any sort of standard on this?
",https://stackoverflow.com/questions/10286204/what-is-the-right-json-date-format,1583,2136708.0,16.0,,,2012-04-23 18:32:32,2025-11-20 13:22:25,2020-09-08 07:54:57,,,javascript;json,Kamyar Nazeri,26714,1041321,registered,true,15952652,,CC BY-SA 4.0,2019-02-08 23:03:52,440,402,1,0,0,2,true,false,false,true,true,true,47,7,true,0.007,0.0007,5325,2012,4,18,Monday,false,false,true,false,false,false,false 7837456,How to compare arrays in JavaScript?,"I'd like to compare two arrays... ideally, efficiently. Nothing fancy, just true if they are identical, and false if not. Not surprisingly, the comparison operator doesn't seem to work.
var a1 = [1,2,3];
var a2 = [1,2,3];
console.log(a1==a2); // Returns false
console.log(JSON.stringify(a1)==JSON.stringify(a2)); // Returns true
JSON encoding each array does, but is there a faster or ""better"" way to simply compare arrays without having to iterate through each value?
",https://stackoverflow.com/questions/7837456/how-to-compare-arrays-in-javascript,1580,1927195.0,57.0,,,2011-10-20 14:27:57,2025-09-22 09:29:04,2015-10-04 22:21:00,,,javascript;arrays;json,Julian H. Lam,26324,122353,registered,true,14853974,,CC BY-SA 3.0,2018-12-02 08:08:02,542,478,3,0,0,3,true,false,false,true,true,true,36,6,true,0.03,0.0008,5511,2011,10,14,Thursday,false,false,true,false,false,false,false 4870328,Read environment variables in Node.js,"Is there a way to read environment variables in Node.js code?
Like for example Python's os.environ['HOME'].
Is there a null coalescing operator in Javascript?
For example, in C#, I can do this:
String someString = null;
var whatIWant = someString ?? ""Cookies!"";
The best approximation I can figure out for Javascript is using the conditional operator:
var someString = null;
var whatIWant = someString ? someString : 'Cookies!';
Which is sorta icky IMHO. Can I do better?
",https://stackoverflow.com/questions/476436/is-there-a-null-coalescing-operator-in-javascript,1575,486799.0,19.0,,,2009-01-24 18:18:02,2023-02-03 05:46:59,2014-02-22 09:24:20,,,javascript;operators;null-coalescing-operator;null-coalescing,Daniel Schaffer,58101,2596,registered,true,476445,,CC BY-SA 3.0,,447,371,2,0,0,4,true,false,false,true,true,true,62,8,true,0.039,0.0032,6510,2009,1,18,Saturday,true,false,true,false,false,false,false 596467,How do I convert a float number to a whole number in JavaScript?,"I'd like to convert a float to a whole number in JavaScript. Actually, I'd like to know how to do BOTH of the standard conversions: by truncating and by rounding. And efficiently, not via converting to a string and parsing.
",https://stackoverflow.com/questions/596467/how-do-i-convert-a-float-number-to-a-whole-number-in-javascript,1573,1815729.0,18.0,,,2009-02-27 20:15:07,2023-06-22 03:01:34,2016-02-24 18:16:57,,,javascript;syntax,mcherm,24794,14570,registered,true,596503,,CC BY-SA 3.0,2019-05-31 05:22:29,231,224,0,0,0,2,true,false,false,true,true,true,64,13,true,0.01,0.0009,6476,2009,2,20,Friday,false,false,true,false,false,false,false 1107220,How can I select an element by name with jQuery?,"I have a table column I’m trying to expand and hide. jQuery seems to hide the <td> elements when I select it by class but not by the element’s name.
For example:
$(".bold").hide(); // Selecting by class works.
$("tcol1").hide(); // Selecting by name does not work. [Edit: this is NOT selecting by name! This is selecting by element type.]
Note the HTML below. The second column has the same name for all rows. How could I create this collection using the name attribute?
<tr>
<td>data1</td>
<td name="tcol1" class="bold"> data2</td>
</tr>
<tr>
<td>data1</td>
<td name="tcol1" class="bold"> data2</td>
</tr>
<tr>
<td>data1</td>
<td name="tcol1" class="bold"> data2</td>
</tr>
",https://stackoverflow.com/questions/1107220/how-can-i-select-an-element-by-name-with-jquery,1564,2402837.0,15.0,,,2009-07-10 01:05:38,2025-02-11 01:10:48,2025-02-11 01:10:48,,,javascript;jquery;html;dom;jquery-selectors,T.T.T.,34947,52256,registered,true,1107264,,CC BY-SA 4.0,2019-08-12 12:37:26,1094,884,7,0,0,5,true,false,false,true,true,true,48,10,true,0.006,0.0007,6343,2009,7,1,Friday,false,false,true,false,false,false,false
10729276,"How can I get the full object in Node.js's console.log(), rather than '[Object]'?","I have this object:
const myObject = {
"a":"a",
"b":{
"c":"c",
"d":{
"e":"e",
"f":{
"g":"g",
"h":{
"i":"i"
}
}
}
}
};
But when I try to show it using console.log(myObject), I receive this output:
{ a: 'a', b: { c: 'c', d: { e: 'e', f: [Object] } } }
How can I get the full object, including the content of property f?
What is the purpose of Node.js module.exports and how do you use it?
I can't seem to find any information on this, but it appears to be a rather important part of Node.js as I often see it in source code.
According to the Node.js documentation:
module
A reference to the current
module. In particularmodule.exportsis the same as the exports object. Seesrc/node.jsfor more information.
But this doesn't really help.
What exactly does module.exports do, and what would a simple example be?
Can someone tell me where can I find the Node.js modules, which I installed using npm?
I'm using $.post() to call a servlet using Ajax and then using the resulting HTML fragment to replace a div element in the user's current page. However, if the session times out, the server sends a redirect directive to send the user to the login page. In this case, jQuery is replacing the div element with the contents of the login page, forcing the user's eyes to witness a rare scene indeed.
How can I manage a redirect directive from an Ajax call with jQuery 1.2.6?
",https://stackoverflow.com/questions/199099/how-to-manage-a-redirect-request-after-a-jquery-ajax-call,1541,1182857.0,34.0,,,2008-10-13 21:29:50,2021-09-29 14:07:43,2016-01-22 20:21:45,,,javascript;jquery;ajax;http-redirect,Elliot Vargas,20899,2024,registered,true,484541,,CC BY-SA 3.0,2014-09-17 18:56:40,526,473,3,0,0,4,true,false,false,true,true,true,57,11,false,0.029,0.0013,6613,2008,10,21,Monday,false,false,true,false,false,false,false 5915096,Get a random item from a JavaScript array,"var items = Array(523, 3452, 334, 31, ..., 5346);
How do I get random item from items?
What is the reason browsers do not correctly recognize:
<script src=""foobar.js"" /> <!-- self-closing script element -->
Only this is recognized:
<script src=""foobar.js""></script>
Does this break the concept of XHTML support?
Note: This statement is correct at least for all IE (6-8 beta 2).
",https://stackoverflow.com/questions/69913/why-dont-self-closing-script-elements-work,1536,177271.0,12.0,,,2008-09-16 06:52:38,2023-06-03 19:41:40,2019-04-09 03:58:42,,,javascript;html;internet-explorer;xhtml,dimarzionist,18787,10778,registered,true,69984,,CC BY-SA 4.0,2015-10-05 09:20:11,398,322,2,0,0,4,true,false,false,true,true,true,48,6,true,0.068,0.0087,6640,2008,9,6,Tuesday,false,false,true,false,false,false,false 1374126,"How to extend an existing JavaScript array with another array, without creating a new array","There doesn't seem to be a way to extend an existing JavaScript array with another array, i.e. to emulate Python's extend method.
I want to achieve the following:
>>> a = [1, 2]
[1, 2]
>>> b = [3, 4, 5]
[3, 4, 5]
>>> SOMETHING HERE
>>> a
[1, 2, 3, 4, 5]
I know there's a a.concat(b) method, but it creates a new array instead of simply extending the first one. I'd like an algorithm that works efficiently when a is significantly larger than b (i.e. one that does not copy a).
Note: This is not a duplicate of How to append something to an array? -- the goal here is to add the whole contents of one array to the other, and to do it ""in place"", i.e. without copying all elements of the extended array.
",https://stackoverflow.com/questions/1374126/how-to-extend-an-existing-javascript-array-with-another-array-without-creating,1524,1111942.0,21.0,,,2009-09-03 15:27:30,2024-11-30 09:13:13,2018-10-15 17:49:50,,,javascript;arrays;concatenation,Dzinx,58262,18745,registered,true,1374131,,CC BY-SA 4.0,,990,743,6,1,0,3,true,false,false,true,true,true,91,15,false,0.019,0.0014,6288,2009,9,15,Thursday,false,false,true,false,false,false,false 11580961,Sending command line arguments to npm script,"The scripts portion of my package.json currently looks like this:
"scripts": {
"start": "node ./script.js server"
}
...which means I can run npm start to start the server. So far so good.
However, I would like to be able to run something like npm start 8080 and have the argument(s) passed to script.js (e.g. npm start 8080 => node ./script.js server 8080). Is this possible?
I noticed that JavaScript's new Date() function is very smart in accepting dates in several formats.
Xmas95 = new Date(""25 Dec, 1995 23:15:00"")
Xmas95 = new Date(""2009 06 12,12:52:39"")
Xmas95 = new Date(""20 09 2006,12:52:39"")
I could not find documentation anywhere showing all the valid string formats while calling new Date() function.
This is for converting a string to a date. If we look at the opposite side, that is, converting a date object to a string, until now I was under the impression that JavaScript doesn't have a built-in API to format a date object into a string.
Editor's note: The following approach is the asker's attempt that worked on a particular browser but does not work in general; see the answers on this page to see some actual solutions.
Today, I played with the toString() method on the date object and surprisingly it serves the purpose of formatting date to strings.
var d1 = new Date();
d1.toString('yyyy-MM-dd'); //Returns ""2009-06-29"" in Internet Explorer, but not Firefox or Chrome
d1.toString('dddd, MMMM ,yyyy') //Returns ""Monday, June 29,2009"" in Internet Explorer, but not Firefox or Chrome
Also here I couldn't find any documentation on all the ways we can format the date object into a string.
Where is the documentation which lists the format specifiers supported by the Date() object?
How can I check if a checkbox in a checkbox array is checked using the id of the checkbox array?
I am using the following code, but it always returns the count of checked checkboxes regardless of id.
function isCheckedById(id) {
alert(id);
var checked = $(""input[@id="" + id + ""]:checked"").length;
alert(checked);
if (checked == 0) {
return false;
} else {
return true;
}
}
",https://stackoverflow.com/questions/2204250/check-if-checkbox-is-checked-with-jquery,1516,2781908.0,27.0,,,2010-02-05 00:23:20,2025-08-12 03:30:31,2020-03-06 20:02:37,,,javascript;jquery;html;checkbox,Jake,26187,229853,registered,true,2204275,,CC BY-SA 4.0,2015-07-09 10:22:27,492,417,1,0,0,4,true,false,false,true,true,true,40,7,false,0.01,0.0005,6133,2010,2,0,Friday,false,false,true,false,false,false,false
75980,When are you supposed to use escape instead of encodeURI / encodeURIComponent?,"When encoding a query string to be sent to a web server - when do you use escape() and when do you use encodeURI() or encodeURIComponent():
Use escape:
escape("% +&=");
OR
use encodeURI() / encodeURIComponent()
encodeURI("http://www.google.com?var1=value1&var2=value2");
encodeURIComponent("var1=value1&var2=value2");
",https://stackoverflow.com/questions/75980/when-are-you-supposed-to-use-escape-instead-of-encodeuri-encodeuricomponent,1516,597956.0,16.0,,,2008-09-16 19:24:34,2023-07-31 08:27:51,2023-07-31 08:27:51,,,javascript;encoding;query-string,Adam,28918,1341,registered,true,3608791,,CC BY-SA 4.0,2016-09-12 12:02:25,504,363,7,0,0,3,true,false,false,true,true,true,78,12,true,0.027,0.0025,6640,2008,9,19,Tuesday,false,false,true,false,false,false,false
1068834,Object comparison in JavaScript,"What is the best way to compare objects in JavaScript?
Example:
var user1 = {name : ""nerd"", org: ""dev""};
var user2 = {name : ""nerd"", org: ""dev""};
var eq = user1 == user2;
alert(eq); // gives false
I know that two objects are equal if they refer to the exact same object, but is there a way to check if they have the same attributes' values?
The following way works for me, but is it the only possibility?
var eq = Object.toJSON(user1) == Object.toJSON(user2);
alert(eq); // gives true
",https://stackoverflow.com/questions/1068834/object-comparison-in-javascript,1515,1550093.0,10.0,,,2009-07-01 12:18:29,2020-06-17 10:05:00,2016-05-10 19:43:45,2016-05-10 19:43:36,Duplicate,javascript;object;comparison;object-comparison,spankmaster79,22381,131664,registered,true,1144249,,,2014-07-06 16:11:39,585,492,2,0,0,4,true,true,false,true,true,true,31,4,false,0.006,0.001,6352,2009,7,12,Wednesday,false,false,true,false,false,false,false
45015,Safely turning a JSON string into an object,"Given a string of JSON data, how can I safely turn that string into a JavaScript object?
Obviously I can do this unsafely with something like:
var obj = eval(""("" + json + ')');
but that leaves me vulnerable to the JSON string containing other code, which it seems very dangerous to simply eval.
",https://stackoverflow.com/questions/45015/safely-turning-a-json-string-into-an-object,1510,1491942.0,28.0,,,2008-09-05 00:12:01,2022-09-21 10:18:43,2020-09-21 12:15:56,,,javascript;json;parsing,Matt Sheppard,118363,797,registered,true,5686237,,CC BY-SA 4.0,2019-02-28 09:07:18,344,299,1,0,0,3,true,false,false,true,true,true,43,8,false,0.019,0.001,6651,2008,9,0,Friday,false,false,true,false,false,false,false 31048953,What are these three dots in React doing?,"What does the ... do in this React (using JSX) code and what is it called?
<Modal {...this.props} title='Modal heading' animation={false}>
",https://stackoverflow.com/questions/31048953/what-are-these-three-dots-in-react-doing,1501,668383.0,21.0,,,2015-06-25 11:21:52,2025-01-25 17:51:34,2024-01-09 15:50:01,,,javascript;reactjs;spread-syntax,Thomas Johansen,15328,5038178,registered,true,31049016,,CC BY-SA 4.0,2018-11-05 08:49:17,191,147,2,0,0,3,true,false,false,true,true,true,41,8,true,0.031,0.0022,4167,2015,6,11,Thursday,false,false,true,false,false,false,false
4592493,Check if element exists in jQuery,"How do I check if an element exists if the element is created by .append() method?
$('elemId').length doesn't work for me.
I am looking to find a clear explanation of what the "this" keyword does, and how to use it correctly.
It seems to behave strangely, and I don't fully understand why.
How does this work and when should it be used?
I am trying to clean up the way my anchors work. I have a header that is fixed to the top of the page, so when you link to an anchor elsewhere in the page, the page jumps so the anchor is at the top of the page, leaving the content behind the fixed header (I hope that makes sense). I need a way to offset the anchor by the 25px from the height of the header. I would prefer HTML or CSS, but Javascript would be acceptable as well.
",https://stackoverflow.com/questions/10732690/offsetting-an-html-anchor-to-adjust-for-fixed-header,1496,953822.0,28.0,,,2012-05-24 07:04:12,2023-04-11 18:22:05,2015-08-29 10:19:50,2015-07-13 09:52:07,Duplicate,javascript;html;css;anchor;offset,Matt Dryden,15015,1245870,registered,true,,,,2015-02-06 04:32:52,440,433,0,0,0,5,false,true,false,true,true,true,52,9,false,0.029,0.0016,5294,2012,5,7,Thursday,false,false,true,false,false,false,false 2140627,How to do case insensitive string comparison?,"How do I perform case insensitive string comparison in JavaScript?
",https://stackoverflow.com/questions/2140627/how-to-do-case-insensitive-string-comparison,1493,1386670.0,23.0,,,2010-01-26 16:07:45,2023-04-21 22:03:01,2019-07-16 16:08:05,,,javascript;string,flybywire,277882,63051,registered,true,2140644,,CC BY-SA 4.0,2017-04-25 23:53:50,74,67,0,0,0,2,true,false,false,true,true,true,45,7,true,0.017,0.0011,6143,2010,1,16,Tuesday,false,false,true,false,false,false,false 170986,What is the best way to add options to a select from a JavaScript object with jQuery?,"What is the best method for adding options to a <select> from a JavaScript object using jQuery?
I'm looking for something that I don't need a plugin to do, but I would also be interested in the plugins that are out there.
This is what I did:
selectValues = { ""1"": ""test 1"", ""2"": ""test 2"" };
for (key in selectValues) {
if (typeof (selectValues[key] == 'string') {
$('#mySelect').append('<option value=""' + key + '"">' + selectValues[key] + '</option>');
}
}
A clean/simple solution:
This is a cleaned up and simplified version of matdumsa's:
$.each(selectValues, function(key, value) {
$('#mySelect')
.append($('<option>', { value : key })
.text(value));
});
Changes from matdumsa's: (1) removed the close tag for the option inside append() and (2) moved the properties/attributes into an map as the second parameter of append().
",https://stackoverflow.com/questions/170986/what-is-the-best-way-to-add-options-to-a-select-from-a-javascript-object-with-jq,1492,1158981.0,37.0,,,2008-10-04 20:58:46,2021-10-22 05:44:29,2020-09-05 13:22:01,,,javascript;jquery;html-select,Darryl Hein,145615,5441,registered,true,171007,,CC BY-SA 4.0,2014-05-29 12:27:12,1161,896,3,1,0,3,true,false,false,true,true,true,85,17,true,0.032,0.0013,6622,2008,10,20,Saturday,true,false,true,false,false,false,false 155188,Trigger a button click with JavaScript on the Enter key in a text box,"I have one text input and one button (see below). How can I use JavaScript to trigger the button's click event when the Enter key is pressed inside the text box?
There is already a different submit button on my current page, so I can't simply make the button a submit button. And, I only want the Enter key to click this specific button if it is pressed from within this one text box, nothing else.
<input type=""text"" id=""txtSearch"" />
<input type=""button"" id=""btnSearch"" value=""Search"" onclick=""doSomething();"" />
",https://stackoverflow.com/questions/155188/trigger-a-button-click-with-javascript-on-the-enter-key-in-a-text-box,1473,1833549.0,31.0,,,2008-09-30 21:32:09,2023-06-30 18:26:12,2022-06-22 15:15:00,,,javascript;button;onclick;onkeydown;onkeypress,kdenney,18593,23947,registered,true,155263,,CC BY-SA 4.0,,616,530,1,0,0,5,true,false,false,true,true,true,69,14,false,0.017,0.0008,6626,2008,9,21,Tuesday,false,false,true,false,false,false,false
3755606,What does the exclamation mark do before the function?,"I found this code:
!function () {}();
What is the purpose of the exclamation mark here?
",https://stackoverflow.com/questions/3755606/what-does-the-exclamation-mark-do-before-the-function,1472,245348.0,8.0,,,2010-09-20 21:21:51,2023-03-15 15:45:40,2023-03-15 15:45:40,,,javascript;function,Sebastian Otto,15289,453227,registered,true,5654929,,CC BY-SA 4.0,2015-09-06 13:38:35,127,89,1,0,0,2,true,false,false,true,true,true,54,9,true,0.033,0.006,5906,2010,9,21,Monday,false,false,true,false,false,false,false 179713,How to change the href attribute for a hyperlink using jQuery,"How can you change the href attribute (link target) for a hyperlink using jQuery?
I am trying to get the highest and lowest value from an array that I know will contain only integers, and it seemed to be harder than I thought.
var numArray = [140000, 104, 99];
numArray = numArray.sort();
console.log(numArray)
I'd expect this to show 99, 104, 140000. Instead, it shows 104, 140000, 99. So it seems the sort is handling the values as strings.
Is there a way to get the sort function to sort on the integer value of each array element?
",https://stackoverflow.com/questions/1063007/how-can-i-sort-an-array-of-integers,1464,1336500.0,34.0,,,2009-06-30 10:43:11,2026-03-11 14:40:26,2026-03-10 01:35:16,,,javascript;arrays;sorting;numbers,peirix,37959,59242,registered,true,1063027,,CC BY-SA 4.0,2014-11-20 13:41:51,781,458,3,0,0,4,true,false,false,true,true,true,36,8,true,0.025,0.0011,6353,2009,6,10,Tuesday,false,false,true,false,false,false,false 32370994,How to pass props to {this.props.children},"I'm trying to find the proper way to define some components which could be used in a generic way:
<Parent>
<Child value=""1"">
<Child value=""2"">
</Parent>
There is a logic going on for rendering between parent and children components of course, you can imagine <select> and <option> as an example of this logic.
This is a dummy implementation for the purpose of the question:
var Parent = React.createClass({
doSomething: function(value) {
},
render: function() {
return (<div>{this.props.children}</div>);
}
});
var Child = React.createClass({
onClick: function() {
this.props.doSomething(this.props.value); // doSomething is undefined
},
render: function() {
return (<div onClick={this.onClick}></div>);
}
});
The question is whenever you use {this.props.children} to define a wrapper component, how do you pass down some property to all its children?
What is the difference between using the delete operator on the array element as opposed to using the Array.splice method?
For example:
myArray = ['a', 'b', 'c', 'd'];
delete myArray[1];
// or
myArray.splice (1, 1);
Why even have the splice method if I can delete array elements like I can with objects?
",https://stackoverflow.com/questions/500606/deleting-array-elements-in-javascript-delete-vs-splice,1460,1699915.0,29.0,,,2009-02-01 11:11:16,2022-06-01 03:16:55,2020-06-25 12:07:59,,,javascript;arrays;element;delete-operator;array-splice,lYriCAlsSH,58197,60102,registered,true,500617,,CC BY-SA 4.0,2012-06-20 18:06:41,613,311,3,2,0,5,true,false,false,true,true,true,56,9,false,0.017,0.0009,6502,2009,2,11,Sunday,true,false,true,false,false,false,false 3955229,Remove all child elements of a DOM node in JavaScript,"How would I go about removing all of the child elements of a DOM node in JavaScript?
Say I have the following (ugly) HTML:
<p id="foo">
<span>hello</span>
<div>world</div>
</p>
And I grab the node I want like so:
var myNode = document.getElementById("foo");
How could I remove the children of foo so that just <p id="foo"></p> is left?
Could I just do:
myNode.childNodes = new Array();
or should I be using some combination of removeElement?
I'd like the answer to be straight up DOM; though extra points if you also provide an answer in jQuery along with the DOM-only answer.
",https://stackoverflow.com/questions/3955229/remove-all-child-elements-of-a-dom-node-in-javascript,1456,1745917.0,33.0,,,2010-10-17 20:51:00,2025-02-05 11:14:42,2023-02-07 17:47:39,,,javascript;dom,DigitalZebra,42018,125278,registered,true,65413839,,CC BY-SA 4.0,2020-07-28 08:13:36,865,666,6,0,0,2,true,false,false,true,true,true,53,10,false,0.019,0.0008,5879,2010,10,20,Sunday,true,false,true,false,false,false,false 10659097,jQuery Get Selected Option From Dropdown,"Usually I use $("#id").val() to return the value of the selected option, but this time it doesn't work.
The selected tag has the id aioConceptName
html code
<label for="name">Name</label>
<input type="text" name="name" id="name" />
<label for="aioConceptName">AIO Concept Name</label>
<select id="aioConceptName">
<option>choose io</option>
<option>roma</option>
<option>totti</option>
</select>
",https://stackoverflow.com/questions/10659097/jquery-get-selected-option-from-dropdown,1451,2451958.0,38.0,,,2012-05-18 20:11:54,2025-04-11 03:05:06,2025-04-11 03:05:06,,,javascript;html;jquery;drop-down-menu;html-select,William Kinaan,28979,1378388,registered,true,10659117,,CC BY-SA 4.0,2025-04-11 05:06:04,639,558,3,0,0,5,true,false,false,true,true,true,40,6,false,0.015,0.0006,5300,2012,5,20,Friday,false,false,true,false,false,false,false
8217419,How to determine if a JavaScript array contains an object with an attribute that equals a given value,"I have an array like
vendors = [{
Name: 'Magenic',
ID: 'ABC'
},
{
Name: 'Microsoft',
ID: 'DEF'
} // and so on...
];
How do I check this array to see if "Magenic" exists? I don't want to loop, unless I have to. I'm working with potentially a couple of thousand records.
",https://stackoverflow.com/questions/8217419/how-to-determine-if-a-javascript-array-contains-an-object-with-an-attribute-that,1448,2026451.0,29.0,,,2011-11-21 19:30:40,2025-01-08 02:24:40,2023-07-19 22:38:36,,,javascript;arrays,David Lozzi,16061,444578,registered,true,8217466,,CC BY-SA 4.0,2019-06-18 08:06:23,340,302,1,0,0,2,true,false,false,true,true,true,101,18,false,0.014,0.0007,5479,2011,11,19,Monday,false,false,true,false,false,false,false 3715047,How to reload a page using JavaScript,"How can I reload the page using JavaScript?
I need a method that works in all browsers.
",https://stackoverflow.com/questions/3715047/how-to-reload-a-page-using-javascript,1431,2113529.0,13.0,,,2010-09-15 06:03:09,2023-05-26 13:13:45,2021-08-18 17:55:41,,,javascript,Resh,14299,448041,unregistered,true,,,CC BY-SA 4.0,2021-08-20 03:35:47,103,89,0,0,0,1,false,false,false,true,true,true,37,7,false,0.006,0.0007,5911,2010,9,6,Wednesday,false,false,true,false,false,false,false 4228356,"How to perform an integer division, and separately get the remainder, in JavaScript","In JavaScript, how do I get:
How can I convert a JavaScript string value to be in all lowercase letters?
Example: "Your Name" to "your name"
Is there a method to remove an item from a JavaScript array?
Given an array:
var ary = ['three', 'seven', 'eleven'];
I would like to do something like:
removeItem('seven', ary);
I've looked into splice() but that only removes by the position number, whereas I need something to remove an item by its value.
I have been reading online and some places say it isn't possible, some say it is and then give an example and others refute the example, etc.
How do I declare a 2 dimensional array in JavaScript? (assuming it's possible)
How would I access its members? (myArray[0][1] or myArray[0,1]?)
Is there a way to return the difference between two arrays in JavaScript?
For example:
var a1 = ['a', 'b'];
var a2 = ['a', 'b', 'c', 'd'];
// need [""c"", ""d""]
",https://stackoverflow.com/questions/1187518/how-to-get-the-difference-between-two-arrays-in-javascript,1410,1270878.0,86.0,,,2009-07-27 10:38:50,2025-11-15 14:45:24,2019-08-15 18:57:30,,,javascript;arrays;array-difference,John Adawan,14297,119033,unregistered,true,1187628,,CC BY-SA 4.0,2019-08-15 18:57:41,237,162,1,0,0,3,true,false,false,true,true,true,59,10,true,0.068,0.0011,6326,2009,7,10,Monday,false,false,true,false,false,false,false
1181575,Determine whether an array contains a value,"I need to determine if a value exists in an array.
I am using the following function:
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] == obj) {
return true;
}
}
return false;
}
The above function always returns false.
The array values and the function call is as below:
arrValues = [""Sam"",""Great"", ""Sample"", ""High""]
alert(arrValues.contains(""Sam""));
",https://stackoverflow.com/questions/1181575/determine-whether-an-array-contains-a-value,1406,1775094.0,18.0,,,2009-07-25 08:18:57,2017-11-04 17:39:20,2015-07-01 11:39:20,2016-04-14 19:09:55,Duplicate,javascript;arrays;contains,Prasad,59669,111435,registered,true,1181586,,,,519,443,2,0,0,3,true,true,false,true,true,true,43,7,false,0.01,0.0008,6328,2009,7,8,Saturday,true,false,true,false,false,false,false
3698200,window.onload vs $(document).ready(),"What are the differences between JavaScript's window.onload and jQuery's $(document).ready() method?
I'm loading elements via AJAX. Some of them are only visible if you scroll down the page. Is there any way I can know if an element is now in the visible part of the page?
",https://stackoverflow.com/questions/487073/how-to-check-if-element-is-visible-after-scrolling,1393,963428.0,47.0,,,2009-01-28 10:00:55,2023-11-06 06:36:24,2020-07-02 19:59:13,,,javascript;jquery;scroll,yoavf,21293,1011,registered,true,488073,,CC BY-SA 4.0,2015-10-05 09:02:13,179,172,0,0,0,3,true,false,false,true,true,true,51,9,true,0.049,0.0014,6506,2009,1,10,Wednesday,false,false,true,false,false,false,false 4162749,Convert JS object to JSON string,"If I defined an object in JS with:
var j={""name"":""binchen""};
How can I convert the object to JSON? The output string should be:
'{""name"":""binchen""}'
",https://stackoverflow.com/questions/4162749/convert-js-object-to-json-string,1393,1819154.0,23.0,,,2010-11-12 08:20:50,2023-04-16 12:30:20,2019-10-16 15:42:03,,,javascript;json;string;object,Bin Chen,63729,197036,registered,true,4162803,,CC BY-SA 4.0,2016-08-24 07:32:42,216,154,2,0,0,4,true,false,false,true,true,true,32,6,false,0.013,0.0008,5853,2010,11,8,Friday,false,false,true,false,false,false,false
43871637,No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API,"I'm trying to fetch some data from the REST API of HP Alm. It works pretty well with a small curl script—I get my data.
Now doing that with JavaScript, fetch and ES6 (more or less) seems to be a bigger issue. I keep getting this error message:
Fetch API cannot load . Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:3000' is therefore not allowed access. The response had HTTP status code 501. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I understand that this is because I am trying to fetch that data from within my localhost and the solution should be using Cross-Origin Resource Sharing (CORS). I thought I actually did that, but somehow it either ignores what I write in the header or the problem is something else.
So, is there an implementation issue? Am I doing it wrong? I can't check the server logs unfortunately. I'm really a bit stuck here.
function performSignIn() {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');
headers.append('Access-Control-Allow-Origin', 'http://localhost:3000');
headers.append('Access-Control-Allow-Credentials', 'true');
headers.append('GET', 'POST', 'OPTIONS');
headers.append('Authorization', 'Basic ' + base64.encode(username + ":" + password));
fetch(sign_in, {
//mode: 'no-cors',
credentials: 'include',
method: 'POST',
headers: headers
})
.then(response => response.json())
.then(json => console.log(json))
.catch(error => console.log('Authorization failed : ' + error.message));
}
I am using Chrome. I also tried using that Chrome CORS Plugin, but then I am getting another error message:
",https://stackoverflow.com/questions/43871637/no-access-control-allow-origin-header-is-present-on-the-requested-resource-whe,1379,4352698.0,34.0,,,2017-05-09 13:47:47,2025-08-13 09:32:14,2022-08-14 12:48:18,,,javascript;cors;fetch-api,daniel.lozynski,17057,1331465,registered,true,43881141,,CC BY-SA 4.0,2018-04-29 10:53:42,2431,2222,1,1,0,3,true,false,false,true,true,true,124,17,false,0.008,0.0003,3483,2017,5,13,Tuesday,false,false,true,false,false,false,false 11381673,Detecting a mobile browser,"The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://127.0.0.1:3000' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
I'm looking for a function that returns a boolean value if the user is using a mobile browser or not.
I know that I can use navigator.userAgent and write that function by using regex, but user-agents are too various for different platforms. I doubt that matching all possible devices would be easy, and I think this problem has been solved many times so there should be some kind of complete solution for such a task.
I was looking at this site, but sadly the script is so cryptic that I have no idea how to use it for my purpose, which is to create a function that returns true/false.
",https://stackoverflow.com/questions/11381673/detecting-a-mobile-browser,1376,1752110.0,38.0,,,2012-07-08 08:13:21,2025-02-17 14:11:47,2022-09-19 13:25:48,,,javascript;browser-detection;mobile-browser;platform-detection,ave,19803,1509733,registered,true,11381730,,CC BY-SA 4.0,2015-12-11 18:41:58,683,586,1,1,0,4,true,false,false,true,true,true,26,4,false,0.022,0.0008,5249,2012,7,8,Sunday,true,false,true,false,false,false,false 498970,Trim string in JavaScript,"How do I remove all whitespace from the start and end of the string?
",https://stackoverflow.com/questions/498970/trim-string-in-javascript,1368,897220.0,20.0,,,2009-01-31 15:12:23,2025-11-07 17:36:31,2022-06-13 01:47:20,,,javascript;string;trim,Vinod,33221,20951,registered,true,498995,,CC BY-SA 4.0,2013-02-23 05:39:34,76,69,0,0,0,3,true,false,false,true,true,true,25,4,false,0.022,0.0015,6503,2009,1,15,Saturday,true,false,true,false,false,false,false 268490,jQuery document.createElement equivalent?,"I'm refactoring some old JavaScript code and there's a lot of DOM manipulation going on.
var d = document;
var odv = d.createElement(""div"");
odv.style.display = ""none"";
this.OuterDiv = odv;
var t = d.createElement(""table"");
t.cellSpacing = 0;
t.className = ""text"";
odv.appendChild(t);
I would like to know if there is a better way to do this using jQuery. I've been experimenting with:
var odv = $.create(""div"");
$.append(odv);
// And many more
But I'm not sure if this is any better.
",https://stackoverflow.com/questions/268490/jquery-document-createelement-equivalent,1368,1063087.0,15.0,,,2008-11-06 12:26:31,2023-05-12 14:21:28,2016-01-22 20:18:54,,,javascript;jquery;html;dom;dhtml,Rob Stevenson-Leggett,35809,4950,registered,true,268520,,CC BY-SA 3.0,2014-03-07 21:31:31,561,492,2,0,0,5,true,false,false,true,true,true,41,3,true,0.014,0.0013,6589,2008,11,12,Thursday,false,false,true,false,false,false,false 1458724,How do I set/unset a cookie with jQuery?,"How do I set and unset a cookie using jQuery, for example create a cookie named test and set the value to 1?
I'm using ArcGIS JSAPI 4.12 and wish to use Spatial Illusions to draw military symbols on a map.
When I add milsymbol.js to the script, the console returns error
Uncaught SyntaxError: Cannot use import statement outside a module`
so I add type="module" to the script, and then it returns
Uncaught ReferenceError: ms is not defined
Here's my code:
<link rel="stylesheet" href="https://js.arcgis.com/4.12/esri/css/main.css">
<script src="https://js.arcgis.com/4.12/"></script>
<script type="module" src="milsymbol-2.0.0/src/milsymbol.js"></script>
<script>
require([
"esri/Map",
"esri/views/MapView",
"esri/layers/MapImageLayer",
"esri/layers/FeatureLayer"
], function (Map, MapView, MapImageLayer, FeatureLayer) {
var symbol = new ms.Symbol("SFG-UCI----D", { size: 30 }).asCanvas(3);
var map = new Map({
basemap: "topo-vector"
});
var view = new MapView({
container: "viewDiv",
map: map,
center: [121, 23],
zoom: 7
});
});
</script>
So, whether I add type="module" or not, there are always errors. However, in the official document of Spatial Illusions, there isn't any type="module" in the script. I'm now really confused. How do they manage to get it work without adding the type?
import { ms } from "./ms.js";
import Symbol from "./ms/symbol.js";
ms.Symbol = Symbol;
export { ms };
",https://stackoverflow.com/questions/58211880/uncaught-syntaxerror-cannot-use-import-statement-outside-a-module-when-import,1356,4617672.0,34.0,,,2019-10-03 03:20:04,2025-05-27 10:48:18,2024-01-04 00:59:36,,,javascript;ecmascript-6;arcgis;arcgis-js-api,Jerry Chen,14067,6647721,registered,true,,,CC BY-SA 4.0,2021-12-31 10:06:44,2002,1669,6,1,0,4,false,false,false,true,true,true,106,13,false,0.007,0.0003,2606,2019,10,3,Thursday,false,false,true,false,false,false,false
332422,Get the name of an object's type,"Is there a JavaScript equivalent of Java's class.getName()?
When removing an element with standard JavaScript, you must go to its parent first:
var element = document.getElementById(""element-id"");
element.parentNode.removeChild(element);
Having to go to the parent node first seems a bit odd to me, is there a reason JavaScript works like this?
",https://stackoverflow.com/questions/3387427/remove-element-by-id,1350,1915221.0,19.0,,,2010-08-01 18:47:14,2022-07-01 16:33:02,2020-06-12 10:05:18,,,javascript;dom,Zaz,49355,405550,registered,true,27710003,,,2012-11-18 02:47:22,326,288,1,0,0,2,true,false,false,true,true,true,20,4,false,0.01,0.0007,5956,2010,8,18,Sunday,true,false,true,false,false,false,false 13964155,Get JavaScript object from array of objects by value of property,"Let's say I have an array of four objects:
var jsObjects = [
{a: 1, b: 2},
{a: 3, b: 4},
{a: 5, b: 6},
{a: 7, b: 8}
];
Is there a way that I can get the third object ({a: 5, b: 6}) by the value of the property b for example without a for...in loop?
I know what is a for... in loop (it iterates over the keys), but I have heard about for... of for the first time (it iterates over values).
I am confused about for... of loop.
var arr = [3, 5, 7];
arr.foo = "hello";
for (var i in arr) {
console.log(i); // logs "0", "1", "2", "foo"
}
for (var i of arr) {
console.log(i); // logs "3", "5", "7"
// it doesn't log "3", "5", "7", "hello"
}
I understand that for... of iterates over property values. Then why doesn't it log "3", "5", "7", "hello" instead of "3", "5", "7"?
Unlike for... in loop, which iterates over each key ("0", "1", "2", "foo") and also iterates over the foo key, the for... of does not iterate over the value of foo property, i.e., "hello". Why it is like that?
Here I console for... of loop. It should log "3", "5", "7","hello" but it logs "3", "5", "7". Why?
I have a JavaScript widget which provides standard extension points. One of them is the beforecreate function. It should return false to prevent an item from being created.
I've added an Ajax call into this function using jQuery:
beforecreate: function (node, targetNode, type, to) {
jQuery.get('http://example.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value),
function (result) {
if (result.isOk == false)
alert(result.message);
});
}
But I want to prevent my widget from creating the item, so I should return false in the mother-function, not in the callback. Is there a way to perform a synchronous AJAX request using jQuery or any other in-browser API?
After experimenting with composite operations and drawing images on the canvas I'm now trying to remove images and compositing. How do I do this?
I need to clear the canvas for redrawing other images; this can go on for a while so I don't think drawing a new rectangle every time will be the most efficient option.
",https://stackoverflow.com/questions/2142535/how-to-clear-the-canvas-for-redrawing,1331,1313856.0,26.0,,,2010-01-26 20:50:42,2024-05-11 17:40:55,2016-09-17 01:35:47,,,javascript;html;canvas;html5-canvas;composite,richard,14690,123048,registered,true,2142549,,CC BY-SA 3.0,2013-06-23 10:12:08,330,316,0,0,0,5,true,false,false,true,true,true,37,7,false,0.02,0.001,6143,2010,1,20,Tuesday,false,false,true,false,false,false,false 31354559,Using Node.js require vs. ES6 import/export,"In a project I am collaborating on, we have two choices on which module system we can use:
require, and exporting using module.exports and exports.foo.import, and exporting using ES6 exportAre there any performance benefits to using one over the other? Is there anything else that we should know if we were to use ES6 modules over Node.js ones?
",https://stackoverflow.com/questions/31354559/using-node-js-require-vs-es6-import-export,1331,874284.0,11.0,,,2015-07-11 07:19:47,2024-01-29 04:04:44,2024-01-29 03:19:22,,,javascript;node.js;ecmascript-6;babeljs,kpimov,13962,4954970,registered,true,31367852,,CC BY-SA 4.0,2019-12-17 07:57:01,617,401,5,1,0,4,true,false,false,true,true,true,43,6,false,0.013,0.0015,4151,2015,7,7,Saturday,true,false,true,false,false,false,false 10123953,How to sort an object array by date property?,"Say I have an array of a few objects:
var array = [{id: 1, date: Mar 12 2012 10:00:00 AM}, {id: 2, date: Mar 8 2012 08:00:00 AM}];
How can I sort this array by the date element in order from the date closest to the current date and time down? Keep in mind that the array may have many objects, but for the sake of simplicity I used 2.
Would I use the sort function and a custom comparator?
",https://stackoverflow.com/questions/10123953/how-to-sort-an-object-array-by-date-property,1323,1728095.0,25.0,,,2012-04-12 12:53:03,2024-09-20 18:24:03,2021-01-21 10:07:15,,,javascript;datetime,ryandlf,28796,838151,registered,true,10124053,,CC BY-SA 4.0,2018-12-20 06:47:40,436,391,1,0,0,2,true,false,false,true,true,true,45,9,true,0.014,0.0008,5336,2012,4,12,Thursday,false,false,true,false,false,false,false 6134039,Format number to always show 2 decimal places,"I would like to format my numbers to always display 2 decimal places, rounding where applicable.
Examples:
number display
------ -------
1 1.00
1.341 1.34
1.345 1.35
I have been using this:
parseFloat(num).toFixed(2);
But it's displaying 1 as 1, rather than 1.00.
I am working on a search with JavaScript. I would use a form, but it messes up something else on my page. I have this input text field:
<input name="searchTxt" type="text" maxlength="512" id="searchTxt" class="searchField"/>
And this is my JavaScript code:
<script type="text/javascript">
function searchURL(){
window.location = "http://www.myurl.com/search/" + (input text value);
}
</script>
How do I get the value from the text field into JavaScript?
",https://stackoverflow.com/questions/11563638/how-do-i-get-the-value-of-text-input-field-using-javascript,1315,4283098.0,16.0,,,2012-07-19 15:00:28,2023-12-03 12:33:52,2022-09-19 19:39:14,,,javascript;dom;html-input,user979331,12139,979331,registered,true,11563667,,CC BY-SA 4.0,2018-11-20 08:31:15,697,552,2,0,0,3,true,false,false,true,true,true,60,12,true,0.004,0.0003,5238,2012,7,15,Thursday,false,false,true,false,false,false,false 4550505,Getting a random value from a JavaScript array,"Consider:
var myArray = ['January', 'February', 'March'];
How can I select a random value from this array using JavaScript?
",https://stackoverflow.com/questions/4550505/getting-a-random-value-from-a-javascript-array,1308,1189423.0,19.0,,,2010-12-29 00:04:44,2025-07-16 07:32:48,2020-06-16 04:35:36,,,javascript;random,Sarah,13251,551339,unregistered,true,4550514,,CC BY-SA 4.0,2019-08-01 07:30:02,169,131,1,0,0,2,true,false,false,true,true,true,46,8,false,0.016,0.0011,5806,2010,12,0,Wednesday,false,false,true,false,false,false,false 27928372,React-router URLs don't work when refreshing or writing manually,"I'm using React-router and it works fine while I'm clicking on link buttons, but when I refresh my webpage it does not load what I want.
For instance, I am in localhost/joblist and everything is fine because I arrived here pressing a link. But if I refresh the webpage I get:
Cannot GET /joblist
By default, it didn't work like this. Initially I had my URL as localhost/#/ and localhost/#/joblist and they worked perfectly fine. But I don't like this kind of URL, so trying to erase that #, I wrote:
Router.run(routes, Router.HistoryLocation, function (Handler) {
React.render(<Handler/>, document.body);
});
This problem does not happen with localhost/, this one always returns what I want.
This app is single-page, so /joblist doesn't need to ask anything to any server.
My entire router.
var routes = (
<Route name="app" path="/" handler={App}>
<Route name="joblist" path="/joblist" handler={JobList}/>
<DefaultRoute handler={Dashboard}/>
<NotFoundRoute handler={NotFound}/>
</Route>
);
Router.run(routes, Router.HistoryLocation, function (Handler) {
React.render(<Handler/>, document.body);
});
",https://stackoverflow.com/questions/27928372/react-router-urls-dont-work-when-refreshing-or-writing-manually,1306,925663.0,62.0,,,2015-01-13 17:51:54,2024-06-16 14:26:50,2022-05-06 13:49:05,,,javascript;reactjs;url;react-router,DavidDev,13423,4377851,registered,true,36623117,,CC BY-SA 4.0,2019-01-17 16:07:47,1460,1220,9,0,0,4,true,false,false,true,true,true,68,9,false,0.067,0.0014,4330,2015,1,17,Tuesday,false,false,true,false,false,false,false
123999,How can I tell if a DOM element is visible in the current viewport?,"Is there an efficient way to tell if a DOM element (in an HTML document) is currently visible (appears in the viewport)?
(The question refers to Firefox.)
",https://stackoverflow.com/questions/123999/how-can-i-tell-if-a-dom-element-is-visible-in-the-current-viewport,1306,896990.0,32.0,,,2008-09-23 21:24:56,2025-08-05 13:12:36,2019-12-15 04:44:59,,,javascript;html;firefox;dom;browser,benzaita,13499,21290,registered,true,125106,,CC BY-SA 4.0,2015-02-05 03:43:13,187,156,0,0,0,5,true,false,false,true,true,true,67,14,true,0.036,0.0015,6633,2008,9,21,Tuesday,false,false,true,false,false,false,false 359788,How to execute a JavaScript function when I have its name as a string,"I have the name of a function in JavaScript as a string. How do I convert that into a function pointer so I can call it later?
Depending on the circumstances, I may need to pass various arguments into the method too.
Some of the functions may take the form of namespace.namespace.function(args[...]).
Suppose I have any variable, which is defined as follows:
var a = function() {/* Statements */};
I want a function which checks if the type of the variable is function-like. i.e. :
function foo(v) {if (v is function type?) {/* do something */}};
foo(a);
How can I check if the variable a is of type Function in the way defined above?
Suppose I have a drop-down list like:
<select id='list'>
<option value='1'>Option A</option>
<option value='2'>Option B</option>
<option value='3'>Option C</option>
</select>
Given the value '2' (i.e., using a specific value, not necessarily the selected one), what selector can I use to get "Option B"?
I tried $("#list[value='2']").text();, but it is not working.
I have a PHP script that can encode a PNG image to a Base64 string.
I'd like to do the same thing using JavaScript. I know how to open files, but I'm not sure how to do the encoding. I'm not used to working with binary data.
",https://stackoverflow.com/questions/246801/how-can-you-encode-decode-a-string-to-base64-in-javascript,1283,2207067.0,33.0,,,2008-10-29 13:34:18,2026-04-21 15:56:52,2024-10-29 16:26:57,,,javascript;base64;binaryfiles,username,19860,4939,registered,true,247261,,CC BY-SA 4.0,2014-01-06 20:45:45,240,226,0,0,0,3,true,false,false,true,true,true,59,10,true,0.015,0.0006,6597,2008,10,13,Wednesday,false,false,true,false,false,false,false 6712034,Sort array by firstname (alphabetically) in JavaScript,"I got an array (see below for one object in the array) that I need to sort by firstname using JavaScript. How can I do it?
var user = {
bio: null,
email: "user@domain.example",
firstname: "Anna",
id: 318,
lastAvatar: null,
lastMessage: null,
lastname: "Nickson",
nickname: "anny"
};
",https://stackoverflow.com/questions/6712034/sort-array-by-firstname-alphabetically-in-javascript,1270,1535030.0,23.0,,,2011-07-15 19:10:55,2024-12-11 10:53:56,2022-06-21 18:56:59,2020-12-14 10:40:02,Duplicate,javascript,Jonathan Clark,20678,261694,registered,true,6712080,,,2017-12-30 02:35:51,380,349,1,0,0,1,true,true,false,true,true,true,54,7,false,0.015,0.0008,5608,2011,7,19,Friday,false,false,true,false,false,false,false
932653,How to prevent buttons from submitting forms,"In the following page, with Firefox the remove button submits the form, but the add button does not.
How do I prevent the remove button from submitting the form?
function addItem() {
var v = $('form :hidden:last').attr('name');
var n = /(.*)input/.exec(v);
var newPrefix;
if (n[1].length == 0) {
newPrefix = '1';
} else {
newPrefix = parseInt(n[1]) + 1;
}
var oldElem = $('form tr:last');
var newElem = oldElem.clone(true);
var lastHidden = $('form :hidden:last');
lastHidden.val(newPrefix);
var pat = '=\""' + n[1] + 'input';
newElem.html(newElem.html().replace(new RegExp(pat, 'g'), '=\""' + newPrefix + 'input'));
newElem.appendTo('table');
$('form :hidden:last').val('');
}
function removeItem() {
var rows = $('form tr');
if (rows.length > 2) {
rows[rows.length - 1].html('');
$('form :hidden:last').val('');
} else {
alert('Cannot remove any more rows');
}
}
<script src=""https://cdnjs.cloudflare.com/ajax/libs/jquery/1.3.2/jquery.min.js""></script>
<html>
<body>
<form autocomplete=""off"" method=""post"" action="""">
<p>Title:<input type=""text"" /></p>
<button onclick=""addItem(); return false;"">Add Item</button>
<button onclick=""removeItem(); return false;"">Remove Last Item</button>
<table>
<th>Name</th>
<tr>
<td><input type=""text"" id=""input1"" name=""input1"" /></td>
<td><input type=""hidden"" id=""input2"" name=""input2"" /></td>
</tr>
</table>
<input id=""submit"" type=""submit"" name=""submit"" value=""Submit"">
</form>
</body>
</html>
What is the difference between event bubbling and capturing? When should one use bubbling vs capturing?
",https://stackoverflow.com/questions/4616694/what-is-event-bubbling-and-capturing,1264,590461.0,11.0,,,2011-01-06 15:44:43,2024-04-05 10:05:22,2019-08-21 21:48:52,,,javascript;dom-events;event-bubbling,Arun P Johny,388837,114251,registered,true,4616720,,CC BY-SA 4.0,2016-07-22 22:32:17,111,104,0,0,0,3,true,false,false,true,true,true,37,6,true,0.019,0.0021,5798,2011,1,15,Thursday,false,false,true,false,false,false,false 23593052,Format JavaScript date as yyyy-mm-dd,"I have a date with the format Sun May 11,2014. How can I convert it to 2014-05-11 using JavaScript?
function taskDate(dateMilli) {
var d = (new Date(dateMilli) + '').split(' ');
d[2] = d[2] + ',';
return [d[0], d[1], d[2], d[3]].join(' ');
}
var datemilli = Date.parse('Sun May 11,2014');
console.log(taskDate(datemilli));
The code above gives me the same date format, sun may 11,2014. How can I fix this?
I have a JavaScript array dataArray which I want to push into a new array newArray. Except I don't want newArray[0] to be dataArray. I want to push in all the items into the new array:
var newArray = [];
newArray.pushValues(dataArray1);
newArray.pushValues(dataArray2);
// ...
or even better:
var newArray = new Array (
dataArray1.values(),
dataArray2.values(),
// ... where values() (or something equivalent) would push the individual values into the array, rather than the array itself
);
So now the new array contains all the values of the individual data arrays. Is there some shorthand like pushValues available so I don't have to iterate over each individual dataArray, adding the items one by one?
Are there any good resources to get started with Node.JS? Any good tutorials, blogs or books?
Of course, I have visited its official website http://nodejs.org/, but I didn't think the documentation they have is a good starting point.
",https://stackoverflow.com/questions/2353818/how-do-i-get-started-with-node-js,1260,1297688.0,3.0,,,2010-03-01 04:09:28,2022-05-23 12:42:40,2013-01-13 16:05:55,2018-02-19 12:12:44,Not suitable for this site,javascript;node.js,Joneph O.,6919,279932,unregistered,true,,,,,299,235,0,1,0,2,false,true,false,true,true,true,33,7,false,0.002,0.001,6109,2010,3,4,Monday,false,false,true,false,false,false,false 94037,Convert character to ASCII code in JavaScript,"How can I convert a character to its ASCII code using JavaScript?
For example:
",https://stackoverflow.com/questions/94037/convert-character-to-ascii-code-in-javascript,1260,1500659.0,18.0,,,2008-09-18 16:13:48,2023-04-26 09:09:40,2020-09-09 04:29:52,,,javascript,levik,118355,4465,registered,true,94049,,CC BY-SA 4.0,2015-09-23 19:08:16,155,109,0,0,0,1,true,false,false,true,true,true,45,7,false,0.012,0.0008,6638,2008,9,16,Thursday,false,false,true,false,false,false,false 294250,How do I retrieve an HTML element's actual width and height?,"get 10 from "\n".
How can I calculate the width and height of a <div> element, so as to be able to center it in the browser's display (viewport)? What browsers support each technique?
What is wrong with my Angular code? I am getting the following error:
Cannot read property 'remove' of undefined at BrowserDomAdapter.removeClass
<ol>
<li *ngClass="{active: step==='step1'}" (click)="step='step1'">Step1</li>
<li *ngClass="{active: step==='step2'}" (click)="step='step2'">Step2</li>
<li *ngClass="{active: step==='step3'}" (click)="step='step3'">Step3</li>
</ol>
",https://stackoverflow.com/questions/35269179/angular-conditional-class-with-ngclass,1247,2339593.0,26.0,,,2016-02-08 12:00:54,2025-04-02 07:19:41,2021-02-28 07:58:35,,,javascript;css;angular;angular-template;angular-ng-class,daniel,35951,516389,registered,true,41974490,,CC BY-SA 4.0,,598,496,1,0,0,5,true,false,false,true,true,true,40,5,false,0.011,0.0005,3939,2016,2,12,Monday,false,false,true,false,false,false,false
5612787,Converting an object to a string,"How can I convert a JavaScript object into a string?
Example:
var o = {a:1, b:2}
console.log(o)
console.log('Item: ' + o)
Output:
",https://stackoverflow.com/questions/5612787/converting-an-object-to-a-string,1247,2452350.0,42.0,,,2011-04-10 15:35:44,2024-10-15 13:17:28,2020-05-14 13:09:42,,,javascript;string;object;serialization;tostring,user680174,12471,680174,registered,true,,,CC BY-SA 4.0,2018-12-29 23:54:27,323,242,1,0,0,5,false,false,false,true,true,true,32,6,false,0.017,0.0005,5704,2011,4,15,Sunday,true,false,true,false,false,false,false 2243824,What is the difference between String.slice and String.substring?,"Object { a=1, b=2} // very nice readable output :)
Item: [object Object] // no idea what's inside :(
Does anyone know what the difference is between these two methods?
String.prototype.slice
String.prototype.substring
",https://stackoverflow.com/questions/2243824/what-is-the-difference-between-string-slice-and-string-substring,1247,476153.0,9.0,,,2010-02-11 10:34:04,2026-01-15 07:49:49,2020-04-17 18:26:27,,,javascript;substring;slice;substr,tmim,13071,263123,registered,true,,,CC BY-SA 4.0,2022-03-09 11:31:45,150,119,1,0,0,4,false,false,false,true,true,true,65,8,true,0.019,0.0026,6127,2010,2,10,Thursday,false,false,true,false,false,false,false
47824,How do you remove all the options of a select box and then add one option and select it with jQuery?,"Using core jQuery, how do you remove all the options of a select box, then add one option and select it?
My select box is the following.
<Select id=""mySelect"" size=""9""> </Select>
EDIT: The following code was helpful with chaining. However, (in Internet Explorer) .val('whatever') did not select the option that was added. (I did use the same 'value' in both .append and .val.)
$('#mySelect').find('option').remove().end()
.append('<option value=""whatever"">text</option>').val('whatever');
EDIT: Trying to get it to mimic this code, I use the following code whenever the page/form is reset. This select box is populated by a set of radio buttons. .focus() was closer, but the option did not appear selected like it does with .selected= ""true"". Nothing is wrong with my existing code - I am just trying to learn jQuery.
var mySelect = document.getElementById('mySelect');
mySelect.options.length = 0;
mySelect.options[0] = new Option (""Foo (only choice)"", ""Foo"");
mySelect.options[0].selected=""true"";
EDIT: selected answer was close to what I needed. This worked for me:
$('#mySelect').children().remove().end()
.append('<option selected value=""whatever"">text</option>') ;
But both answers led me to my final solution..
",https://stackoverflow.com/questions/47824/how-do-you-remove-all-the-options-of-a-select-box-and-then-add-one-option-and-se,1246,1425122.0,28.0,,,2008-09-06 20:53:54,2022-06-26 07:36:17,2022-01-12 21:05:50,,,javascript;jquery;html-select;dynamic-html,Jay Corbett,28521,2755,registered,true,47829,,CC BY-SA 4.0,2018-10-12 09:15:02,1475,1272,9,0,0,4,true,false,false,true,true,true,100,21,true,0.02,0.0009,6650,2008,9,20,Saturday,true,false,true,false,false,false,false 2917175,Return multiple values in JavaScript?,"I am trying to return two values in JavaScript. Is this possible?
var newCodes = function() {
var dCodes = fg.codecsCodes.rs;
var dCodes2 = fg.codecsCodes2.rs;
return dCodes, dCodes2;
};
",https://stackoverflow.com/questions/2917175/return-multiple-values-in-javascript,1244,1316336.0,21.0,,,2010-05-26 22:06:55,2024-10-01 17:43:58,2020-04-17 18:09:42,,,javascript;return;multiple-variable-return,Asim Zaidi,28541,295189,registered,true,2917186,,CC BY-SA 4.0,2019-09-20 17:15:00,253,205,1,0,0,3,true,false,false,true,true,true,37,5,true,0.016,0.0009,6023,2010,5,22,Wednesday,false,false,true,false,false,false,false
7505623,Colors in JavaScript console,"Can Chrome's built-in JavaScript console display colors?
I want errors in red, warnings in orange and console.log's in green. Is that possible?
I'm fairly new to Node.js and I am having some issues.
I am using Node.js 4.10 and Express 2.4.3.
When I try to access http://127.0.0.1:8888/auth/facebook, i'll be redirected to http://127.0.0.1:8888/auth/facebook_callback.
I then received the following error:
Error: Can't render headers after they are sent to the client.
at ServerResponse.<anonymous> (http.js:573:11)
at ServerResponse._renderHeaders (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/patch.js:64:25)
at ServerResponse.writeHead (http.js:813:20)
at /home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/auth.strategies/facebook.js:28:15
at /home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/index.js:113:13
at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/strategyExecutor.js:45:39)
at [object Object].pass (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/authExecutionScope.js:32:3)
at [object Object].halt (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/authExecutionScope.js:29:8)
at [object Object].redirect (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/authExecutionScope.js:16:8)
at [object Object].<anonymous> (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/auth.strategies/facebook.js:77:15)
Error: Can't set headers after they are sent.
at ServerResponse.<anonymous> (http.js:527:11)
at ServerResponse.setHeader (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/patch.js:50:20)
at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:162:13)
at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:195:11)
at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:150:23)
at param (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/router.js:189:13)
at pass (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/router.js:191:10)
at Object.router [as handle] (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/router.js:197:6)
at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:198:15)
at Object.auth [as handle] (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/index.js:153:7)
Error: Can't set headers after they are sent.
at ServerResponse.<anonymous> (http.js:527:11)
at ServerResponse.setHeader (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/patch.js:50:20)
at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:162:13)
at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:207:9)
at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:150:23)
at param (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/router.js:189:13)
at pass (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/router.js:191:10)
at Object.router [as handle] (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/router.js:197:6)
at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:198:15)
at Object.auth [as handle] (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/index.js:153:7)
Error: Can't set headers after they are sent.
at ServerResponse.<anonymous> (http.js:527:11)
at ServerResponse.setHeader (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/patch.js:50:20)
at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:162:13)
at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:150:23)
at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:207:9)
at Object.auth [as handle] (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/index.js:153:7)
at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:198:15)
at HTTPServer.handle (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:211:3)
at Object.handle (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:105:14)
at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:198:15)
Error: Can't set headers after they are sent.
at ServerResponse.<anonymous> (http.js:527:11)
at ServerResponse.setHeader (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/patch.js:50:20)
at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:162:13)
at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:150:23)
at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:207:9)
at HTTPServer.handle (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:211:3)
at Object.handle (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:105:14)
at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:198:15)
at /home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/session.js:323:9
at /home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/session.js:338:9
node.js:134
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: Can't set headers after they are sent.
at ServerResponse.<anonymous> (http.js:527:11)
at ServerResponse.setHeader (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/patch.js:50:20)
at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:162:13)
at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:207:9)
at /home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/session.js:323:9
at /home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/session.js:338:9
at Array.<anonymous> (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/session/memory.js:57:7)
at EventEmitter._tickCallback (node.js:126:26)
The following is my code:
var fbId= ""XXX"";
var fbSecret= ""XXXXXX"";
var fbCallbackAddress= ""http://127.0.0.1:8888/auth/facebook_callback""
var cookieSecret = ""node""; // enter a random hash for security
var express= require('express');
var auth = require('connect-auth')
var app = express.createServer();
app.configure(function(){
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({secret: cookieSecret}));
app.use(auth([
auth.Facebook({
appId : fbId,
appSecret: fbSecret,
callback: fbCallbackAddress,
scope: 'offline_access,em",https://stackoverflow.com/questions/7042340/error-cant-set-headers-after-they-are-sent-to-the-client,1239,2186933.0,49.0,,,2011-08-12 15:21:00,2023-11-14 07:44:03,2017-12-25 15:07:10,,,javascript;node.js;express,DjangoRocks,14228,394747,registered,true,7086621,,CC BY-SA 3.0,2015-11-24 16:00:43,8680,8447,2,2,0,3,true,false,false,true,true,true,62,11,false,0.022,0.0006,5580,2011,8,15,Friday,false,false,true,false,false,false,false
13207927,Switch statement for multiple cases in JavaScript,"I need multiple cases in switch statement in JavaScript, Something like:
switch (varName)
{
case "afshin", "saeed", "larry":
alert('Hey');
break;
default:
alert('Default case');
break;
}
How can I do that? If there's no way to do something like that in JavaScript, I want to know an alternative solution that also follows the DRY concept.
",https://stackoverflow.com/questions/13207927/switch-statement-for-multiple-cases-in-javascript,1237,1313509.0,26.0,,,2012-11-03 09:43:09,2023-01-30 13:11:09,2021-08-08 11:07:40,,,javascript;switch-statement,Afshin Mehrabani,35379,375966,registered,true,13207939,,CC BY-SA 4.0,2020-02-11 11:03:09,516,405,1,1,0,2,true,false,false,true,true,true,49,7,false,0.02,0.0009,5131,2012,11,9,Saturday,true,false,true,false,false,false,false
1226714,How to get the browser to navigate to URL in JavaScript,"What is the best (correct, modern, cross-browser, safe) way to get a web browser to navigate to a URL of your choice using JavaScript?
",https://stackoverflow.com/questions/1226714/how-to-get-the-browser-to-navigate-to-url-in-javascript,1237,1580085.0,3.0,,,2009-08-04 10:18:17,2021-12-17 17:32:22,2018-02-06 14:54:54,2017-03-26 15:43:58,Duplicate,javascript;browser;navigation,jjujuma,22945,75863,registered,true,1226718,,,2016-11-22 15:13:03,142,135,0,0,0,3,true,true,false,true,true,true,55,11,false,0.002,0.0008,6318,2009,8,10,Tuesday,false,false,true,false,false,false,false
191881,Serializing to JSON in jQuery,"I need to serialize an object to JSON. I'm using jQuery. Is there a ""standard"" way to do this?
My specific situation: I have an array defined as shown below:
var countries = new Array();
countries[0] = 'ga';
countries[1] = 'cd';
...
and I need to turn this into a string to pass to $.ajax() like this:
$.ajax({
type: ""POST"",
url: ""Concessions.aspx/GetConcessions"",
data: ""{'countries':['ga','cd']}"",
...
",https://stackoverflow.com/questions/191881/serializing-to-json-in-jquery,1236,932967.0,11.0,,,2008-10-10 15:29:56,2020-04-19 11:24:30,2019-07-03 04:50:19,2017-04-07 13:35:01,Duplicate,javascript;jquery;ajax;json;serialization,Herb Caudill,50130,239663,registered,true,912247,,,2013-05-09 10:07:50,765,422,3,4,0,5,true,true,false,true,true,true,29,5,false,0.012,0.0013,6616,2008,10,15,Friday,false,false,true,false,false,false,false
5797852,How do I "include" functions from my other files?,"Let's say I have a file called app.js. Pretty simple:
var express = require('express');
var app = express.createServer();
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.get('/', function(req, res){
res.render('index', {locals: {
title: 'NowJS + Express Example'
}});
});
app.listen(8080);
What if I have a functions inside ""tools.js"". How would I import them to use in apps.js?
Or...am I supposed to turn ""tools"" into a module, and then require it? << seems hard, I rather do the basic import of the tools.js file.
",https://stackoverflow.com/questions/5797852/how-do-i-include-functions-from-my-other-files,1233,1179044.0,30.0,,,2011-04-26 23:56:59,2025-07-07 08:16:37,2025-07-07 08:16:37,,,javascript;import;header;node.js,TIMEX,275634,179736,registered,true,,,CC BY-SA 4.0,,608,563,1,0,0,4,false,false,false,true,true,true,59,9,true,0.025,0.001,5688,2011,4,23,Tuesday,false,false,true,false,false,false,false
6603015,Check whether a string matches a regex in JS,"I want to use JavaScript (I can also use jQuery) to do check whether a string matches the regex ^([a-z0-9]{5,})$, and get a true or false result.
match() seems to check whether part of a string matches a regex, not the whole thing. Does it solve the problem? Can I adapt it to solve the problem? How?
",https://stackoverflow.com/questions/6603015/check-whether-a-string-matches-a-regex-in-js,1219,1588542.0,15.0,,,2011-07-06 21:08:50,2023-05-29 19:04:20,2023-01-09 23:44:35,,,javascript;regex;match,Richard,33145,806539,registered,true,6603043,,CC BY-SA 4.0,,367,301,4,0,0,3,true,false,false,true,true,true,44,9,false,0.009,0.0008,5617,2011,7,21,Wednesday,false,false,true,false,false,false,false
1669190,Find the min/max element of an array in JavaScript,"How can I easily obtain the min or max element of a JavaScript array?
Example pseudocode:
let array = [100, 0, 50]
array.min() //=> 0
array.max() //=> 100
",https://stackoverflow.com/questions/1669190/find-the-min-max-element-of-an-array-in-javascript,1218,1721939.0,59.0,,,2009-11-03 18:18:26,2024-01-29 20:12:48,2021-02-18 11:40:39,,,javascript,HankH,12143,201886,unregistered,true,,,CC BY-SA 4.0,2014-12-18 02:56:00,201,163,1,0,0,1,false,false,false,true,true,true,50,9,false,0.034,0.0007,6227,2009,11,18,Tuesday,false,false,true,false,false,false,false
34883068,How to get first N number of elements from an array,"I am working with Javascript(ES6) /FaceBook react and trying to get the first 3 elements of an array that varies in size. I would like do the equivalent of Linq take(n).
In my Jsx file I have the following:
var items = list.map(i => {
return (
<myview item={i} key={i.id} />
);
});
Then to get the first 3 items I tried
var map = new Map(list);
map.size = 3;
var items = map(i => {
return (<SpotlightLandingGlobalInboxItem item={i} key={i.id} />);
});
This didn't work as map doesn't have a set function. What can I try next?
",https://stackoverflow.com/questions/34883068/how-to-get-first-n-number-of-elements-from-an-array,1214,1453336.0,13.0,,,2016-01-19 17:19:18,2023-07-20 13:17:21,2023-02-21 15:16:14,,,javascript;arrays;filtering;slice;extract,user1526912,17520,1526912,registered,true,34883368,,CC BY-SA 4.0,2022-06-14 16:31:06,651,575,2,0,0,5,true,false,false,true,true,true,51,11,false,0.009,0.0008,3959,2016,1,17,Tuesday,false,false,true,false,false,false,false
1309452,How to replace innerHTML of a div?,"How could I achieve the following:
document.all.regTitle.innerHTML = 'Hello World';
Using jQuery where regTitle is my div id?
",https://stackoverflow.com/questions/1309452/how-to-replace-innerhtml-of-a-div,1210,1996846.0,14.0,,,2009-08-20 23:51:36,2025-04-23 09:54:51,2025-04-23 09:54:51,,,javascript;jquery;innerhtml,tonyf,35845,111479,registered,true,1309454,,CC BY-SA 4.0,2011-05-25 10:14:29,191,127,3,0,0,3,true,false,false,true,true,true,34,7,true,0.007,0.0006,6302,2009,8,23,Thursday,false,false,true,false,false,false,false
130396,Are there constants in JavaScript?,"Is there a way to use constants in JavaScript?
If not, what's the common practice for specifying variables that are used as constants?
",https://stackoverflow.com/questions/130396/are-there-constants-in-javascript,1178,521009.0,33.0,,,2008-09-24 22:45:05,2023-03-02 18:16:35,2020-04-19 11:33:32,,,javascript;constants,fuentesjr,52664,10708,registered,true,130399,,CC BY-SA 4.0,2013-07-22 08:02:27,167,136,0,0,0,2,true,false,false,true,true,true,34,5,true,0.063,0.0023,6632,2008,9,22,Wednesday,false,false,true,false,false,false,false
1197928,How to add 30 minutes to a JavaScript Date object?,"I'd like to get a Date object which is 30 minutes later than another Date object. How do I do it with JavaScript?
",https://stackoverflow.com/questions/1197928/how-to-add-30-minutes-to-a-javascript-date-object,1176,1239871.0,29.0,,,2009-07-29 03:34:35,2023-03-06 01:28:52,2022-07-11 16:06:09,,,javascript;date;date-manipulation,Morgan Cheng,76508,26349,registered,true,,,CC BY-SA 4.0,2011-05-21 22:34:36,122,115,0,0,0,3,false,false,false,true,true,true,50,10,true,0.023,0.0009,6324,2009,7,3,Wednesday,false,false,true,false,false,false,false
36795819,When should I use curly braces for ES6 import?,"It seems to be obvious, but I found myself a bit confused about when to use curly braces for importing a single module in ES6. For example, in the React-Native project I am working on, I have the following file and its content:
File initialState.js
var initialState = {
todo: {
todos: [
{id: 1, task: 'Finish Coding', completed: false},
{id: 2, task: 'Do Laundry', completed: false},
{id: 2, task: 'Shopping Groceries', completed: false},
]
}
};
export default initialState;
In the TodoReducer.js, I have to import it without curly braces:
import initialState from './todoInitialState';
If I enclose the initialState in curly braces, I get the following error for the following line of code:
Cannot read property todo of undefined
File TodoReducer.js:
export default function todos(state = initialState.todo, action) {
// ...
}
Similar errors also happen to my components with the curly braces. I was wondering when I should use curly braces for a single import, because obviously, when importing multiple component/modules, you have to enclose them in curly braces, which I know.
The Stack Overflow post at here does not answer my question, instead I am asking when I should or should not use curly braces for importing a single module, or I should never use curly braces for importing a single module in ES6 (this is apparently not the case, as I have seen single import with curly braces required).
",https://stackoverflow.com/questions/36795819/when-should-i-use-curly-braces-for-es6-import,1173,361478.0,12.0,,,2016-04-22 13:58:14,2023-08-30 10:24:42,2020-12-31 02:00:16,,,javascript;import;ecmascript-6,TonyW,18975,2228325,registered,true,36796281,,CC BY-SA 4.0,,1790,1472,4,1,0,3,true,false,false,true,true,true,46,9,true,0.033,0.0032,3865,2016,4,13,Friday,false,false,true,false,false,false,false
5041494,Selecting and manipulating CSS pseudo-elements such as ::before and ::after using javascript (or jQuery),"Is there any way to select/manipulate CSS pseudo-elements such as ::before and ::after (and the old version with one semi-colon) using jQuery?
For example, my stylesheet has the following rule:
.span::after{ content:'foo' }
How can I change 'foo' to 'bar' using vanilla JS or jQuery?
",https://stackoverflow.com/questions/5041494/selecting-and-manipulating-css-pseudo-elements-such-as-before-and-after-usin,1169,919780.0,29.0,,,2011-02-18 12:53:10,2024-08-16 16:20:23,2023-11-04 18:43:50,,,javascript;jquery;css;jquery-selectors;pseudo-element,JBradwell,11813,580527,registered,true,5734583,,CC BY-SA 4.0,2014-10-11 23:37:47,394,285,3,0,0,5,true,false,false,true,true,true,104,14,false,0.032,0.0013,5755,2011,2,12,Friday,false,false,true,false,false,false,false
3480771,How do I check if string contains substring?,"I have a shopping cart that displays product options in a dropdown menu and if they select ""yes"", I want to make some other fields on the page visible.
The problem is that the shopping cart also includes the price modifier in the text, which can be different for each product. The following code works:
$(document).ready(function() {
$('select[id=""Engraving""]').change(function() {
var str = $('select[id=""Engraving""] option:selected').text();
if (str == ""Yes (+ $6.95)"") {
$('.engraving').show();
} else {
$('.engraving').hide();
}
});
});
However I would rather use something like this, which doesn't work:
$(document).ready(function() {
$('select[id=""Engraving""]').change(function() {
var str = $('select[id=""Engraving""] option:selected').text();
if (str *= ""Yes"") {
$('.engraving').show();
} else {
$('.engraving').hide();
}
});
});
I only want to perform the action if the selected option contains the word ""Yes"", and would ignore the price modifier.
",https://stackoverflow.com/questions/3480771/how-do-i-check-if-string-contains-substring,1168,2028730.0,12.0,,,2010-08-13 21:25:54,2021-03-22 09:07:45,2018-10-02 14:09:00,2017-07-17 00:17:26,Duplicate,javascript;jquery;string;substring;contains,Jordan Garis,11699,420022,unregistered,true,3480785,,,2016-12-06 00:00:11,1168,1092,2,0,0,5,true,true,false,true,true,true,44,8,true,0.006,0.0006,5944,2010,8,21,Friday,false,false,true,false,false,false,false
3665115,"How to create a file in memory for user to download, but not through server?","Is there a way to create a text file on the client side and prompt the user to download it without any interaction with the server?
I know I can't write directly to their machine (security and all), but can I create the file and prompt them to save it?
",https://stackoverflow.com/questions/3665115/how-to-create-a-file-in-memory-for-user-to-download-but-not-through-server,1168,718142.0,23.0,,,2010-09-08 06:24:18,2026-11-16 19:35:21,2026-11-16 19:35:21,,,javascript;file;client-side,Joseph Silber,221181,825568,registered,true,3665147,,CC BY-SA 4.0,2021-12-30 13:02:13,267,253,0,0,0,3,true,false,false,true,true,true,76,15,true,0.032,0.0016,5918,2010,9,6,Wednesday,false,false,true,false,false,false,false
3586775,What is the correct way to check for string equality in JavaScript?,"What is the correct way to check for equality between Strings in JavaScript?
",https://stackoverflow.com/questions/3586775/what-is-the-correct-way-to-check-for-string-equality-in-javascript,1168,1785504.0,10.0,,,2010-08-27 17:37:55,2022-08-07 08:17:03,2020-08-03 19:45:09,,,javascript;string;string-comparison,JSS,11687,433205,unregistered,true,,,CC BY-SA 4.0,2018-04-16 03:15:00,84,77,0,0,0,3,false,false,false,true,true,true,67,12,true,0.006,0.0007,5930,2010,8,17,Friday,false,false,true,false,false,false,false
5963669,What's the difference between event.stopPropagation and event.preventDefault?,"They seem to be doing the same thing...
Is one modern and one old? Or are they supported by different browsers?
When I handle events myself (without framework) I just always check for both and execute both if present. (I also return false, but I have the feeling that doesn't work with events attached with node.addEventListener).
So why both? Should I keep checking for both? Or is there actually a difference?
(I know, a lot of questions, but they're all sort of the same =))
",https://stackoverflow.com/questions/5963669/whats-the-difference-between-event-stoppropagation-and-event-preventdefault,1166,706949.0,9.0,,,2011-05-11 11:45:18,2024-01-25 07:56:24,2020-04-17 18:32:47,,,javascript;events;preventdefault;stoppropagation,Rudie,54370,247372,registered,true,5963688,,CC BY-SA 4.0,,568,485,2,0,0,4,true,false,false,true,true,true,81,7,true,0.013,0.0016,5673,2011,5,11,Wednesday,false,false,true,false,false,false,false
446892,How to find event listeners on a DOM node in JavaScript or in debugging?,"I have a page where some event listeners are attached to input boxes and select boxes. Is there a way to find out which event listeners are observing a particular DOM node and for what event?
Events are attached using:
- Prototype's
Event.observe;
- DOM's
addEventListener;
- As element attribute
element.onclick.
",https://stackoverflow.com/questions/446892/how-to-find-event-listeners-on-a-dom-node-in-javascript-or-in-debugging,1162,1050536.0,21.0,,,2009-01-15 14:19:44,2025-01-05 19:44:25,2021-08-11 04:11:26,,,javascript;events;dom,Navneet,12027,54540,registered,true,3426352,,CC BY-SA 4.0,2015-05-19 12:45:51,492,312,3,1,0,3,true,false,false,true,true,true,72,14,true,0.02,0.0011,6519,2009,1,14,Thursday,false,false,true,false,false,false,false
280634,endsWith in JavaScript,"How can I check if a string ends with a particular character in JavaScript?
Example: I have a string
var str = ""mystring#"";
I want to know if that string is ending with #. How can I check it?
Is there a endsWith() method in JavaScript?
One solution I have is take the length of the string and get the last character and check it.
Is this the best way or there is any other way?
",https://stackoverflow.com/questions/280634/endswith-in-javascript,1152,483444.0,31.0,,,2008-11-11 11:15:32,2024-05-30 13:34:43,2016-01-24 19:34:03,,,javascript;string;ends-with,Phani Kumar Bhamidipati,13303,15177,registered,true,2548133,,CC BY-SA 3.0,2014-05-19 07:54:43,506,387,3,0,0,3,true,false,false,true,true,true,22,3,false,0.064,0.0024,6584,2008,11,11,Tuesday,false,false,true,false,false,false,false
29775797,Fetch: POST JSON data,"I'm trying to POST a JSON object using fetch.
From what I can understand, I need to attach a stringified object to the body of the request, e.g.:
fetch("/echo/json/",
{
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: "POST",
body: JSON.stringify({a: 1, b: 2})
})
.then(function(res){ console.log(res) })
.catch(function(res){ console.log(res) })
When using jsfiddle's JSON echo I'd expect to see the object I've sent ({a: 1, b: 2}) back, but this does not happen - chrome devtools doesn't even show the JSON as part of the request, which means that it's not being sent.
",https://stackoverflow.com/questions/29775797/fetch-post-json-data,1152,1973707.0,19.0,,,2015-04-21 14:54:41,2024-12-12 17:56:58,2022-08-18 07:09:00,,,javascript;json;fetch-api,Razor,30108,304174,registered,true,29823632,,CC BY-SA 4.0,2019-05-20 12:45:19,913,658,2,2,0,3,true,false,false,true,true,true,21,4,false,0.01,0.0006,4232,2015,4,14,Tuesday,false,false,true,false,false,false,false
205853,Why would a JavaScript variable start with a dollar sign?,"I quite often see JavaScript with variables that start with a dollar sign. When/why would you choose to prefix a variable in this way?
(I'm not asking about $('p.foo') syntax that you see in jQuery and others, but normal variables like $name and $order)
",https://stackoverflow.com/questions/205853/why-would-a-javascript-variable-start-with-a-dollar-sign,1149,314570.0,16.0,,,2008-10-15 18:26:34,2023-05-30 16:10:38,2011-09-24 05:47:22,2020-06-03 09:58:04,Duplicate,javascript;naming-conventions,Ken,79372,20074,registered,true,553734,,,2016-02-10 14:23:06,308,255,3,0,0,2,true,true,false,true,true,true,57,10,true,0.051,0.0037,6611,2008,10,18,Wednesday,false,false,true,false,false,false,false
11922383,"How can I access and process nested objects, arrays, or JSON?","I have a nested data structure containing objects and arrays. How can I extract the information, i.e. access a specific or multiple values (or keys)?
For example:
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
How could I access the name of the second item in items?
",https://stackoverflow.com/questions/11922383/how-can-i-access-and-process-nested-objects-arrays-or-json,1141,1303135.0,31.0,,,2012-08-12 13:02:12,2024-12-03 12:24:36,2022-07-04 15:33:17,,,javascript;arrays;object;nested;data-manipulation,Felix Kling,821480,218196,registered,true,11922384,,CC BY-SA 4.0,2015-10-05 08:58:37,425,354,3,0,0,5,true,false,false,true,true,true,61,11,true,0.024,0.0009,5214,2012,8,13,Sunday,true,false,true,false,false,false,false
1249531,How to get a JavaScript object's class?,"I created a JavaScript object, but how I can determine the class of that object?
I want something similar to Java's .getClass() method.
",https://stackoverflow.com/questions/1249531/how-to-get-a-javascript-objects-class,1133,1164415.0,25.0,,,2009-08-08 18:11:57,2025-11-24 09:17:04,2025-03-12 17:38:51,,,javascript;class;oop;types;constructor,DNB5brims,30902,148978,registered,true,1249554,,CC BY-SA 4.0,,165,138,1,0,0,5,true,false,false,true,true,true,43,7,true,0.021,0.001,6314,2009,8,18,Saturday,true,false,true,false,false,false,false
779379,"Why is setTimeout(fn, 0) sometimes useful?","I've recently run into a rather nasty bug, wherein the code was loading a <select> dynamically via JavaScript. This dynamically loaded <select> had a pre-selected value. In IE6, we already had code to fix the selected <option>, because sometimes the <select>'s selectedIndex value would be out of sync with the selected <option>'s index attribute, as below:
field.selectedIndex = element.index;
However, this code wasn't working. Even though the field's selectedIndex was being set correctly, the wrong index would end up being selected. However, if I stuck an alert() statement in at the right time, the correct option would be selected. Thinking this might be some sort of timing issue, I tried something random that I'd seen in code before:
var wrapFn = (function() {
var myField = field;
var myElement = element;
return function() {
myField.selectedIndex = myElement.index;
}
})();
setTimeout(wrapFn, 0);
And this worked!
I've got a solution for my problem, but I'm uneasy that I don't know exactly why this fixes my problem. Does anyone have an official explanation? What browser issue am I avoiding by calling my function ""later"" using setTimeout()?
",https://stackoverflow.com/questions/779379/why-is-settimeoutfn-0-sometimes-useful,1132,428448.0,19.0,,,2009-04-22 21:46:08,2024-01-03 20:22:17,2016-07-14 12:38:22,,,javascript;dom;event-loop,Dan Lew,87830,60261,registered,true,779785,,CC BY-SA 3.0,2015-10-05 09:22:12,1431,1225,12,0,0,3,true,false,false,true,true,true,42,6,true,0.044,0.0026,6422,2009,4,21,Wednesday,false,false,true,false,false,false,false
469357,HTML text input allow only numeric input,"Is there a quick way to set an HTML text input (<input type=text />) to only allow numeric keystrokes (plus '.')?
",https://stackoverflow.com/questions/469357/html-text-input-allow-only-numeric-input,1128,2923054.0,79.0,,,2009-01-22 14:36:17,2025-04-06 21:35:47,2019-11-22 07:38:52,,,javascript;jquery;html,Julius A,40112,13370,registered,true,469362,,CC BY-SA 4.0,2014-06-17 15:44:51,140,120,1,0,0,3,true,false,false,true,true,true,40,7,false,0.027,0.0004,6512,2009,1,14,Thursday,false,false,true,false,false,false,false
11704267,How to conditionally add a member to an object?,"I would like to create an object with a member added conditionally.
The simple approach is:
var a = {};
if (someCondition)
a.b = 5;
Now, I would like to write a more idiomatic code. I am trying:
a = {
b: (someCondition? 5 : undefined)
};
But now, b is a member of a whose value is undefined. This is not the desired result.
Is there a handy solution?
Update
I seek for a solution that could handle the general case with several members.
a = {
b: (conditionB? 5 : undefined),
c: (conditionC? 5 : undefined),
d: (conditionD? 5 : undefined),
e: (conditionE? 5 : undefined),
f: (conditionF? 5 : undefined),
g: (conditionG? 5 : undefined),
};
",https://stackoverflow.com/questions/11704267/how-to-conditionally-add-a-member-to-an-object,1126,750296.0,28.0,,,2012-07-28 20:07:24,2025-04-08 13:25:45,2025-04-08 13:25:45,,,javascript;object;properties,viebel,20950,813665,registered,true,11704524,,CC BY-SA 4.0,,840,670,6,0,0,3,true,false,false,true,true,true,47,9,true,0.037,0.0015,5229,2012,7,20,Saturday,true,false,true,false,false,false,false
307179,What is JavaScript's highest integer value that a number can go to without losing precision?,"Is this defined by the language? Is there a defined maximum? Is it different in different browsers?
",https://stackoverflow.com/questions/307179/what-is-javascripts-highest-integer-value-that-a-number-can-go-to-without-losin,1125,710709.0,21.0,,,2008-11-20 22:47:54,2026-07-21 09:28:36,2026-07-21 09:28:36,,,javascript;math;browser;cross-browser;largenumber,TALlama,16497,5657,registered,true,307200,,CC BY-SA 4.0,2014-09-26 16:33:05,107,100,0,0,0,5,true,false,false,true,true,true,96,15,true,0.03,0.0016,6575,2008,11,22,Thursday,false,false,true,false,false,false,false
32461229,Why use Redux over Facebook Flux?,"I've read this answer, reducing boilerplate, looked at few GitHub examples and even tried redux a little bit (todo apps).
As I understand, official redux doc motivations provide pros comparing to traditional MVC architectures. BUT it doesn't provide an answer to the question:
Why you should use Redux over Facebook Flux?
Is that only a question of programming styles: functional vs non-functional? Or the question is in abilities/dev-tools that follow from redux approach? Maybe scaling? Or testing?
Am I right if I say that redux is a flux for people who come from functional languages?
To answer this question you may compare the complexity of implementation redux's motivation points on flux vs redux.
Here are motivation points from official redux doc motivations:
- Handling optimistic updates (as I understand, it hardly depends on 5th point. Is it hard to implement it in facebook flux?)
- Rendering on the server (facebook flux also can do this. Any benefits comparing to redux?)
- Fetching data before performing route transitions (Why it can't be achieved in facebook flux? What's the benefits?)
- Hot reload (It's possible with React Hot Reload. Why do we need redux?)
- Undo/Redo functionality
- Any other points? Like persisting state...
",https://stackoverflow.com/questions/32461229/why-use-redux-over-facebook-flux,1123,283557.0,8.0,,,2015-09-08 15:05:14,2019-04-11 13:10:33,2018-07-05 03:59:35,2019-04-11 14:34:53,Opinion-based,javascript;reactjs;reactjs-flux;flux;redux,VB_,45902,2761509,registered,true,32920459,,,2018-12-19 07:07:37,1904,1253,0,5,0,5,true,true,false,true,true,true,33,6,true,0.028,0.004,4092,2015,9,15,Tuesday,false,false,true,false,false,false,false
4793604,How to insert an element after another element in JavaScript without using a library?,"There's insertBefore() in JavaScript, but how can I insert an element after another element without using jQuery or another library?
",https://stackoverflow.com/questions/4793604/how-to-insert-an-element-after-another-element-in-javascript-without-using-a-lib,1120,991384.0,20.0,,,2011-01-25 12:39:36,2025-03-21 16:04:58,2018-07-03 18:39:24,,,javascript;dom;insert;append,Xah Lee,17775,369203,registered,true,4793630,,CC BY-SA 4.0,2017-03-08 19:49:39,162,133,1,0,0,4,true,false,false,true,true,true,85,14,true,0.02,0.0011,5779,2011,1,12,Tuesday,false,false,true,false,false,false,false
807878,How to make JavaScript execute after page load?,"I'm executing an external script, using a <script> inside <head>.
Now since the script executes before the page has loaded, I can't access the <body>, among other things. I'd like to execute some JavaScript after the document has been ""loaded"" (HTML fully downloaded and in-RAM). Are there any events that I can hook onto when my script executes, that will get triggered on page load?
",https://stackoverflow.com/questions/807878/how-to-make-javascript-execute-after-page-load,1120,2474745.0,26.0,,,2009-04-30 16:38:36,2025-10-11 21:18:37,2020-06-17 18:49:55,,,javascript;html;dom;dom-events;pageload,Robin Rodricks,114780,41021,registered,true,807895,,CC BY-SA 4.0,2018-12-20 06:49:04,474,404,3,0,0,5,true,false,false,true,true,true,47,8,true,0.011,0.0005,6414,2009,4,16,Thursday,false,false,true,false,false,false,false
17937960,How to list npm user-installed packages?,"How do I list the user-installed / environment package only in npm?
When I do npm -g list, it outputs every package and their dependencies. Instead I'd like to see the packages installed in the current working project or environment.
",https://stackoverflow.com/questions/17937960/how-to-list-npm-user-installed-packages,1119,925575.0,19.0,,,2013-07-30 03:45:53,2025-01-13 10:50:57,2024-07-04 19:47:03,,,javascript;node.js;npm;package;package-managers,lolski,17861,1622847,registered,true,25497068,,CC BY-SA 4.0,2021-10-31 17:53:31,279,234,1,0,0,5,true,false,false,true,true,true,40,6,true,0.021,0.0012,4862,2013,7,3,Tuesday,false,false,true,false,false,false,false
50605219,Difference between npx and npm,"I have just started learning React, and Facebook helps in simplifying the initial setup by providing the following ready-made project.
If I have to install the skeleton project, I have to type npx create-react-app my-app on the command line.
Why does Facebook have npx create-react-app my-app on GitHub rather than npm create-react-app my-app?
",https://stackoverflow.com/questions/50605219/difference-between-npx-and-npm,1118,452435.0,15.0,,,2018-05-30 12:51:54,2026-08-20 23:04:59,2026-06-12 01:36:10,,,javascript;reactjs;npm;npx,Paresh Maniyar,11340,9279156,registered,true,52018825,,CC BY-SA 4.0,2024-01-01 12:20:42,489,344,3,1,0,4,true,false,false,true,true,true,30,5,false,0.033,0.0025,3097,2018,5,12,Wednesday,false,false,true,false,false,false,false
21023763,What is the difference between angular-route and angular-ui-router?,"I'm planning to use AngularJS in my big applications. I'm in the process to find out the right modules to use.
What is the difference between ngRoute (angular-route.js) and ui-router (angular-ui-router.js) modules?
In many articles when ngRoute is used, routes are configured with $routeProvider. However, when used with ui-router, routes are configured with $stateProvider and $urlRouterProvider.
Which module should I use for better manageability and extensibility?
",https://stackoverflow.com/questions/21023763/what-is-the-difference-between-angular-route-and-angular-ui-router,1114,272153.0,15.0,,,2014-01-09 15:03:28,2023-11-06 17:15:38,2023-04-30 23:54:34,,,javascript;angularjs;angularjs-routing;angular-ui-router;angularjs-module,Premchandra Singh,14312,1586517,registered,true,21024270,,CC BY-SA 4.0,2016-01-05 06:06:07,561,468,5,0,0,5,true,false,false,true,true,true,67,8,true,0.055,0.0041,4699,2014,1,15,Thursday,false,false,true,false,false,false,false
9847580,"How to detect Safari, Chrome, IE, Firefox and Opera browsers?","I have 5 addons/extensions for Firefox, Chrome, Internet Explorer(IE), Opera, and Safari.
How can I correctly recognize the user browser and redirect (once an install button has been clicked) to download the corresponding addon?
",https://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browsers,1104,1265316.0,30.0,,,2012-03-23 23:06:42,2024-06-15 06:32:22,2022-07-10 22:22:42,,,javascript;browser-detection,FrankC,11473,1289292,registered,true,9851769,,CC BY-SA 4.0,2015-12-14 12:08:21,243,229,0,0,0,2,true,false,false,true,true,true,61,10,true,0.024,0.0009,5356,2012,3,23,Friday,false,false,true,false,false,false,false
48239,Getting the ID of the element that fired an event,"Is there any way to get the ID of the element that fires an event?
I'm thinking something like:
$(document).ready(function() {
$(""a"").click(function() {
var test = caller.id;
alert(test.val());
});
});
<script type=""text/javascript"" src=""starterkit/jquery.js""></script>
<form class=""item"" id=""aaa"">
<input class=""title""></input>
</form>
<form class=""item"" id=""bbb"">
<input class=""title""></input>
</form>
Except of course that the var test should contain the id ""aaa"", if the event is fired from the first form, and ""bbb"", if the event is fired from the second form.
",https://stackoverflow.com/questions/48239/getting-the-id-of-the-element-that-fired-an-event,1104,1623109.0,24.0,,,2008-09-07 08:09:38,2023-04-04 05:10:49,2020-06-26 20:38:41,,,javascript;jquery;dom-events,Joda,12926,1090,registered,true,48684,,CC BY-SA 4.0,2014-05-03 00:52:05,1026,669,5,0,0,3,true,false,false,true,true,true,49,10,false,0.015,0.0007,6649,2008,9,8,Sunday,true,false,true,false,false,false,false
31163693,How do I conditionally add attributes to React components?,"Is there a way to only add attributes to a React component if a certain condition is met?
I'm supposed to add required and readOnly attributes to form elements based on an Ajax call after render, but I can't see how to solve this since readOnly="false" is not the same as omitting the attribute completely.
The example below should explain what I want, but it doesn't work.
(Parse Error: Unexpected identifier)
function MyInput({isRequired}) {
return <input classname="foo" {isRequired ? "required" : ""} />
}
",https://stackoverflow.com/questions/31163693/how-do-i-conditionally-add-attributes-to-react-components,1102,791902.0,29.0,,,2015-07-01 14:07:27,2024-08-13 03:41:28,2021-12-04 03:20:18,,,javascript;reactjs,Remi Sture,13148,3118684,registered,true,31164090,,CC BY-SA 4.0,2024-05-14 20:25:03,688,561,2,0,0,2,true,false,false,true,true,true,58,9,true,0.037,0.0014,4161,2015,7,14,Wednesday,false,false,true,false,false,false,false
270612,Scroll to bottom of div?,"I am creating a chat using Ajax requests and I'm trying to get messages div to scroll to the bottom without much luck.
I am wrapping everything in this div:
#scroll {
height:400px;
overflow:scroll;
}
Is there a way to keep it scrolled to the bottom by default using JS?
Is there a way to keep it scrolled to the bottom after an ajax request?
",https://stackoverflow.com/questions/270612/scroll-to-bottom-of-div,1100,1292304.0,35.0,,,2008-11-06 22:37:30,2023-07-20 18:25:45,2020-06-21 02:44:47,,,javascript;html;ajax;chat,kush,16998,10258,registered,true,270628,,CC BY-SA 4.0,2014-02-10 17:16:43,403,351,1,0,0,4,true,false,false,true,true,true,24,5,true,0.027,0.0009,6589,2008,11,22,Thursday,false,false,true,false,false,false,false
12506897,Is Safari on iOS 6 caching $.ajax results?,"Since the upgrade to iOS 6, we are seeing Safari's web view take the liberty of caching $.ajax calls. This is in the context of a PhoneGap application so it is using the Safari WebView. Our $.ajax calls are POST methods and we have cache set to false {cache:false}, but still this is happening. We tried manually adding a TimeStamp to the headers but it did not help.
We did more research and found that Safari is only returning cached results for web services that have a function signature that is static and does not change from call to call. For instance, imagine a function called something like:
getNewRecordID(intRecordType)
This function receives the same input parameters over and over again, but the data it returns should be different every time.
Must be in Apple's haste to make iOS 6 zip along impressively they got too happy with the cache settings. Has anyone else seen this behavior on iOS 6? If so, what exactly is causing it?
The workaround that we found was to modify the function signature to be something like this:
getNewRecordID(intRecordType, strTimestamp)
and then always pass in a TimeStamp parameter as well, and just discard that value on the server side. This works around the issue.
",https://stackoverflow.com/questions/12506897/is-safari-on-ios-6-caching-ajax-results,1100,146098.0,25.0,,,2012-09-20 06:07:23,2023-07-07 03:45:04,2021-03-12 02:39:39,,,javascript;jquery;ajax;caching;mobile-safari,user1684978,8559,1684978,registered,true,,,CC BY-SA 4.0,2012-09-23 16:51:50,1393,1219,8,0,0,5,false,false,false,true,true,true,42,8,true,0.171,0.0075,5175,2012,9,6,Thursday,false,false,true,false,false,false,false
1960240,jQuery AJAX submit form,"I have a form with name orderproductForm and an undefined number of inputs.
I want to do some kind of jQuery.get or ajax or anything like that that would call a page through Ajax, and send along all the inputs of the form orderproductForm.
I suppose one way would be to do something like
jQuery.get(""myurl"",
{action : document.orderproductForm.action.value,
cartproductid : document.orderproductForm.cartproductid.value,
productid : document.orderproductForm.productid.value,
...
However I do not know exactly all the form inputs. Is there a feature, function or something that would just send ALL the form inputs?
",https://stackoverflow.com/questions/1960240/jquery-ajax-submit-form,1097,2632688.0,22.0,,,2009-12-25 01:31:48,2024-10-05 23:42:42,2020-01-21 18:51:08,,,javascript;jquery;ajax;submit;forms,Nathan H,49811,25645,registered,true,1960245,,CC BY-SA 4.0,2017-01-04 06:38:13,741,663,3,0,0,5,true,false,false,true,true,true,23,4,false,0.008,0.0004,6175,2009,12,1,Friday,false,false,true,false,false,false,false
28329382,Understanding unique keys for array children in React.js,"I'm building a React component that accepts a JSON data source and creates a sortable table.
Each of the dynamic data rows has a unique key assigned to it but I'm still getting an error of:
Each child in an array should have a unique ""key"" prop.
Check the render method of TableComponent.
My TableComponent render method returns:
<table>
<thead key=""thead"">
<TableHeader columns={columnNames}/>
</thead>
<tbody key=""tbody"">
{ rows }
</tbody>
</table>
The TableHeader component is a single row and also has a unique key assigned to it.
Each row in rows is built from a component with a unique key:
<TableRowItem key={item.id} data={item} columns={columnNames}/>
And the TableRowItem looks like this:
var TableRowItem = React.createClass({
render: function() {
var td = function() {
return this.props.columns.map(function(c) {
return <td key={this.props.data[c]}>{this.props.data[c]}</td>;
}, this);
}.bind(this);
return (
<tr>{ td(this.props.item) }</tr>
)
}
});
What is causing the unique key prop error?
",https://stackoverflow.com/questions/28329382/understanding-unique-keys-for-array-children-in-react-js,1096,1420758.0,32.0,,,2015-02-04 19:06:11,2025-08-16 05:12:11,2015-02-04 20:16:03,,,javascript;reactjs,Brett DeWoody,63475,438581,registered,true,28329550,,CC BY-SA 3.0,,1388,1169,8,0,0,2,true,false,false,true,true,true,56,8,false,0.023,0.0008,4308,2015,2,19,Wednesday,false,false,true,false,false,false,false
18365315,jQuery's jquery-1.10.2.min.map is triggering a 404 (Not Found),"I'm seeing error messages about a file, min.map, being not found:
GET jQuery's jquery-1.10.2.min.map is triggering a 404 (Not Found)
Screenshot
![]()
Where is this coming from?
",https://stackoverflow.com/questions/18365315/jquerys-jquery-1-10-2-min-map-is-triggering-a-404-not-found,1094,490524.0,11.0,,,2013-08-21 18:46:31,2022-03-22 16:31:30,2020-06-20 09:12:55,,,javascript;jquery;google-chrome-devtools,Paul Irish,49681,89484,registered,true,18365316,,CC BY-SA 4.0,2013-08-27 15:34:25,336,175,1,0,1,3,true,false,false,true,true,true,66,8,false,0.022,0.0022,4840,2013,8,18,Wednesday,false,false,true,false,false,false,false
11227809,Why is conditional processing of a sorted array faster than of an unsorted array?,"In this C++ code, sorting the data (before the timed region) makes the primary loop ~6x faster:
#include <algorithm>
#include <ctime>
#include <iostream>
int main()
{
// Generate data
const unsigned arraySize = 32768;
int data[arraySize];
for (unsigned c = 0; c < arraySize; ++c)
data[c] = std::rand() % 256;
// !!! With this, the next loop runs faster.
std::sort(data, data + arraySize);
// Test
clock_t start = clock();
long long sum = 0;
for (unsigned i = 0; i < 100000; ++i)
{
for (unsigned c = 0; c < arraySize; ++c)
{ // Primary loop.
if (data[c] >= 128)
sum += data[c];
}
}
double elapsedTime = static_cast<double>(clock()-start) / CLOCKS_PER_SEC;
std::cout << elapsedTime << '\n';
std::cout << "sum = " << sum << '\n';
}
- Without
std::sort(data, data + arraySize);, the code runs in 11.54 seconds.
- With the sorted data, the code runs in 1.93 seconds.
(Sorting itself takes more time than this one pass over the array, so it's not actually worth doing if we needed to calculate this for an unknown array.)
Initially, I thought this might be just a language or compiler anomaly, so I tried Java:
import java.util.Arrays;
import java.util.Random;
public class Main
{
public static void main(String[] args)
{
// Generate data
int arraySize = 32768;
int data[] = new int[arraySize];
Random rnd = new Random(0);
for (int c = 0; c < arraySize; ++c)
data[c] = rnd.nextInt() % 256;
// !!! With this, the next loop runs faster
Arrays.sort(data);
// Test
long start = System.nanoTime();
long sum = 0;
for (int i = 0; i < 100000; ++i)
{
for (int c = 0; c < arraySize; ++c)
{ // Primary loop.
if (data[c] >= 128)
sum += data[c];
}
}
System.out.println((System.nanoTime() - start) / 1000000000.0);
System.out.println("sum = " + sum);
}
}
With a similar but less extreme result.
My first thought was that sorting brings the data into the cache, but that's silly because the array was just generated.
- What is going on?
- Why is processing a sorted array faster than processing an unsorted array?
The code is summing up some independent terms, so the order should not matter.
Related / follow-up Q&As with more modern C++ compilers
- Why is processing an unsorted array the same speed as processing a sorted array with modern x86-64 clang? - modern C++ compilers auto-vectorize the loop, especially when SSE4.1 or AVX2 is available. This avoids any data-dependent branching so performance isn't data-dependent.
- gcc optimization flag -O3 makes code slower than -O2 - branchless scalar with
cmov can result in a longer dependency chain (especially when GCC chooses poorly), creating a latency bottleneck that makes it slower than branchy asm for the sorted case.
",https://stackoverflow.com/questions/11227809/why-is-conditional-processing-of-a-sorted-array-faster-than-of-an-unsorted-array,27548,2040691.0,25.0,,,2012-06-27 13:51:36,2026-09-04 02:36:50,2026-04-08 05:35:32,,,java;c++;performance;cpu-architecture;branch-prediction,GManNickG,507447,87234,registered,true,11227902,,CC BY-SA 4.0,2014-05-02 21:51:10,3612,3112,4,3,0,5,true,false,false,true,true,true,81,14,true,0.012,0.0135,5260,2012,6,13,Wednesday,false,false,false,true,false,false,false
40480,Is Java "pass-by-reference" or "pass-by-value"?,"I always thought Java uses pass-by-reference. However, I read a blog post which claims that Java uses pass-by-value. I don't think I understand the distinction the author is making.
What is the explanation?
",https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value,7742,2845886.0,87.0,,,2008-09-02 20:14:29,2025-08-12 01:01:40,2023-02-14 20:31:14,,,java;methods;parameter-passing;pass-by-reference;pass-by-value,user4315,4795,4315,registered,true,,,CC BY-SA 4.0,2011-06-24 18:08:43,331,207,0,1,0,5,false,false,false,true,true,true,67,5,true,0.031,0.0027,6654,2008,9,20,Tuesday,false,false,false,true,false,false,false
6841333,Why is subtracting these two epoch-milli Times (in year 1927) giving a strange result?,"If I run the following program, which parses two date strings referencing times 1 second apart and compares them:
public static void main(String[] args) throws ParseException {
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String str3 = "1927-12-31 23:54:07";
String str4 = "1927-12-31 23:54:08";
Date sDt3 = sf.parse(str3);
Date sDt4 = sf.parse(str4);
long ld3 = sDt3.getTime() /1000;
long ld4 = sDt4.getTime() /1000;
System.out.println(ld4-ld3);
}
The output is:
353
Why is ld4-ld3, not 1 (as I would expect from the one-second difference in the times), but 353?
If I change the dates to times 1 second later:
String str3 = "1927-12-31 23:54:08";
String str4 = "1927-12-31 23:54:09";
Then ld4-ld3 will be 1.
Java version:
java version "1.6.0_22"
Java(TM) SE Runtime Environment (build 1.6.0_22-b04)
Dynamic Code Evolution Client VM (build 0.2-b02-internal, 19.0-b04-internal, mixed mode)
Timezone(`TimeZone.getDefault()`):
sun.util.calendar.ZoneInfo[id="Asia/Shanghai",
offset=28800000,dstSavings=0,
useDaylight=false,
transitions=19,
lastRule=null]
Locale(Locale.getDefault()): zh_CN
",https://stackoverflow.com/questions/6841333/why-is-subtracting-these-two-epoch-milli-times-in-year-1927-giving-a-strange-r,7615,830697.0,11.0,,,2011-07-27 08:15:58,2025-09-26 11:16:51,2023-05-20 18:11:39,,,java;date;timezone,Freewind,199358,342235,registered,true,6841479,,CC BY-SA 4.0,2015-06-09 16:07:05,1579,1234,10,0,0,3,true,false,false,true,true,true,86,14,true,0.013,0.0092,5596,2011,7,8,Wednesday,false,false,false,true,false,false,false
309424,How do I read / convert an InputStream into a String in Java?,"If you have a java.io.InputStream object, how should you process that object and produce a String?
Suppose I have an InputStream that contains text data, and I want to convert it to a String, so for example I can write that to a log file.
What is the easiest way to take the InputStream and convert it to a String?
public String convertStreamToString(InputStream is) {
// ???
}
",https://stackoverflow.com/questions/309424/how-do-i-read-convert-an-inputstream-into-a-string-in-java,4771,2782825.0,67.0,,,2008-11-21 16:47:40,2024-12-20 07:22:25,2022-09-23 14:49:38,,,java;string;io;stream;inputstream,Johnny Maelstrom,48571,16616,registered,true,309448,,CC BY-SA 4.0,2013-06-10 05:09:13,509,380,7,0,0,5,true,false,false,true,true,true,61,13,true,0.024,0.0017,6574,2008,11,16,Friday,false,false,false,true,false,false,false
271526,How do I avoid checking for nulls in Java?,"I use x != null to avoid NullPointerException. Is there an alternative?
if (x != null) {
// ...
}
",https://stackoverflow.com/questions/271526/how-do-i-avoid-checking-for-nulls-in-java,4440,1463980.0,73.0,,,2008-11-07 08:31:40,2025-05-28 18:19:10,2023-05-24 11:37:07,,,java;nullpointerexception;null,Goran Martinic,3837,34856,registered,true,271874,,CC BY-SA 4.0,2013-05-11 21:47:55,308,103,3,1,0,3,true,false,false,true,true,true,42,9,true,0.05,0.003,6588,2008,11,8,Friday,false,false,false,true,false,false,false
40471,What are the differences between a HashMap and a Hashtable in Java?,"What are the differences between a HashMap and a Hashtable in Java?
Which is more efficient for non-threaded applications?
",https://stackoverflow.com/questions/40471/what-are-the-differences-between-a-hashmap-and-a-hashtable-in-java,4352,1793066.0,35.0,,,2008-09-02 20:12:00,2024-08-12 17:38:34,2020-08-01 11:19:23,,,java;collections;hashmap;hashtable,dmanxiii,52273,4316,registered,true,40878,,CC BY-SA 4.0,2012-03-16 19:13:29,396,124,2,2,0,4,true,false,false,true,true,true,67,12,true,0.02,0.0024,6654,2008,9,20,Tuesday,false,false,false,true,false,false,false
157944,Create ArrayList from array,"Element[] array = {new Element(1), new Element(2), new Element(3)};
How do I convert the above variable of type Element[] into a variable of type ArrayList<Element>?
ArrayList<Element> arrayList = ...;
",https://stackoverflow.com/questions/157944/create-arraylist-from-array,4129,1910355.0,42.0,,,2008-10-01 14:38:32,2023-11-20 15:00:59,2023-10-09 07:51:04,,,java;arrays;arraylist;type-conversion,Ron Tuffin,54828,939,registered,true,157950,,CC BY-SA 4.0,2016-11-23 19:10:58,492,216,4,1,0,4,true,false,false,true,true,true,27,4,false,0.022,0.0022,6625,2008,10,14,Wednesday,false,false,false,true,false,false,false
363681,How do I generate random integers within a specific range in Java?,"How do I generate a random int value in a specific range?
The following methods have bugs related to integer overflow:
randomNum = minimum + (int)(Math.random() * maximum);
// Bug: `randomNum` can be bigger than `maximum`.
Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt() % n;
randomNum = minimum + i;
// Bug: `randomNum` can be smaller than `minimum`.
",https://stackoverflow.com/questions/363681/how-do-i-generate-random-integers-within-a-specific-range-in-java,4125,5355919.0,59.0,,,2008-12-12 18:20:57,2024-08-22 19:53:03,2022-12-02 14:06:05,,,java;random;integer,user42155,49703,42155,registered,true,,,CC BY-SA 4.0,2011-02-03 20:16:42,538,385,3,0,0,3,false,false,false,true,true,true,66,12,true,0.011,0.0008,6553,2008,12,18,Friday,false,false,false,true,false,false,false
13375357,Proper use cases for Android UserManager.isUserAGoat()?,"I was looking at the new APIs introduced in Android 4.2.
While looking at the UserManager class I came across the following method:
public boolean isUserAGoat()
Used to determine whether the user making this call is subject to teleportations.
Returns whether the user making this call is a goat.
How and when should this be used?
",https://stackoverflow.com/questions/13375357/proper-use-cases-for-android-usermanager-isuseragoat,4055,385387.0,12.0,,,2012-11-14 08:34:01,2024-09-02 10:31:03,2018-09-07 08:21:54,,,java;android;usermanager,Ovidiu Latcu,72371,542091,registered,true,13375461,,CC BY-SA 4.0,2012-11-22 00:11:46,646,345,2,2,0,3,true,false,false,true,true,true,55,6,true,0.031,0.0105,5120,2012,11,8,Wednesday,false,false,false,true,false,false,false
46898,How do I efficiently iterate over each entry in a Java Map?,"If I have an object implementing the Map interface in Java and I wish to iterate over every pair contained within it, what is the most efficient way of going through the map?
Will the ordering of elements depend on the specific map implementation that I have for the interface?
",https://stackoverflow.com/questions/46898/how-do-i-efficiently-iterate-over-each-entry-in-a-java-map,4035,3601354.0,46.0,,,2008-09-05 21:12:48,2026-03-30 15:53:00,2020-03-08 06:31:13,,,java;dictionary;collections;iteration,iMack,39343,4807,registered,true,46908,,CC BY-SA 4.0,2013-04-10 06:54:15,307,280,1,0,0,4,true,false,false,true,true,true,59,12,true,0.013,0.0011,6651,2008,9,21,Friday,false,false,false,true,false,false,false
8881291,Why is char[] preferred over String for passwords?,"In Swing, the password field has a getPassword() (returns char[]) method instead of the usual getText() (returns String) method. Similarly, I have come across a suggestion not to use String to handle passwords.
Why does String pose a threat to security when it comes to passwords?
It feels inconvenient to use char[].
",https://stackoverflow.com/questions/8881291/why-is-char-preferred-over-string-for-passwords,3872,538693.0,17.0,,,2012-01-16 14:20:42,2024-01-04 13:18:11,2017-01-13 11:48:09,,,java;string;security;passwords;char,Ahamed,39785,953140,registered,true,8881376,,CC BY-SA 3.0,2012-08-25 12:51:32,424,319,7,0,0,5,true,false,false,true,true,true,50,8,true,0.032,0.0072,5423,2012,1,14,Monday,false,false,false,true,false,false,false
8710619,"Why don't Java's +=, -=, *=, /= compound assignment operators require casting?","Until today, I thought that for example:
i += j;
Was just a shortcut for:
i = i + j;
But if we try this:
int i = 5;
long j = 8;
Then i = i + j; will not compile but i += j; will compile fine.
Does it mean that in fact i += j; is a shortcut for something like this
i = (type of i) (i + j)?
",https://stackoverflow.com/questions/8710619/why-dont-javas-compound-assignment-operators-require-casting,3860,325664.0,12.0,,,2012-01-03 10:10:32,2025-02-20 14:49:31,2024-02-01 20:07:48,,,java;casting;operators;variable-assignment;assignment-operator,Honza Brabec,37618,1127571,registered,true,8710685,,CC BY-SA 4.0,2013-02-27 09:08:11,458,299,7,0,0,5,true,false,false,true,true,true,86,12,true,0.037,0.0119,5436,2012,1,10,Tuesday,false,false,false,true,false,false,false
1066589,Iterate through a HashMap,"What's the best way to iterate over the items in a HashMap?
",https://stackoverflow.com/questions/1066589/iterate-through-a-hashmap,3787,4570971.0,7.0,,,2009-06-30 23:24:14,2022-09-25 17:46:32,2019-10-29 16:00:24,2019-11-08 08:09:16,Duplicate,java;loops;hashmap;iteration,burntsugar,58270,84916,registered,true,1066603,,,2013-12-03 13:23:06,177,60,1,1,0,4,true,true,false,true,true,true,25,4,false,0.002,0.0008,6353,2009,6,23,Tuesday,false,false,false,true,false,false,false
6470651,How can I create a memory leak in Java?,"I just had an interview where I was asked to create a memory leak with Java.
Needless to say, I felt pretty dumb, having no idea how to start creating one.
What would an example be?
",https://stackoverflow.com/questions/6470651/how-can-i-create-a-memory-leak-in-java,3760,774524.0,61.0,,,2011-06-24 16:11:52,2024-10-29 21:46:06,2023-01-25 13:09:55,,,java;memory;memory-leaks,MatBanik,26965,465179,registered,true,6471947,,CC BY-SA 4.0,2013-04-15 15:25:25,229,182,0,0,0,3,true,false,false,true,true,true,39,9,true,0.079,0.0049,5629,2011,6,16,Friday,false,false,false,true,false,false,false
215497,"What is the difference between public, protected, package-private and private in Java?","In Java, are there clear rules on when to use each of access modifiers, namely the default (package private), public, protected and private, while making class and interface and dealing with inheritance?
",https://stackoverflow.com/questions/215497/what-is-the-difference-between-public-protected-package-private-and-private-in,3743,2758594.0,33.0,,,2008-10-18 19:53:12,2025-09-26 10:04:06,2018-09-11 14:54:49,,,java;private;public;protected;access-modifiers,intrepion,39067,625,registered,true,215505,,CC BY-SA 4.0,2013-03-28 02:18:51,276,204,5,0,0,5,true,false,false,true,true,true,86,12,true,0.012,0.0014,6608,2008,10,19,Saturday,true,false,false,true,false,false,false
322715,When to use LinkedList over ArrayList in Java?,"I've always been one to simply use:
List<String> names = new ArrayList<>();
I use the interface as the type name for portability, so that when I ask questions such as this, I can rework my code.
When should LinkedList be used over ArrayList and vice-versa?
",https://stackoverflow.com/questions/322715/when-to-use-linkedlist-over-arraylist-in-java,3648,1429297.0,34.0,,,2008-11-27 01:36:35,2026-05-27 21:29:33,2022-01-05 21:13:24,,,java;arraylist;collections;linked-list,sdellysse,39746,41200,registered,true,322742,,CC BY-SA 4.0,2011-05-01 03:20:57,547,270,3,2,0,4,true,false,false,true,true,true,46,8,true,0.024,0.0026,6568,2008,11,1,Thursday,false,false,false,true,false,false,false
5585779,How do I convert a String to an int in Java?,"How can I convert a String value to an int type?
"1234" → 1234
",https://stackoverflow.com/questions/5585779/how-do-i-convert-a-string-to-an-int-in-java,3539,7071847.0,30.0,,,2011-04-07 18:27:54,2025-09-27 09:48:38,2023-10-12 05:19:05,,,java;string;type-conversion;integer,Unknown user,45451,537967,registered,true,5585800,,CC BY-SA 4.0,2013-05-18 14:35:01,172,76,3,0,0,4,true,false,false,true,true,true,44,11,true,0.004,0.0005,5707,2011,4,18,Thursday,false,false,false,true,false,false,false
285793,What is a serialVersionUID and why should I use it?,"Eclipse issues warnings when a serialVersionUID is missing.
The serializable class Foo does not declare a static final
serialVersionUID field of type long
What is serialVersionUID and why is it important? Please show an example where missing serialVersionUID will cause a problem.
",https://stackoverflow.com/questions/285793/what-is-a-serialversionuid-and-why-should-i-use-it,3479,1227857.0,25.0,,,2008-11-12 23:24:56,2024-02-27 16:09:12,2015-03-17 22:44:09,,,java;serialization;serialversionuid,ashokgelal,81796,33203,registered,true,285809,,CC BY-SA 3.0,2015-05-04 15:36:08,377,292,3,0,0,3,true,false,false,true,true,true,51,10,true,0.02,0.0028,6583,2008,11,23,Wednesday,false,false,false,true,false,false,false
1005073,Initialization of an ArrayList in one line,"I wanted to create a list of options for testing purposes.
At first, I did this:
ArrayList<String> places = new ArrayList<String>();
places.add("Buenos Aires");
places.add("Córdoba");
places.add("La Plata");
Then, I refactored the code as follows:
ArrayList<String> places = new ArrayList<String>(
Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));
Is there a better way to do this?
",https://stackoverflow.com/questions/1005073/initialization-of-an-arraylist-in-one-line,3417,4095010.0,36.0,,,2009-06-17 04:10:20,2026-09-23 15:28:40,2026-09-23 15:28:40,,,java;collections;arraylist;initialization,Macarse,93369,119895,registered,true,1005083,,CC BY-SA 4.0,2015-04-09 09:51:06,552,477,2,0,0,4,true,false,false,true,true,true,42,7,false,0.009,0.0008,6366,2009,6,4,Wednesday,false,false,false,true,false,false,false
34571,"How do I test a class that has private methods, fields or inner classes?","How do I use JUnit to test a class that has internal private methods, fields or nested classes?
It seems bad to change the access modifier for a method just to be able to run a test.
",https://stackoverflow.com/questions/34571/how-do-i-test-a-class-that-has-private-methods-fields-or-inner-classes,3263,1355896.0,59.0,,,2008-08-29 16:11:09,2023-03-16 08:58:06,2021-10-19 20:41:15,,,java;unit-testing;junit;tdd,MattGrommes,12444,3098,registered,true,34658,,CC BY-SA 4.0,2012-01-02 03:45:19,197,183,0,0,0,4,true,false,false,true,true,true,72,14,true,0.044,0.0024,6658,2008,8,16,Friday,false,false,false,true,false,false,false
21947452,Why is printing "B" dramatically slower than printing "#"?,"I generated two matrices of 1000 x 1000:
First Matrix: O and #.
Second Matrix: O and B.
Using the following code, the first matrix took 8.52 seconds to complete:
Random r = new Random();
for (int i = 0; i < 1000; i++) {
for (int j = 0; j < 1000; j++) {
if (r.nextInt(4) == 0) {
System.out.print("O");
} else {
System.out.print("#");
}
}
System.out.println("");
}
With this code, the second matrix took 259.152 seconds to complete:
Random r = new Random();
for (int i = 0; i < 1000; i++) {
for (int j = 0; j < 1000; j++) {
if (r.nextInt(4) == 0) {
System.out.print("O");
} else {
System.out.print("B"); // only line changed
}
}
System.out.println("");
}
What is the reason behind the dramatically different run times?
As suggested in the comments, printing only System.out.print("#"); takes 7.8871 seconds, whereas System.out.print("B"); gives still printing....
As others pointed out that it works for them normally, I tried Ideone.com for instance, and both pieces of code execute at the same speed.
Test Conditions:
- I ran this test from Netbeans 7.2, with the output into its console
- I used
System.nanoTime() for measurements
",https://stackoverflow.com/questions/21947452/why-is-printing-b-dramatically-slower-than-printing,3007,266075.0,3.0,,,2014-02-21 23:45:43,2023-07-05 12:27:51,2023-07-05 12:21:02,,,java;performance;loops;for-loop;system.out,Kuba Spatny,27040,1732709,registered,true,21947627,,CC BY-SA 4.0,2014-02-25 20:05:00,1719,1375,13,1,0,5,true,false,false,true,true,true,78,9,true,0.011,0.0113,4656,2014,2,23,Friday,false,false,false,true,false,false,false
574594,How can I create an executable/runnable JAR with dependencies using Maven?,"I want to package my project in a single executable JAR for distribution.
How can I make a Maven project package all dependency JARs into my output JAR?
",https://stackoverflow.com/questions/574594/how-can-i-create-an-executable-runnable-jar-with-dependencies-using-maven,2944,2052538.0,33.0,,,2009-02-22 08:43:45,2024-08-24 15:00:49,2022-10-15 10:06:46,,,java;build;maven-2;executable-jar;build-automation,soemirno,29984,67219,registered,true,574650,,CC BY-SA 4.0,2011-04-14 18:34:01,168,154,0,0,0,5,true,false,false,true,true,true,74,11,true,0.016,0.0014,6481,2009,2,8,Sunday,true,false,false,true,false,false,false
1128723,How do I determine whether an array contains a particular value in Java?,"I have a String[] with values like so:
public static final String[] VALUES = new String[] {""AB"",""BC"",""CD"",""AE""};
Given String s, is there a good way of testing whether VALUES contains s?
",https://stackoverflow.com/questions/1128723/how-do-i-determine-whether-an-array-contains-a-particular-value-in-java,2762,2875188.0,33.0,,,2009-07-15 00:03:21,2025-08-22 14:58:48,2019-01-05 09:06:06,,,java;arrays,Mike Sickler,34671,16534,registered,true,1128728,,CC BY-SA 4.0,2015-06-10 10:09:04,280,190,5,0,0,2,true,false,false,true,true,true,72,13,true,0.011,0.001,6338,2009,7,0,Wednesday,false,false,false,true,false,false,false
6343166,How can I fix 'android.os.NetworkOnMainThreadException'?,"I got an error while running my Android project for RssReader.
Code:
URL url = new URL(urlToRssFeed);
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader xmlreader = parser.getXMLReader();
RssHandler theRSSHandler = new RssHandler();
xmlreader.setContentHandler(theRSSHandler);
InputSource is = new InputSource(url.openStream());
xmlreader.parse(is);
return theRSSHandler.getFeed();
And it shows the below error:
android.os.NetworkOnMainThreadException
How can I fix this issue?
",https://stackoverflow.com/questions/6343166/how-can-i-fix-android-os-networkonmainthreadexception,2747,1549974.0,65.0,,,2011-06-14 12:02:00,2026-08-18 21:24:47,2021-07-22 10:25:23,,,java;android;android-networking;networkonmainthread,bejoy george,29905,797593,registered,true,6343299,,CC BY-SA 4.0,2014-01-28 18:29:34,623,547,2,0,0,4,true,false,false,true,true,true,64,5,true,0.042,0.0018,5639,2011,6,12,Tuesday,false,false,false,true,false,false,false
65035,Does a finally block always get executed in Java?,"Considering this code, can I be absolutely sure that the finally block always executes, no matter what something() is?
try {
something();
return success;
}
catch (Exception e) {
return failure;
}
finally {
System.out.println(""I don't know if this will get printed out"");
}
",https://stackoverflow.com/questions/65035/does-a-finally-block-always-get-executed-in-java,2714,653436.0,51.0,,,2008-09-15 17:43:54,2025-03-17 11:29:34,2020-05-28 00:58:39,,,java;error-handling;return;try-catch-finally,jonny five,27640,885027,registered,true,65049,,CC BY-SA 4.0,2017-08-20 10:37:54,374,308,3,0,0,4,true,false,false,true,true,true,49,9,true,0.078,0.0042,6641,2008,9,17,Monday,false,false,false,true,false,false,false
285177,How do I call one constructor from another in Java?,"Is it possible to call a constructor from another (within the same class, not from a subclass)? If yes how? And what could be the best way to call another constructor (if there are several ways to do it)?
",https://stackoverflow.com/questions/285177/how-do-i-call-one-constructor-from-another-in-java,2714,1217554.0,22.0,,,2008-11-12 20:10:19,2024-01-19 14:23:42,2008-11-12 20:16:59,,,java;constructor,ashokgelal,81796,33203,registered,true,285184,,CC BY-SA 2.5,2013-07-08 17:58:16,212,205,0,0,0,2,true,false,false,true,true,true,51,10,true,0.018,0.0022,6583,2008,11,20,Wednesday,false,false,false,true,false,false,false
6827752,"What's the difference between @Component, @Repository & @Service annotations in Spring?","Can @Component, @Repository, and @Service annotations be used interchangeably in Spring or do they provide any particular functionality besides acting as a notation device?
In other words, if I have a Service class and I change its annotation from @Service to @Component, will it still behave the same way?
Or does the annotation also influence the behavior and functionality of the class?
",https://stackoverflow.com/questions/6827752/whats-the-difference-between-component-repository-service-annotations-in,2652,1239100.0,30.0,,,2011-07-26 09:10:46,2025-09-09 13:46:40,2023-10-04 04:31:12,,,java;spring;spring-mvc;annotations;inversion-of-control,Colin McCree,26565,863084,unregistered,true,,,CC BY-SA 4.0,2016-01-12 20:10:49,901,390,5,3,0,5,false,false,false,true,true,true,95,11,true,0.024,0.0021,5597,2011,7,9,Tuesday,false,false,false,true,false,false,false
37628,What is reflection and why is it useful?,"What is reflection, and why is it useful?
I'm particularly interested in Java, but I assume the principles are the same in any language.
",https://stackoverflow.com/questions/37628/what-is-reflection-and-why-is-it-useful,2590,1103601.0,24.0,,,2008-09-01 08:39:21,2024-12-05 08:32:17,2022-11-27 07:51:35,,,java;reflection;terminology,Lehane,48968,142,registered,true,37632,,CC BY-SA 4.0,2014-06-07 05:54:34,151,137,0,0,0,3,true,false,false,true,true,true,40,8,true,0.022,0.0023,6655,2008,9,8,Monday,false,false,false,true,false,false,false
1200621,How do I declare and initialize an array in Java?,"How do I declare and initialize an array in Java?
",https://stackoverflow.com/questions/1200621/how-do-i-declare-and-initialize-an-array-in-java,2576,6009524.0,31.0,,,2009-07-29 14:22:27,2025-05-01 09:04:22,2019-11-21 16:58:12,,,java;arrays,bestattendance,26992,40842,registered,true,1200646,,CC BY-SA 4.0,2013-08-08 09:23:29,57,50,0,0,0,2,true,false,false,true,true,true,49,10,true,0.005,0.0004,6324,2009,7,14,Wednesday,false,false,false,true,false,false,false
409784,What's the simplest way to print a Java array?,"In Java, arrays don't override toString(), so if you try to print one directly, you get the className + '@' + the hex of the hashCode of the array, as defined by Object.toString():
int[] intArray = new int[] {1, 2, 3, 4, 5};
System.out.println(intArray); // Prints something like '[I@3343c8b3'
But usually, we'd actually want something more like [1, 2, 3, 4, 5]. What's the simplest way of doing that? Here are some example inputs and outputs:
// Array of primitives:
int[] intArray = new int[] {1, 2, 3, 4, 5};
// Output: [1, 2, 3, 4, 5]
// Array of object references:
String[] strArray = new String[] {"John", "Mary", "Bob"};
// Output: [John, Mary, Bob]
",https://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array,2453,3402207.0,36.0,,,2009-01-03 20:39:39,2025-08-19 20:49:44,2022-12-02 14:02:24,,,java;arrays;printing;tostring,Alex Spurling,56152,12149,registered,true,409795,,CC BY-SA 4.0,2015-10-02 18:54:33,972,690,7,1,0,4,true,false,false,true,true,true,50,9,true,0.011,0.0007,6531,2009,1,20,Saturday,true,false,false,true,false,false,false
3295496,What is a JavaBean exactly?,"I understood, I think, that a "Bean" is a Java-class with properties and getters/setters.
As much as I understand, it is the equivalent of a C struct. Is that true?
Also, is there a real syntactic difference between a JavaBean and a regular class?
Is there any special definition or an Interface?
Basically, why is there a term for this?
Also what does the Serializable interface mean?
",https://stackoverflow.com/questions/3295496/what-is-a-javabean-exactly,2428,873149.0,23.0,,,2010-07-21 00:41:11,2022-08-27 12:46:45,2021-10-12 12:25:56,,,java;dependency-injection;inversion-of-control;javabeans;serializable,Amir Rachum,80603,166067,registered,true,3295517,,CC BY-SA 4.0,2016-05-31 15:50:53,512,398,5,0,0,5,true,false,false,true,true,true,27,5,true,0.026,0.0028,5967,2010,7,0,Wednesday,false,false,false,true,false,false,false
604424,How to get an enum value from a string value in Java,"Say I have an enum which is just
public enum Blah {
A, B, C, D
}
and I would like to find the enum value of a string, for example "A" which would be Blah.A. How would it be possible to do this?
Is the Enum.valueOf() the method I need? If so, how would I use this?
",https://stackoverflow.com/questions/604424/how-to-get-an-enum-value-from-a-string-value-in-java,2408,1755878.0,32.0,,,2009-03-02 22:56:34,2026-10-11 06:56:19,2021-08-10 17:32:06,,,java;enums,Malachi,33870,50913,registered,true,604426,,CC BY-SA 4.0,2012-07-13 08:20:56,517,279,4,1,0,2,true,false,false,true,true,true,52,12,false,0.018,0.0014,6473,2009,3,22,Monday,false,false,false,true,false,false,false
541487,"implements Runnable" vs "extends Thread" in Java,"From what time I've spent with threads in Java, I've found these two ways to write threads:
With implements Runnable:
public class MyRunnable implements Runnable {
public void run() {
//Code
}
}
//Started with a "new Thread(new MyRunnable()).start()" call
Or, with extends Thread:
public class MyThread extends Thread {
public MyThread() {
super("MyThread");
}
public void run() {
//Code
}
}
//Started with a "new MyThread().start()" call
Is there any significant difference in these two blocks of code?
",https://stackoverflow.com/questions/541487/implements-runnable-vs-extends-thread-in-java,2380,792363.0,42.0,,,2009-02-12 14:28:46,2025-06-07 22:23:49,2024-04-12 13:34:51,,,java;multithreading;runnable;implements;java-threads,user65374,24469,65374,registered,true,541506,,CC BY-SA 4.0,2013-07-24 18:31:25,720,584,4,0,0,5,true,false,false,true,true,true,69,7,false,0.053,0.003,6491,2009,2,14,Thursday,false,false,false,true,false,false,false
156503,How do you assert that a certain exception is thrown in JUnit tests?,"How can I use JUnit idiomatically to test that some code throws an exception?
While I can certainly do something like this:
@Test
public void testFooThrowsIndexOutOfBoundsException() {
boolean thrown = false;
try {
foo.doStuff();
} catch (IndexOutOfBoundsException e) {
thrown = true;
}
assertTrue(thrown);
}
I recall that there is an annotation or an Assert.xyz or something that is far less kludgy and far more in-the-spirit of JUnit for these sorts of situations.
",https://stackoverflow.com/questions/156503/how-do-you-assert-that-a-certain-exception-is-thrown-in-junit-tests,2340,2115063.0,35.0,,,2008-10-01 06:56:08,2024-04-07 22:07:58,2023-06-28 09:49:45,,,java;exception;junit;junit4;assert,SCdF,59826,1666,registered,true,156528,,CC BY-SA 4.0,2018-12-20 04:44:46,561,507,1,0,0,5,true,false,false,true,true,true,68,13,true,0.017,0.0011,6625,2008,10,6,Wednesday,false,false,false,true,false,false,false
1750435,Comparing Java enum members: == or equals()?,"I know that Java enums are compiled to classes with private constructors and a bunch of public static members. When comparing two members of a given enum, I've always used .equals(), e.g.
public useEnums(SomeEnum a)
{
if(a.equals(SomeEnum.SOME_ENUM_VALUE))
{
...
}
...
}
However, I just came across some code that uses the equals operator == instead of .equals():
public useEnums2(SomeEnum a)
{
if(a == SomeEnum.SOME_ENUM_VALUE)
{
...
}
...
}
Which operator is the one I should be using?
",https://stackoverflow.com/questions/1750435/comparing-java-enum-members-or-equals,2227,1166668.0,15.0,,,2009-11-17 17:26:27,2025-11-17 19:00:18,2019-11-09 16:13:27,,,java;enums,Matt Ball,361332,139010,registered,true,1750453,,CC BY-SA 4.0,2012-09-03 13:44:51,637,542,4,0,0,2,true,false,false,true,true,true,44,7,true,0.013,0.0019,6213,2009,11,17,Tuesday,false,false,false,true,false,false,false
997482,Does Java support default parameter values?,"I came across some Java code that had the following structure:
public MyParameterizedFunction(String param1, int param2)
{
this(param1, param2, false);
}
public MyParameterizedFunction(String param1, int param2, boolean param3)
{
//use all three parameters here
}
I know that in C++ I can assign a parameter a default value. For example:
void MyParameterizedFunction(String param1, int param2, bool param3=false);
Does Java support this kind of syntax? Are there any reasons why this two step syntax is preferable?
",https://stackoverflow.com/questions/997482/does-java-support-default-parameter-values,2197,2221831.0,26.0,,,2009-06-15 18:04:28,2024-01-05 21:28:36,2019-05-08 09:01:21,2024-08-30 07:47:52,Duplicate,java;methods;parameters;overloading;default-parameters,gnavi,26282,99317,registered,true,997529,,,2013-04-10 11:04:26,601,532,2,0,0,5,true,true,false,true,true,true,43,6,true,0.012,0.001,6368,2009,6,18,Monday,false,false,false,true,false,false,false
2793150,How to use java.net.URLConnection to fire and handle HTTP requests,"Use of java.net.URLConnection is asked about pretty often here, and the Oracle tutorial is too concise about it.
That tutorial basically only shows how to fire a GET request and read the response. It doesn't explain anywhere how to use it to, among others, perform a POST request, set request headers, read response headers, deal with cookies, submit a HTML form, upload a file, etc.
So, how can I use java.net.URLConnection to fire and handle "advanced" HTTP requests?
",https://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests,2144,1216622.0,12.0,,,2010-05-08 06:16:11,2026-04-15 15:08:31,2021-08-11 12:23:07,,,java;http;httprequest;httpurlconnection;urlconnection,BalusC,1116180,157882,registered,true,2793153,,CC BY-SA 4.0,2011-05-09 18:30:37,924,480,2,4,0,5,true,false,false,true,true,true,66,10,false,0.01,0.0018,6041,2010,5,6,Saturday,true,false,false,true,false,false,false
70324,Java inner class and static nested class,"What is the main difference between an inner class and a static nested class in Java? Does design / implementation play a role in choosing one of these?
",https://stackoverflow.com/questions/70324/java-inner-class-and-static-nested-class,2108,986504.0,28.0,,,2008-09-16 08:22:35,2025-12-22 08:46:48,2019-01-07 17:41:37,,,java;inner-classes;static-classes,Omnipotent,28307,11193,registered,true,70358,,CC BY-SA 4.0,2014-02-21 18:33:36,160,153,0,0,0,3,true,false,false,true,true,true,40,7,false,0.028,0.0021,6640,2008,9,8,Tuesday,false,false,false,true,false,false,false
886955,How do I break out of nested loops in Java?,"I've got a nested loop construct like this:
for (Type type : types) {
for (Type t : types2) {
if (some condition) {
// Do something and break...
break; // Breaks out of the inner loop
}
}
}
Now how can I break out of both loops? I've looked at similar questions, but none concerns Java specifically. I couldn't apply these solutions because most used gotos.
I don't want to put the inner loop in a different method.
I don't want to return the loops. When breaking I'm finished with the execution of the loop block.
",https://stackoverflow.com/questions/886955/how-do-i-break-out-of-nested-loops-in-java,2099,1475551.0,37.0,,,2009-05-20 09:07:43,2023-04-08 20:42:08,2021-12-06 06:35:30,,,java;loops;nested-loops,boutta,24679,15108,registered,true,886979,,CC BY-SA 4.0,2013-07-29 17:04:02,620,568,1,0,0,3,true,false,false,true,true,true,43,10,true,0.025,0.0014,6394,2009,5,9,Wednesday,false,false,false,true,false,false,false
41107,How to generate a random alpha-numeric string,"I've been looking for a simple Java algorithm to generate a pseudo-random alpha-numeric string. In my situation it would be used as a unique session/key identifier that would ""likely"" be unique over 500K+ generation (my needs don't really require anything much more sophisticated).
Ideally, I would be able to specify a length depending on my uniqueness needs. For example, a generated string of length 12 might look something like ""AEYGF7K0DM1X"".
",https://stackoverflow.com/questions/41107/how-to-generate-a-random-alpha-numeric-string,1987,1703866.0,48.0,,,2008-09-03 02:58:43,2025-07-14 13:49:20,2020-11-12 15:36:38,,,java;string;random;alphanumeric,Todd,3363,3803,registered,true,41156,,CC BY-SA 4.0,2013-10-09 19:34:37,503,454,2,0,0,4,true,false,false,true,true,true,45,7,false,0.028,0.0012,6653,2008,9,2,Wednesday,false,false,false,true,false,false,false
3481828,How do I split a string in Java?,"I want to split a string using a delimiter, for example split "004-034556" into two separate strings by the delimiter "-":
part1 = "004";
part2 = "034556";
That means the first string will contain the characters before '-', and the second string will contain the characters after '-'.
I also want to check if the string has the delimiter ('-') in it.
",https://stackoverflow.com/questions/3481828/how-do-i-split-a-string-in-java,1950,4920022.0,38.0,,,2010-08-14 03:01:53,2024-01-24 11:53:11,2023-10-12 05:27:07,,,java;string;split,riyana,21805,303459,registered,true,3481842,,CC BY-SA 4.0,2014-03-29 13:31:07,502,392,6,0,0,3,true,false,false,true,true,true,32,8,true,0.008,0.0004,5943,2010,8,3,Saturday,true,false,false,true,false,false,false
18093928,What does "Could not find or load main class" mean?,"A common problem that new Java developers experience is that their programs fail to run with the error message: Could not find or load main class ...
What does this mean, what causes it, and how should you fix it?
",https://stackoverflow.com/questions/18093928/what-does-could-not-find-or-load-main-class-mean,1950,4811214.0,67.0,,,2013-08-07 03:02:46,2025-03-26 06:28:57,2018-01-07 06:58:35,,,java;class;program-entry-point,Stephen C,725244,139985,registered,true,18093929,,CC BY-SA 3.0,2013-12-02 15:36:22,243,216,1,0,0,3,true,false,false,true,true,true,61,10,true,0.014,0.0004,4854,2013,8,3,Wednesday,false,false,false,true,false,false,false
109383,"Sort a Map<Key, Value> by values","I need to sort a Map<Key, Value> on the values.
Since the values are not unique, I find myself converting the keySet into an array, and sorting that array through array sort with a custom comparator that sorts on the value associated with the key.
Is there an easier way?
",https://stackoverflow.com/questions/109383/sort-a-mapkey-value-by-values,1910,1866125.0,65.0,,,2008-09-20 21:03:23,2026-03-10 22:21:59,2023-08-31 10:48:18,,,java;sorting;dictionary;collections,Abe,2463,9466,registered,true,,,CC BY-SA 4.0,2015-06-17 23:08:01,372,278,3,0,0,4,false,false,false,true,true,true,38,6,false,0.035,0.001,6636,2008,9,21,Saturday,true,false,false,true,false,false,false
15182496,Why does this code using random strings print "hello world"?,"The following print statement would print ""hello world"".
Could anyone explain this?
System.out.println(randomString(-229985452) + "" "" + randomString(-147909649));
And randomString() looks like this:
public static String randomString(int i)
{
Random ran = new Random(i);
StringBuilder sb = new StringBuilder();
while (true)
{
int k = ran.nextInt(27);
if (k == 0)
break;
sb.append((char)('`' + k));
}
return sb.toString();
}
",https://stackoverflow.com/questions/15182496/why-does-this-code-using-random-strings-print-hello-world,1907,231581.0,14.0,,,2013-03-03 04:38:06,2023-12-27 06:07:42,2015-08-28 16:12:17,,,java;string;random,0x56794E,21431,1031797,registered,true,15182511,,CC BY-SA 3.0,2013-03-04 15:32:53,565,490,3,0,0,3,true,false,false,true,true,true,70,10,true,0.06,0.0082,5011,2013,3,4,Sunday,true,false,false,true,false,false,false
1568091,Why use getters and setters/accessors?,"What's the advantage of using getters and setters - that only get and set - instead of simply using public fields for those variables?
If getters and setters are ever doing more than just the simple get/set, I can figure this one out very quickly, but I'm not 100% clear on how:
public String foo;
is any worse than:
private String foo;
public void setFoo(String foo) { this.foo = foo; }
public String getFoo() { return foo; }
Whereas the former takes a lot less boilerplate code.
",https://stackoverflow.com/questions/1568091/why-use-getters-and-setters-accessors,1891,587337.0,37.0,,,2009-10-14 18:20:56,2023-08-23 16:24:43,2023-08-23 16:24:43,,,java;oop;setter;getter;abstraction,Dean J,40637,182690,registered,true,1568230,,CC BY-SA 4.0,2014-01-27 03:02:33,637,483,2,0,0,5,true,false,false,true,true,true,38,5,true,0.063,0.0032,6247,2009,10,18,Wednesday,false,false,false,true,false,false,false
326390,How do I create a Java string from the contents of a file?,"I've been using the idiom below for some time now. And it seems to be the most wide-spread, at least on the sites I've visited.
Is there a better/different way to read a file into a string in Java?
private String readFile(String file) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader (file));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
try {
while((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(ls);
}
return stringBuilder.toString();
} finally {
reader.close();
}
}
",https://stackoverflow.com/questions/326390/how-do-i-create-a-java-string-from-the-contents-of-a-file,1806,1786254.0,35.0,,,2008-11-28 18:32:07,2026-04-01 15:42:35,2023-12-27 06:08:54,,,java;string;file;file-io;io,OscarRyz,200157,20654,registered,true,326440,,CC BY-SA 4.0,2013-10-21 20:50:06,750,712,1,0,0,5,true,false,false,true,true,true,58,13,true,0.02,0.001,6567,2008,11,18,Friday,false,false,false,true,false,false,false
3177733,"How can I avoid Java code in JSP files, using JSP 2?","I know that something like the following three lines
<%= x+1 %>
<%= request.getParameter("name") %>
<%! counter++; %>
is an old school way of coding and in JSP version 2 there exists a method to avoid Java code in JSP files. What are the alternative JSP 2 lines, and what is this technique called?
",https://stackoverflow.com/questions/3177733/how-can-i-avoid-java-code-in-jsp-files-using-jsp-2,1773,330525.0,31.0,,,2010-07-05 07:24:06,2023-01-03 08:53:27,2022-12-28 23:44:37,,,java;jsp;scriptlet,chmoelders,18692,95914,registered,true,3180202,,CC BY-SA 4.0,2011-07-11 11:17:36,365,327,1,0,0,3,true,false,false,true,true,true,52,12,true,0.094,0.0054,5983,2010,7,7,Monday,false,false,false,true,false,false,false
10382929,How to fix java.lang.UnsupportedClassVersionError: Unsupported major.minor version,"I am trying to use Notepad++ as my all-in-one tool edit, run, compile, etc.
I have JRE installed, and I have setup my path variable to the .../bin directory.
When I run my "Hello world" in Notepad++, I get this message:
java.lang.UnsupportedClassVersionError: test_hello_world :
Unsupported major.minor version 51.0
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(Unknown Source)
...
More recent versions of Java produce a more detailed exception message:
java.lang.UnsupportedClassVersionError: com/xxx/yyy/Application has been compiled by a more recent version of the Java Runtime (class file version 65.0), this version of the Java Runtime only recognizes class file versions up to 61.0
I think the problem here is about versions; some versions of Java may be old or too new.
- How do I fix it?
- Should I install the JDK, and setup my path variable to the JDK instead of JRE?
- What is the difference between the
PATH variable in JRE or JDK?
",https://stackoverflow.com/questions/10382929/how-to-fix-java-lang-unsupportedclassversionerror-unsupported-major-minor-versi,1763,2486462.0,52.0,,,2012-04-30 11:28:24,2026-10-06 10:33:59,2024-09-12 09:07:49,,,java;jvm;incompatibility;unsupported-class-version,ERJAN,24619,898042,registered,true,11432195,,CC BY-SA 4.0,2014-09-22 16:30:22,1386,1017,3,2,0,4,true,false,false,true,true,true,82,7,false,0.021,0.0007,5318,2012,4,11,Monday,false,false,false,true,false,false,false
355089,Difference between StringBuilder and StringBuffer,"What is the main difference between StringBuffer and StringBuilder?
Is there any performance issues when deciding on any one of these?
",https://stackoverflow.com/questions/355089/difference-between-stringbuilder-and-stringbuffer,1759,910460.0,33.0,,,2008-12-10 04:34:26,2025-12-16 16:25:17,2016-05-10 08:20:28,,,java;stringbuilder;stringbuffer,blacktiger,19237,44848,registered,true,355092,,CC BY-SA 3.0,2013-07-01 13:58:41,168,135,2,0,0,3,true,false,false,true,true,true,49,5,false,0.036,0.0019,6555,2008,12,4,Wednesday,false,false,false,true,false,false,false
1149703,How can I convert a stack trace to a string?,"What is the easiest way to convert the result of Throwable.getStackTrace() to a string that depicts the stacktrace?
",https://stackoverflow.com/questions/1149703/how-can-i-convert-a-stack-trace-to-a-string,1755,811546.0,33.0,,,2009-07-19 11:31:43,2024-04-19 19:03:26,2016-03-11 20:04:37,,,java;stack-trace;tostring,ripper234,232304,11236,registered,true,2109985,,CC BY-SA 3.0,2018-07-26 18:46:54,136,116,1,0,0,3,true,false,false,true,true,true,44,10,true,0.041,0.0022,6334,2009,7,11,Sunday,true,false,false,true,false,false,false
85190,"In detail, how does the 'for each' loop work in Java?","Consider:
List<String> someList = new ArrayList<>();
// add "monkey", "donkey", "skeleton key" to someList
for (String item : someList) {
System.out.println(item);
}
What would the equivalent for loop look like without using the for each syntax?
People new to Java commonly encounter issues when trying to modify the original data using the new style foreach loop. Use Why doesn't assigning to the iteration variable in a foreach loop change the underlying data? to close duplicates about that common problem. Note that other languages with analogous constructs generally have the same issue; for example, see Why doesn't modifying the iteration variable affect subsequent iterations? for the same issue in Python.
",https://stackoverflow.com/questions/85190/in-detail-how-does-the-for-each-loop-work-in-java,1732,2950344.0,29.0,,,2008-09-17 16:44:32,2024-04-05 15:59:20,2023-10-13 19:25:11,,,java;foreach;syntactic-sugar,Jay R.,32209,5074,registered,true,85206,,CC BY-SA 4.0,2014-07-26 07:40:27,1087,774,3,2,0,3,true,false,false,true,true,true,61,11,true,0.01,0.0006,6639,2008,9,16,Wednesday,false,false,false,true,false,false,false
6802483,How to directly initialize a HashMap (in a literal way)?,"Is there some way of initializing a Java HashMap like this?:
Map<String,String> test =
new HashMap<String, String>{""test"":""test"",""test"":""test""};
What would be the correct syntax? I have not found anything regarding this. Is this possible? I am looking for the shortest/fastest way to put some ""final/static"" values in a map that never change and are known in advance when creating the Map.
",https://stackoverflow.com/questions/6802483/how-to-directly-initialize-a-hashmap-in-a-literal-way,1709,2161349.0,23.0,,,2011-07-23 18:40:33,2025-06-30 21:26:41,2018-04-02 18:51:13,,,java;dictionary;collections;initialization,jens,17825,634682,registered,true,6802502,,CC BY-SA 3.0,,448,410,1,0,0,4,true,false,false,true,true,true,56,10,true,0.011,0.0008,5600,2011,7,18,Saturday,true,false,false,true,false,false,false
4955635,How can I add local JAR files to a Maven project?,"How do I add local JAR files (not yet part of the Maven repository) directly in my project's library sources?
",https://stackoverflow.com/questions/4955635/how-can-i-add-local-jar-files-to-a-maven-project,1693,1880601.0,35.0,,,2011-02-10 10:03:26,2025-07-30 21:35:20,2025-07-29 16:15:48,,,java;maven;dependencies;libraries;mvn-repo,Praneel PIDIKITI,19727,410693,registered,true,4955695,,CC BY-SA 4.0,2018-10-26 07:41:25,117,110,0,0,0,5,true,false,false,true,true,true,49,11,true,0.019,0.0009,5763,2011,2,10,Thursday,false,false,false,true,false,false,false
910374,Why does Java have transient fields?,"Why does Java have transient fields?
",https://stackoverflow.com/questions/910374/why-does-java-have-transient-fields,1676,815623.0,15.0,,,2009-05-26 12:11:36,2025-07-11 15:18:08,2016-05-06 12:05:12,,,java;field;transient,Animesh,17054,112532,registered,true,910522,,CC BY-SA 3.0,2014-04-10 11:51:43,61,37,0,0,0,3,true,false,false,true,true,true,36,6,true,0.018,0.0021,6388,2009,5,12,Tuesday,false,false,false,true,false,false,false
8845186,What exactly is Apache Camel?,"I don't understand what exactly Camel does.
If you could give in 101 words an introduction to Camel:
- What exactly is it?
- How does it interact with an application written in Java?
- Is it something that goes together with the server?
- Is it an independent program?
Please explain what Camel is.
",https://stackoverflow.com/questions/8845186/what-exactly-is-apache-camel,1655,713493.0,21.0,,,2012-01-13 02:32:18,2025-01-14 22:23:13,2016-01-28 15:25:32,,,java;apache-camel;soa;enterprise-integration,Myy,18637,929694,registered,true,11540451,,CC BY-SA 3.0,2012-06-18 11:48:11,449,300,0,1,0,4,true,false,false,true,true,true,29,5,true,0.029,0.0023,5426,2012,1,2,Friday,false,false,false,true,false,false,false
2950319,Is null check needed before calling instanceof?,"Will null instanceof SomeClass return false or throw a NullPointerException?
",https://stackoverflow.com/questions/2950319/is-null-check-needed-before-calling-instanceof,1639,386243.0,8.0,,,2010-06-01 13:53:15,2024-02-02 09:13:01,2017-12-03 14:37:46,,,java;nullpointerexception;null,Johan Lübcke,20434,4220,registered,true,2950415,,CC BY-SA 3.0,2013-07-29 12:10:49,123,77,3,0,0,3,true,false,false,true,true,true,47,7,true,0.021,0.0042,6017,2010,6,13,Tuesday,false,false,false,true,false,false,false
295579,Fastest way to determine if an integer's square root is an integer,"I'm looking for the fastest way to determine if a long value is a perfect square (i.e. its square root is another integer):
- I've done it the easy way, by using the built-in
Math.sqrt()
function, but I'm wondering if there is a way to do it faster by
restricting yourself to integer-only domain.
- Maintaining a lookup table is impractical (since there are about
231.5 integers whose square is less than 263).
Here is the very simple and straightforward way I'm doing it now:
public final static boolean isPerfectSquare(long n)
{
if (n < 0)
return false;
long tst = (long)(Math.sqrt(n) + 0.5);
return tst*tst == n;
}
Note: I'm using this function in many Project Euler problems. So no one else will ever have to maintain this code. And this kind of micro-optimization could actually make a difference, since part of the challenge is to do every algorithm in less than a minute, and this function will need to be called millions of times in some problems.
I've tried the different solutions to the problem:
- After exhaustive testing, I found that adding
0.5 to the result of Math.sqrt() is not necessary, at least not on my machine.
- The fast inverse square root was faster, but it gave incorrect results for n >= 410881. However, as suggested by BobbyShaftoe, we can use the FISR hack for n < 410881.
- Newton's method was a good bit slower than
Math.sqrt(). This is probably because Math.sqrt() uses something similar to Newton's Method, but implemented in the hardware so it's much faster than in Java. Also, Newton's Method still required use of doubles.
- A modified Newton's method, which used a few tricks so that only integer math was involved, required some hacks to avoid overflow (I want this function to work with all positive 64-bit signed integers), and it was still slower than
Math.sqrt().
- Binary chop was even slower. This makes sense because the binary chop will on average require 16 passes to find the square root of a 64-bit number.
- According to John's tests, using
or statements is faster in C++ than using a switch, but in Java and C# there appears to be no difference between or and switch.
- I also tried making a lookup table (as a private static array of 64 boolean values). Then instead of either switch or
or statement, I would just say if(lookup[(int)(n&0x3F)]) { test } else return false;. To my surprise, this was (just slightly) slower. This is because array bounds are checked in Java.
",https://stackoverflow.com/questions/295579/fastest-way-to-determine-if-an-integers-square-root-is-an-integer,1617,342975.0,38.0,,,2008-11-17 13:43:21,2026-01-20 17:41:50,2019-10-29 17:00:34,,,java;math;optimization;perfect-square,Kip,110053,18511,registered,true,424936,,CC BY-SA 4.0,2012-09-18 09:48:31,3274,2452,13,5,0,4,true,false,false,true,true,true,70,12,false,0.111,0.0047,6578,2008,11,13,Monday,false,false,false,true,false,false,false
80476,How can I concatenate two arrays in Java?,"I need to concatenate two String arrays in Java.
void f(String[] first, String[] second) {
String[] both = ???
}
Which is the easiest way to do this?
",https://stackoverflow.com/questions/80476/how-can-i-concatenate-two-arrays-in-java,1606,1442952.0,66.0,,,2008-09-17 06:14:23,2024-01-19 04:39:09,2022-04-02 09:44:03,,,java;arrays;concatenation;addition,Antti Kissaniemi,19523,2948,registered,true,,,CC BY-SA 4.0,2014-03-16 08:28:33,206,155,2,0,0,4,false,false,false,true,true,true,41,8,true,0.046,0.0011,6639,2008,9,6,Wednesday,false,false,false,true,false,false,false
2885173,How do I create a file and write to it?,"What's the simplest way to create and write to a (text) file in Java?
",https://stackoverflow.com/questions/2885173/how-do-i-create-a-file-and-write-to-it,1550,3253037.0,35.0,,,2010-05-21 19:58:55,2025-02-11 03:45:37,2021-01-27 11:20:42,,,java;file-io,Drew Johnson,19233,57643,registered,true,2885224,,CC BY-SA 4.0,2016-11-26 01:27:16,171,70,0,1,0,2,true,false,false,true,true,true,39,10,true,0.011,0.0005,6028,2010,5,19,Friday,false,false,false,true,false,false,false
14763079,What are the -Xms and -Xmx parameters when starting JVM?,"What are the Xms and Xmx parameters in JVMs - and what are their default values?
",https://stackoverflow.com/questions/14763079/what-are-the-xms-and-xmx-parameters-when-starting-jvm,1526,3149074.0,5.0,,,2013-02-07 23:28:20,2024-06-11 13:55:59,2024-06-11 13:55:59,,,java;memory-management;parameters;jvm,Pankaj,15636,1239857,registered,true,14763095,,CC BY-SA 4.0,2015-05-12 21:01:05,114,81,2,0,0,4,true,false,false,true,true,true,56,10,true,0.002,0.0005,5035,2013,2,23,Thursday,false,false,false,true,false,false,false
153724,How to round a number to n decimal places in Java,"What I would like is a method to convert a double to a string which rounds using the half-up method - i.e. if the decimal to be rounded is 5, it always rounds up to the next number. This is the standard method of rounding most people expect in most situations.
I also would like only significant digits to be displayed - i.e. there should not be any trailing zeroes.
I know one method of doing this is to use the String.format method:
String.format(""%.5g%n"", 0.912385);
returns:
0.91239
which is great, however it always displays numbers with 5 decimal places even if they are not significant:
String.format(""%.5g%n"", 0.912300);
returns:
0.91230
Another method is to use the DecimalFormatter:
DecimalFormat df = new DecimalFormat(""#.#####"");
df.format(0.912385);
returns:
0.91238
However as you can see this uses half-even rounding. That is it will round down if the previous digit is even. What I'd like is this:
0.912385 -> 0.91239
0.912300 -> 0.9123
What is the best way to achieve this in Java?
",https://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-in-java,1490,2183351.0,40.0,,,2008-09-30 16:01:34,2024-06-28 01:47:21,2019-11-11 21:47:11,,,java;decimal;rounding;digits,Alex Spurling,56152,12149,registered,true,153785,,CC BY-SA 4.0,2011-12-11 18:12:37,1293,1029,9,0,0,4,true,false,false,true,true,true,49,11,false,0.018,0.0007,6626,2008,9,16,Tuesday,false,false,false,true,false,false,false
9689793,Can't execute jar- file: "no main manifest attribute","I have installed an application and when I try to run it (it's an executable jar) nothing happens. When I run it from the command line with:
java -jar "app.jar"
I get the following message:
no main manifest attribute, in "app.jar"
Normally, if I had created the program myself, I would have added a main class attribute to the manifest file. But in this case, since the file is from an application, I cannot do that. I also tried extracting the jar to see if I could find the main class, but there are too many classes and none of them has the word "main" in it's name. There must be a way to fix this because the program runs fine on other systems.
",https://stackoverflow.com/questions/9689793/cant-execute-jar-file-no-main-manifest-attribute,1439,2653534.0,46.0,,,2012-03-13 18:20:40,2025-02-27 00:19:36,2024-08-03 18:37:38,,,java;jar;manifest;program-entry-point,Ewoud,14565,923421,registered,true,,,CC BY-SA 4.0,2018-12-20 04:42:19,760,683,1,0,0,4,false,false,false,true,true,true,67,8,false,0.017,0.0005,5366,2012,3,18,Tuesday,false,false,false,true,false,false,false
21964709,How to set or change the default Java (JDK) version on macOS?,"How can you change the default version of Java on a mac?
",https://stackoverflow.com/questions/21964709/how-to-set-or-change-the-default-java-jdk-version-on-macos,1421,1904339.0,39.0,,,2014-02-23 05:46:07,2025-02-18 09:08:18,2021-04-01 10:52:49,2025-05-09 19:13:42,Duplicate,java;macos,Venkat,14323,1492223,registered,true,,,,2018-02-06 08:27:55,64,57,0,0,0,2,false,true,false,true,true,true,61,12,true,0.02,0.0007,4654,2014,2,5,Sunday,true,false,false,true,false,false,false
4871051,How to get the current working directory in Java?,"I want to access my current working directory using Java.
My code:
String currentPath = new java.io.File(".").getCanonicalPath();
System.out.println("Current dir:" + currentPath);
String currentDir = System.getProperty("user.dir");
System.out.println("Current dir using System:" + currentDir);
Output:
Current dir: C:\WINDOWS\system32
Current dir using System: C:\WINDOWS\system32
My output is not correct because the C drive is not my current directory.
How to get the current directory?
",https://stackoverflow.com/questions/4871051/how-to-get-the-current-working-directory-in-java,1419,2029412.0,27.0,,,2011-02-02 05:24:06,2023-03-02 23:50:16,2021-07-05 06:52:24,,,java;java-io,Qazi,14391,541929,registered,true,,,CC BY-SA 4.0,2016-11-02 13:03:06,619,536,2,0,0,2,false,false,false,true,true,true,49,9,true,0.013,0.0007,5771,2011,2,5,Wednesday,false,false,false,true,false,false,false
30727515,Why is executing Java code in comments with certain Unicode characters allowed?,"The following code produces the output "Hello World!" (no really, try it).
public static void main(String... args) {
// The comment below is not a typo.
// \u000d System.out.println("Hello World!");
}
The reason for this is that the Java compiler parses the Unicode character \u000d as a new line and gets transformed into:
public static void main(String... args) {
// The comment below is not a typo.
//
System.out.println("Hello World!");
}
Thus resulting into a comment being "executed".
Since this can be used to "hide" malicious code or whatever an evil programmer can conceive, why is it allowed in comments?
Why is this allowed by the Java specification?
Update:
In my original question, I used IntelliJ Idea. And like @dhke pointed out, IntelliJ got it wrong.
However, I noticed that Idea 2024.1.1 addresses the issue directly. The formatting indicates that it is not a comment. Additionally, when auto-formatting, it will change \u000d to an actual new line.
(I am not sure when this issue was addressed)
",https://stackoverflow.com/questions/30727515/why-is-executing-java-code-in-comments-with-certain-unicode-characters-allowed,1416,87600.0,8.0,,,2015-06-09 09:02:16,2024-09-09 10:43:00,2024-05-13 14:35:51,,,java;unicode;comments,Reg,11343,1169349,registered,true,30727799,,CC BY-SA 4.0,2018-12-13 10:13:15,1374,1086,3,1,1,3,true,false,false,true,true,true,79,12,true,0.091,0.0162,4183,2015,6,9,Tuesday,false,false,false,true,false,false,false
4963300,Which @NotNull Java annotation should I use?,"I'm looking to make my code more readable as well as use tooling like IDE code inspection and/or static code analysis (FindBugs and Sonar) to avoid NullPointerExceptions. Many of the tools seem incompatible with each others' @NotNull/@NonNull/@Nonnull annotation and listing all of them in my code would be terrible to read. Any suggestions of which one is the 'best'? Here is the list of equivalent annotations I've found:
javax.validation.constraints.NotNull
Created for runtime validation, not static analysis.
documentation
edu.umd.cs.findbugs.annotations.NonNull
Used by FindBugs (dead project) and its successor SpotBugs static analysis and therefore Sonar (now Sonarqube)
FindBugs documentation, SpotBugs documentation
javax.annotation.Nonnull
This might work with FindBugs too, but JSR-305 is inactive. (See also: What is the status of JSR 305?)
source
org.jetbrains.annotations.NotNull
Used by IntelliJ IDEA IDE for static analysis.
documentation
lombok.NonNull
Used to control code generation in Project Lombok.
Placeholder annotation since there is no standard.
source,
documentation
androidx.annotation.NonNull
Marker annotation available in Android, provided by annotation package
documentation
org.eclipse.jdt.annotation.NonNull
Used by Eclipse for static code analysis
documentation
",https://stackoverflow.com/questions/4963300/which-notnull-java-annotation-should-i-use,1414,478897.0,26.0,,,2011-02-10 22:05:35,2026-09-10 13:58:08,2021-06-28 12:11:00,,,java;nullpointerexception;null;annotations;ide,jaxzin,14557,416130,registered,true,,,CC BY-SA 4.0,2018-12-13 10:11:28,3293,1310,10,16,0,5,false,false,false,true,true,true,44,7,true,0.054,0.003,5763,2011,2,22,Thursday,false,false,false,true,false,false,false
1036754,Difference between "wait()" vs "sleep()" in Java,"What is the difference between a wait() and sleep() in Threads?
Is my understanding that a wait()-ing Thread is still in running mode and uses CPU cycles but a sleep()-ing does not consume any CPU cycles correct?
Why do we have both wait() and sleep()?
How does their implementation vary at a lower level?
",https://stackoverflow.com/questions/1036754/difference-between-wait-vs-sleep-in-java,1362,1017934.0,33.0,,,2009-06-24 06:48:40,2022-09-16 10:56:38,2022-09-16 10:56:38,,,java;multithreading;wait;sleep;java-threads,Geek,23513,102040,registered,true,1036763,,CC BY-SA 4.0,2017-05-10 09:58:45,421,306,6,0,0,5,true,false,false,true,true,true,68,7,false,0.032,0.0013,6359,2009,6,6,Wednesday,false,false,false,true,false,false,false
2591098,How to parse JSON in Java,"I have the following JSON text. How can I parse it to get the values of pageName, pagePic, post_id, etc.?
{
"pageInfo": {
"pageName": "abc",
"pagePic": "http://example.com/content.jpg"
},
"posts": [
{
"post_id": "123456789012_123456789012",
"actor_id": "1234567890",
"picOfPersonWhoPosted": "http://example.com/photo.jpg",
"nameOfPersonWhoPosted": "Jane Doe",
"message": "Sounds cool. Can't wait to see it!",
"likesCount": "2",
"comments": [],
"timeOfPost": "1234567890"
}
]
}
",https://stackoverflow.com/questions/2591098/how-to-parse-json-in-java,1357,2607014.0,38.0,,,2010-04-07 09:00:21,2025-02-26 01:30:31,2022-08-18 13:31:47,,,java;json;parsing,Maqsood,34315,2355649,registered,true,,,CC BY-SA 4.0,2018-01-31 16:55:12,869,760,4,0,0,3,false,false,false,true,true,true,25,6,false,0.015,0.0005,6072,2010,4,9,Wednesday,false,false,false,true,false,false,false
2607289,Converting array to list in Java,"How do I convert an array to a list in Java?
I used the Arrays.asList() but the behavior (and signature) somehow changed from Java SE 1.4.2 (docs now in archive) to 8 and most snippets I found on the web use the 1.4.2 behaviour.
For example:
int[] numbers = new int[] { 1, 2, 3 };
Arrays.asList(numbers)
- on 1.4.2 returns a list containing the elements 1, 2, 3
- on 1.5.0+ returns a list containing the array 'numbers'
In many cases it should be easy to detect, but sometimes it can slip unnoticed:
Assert.assertTrue(Arrays.asList(numbers).indexOf(4) == -1);
",https://stackoverflow.com/questions/2607289/converting-array-to-list-in-java,1316,2171150.0,25.0,,,2010-04-09 12:20:20,2023-08-23 13:32:03,2022-05-09 12:17:23,,,java;arrays;list,Alexandru,26020,88622,registered,true,2607335,,CC BY-SA 4.0,2018-02-03 12:34:30,923,560,3,2,0,3,true,false,false,true,true,true,32,6,false,0.012,0.0006,6070,2010,4,12,Friday,false,false,false,true,false,false,false
223918,Removing objects from a collection in a loop without causing ConcurrentModificationException,"We all know you can't do the following because of ConcurrentModificationException:
for (Object i : list) {
if (condition(i)) {
list.remove(i);
}
}
But this apparently works sometimes, but not always. Here's some specific code:
public static void main(String[] args) {
Collection<Integer> list = new ArrayList<>();
for (int i = 0; i < 10; ++i) {
list.add(4);
list.add(5);
list.add(6);
}
for (int i : list) {
if (i == 5) {
list.remove(i);
}
}
System.out.println(list);
}
This, of course, results in:
Exception in thread "main" java.util.ConcurrentModificationException
Even though multiple threads aren't doing it. Anyway.
What's the best solution to this problem? How can I remove an item from the collection in a loop without throwing this exception?
I'm also using an arbitrary Collection here, not necessarily an ArrayList, so you can't rely on get.
",https://stackoverflow.com/questions/223918/removing-objects-from-a-collection-in-a-loop-without-causing-concurrentmodificat,1309,528407.0,32.0,,,2008-10-21 23:23:33,2025-04-08 15:43:50,2025-04-08 15:43:50,,,java;collections;iteration,Claudiu,231311,15055,registered,true,223929,,CC BY-SA 4.0,2015-09-22 14:40:34,1180,975,7,0,0,3,true,false,false,true,true,true,92,11,false,0.061,0.0025,6605,2008,10,23,Tuesday,false,false,false,true,false,false,false
1678122,'Must Override a Superclass Method' Errors after importing a project into Eclipse,"Anytime I have to re-import my projects into Eclipse (if I reinstalled Eclipse, or changed the location of the projects), almost all of my overridden methods are not formatted correctly, causing the error:
The method must override a superclass method
It may be noteworthy to mention this is with Android projects for whatever reason, the method argument values are not always populated, so I have to manually populate them myself. For instance:
list.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
//These arguments have their correct names
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
}
});
will be initially populated like this:
list.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
//This methods arguments were not automatically provided
public void onCreateContextMenu(ContextMenu arg1, View arg2,
ContextMenuInfo arg3) {
}
});
The odd thing is, if I remove my code, and have Eclipse automatically recreate the method, it uses the same argument names I already had, so I don't really know where the problem is, other then it auto-formatting the method for me.
This becomes quite a pain having to manually recreate ALL my overridden methods by hand. If anyone can explain why this happens or how to fix it. I would be very happy.
Maybe it is due to the way I am formatting the methods, which are inside an argument of another method?
",https://stackoverflow.com/questions/1678122/must-override-a-superclass-method-errors-after-importing-a-project-into-eclips,1306,270912.0,13.0,,,2009-11-05 03:17:53,2020-08-29 14:14:34,2020-04-19 11:13:35,,,java;android;eclipse;overriding;superclass,Tim H,13543,190303,registered,true,1678170,,CC BY-SA 4.0,2010-11-19 15:17:55,1691,1552,2,0,0,5,true,false,false,true,true,true,89,12,false,0.048,0.0048,6225,2009,11,3,Thursday,false,false,false,true,false,false,false
4042434,Converting 'ArrayList<String> to 'String[]' in Java,"How might I convert an ArrayList<String> object to a String[] array in Java?
",https://stackoverflow.com/questions/4042434/converting-arrayliststring-to-string-in-java,1302,993123.0,17.0,,,2010-10-28 11:30:53,2023-10-05 01:33:23,2018-07-26 19:10:07,,,java;arrays;string;arraylist;collections,Alex,16765,482568,unregistered,true,4042464,,CC BY-SA 4.0,2017-12-19 22:25:56,116,83,2,0,0,5,true,false,false,true,true,true,69,6,false,0.017,0.0013,5868,2010,10,11,Thursday,false,false,false,true,false,false,false
24342886,How to install Java 8 on Mac,"Editors note: This question was asked in 2014, and the answers may be outdated.
I want to do some programming with the latest JavaFX, which requires Java 8. I'm using IntelliJ 13 CE and Mac OS X 9 Mavericks. I ran Oracle's Java 8 installer, and the files look like they ended up at
/Library/Java/JavaVirtualMachines/jdk1.8.0_05.jdk
but previous versions are at
/System/Library/Java/JavaFrameworks/jdk1.6....
Not sure why the latest installer puts this in /Library instead of /System/Library (nor what the difference is). But /usr/libexec/java_home doesn't find 1.8, so all the posts I've found on how to set your current java version don't work. I've tried adding a symbolic link to make it look like 1.8 is in the /System/Library... path, but it doesn't help. /usr/libexec/java_home -V still only lists the old Java 1.6.
Ironically, the "Java" control panel under System Preferences shows only Java 1.8!
Why doesn't Oracle's installer put it where it really goes? And how can I work around this problem?
",https://stackoverflow.com/questions/24342886/how-to-install-java-8-on-mac,1296,1437231.0,35.0,,,2014-06-21 15:05:12,2025-03-23 10:48:31,2021-02-28 16:26:39,,,java;macos;java-8;installation,user3763100,13324,3763100,registered,true,,,CC BY-SA 4.0,2018-02-05 09:16:15,1180,1019,7,0,0,4,false,false,false,true,true,true,28,7,false,0.024,0.0009,4536,2014,6,15,Saturday,true,false,false,true,false,false,false
43574426,How to resolve java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException,"I have some code that uses JAXB API classes which have been provided as a part of the JDK in Java 6/7/8. When I run the same code with Java 9, at runtime I get errors indicating that JAXB classes can not be found.
The JAXB classes have been provided as a part of the JDK since Java 6, so why can Java 9 no longer find these classes?
",https://stackoverflow.com/questions/43574426/how-to-resolve-java-lang-noclassdeffounderror-javax-xml-bind-jaxbexception,1296,1631610.0,46.0,,,2017-04-23 17:40:23,2025-03-28 00:45:48,2021-03-01 12:45:37,,,java;jaxb;java-9;java-11;java-10,Andy Guibert,43266,3814029,registered,true,43574427,,CC BY-SA 4.0,2018-01-08 09:31:55,349,335,0,0,0,5,true,false,false,true,true,true,75,5,false,0.028,0.0008,3499,2017,4,17,Sunday,true,false,false,true,false,false,false
2784514,Sort ArrayList of custom Objects by property,"I read about sorting ArrayLists using a Comparator but in all of the examples people used compareTo which according to some research is a method for Strings.
I wanted to sort an ArrayList of custom objects by one of their properties: a Date object
(getStartDay()). Normally I compare them by item1.getStartDate().before(item2.getStartDate()) so I was wondering whether I could write something like:
public class CustomComparator {
public boolean compare(Object object1, Object object2) {
return object1.getStartDate().before(object2.getStartDate());
}
}
public class RandomName {
...
Collections.sort(Database.arrayList, new CustomComparator);
...
}
",https://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property,1294,1389759.0,29.0,,,2010-05-06 21:09:36,2020-07-17 01:01:15,2016-01-27 17:18:25,,,java;sorting;date;comparator,Samuel,18624,253387,registered,true,2784576,,CC BY-SA 3.0,2018-08-28 19:02:31,759,682,4,0,0,4,true,false,false,true,true,true,44,7,false,0.021,0.0009,6043,2010,5,21,Thursday,false,false,false,true,false,false,false
438146,What are the possible values of the Hibernate hbm2ddl.auto configuration and what do they do,"I really want to know more about the update, export and the values that could be given to hibernate.hbm2ddl.auto
I need to know when to use the update and when not? And what is the alternative?
These are changes that could happen over DB:
- new tables
- new columns in old tables
- columns deleted
- data type of a column changed
- a type of a column changed its attributes
- tables dropped
- values of a column changed
In each case what is the best solution?
",https://stackoverflow.com/questions/438146/what-are-the-possible-values-of-the-hibernate-hbm2ddl-auto-configuration-and-wha,1282,1385460.0,15.0,,,2009-01-13 06:40:48,2025-11-28 18:18:58,2019-04-15 15:24:13,,,java;hibernate;hbm2ddl,Suzan,,,does_not_exist,true,,,CC BY-SA 4.0,2011-11-23 12:46:00,562,452,1,0,0,3,false,false,false,true,false,true,92,15,false,0.011,0.0009,6521,2009,1,6,Tuesday,false,false,false,true,false,false,false
3106452,"How do servlets work? Instantiation, sessions, shared variables and multithreading","Suppose, I have a webserver which holds numerous servlets. For information passing among those servlets I am setting session and instance variables.
Now, if 2 or more users send request to this server then what happens to the session variables?
Will they all be common for all the users or they will be different for each user?
If they are different, then how was the server able to differentiate between different users?
One more similar question, if there are n users accessing a particular servlet, then this servlet gets instantiated only the first time the first user accessed it or does it get instantiated for all the users separately?
In other words, what happens to the instance variables?
",https://stackoverflow.com/questions/3106452/how-do-servlets-work-instantiation-sessions-shared-variables-and-multithreadi,1265,333366.0,8.0,,,2010-06-24 00:16:15,2023-11-14 09:29:00,2020-04-19 11:32:28,,,java;multithreading;servlets;session-variables;instance-variables,Ku Jon,12653,374769,unregistered,true,3106909,,CC BY-SA 4.0,2012-06-06 10:02:33,747,701,1,0,0,5,true,false,false,true,true,true,82,10,false,0.024,0.0038,5994,2010,6,0,Thursday,false,false,false,true,false,false,false
507602,How can I initialise a static Map?,"How would you initialise a static Map in Java?
Method one: static initialiser
Method two: instance initialiser (anonymous subclass)
or
some other method?
What are the pros and cons of each?
Here is an example illustrating the two methods:
import java.util.HashMap;
import java.util.Map;
public class Test {
private static final Map<Integer, String> myMap = new HashMap<>();
static {
myMap.put(1, ""one"");
myMap.put(2, ""two"");
}
private static final Map<Integer, String> myMap2 = new HashMap<>(){
{
put(1, ""one"");
put(2, ""two"");
}
};
}
",https://stackoverflow.com/questions/507602/how-can-i-initialise-a-static-map,1260,1086613.0,43.0,,,2009-02-03 15:41:33,2023-09-08 09:28:49,2020-03-18 14:07:05,,,java;dictionary;collections;initialization;idioms,dogbane,277153,7412,registered,true,507658,,CC BY-SA 4.0,2018-01-31 12:10:18,711,642,2,0,0,5,true,false,false,true,true,true,34,7,true,0.04,0.0012,6500,2009,2,15,Tuesday,false,false,false,true,false,false,false
529085,How can I create a generic array in Java?,"Due to the implementation of Java generics, you can't have code like this:
public class GenSet<E> {
private E a[];
public GenSet() {
a = new E[INITIAL_ARRAY_LENGTH]; // Error: generic array creation
}
}
How can I implement this while maintaining type safety?
I saw a solution on the Java forums that goes like this:
import java.lang.reflect.Array;
class Stack<T> {
public Stack(Class<T> clazz, int capacity) {
array = (T[])Array.newInstance(clazz, capacity);
}
private final T[] array;
}
What's going on?
",https://stackoverflow.com/questions/529085/how-can-i-create-a-generic-array-in-java,1255,1037156.0,32.0,,,2009-02-09 17:30:44,2023-12-15 23:39:09,2023-12-14 01:18:35,,,java;arrays;generics;reflection;instantiation,tatsuhirosatou,25957,64250,registered,true,530289,,CC BY-SA 4.0,2015-10-02 19:02:08,644,568,2,0,0,5,true,false,false,true,true,true,41,9,true,0.031,0.0012,6494,2009,2,17,Monday,false,false,false,true,false,false,false
473282,How can I pad an integer with zeros on the left?,"How do you left pad an int with zeros when converting to a String in java?
I'm basically looking to pad out integers up to 9999 with leading zeros (e.g. 1 = 0001).
",https://stackoverflow.com/questions/473282/how-can-i-pad-an-integer-with-zeros-on-the-left,1245,870438.0,18.0,,,2009-01-23 15:21:24,2025-08-12 18:54:23,2025-08-12 18:54:23,,,java;formatting;zero-padding,Omar Kooheji,56044,20400,registered,true,473309,,CC BY-SA 4.0,2013-09-03 15:51:39,231,165,4,0,0,3,true,false,false,true,true,true,48,11,true,0.021,0.0014,6511,2009,1,15,Friday,false,false,false,true,false,false,false
2276271,How to mock void methods with Mockito,"How to mock methods with void return type?
I implemented an observer pattern but I can't mock it with Mockito because I don't know how.
And I tried to find an example on the Internet but didn't succeed.
My class looks like this:
public class World {
List<Listener> listeners;
void addListener(Listener item) {
listeners.add(item);
}
void doAction(Action goal,Object obj) {
setState(""i received"");
goal.doAction(obj);
setState(""i finished"");
}
private string state;
//setter getter state
}
public class WorldTest implements Listener {
@Test public void word{
World w= mock(World.class);
w.addListener(this);
...
...
}
}
interface Listener {
void doAction();
}
The system is not triggered with mock.
I want to show the above-mentioned system state. And make assertions according to them.
",https://stackoverflow.com/questions/2276271/how-to-mock-void-methods-with-mockito,1243,1348941.0,12.0,,,2010-02-16 20:54:39,2025-03-18 12:31:09,2019-10-21 10:41:31,,,java;unit-testing;mocking;mockito;void,ibrahimyilmaz,19079,115890,registered,true,2278221,,CC BY-SA 4.0,2015-04-06 16:08:51,964,898,1,0,0,5,true,false,false,true,true,true,37,7,false,0.009,0.0009,6122,2010,2,20,Tuesday,false,false,false,true,false,false,false
4382178,Android SDK installation doesn't find JDK,"I'm trying to install the Android SDK on my Windows 7 x64 System.
jdk-6u23-windows-x64.exe is installed, but the Android SDK setup refuses to proceed because it doesn't find the JDK installation.
Is this a known issue? And is there a solution?
![]()
",https://stackoverflow.com/questions/4382178/android-sdk-installation-doesnt-find-jdk,1243,452431.0,45.0,,,2010-12-07 22:12:14,2023-01-24 13:00:27,2020-04-19 11:18:42,,,java;android;sdk;windows-7-x64;jdk6,Simon,5693,534294,unregistered,true,,,CC BY-SA 4.0,2011-03-20 19:35:39,384,250,1,0,1,5,false,false,false,true,true,true,45,6,false,0.099,0.0027,5828,2010,12,22,Tuesday,false,false,false,true,false,false,false
5374311,Convert ArrayList<String> to String[] array,"I'm working in the android environment and have tried the following code, but it doesn't seem to be working.
String [] stockArr = (String[]) stock_list.toArray();
If I define as follows:
String [] stockArr = {""hello"", ""world""};
it works. Is there something that I'm missing?
",https://stackoverflow.com/questions/5374311/convert-arrayliststring-to-string-array,1220,1658502.0,6.0,,,2011-03-21 05:57:59,2018-10-01 09:34:58,2018-07-30 18:32:04,2014-12-04 16:41:43,Duplicate,java;arrays;arraylist,locoboy,39226,382906,registered,true,5374359,,,2013-06-19 11:45:28,350,281,2,0,0,3,true,true,false,true,true,true,49,5,false,0.004,0.0007,5724,2011,3,5,Monday,false,false,false,true,false,false,false
219585,Including all the jars in a directory within the Java classpath,"Is there a way to include all the jar files within a directory in the classpath?
I'm trying java -classpath lib/*.jar:. my.package.Program and it is not able to find class files that are certainly in those jars. Do I need to add each jar file to the classpath separately?
",https://stackoverflow.com/questions/219585/including-all-the-jars-in-a-directory-within-the-java-classpath,1202,1320649.0,25.0,,,2008-10-20 19:32:45,2022-11-12 15:09:00,2017-06-08 08:47:33,,,java;command-line;classpath,Chris Serra,13586,13435,registered,true,,,CC BY-SA 3.0,2011-09-02 03:38:08,302,275,1,0,0,3,false,false,false,true,true,true,63,11,false,0.019,0.0009,6606,2008,10,19,Monday,false,false,false,true,false,false,false
15202997,"What is the difference between canonical name, simple name and class name in Java Class?","In Java, what is the difference between these:
Object o1 = ....
o1.getClass().getSimpleName();
o1.getClass().getName();
o1.getClass().getCanonicalName();
I have checked the Javadoc multiple times and yet this never explains it well.
I also ran a test and that didn't reflect any real meaning behind the way these methods are called.
",https://stackoverflow.com/questions/15202997/what-is-the-difference-between-canonical-name-simple-name-and-class-name-in-jav,1193,363653.0,8.0,,,2013-03-04 13:45:28,2025-05-11 16:56:11,2018-06-25 15:03:56,,,java,Mohamed Taher Alrefaie,16343,1019952,registered,true,15203417,,CC BY-SA 4.0,,374,336,1,0,0,1,true,false,false,true,true,true,88,15,true,0.022,0.0033,5010,2013,3,13,Monday,false,false,false,true,false,false,false
7486012,What is a "static class" in Java?,"Is there anything like static class in Java?
What is the meaning of such a class? Do all the methods of the static class need to be static too?
Is it required the other way round as well? That if a class contains only static methods, the class shall be static too?
What are static classes good for?
",https://stackoverflow.com/questions/7486012/what-is-a-static-class-in-java,1186,1180736.0,14.0,,,2011-09-20 13:32:42,2025-03-05 20:12:19,2023-12-05 09:48:25,,,java;static-classes,Kraken,24443,216190,registered,true,7486111,,CC BY-SA 4.0,2015-03-20 00:18:09,353,299,2,0,0,2,true,false,false,true,true,true,43,7,true,0.012,0.001,5541,2011,9,13,Tuesday,false,false,false,true,false,false,false
1085709,What does 'synchronized' mean?,"I have some questions regarding the usage and significance of the synchronized keyword.
- What is the significance of the
synchronized keyword?
- When should methods be
synchronized?
- What does it mean programmatically and logically?
",https://stackoverflow.com/questions/1085709/what-does-synchronized-mean,1163,612833.0,18.0,,,2009-07-06 06:47:23,2023-12-07 20:09:03,2016-01-26 23:14:25,,,java;multithreading;keyword;synchronized,Johanna,27770,124339,registered,true,1085745,,CC BY-SA 3.0,2017-07-24 16:24:12,315,233,3,0,0,4,true,false,false,true,true,true,38,4,true,0.029,0.0019,6347,2009,7,6,Monday,false,false,false,true,false,false,false
20001427,:: (double colon) operator in Java 8,"I was exploring the Java 8 source and found this particular part of code very surprising:
// Defined in IntPipeline.java
@Override
public final OptionalInt reduce(IntBinaryOperator op) {
return evaluate(ReduceOps.makeInt(op));
}
@Override
public final OptionalInt max() {
return reduce(Math::max); // This is the gotcha line
}
// Defined in Math.java
public static int max(int a, int b) {
return (a >= b) ? a : b;
}
Is Math::max something like a method pointer?
How does a normal static method get converted to IntBinaryOperator?
",https://stackoverflow.com/questions/20001427/double-colon-operator-in-java-8,1150,530661.0,17.0,,,2013-11-15 12:46:32,2023-05-19 14:41:27,2023-03-08 11:49:36,,,java;java-8;method-reference,Narendra Pathai,42055,1719067,registered,true,20001866,,CC BY-SA 4.0,,648,548,4,0,0,3,true,false,false,true,true,true,36,7,false,0.032,0.0022,4754,2013,11,12,Friday,false,false,false,true,false,false,false
1069066,How can I get the current stack trace in Java?,"How do I get the current stack trace in Java, like how in .NET you can do Environment.StackTrace?
I found Thread.dumpStack() but it is not what I want - I want to get the stack trace back, not print it out.
",https://stackoverflow.com/questions/1069066/how-can-i-get-the-current-stack-trace-in-java,1145,721543.0,23.0,,,2009-07-01 13:13:01,2024-07-17 23:42:59,2019-11-16 19:01:02,,,stack-trace;java,ripper234,232304,11236,registered,true,1069074,,CC BY-SA 4.0,2015-06-18 15:53:54,433,208,2,2,0,2,true,false,false,true,true,true,46,10,true,0.032,0.0016,6352,2009,7,13,Wednesday,false,false,false,true,false,false,false
40352684,What is the equivalent of Java static methods in Kotlin?,"There is no static keyword in Kotlin.
What is the best way to represent a static Java method in Kotlin?
",https://stackoverflow.com/questions/40352684/what-is-the-equivalent-of-java-static-methods-in-kotlin,1143,630230.0,30.0,,,2016-11-01 00:52:33,2024-05-13 06:46:21,2023-09-24 07:02:31,,,java;kotlin;static;static-methods,pdeva,45971,14316,registered,true,40352734,,CC BY-SA 4.0,2021-02-04 08:57:51,144,104,2,0,0,4,true,false,false,true,true,true,56,10,true,0.048,0.0018,3672,2016,11,0,Tuesday,false,false,false,true,false,false,false
189559,How do I join two lists in Java?,"Is there a simpler way than:
List<String> newList = new ArrayList<String>();
newList.addAll(listOne);
newList.addAll(listTwo);
Conditions:
- Do not modify the original lists.
- JDK only.
- No external libraries.
Bonus points for a one-liner or a JDK 1.3 version.
",https://stackoverflow.com/questions/189559/how-do-i-join-two-lists-in-java,1140,1606814.0,33.0,,,2008-10-09 23:17:43,2025-03-27 21:21:03,2023-10-26 05:26:42,,,java;list;merge;java-5,Robert Atkins,25008,17294,registered,true,,,CC BY-SA 4.0,2013-07-28 17:08:12,353,272,1,0,0,4,false,false,false,true,true,true,32,8,true,0.021,0.0007,6617,2008,10,23,Thursday,false,false,false,true,false,false,false
5901378,What exactly is a Maven Snapshot and why do we need it?,"I am a bit confused about the meaning of a Maven SNAPSHOT and why we build one?
",https://stackoverflow.com/questions/5901378/what-exactly-is-a-maven-snapshot-and-why-do-we-need-it,1137,547516.0,13.0,,,2011-05-05 16:50:50,2024-08-16 10:51:02,2024-07-21 06:10:17,,,java;maven;dependency-management,meisam,12026,685658,registered,true,5901460,,CC BY-SA 4.0,2019-07-21 21:34:24,100,80,1,0,0,3,true,false,false,true,true,true,55,12,true,0.024,0.0021,5679,2011,5,16,Thursday,false,false,false,true,false,false,false
14014086,What is difference between CrudRepository and JpaRepository interfaces in Spring Data JPA?,"What is the difference between CrudRepository and JpaRepository interfaces in Spring Data JPA?
When I see the examples on the web, I see them there used kind of interchangeably.
- What is the difference between them?
- Why would you want to use one over the other?
",https://stackoverflow.com/questions/14014086/what-is-difference-between-crudrepository-and-jparepository-interfaces-in-spring,1136,532243.0,9.0,,,2012-12-23 19:35:12,2025-01-03 20:37:39,2024-01-04 09:11:32,,,java;spring;spring-data-jpa;spring-repositories,kseeker,11403,1372890,registered,true,14025100,,CC BY-SA 4.0,2018-09-07 12:16:15,671,263,0,3,0,4,true,false,false,true,true,true,90,12,true,0.017,0.0021,5081,2012,12,19,Sunday,true,false,false,true,false,false,false
6349421,How to use Jackson to deserialise an array of objects,"The Jackson data binding documentation indicates that Jackson supports deserialising ""Arrays of all supported types"" but I can't figure out the exact syntax for this.
For a single object I would do this:
//json input
{
""id"" : ""junk"",
""stuff"" : ""things""
}
//Java
MyClass instance = objectMapper.readValue(json, MyClass.class);
Now for an array I want to do this:
//json input
[{
""id"" : ""junk"",
""stuff"" : ""things""
},
{
""id"" : ""spam"",
""stuff"" : ""eggs""
}]
//Java
List<MyClass> entries = ?
Anyone know if there is a magic missing command? If not then what is the solution?
",https://stackoverflow.com/questions/6349421/how-to-use-jackson-to-deserialise-an-array-of-objects,1134,1194909.0,11.0,,,2011-06-14 20:05:11,2025-03-02 09:54:45,2017-08-16 07:05:59,,,java;json;jackson,Ollie Edwards,14909,111082,registered,true,6349488,,CC BY-SA 3.0,,763,608,2,1,0,3,true,false,false,true,true,true,53,10,false,0.009,0.0009,5639,2011,6,20,Tuesday,false,false,false,true,false,false,false
3028306,"Download a file with Android, and showing the progress in a ProgressDialog","I am trying to write a simple application that gets updated. For this I need a simple function that can download a file and show the current progress in a ProgressDialog. I know how to do the ProgressDialog, but I'm not sure how to display the current progress and how to download the file in the first place.
",https://stackoverflow.com/questions/3028306/download-a-file-with-android-and-showing-the-progress-in-a-progressdialog,1131,634597.0,17.0,,,2010-06-12 10:22:56,2024-05-26 13:04:12,2014-11-26 14:42:38,,,java;android;download;android-asynctask,Tom Leese,19767,363606,registered,true,3028660,,CC BY-SA 3.0,2011-12-07 11:13:12,352,310,2,0,0,4,true,false,false,true,true,true,74,12,false,0.027,0.0018,6006,2010,6,10,Saturday,true,false,false,true,false,false,false
1532461,StringBuilder vs String concatenation in toString() in Java,"Given the 2 toString() implementations below, which one is preferred:
public String toString(){
return ""{a:""+ a + "", b:"" + b + "", c: "" + c +""}"";
}
or
public String toString(){
StringBuilder sb = new StringBuilder(100);
return sb.append(""{a:"").append(a)
.append("", b:"").append(b)
.append("", c:"").append(c)
.append(""}"")
.toString();
}
?
More importantly, given we have only 3 properties it might not make a difference, but at what point would you switch from + concat to StringBuilder?
",https://stackoverflow.com/questions/1532461/stringbuilder-vs-string-concatenation-in-tostring-in-java,1128,522132.0,20.0,,,2009-10-07 15:44:08,2024-07-23 21:46:00,2016-09-09 19:33:01,,,java;performance;string;concatenation;stringbuilder,non sequitor,18966,117783,registered,true,1532499,,CC BY-SA 3.0,,659,544,5,0,0,5,true,false,false,true,true,true,59,8,false,0.038,0.0022,6254,2009,10,15,Wednesday,false,false,false,true,false,false,false
21083170,How to configure port for a Spring Boot application,"How do I configure the TCP/IP port listened on by a Spring Boot application, so it does not use the default port of 8080.
",https://stackoverflow.com/questions/21083170/how-to-configure-port-for-a-spring-boot-application,1122,1262026.0,65.0,,,2014-01-13 02:59:47,2024-10-02 05:54:57,2024-07-21 13:39:24,,,java;spring-boot;server;port;application.properties,Paul Verest on LinkedIn,64938,482717,registered,true,21083284,,CC BY-SA 4.0,2017-11-26 16:20:51,142,122,1,0,0,5,true,false,false,true,true,true,51,9,false,0.052,0.0009,4695,2014,1,2,Monday,false,false,false,true,false,false,false
23079003,How can I convert a Java 8 Stream to an Array?,"What is the easiest/shortest way to convert a Java 8 Stream into an array?
",https://stackoverflow.com/questions/23079003/how-can-i-convert-a-java-8-stream-to-an-array,1115,777593.0,10.0,,,2014-04-15 09:00:13,2025-10-31 15:42:33,2025-10-31 14:21:46,,,java;arrays;java-8;java-stream,user972946,,,does_not_exist,true,23079174,,CC BY-SA 4.0,2019-03-08 08:21:10,95,75,1,0,0,4,true,false,false,true,false,true,46,11,true,0.013,0.0014,4603,2014,4,9,Tuesday,false,false,false,true,false,false,false
1906445,What is the difference between JDK and JRE?,"
Editors note: This question was asked in 2009 where the world was different. In 2022 the standard open sourced OpenJDK is JDK-only.
What is the difference between JDK and JRE?
What are their roles and when should I use one or the other?
",https://stackoverflow.com/questions/1906445/what-is-the-difference-between-jdk-and-jre,1113,892501.0,20.0,,,2009-12-15 10:19:27,2022-11-01 13:40:17,2022-11-01 13:40:17,,,java,i2ijeya,16538,167114,registered,true,1906455,,CC BY-SA 4.0,2016-09-02 17:07:26,292,240,0,0,0,1,true,false,false,true,true,true,43,8,true,0.022,0.0012,6185,2009,12,10,Tuesday,false,false,false,true,false,false,false
415953,How can I generate an MD5 hash in Java?,"Is there any method to generate MD5 hash of a string in Java?
",https://stackoverflow.com/questions/415953/how-can-i-generate-an-md5-hash-in-java,1107,1178290.0,35.0,,,2009-01-06 09:45:12,2026-01-28 06:25:41,2021-09-22 18:53:02,,,java;hash;md5;hashcode,Akshay,11983,356145,registered,true,415956,,CC BY-SA 4.0,2016-11-11 04:34:03,69,62,0,0,0,4,true,false,false,true,true,true,39,9,true,0.03,0.0009,6528,2009,1,9,Tuesday,false,false,false,true,false,false,false
2671496,When to use static methods,"I am wondering when to use static methods? Say if I have a class with a few getters and setters, a method or two, and I want those methods only to be invokable on an instance object of the class. Does this mean I should use a static method?
Example:
Obj x = new Obj();
x.someMethod();
...or:
Obj.someMethod(); // Is this the static way?
I'm rather confused!
",https://stackoverflow.com/questions/2671496/when-to-use-static-methods,1099,1360766.0,25.0,,,2010-04-19 23:05:33,2024-04-22 18:30:48,2020-11-05 10:36:12,,,java;static-methods,KP65,13715,94279,registered,true,2671636,,CC BY-SA 4.0,2013-11-20 19:15:50,436,360,2,0,0,2,true,false,false,true,true,true,26,5,false,0.018,0.0008,6060,2010,4,23,Monday,false,false,false,true,false,false,false
2889777,"Difference between HashMap, LinkedHashMap and TreeMap","What is the difference between HashMap, LinkedHashMap and TreeMap in Java?
I don't see any difference in the output as all the three has keySet and values.
Also, what are Hashtables?
Map<String, String> m1 = new HashMap<>();
m1.put("map", "HashMap");
m1.put("schildt", "java2");
m1.put("mathew", "Hyden");
m1.put("schildt", "java2s");
print(m1.keySet());
print(m1.values());
SortedMap<String, String> sm = new TreeMap<>();
sm.put("map", "TreeMap");
sm.put("schildt", "java2");
sm.put("mathew", "Hyden");
sm.put("schildt", "java2s");
print(sm.keySet());
print(sm.values());
LinkedHashMap<String, String> lm = new LinkedHashMap<>();
lm.put("map", "LinkedHashMap");
lm.put("schildt", "java2");
lm.put("mathew", "Hyden");
lm.put("schildt", "java2s");
print(lm.keySet());
print(lm.values());
",https://stackoverflow.com/questions/2889777/difference-between-hashmap-linkedhashmap-and-treemap,1090,691409.0,18.0,,,2010-05-22 21:10:15,2025-09-20 04:41:43,2023-09-23 13:48:18,,,java;dictionary,Kevin,23694,98514,registered,true,2889800,,CC BY-SA 4.0,2012-03-16 14:30:10,1193,1070,7,0,0,2,true,false,false,true,true,true,53,6,false,0.026,0.0016,6027,2010,5,21,Saturday,true,false,false,true,false,false,false
4716503,Reading a plain text file in Java,"It seems there are different ways to read and write data of files in Java.
I want to read ASCII data from a file. What are the possible ways and their differences?
",https://stackoverflow.com/questions/4716503/reading-a-plain-text-file-in-java,1086,2733723.0,31.0,,,2011-01-17 18:29:13,2026-04-12 15:37:03,2022-12-16 10:13:24,,,java;text;file-io;ascii;text-files,Tim the Enchanter,11187,130888,registered,true,4716521,,CC BY-SA 4.0,2016-11-28 03:36:07,178,164,0,0,0,5,true,false,false,true,true,true,33,7,false,0.011,0.0004,5787,2011,1,18,Monday,false,false,false,true,false,false,false
20363719,"Java 8 List<V> into Map<K, V>","I want to translate a List of objects into a Map using Java 8's streams and lambdas.
This is how I would write it in Java 7 and below:
private Map<String, Choice> nameMap(List<Choice> choices) {
final Map<String, Choice> hashMap = new HashMap<>();
for (final Choice choice : choices) {
hashMap.put(choice.getName(), choice);
}
return hashMap;
}
I can accomplish this easily using Java 8 and Guava but I would like to know how to do this without Guava.
In Guava:
private Map<String, Choice> nameMap(List<Choice> choices) {
return Maps.uniqueIndex(choices, new Function<Choice, String>() {
@Override
public String apply(final Choice input) {
return input.getName();
}
});
}
And Guava with Java 8 lambdas:
private Map<String, Choice> nameMap(List<Choice> choices) {
return Maps.uniqueIndex(choices, Choice::getName);
}
",https://stackoverflow.com/questions/20363719/java-8-listv-into-mapk-v,1076,819744.0,23.0,,,2013-12-03 23:18:49,2024-07-07 22:43:56,2024-07-07 22:43:56,,,java;lambda;java-8;java-stream,Tom,16378,1665365,registered,true,20363874,,CC BY-SA 4.0,2017-10-27 01:16:16,1056,949,3,0,0,4,true,false,false,true,true,true,41,6,false,0.028,0.0013,4736,2013,12,23,Tuesday,false,false,false,true,false,false,false
6217378,Place cursor at the end of text in EditText,"I am changing the value of an EditText on keyListener.
But when I change the text the cursor is moving to the beginning of the EditText.
I need the cursor to be at the end of the text.
How to move the cursor to the end of the text in a EditText.
",https://stackoverflow.com/questions/6217378/place-cursor-at-the-end-of-text-in-edittext,1074,379278.0,29.0,,,2011-06-02 16:32:42,2024-05-07 08:30:55,2021-01-26 19:52:24,,,java;android;kotlin;android-edittext;keylistener,Manu,10749,781501,unregistered,true,,,CC BY-SA 4.0,2019-06-26 10:52:59,321,248,4,0,0,5,false,false,false,true,true,true,43,9,false,0.076,0.0028,5651,2011,6,16,Thursday,false,false,false,true,false,false,false
1102891,How to check if a String is numeric in Java,"How would you check if a String was a number before parsing it?
",https://stackoverflow.com/questions/1102891/how-to-check-if-a-string-is-numeric-in-java,1071,2021378.0,41.0,,,2009-07-09 09:49:47,2025-10-16 20:38:32,2024-10-21 08:45:39,,,java;string;numeric,Craig Angus,23268,15352,registered,true,12569609,,CC BY-SA 4.0,2015-11-29 08:34:12,84,64,1,0,0,3,true,false,false,true,true,true,43,10,false,0.02,0.0005,6344,2009,7,9,Thursday,false,false,false,true,false,false,false
965690,How do I use optional parameters in Java?,"What specification supports optional parameters?
",https://stackoverflow.com/questions/965690/how-do-i-use-optional-parameters-in-java,1066,1645888.0,18.0,,,2009-06-08 16:12:29,2025-05-03 12:13:34,2022-02-27 00:30:54,,,java;optional-parameters,Mike Pone,19468,16404,registered,true,12994104,,CC BY-SA 4.0,2020-02-20 15:48:07,56,49,0,0,0,2,true,false,false,true,true,true,41,8,true,0.011,0.0006,6375,2009,6,16,Monday,false,false,false,true,false,false,false
4343202,Difference between <? super T> and <? extends T> in Java,"What is the difference between List<? super T> and List<? extends T> ?
I used to use List<? extends T>, but it does not allow me to add elements to it list.add(e), whereas the List<? super T> does.
",https://stackoverflow.com/questions/4343202/difference-between-super-t-and-extends-t-in-java,1066,380699.0,13.0,,,2010-12-03 06:57:06,2022-12-24 00:02:40,2017-09-14 10:13:34,2018-09-29 20:05:00,Duplicate,java;generics;collections,Anand,12212,501767,registered,true,4343547,,,,302,223,5,0,0,3,true,true,false,true,true,true,68,11,false,0.034,0.0028,5832,2010,12,6,Friday,false,false,false,true,false,false,false
26245139,How to create RecyclerView with multiple view types,"From Create dynamic lists with RecyclerView:
When we create a RecyclerView.Adapter we have to specify ViewHolder that will bind with the adapter.
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private String[] mDataset;
public MyAdapter(String[] myDataset) {
mDataset = myDataset;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView mTextView;
public ViewHolder(TextView v) {
super(v);
mTextView = v;
}
}
@Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.some_layout, parent, false);
//findViewById...
ViewHolder vh = new ViewHolder(v);
return vh;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.mTextView.setText(mDataset[position]);
}
@Override
public int getItemCount() {
return mDataset.length;
}
}
Is it possible to create RecyclerView with multiple view types?
",https://stackoverflow.com/questions/26245139/how-to-create-recyclerview-with-multiple-view-types,1064,616780.0,23.0,,,2014-10-07 20:55:30,2023-01-10 15:45:48,2021-07-07 17:55:38,,,java;android;user-interface;android-recyclerview,Pongpat,13368,885179,registered,true,26245463,,CC BY-SA 4.0,2018-04-15 08:56:42,1332,1145,4,1,0,4,true,false,false,true,true,true,51,8,false,0.037,0.0017,4428,2014,10,20,Tuesday,false,false,false,true,false,false,false
3158730,What do 3 dots next to a parameter type mean in Java?,"What do the 3 dots following String in the following method mean?
public void myMethod(String... strings) {
// method body
}
",https://stackoverflow.com/questions/3158730/what-do-3-dots-next-to-a-parameter-type-mean-in-java,1058,631149.0,9.0,,,2010-07-01 14:27:49,2024-10-14 07:35:05,2022-08-14 08:45:49,,,java;variadic-functions,Vikram,12329,381203,registered,true,3158767,,CC BY-SA 4.0,2013-08-21 08:14:58,174,130,2,0,0,2,true,false,false,true,true,true,53,12,true,0.014,0.0017,5987,2010,7,14,Thursday,false,false,false,true,false,false,false
782178,How do I convert a String to an InputStream in Java?,"Given a string:
String exampleString = ""example"";
How do I convert it to an InputStream?
",https://stackoverflow.com/questions/782178/how-do-i-convert-a-string-to-an-inputstream-in-java,1057,846447.0,5.0,,,2009-04-23 15:11:23,2021-02-28 06:34:18,2015-07-29 14:59:54,,,java;string;type-conversion;inputstream,Iain,10849,5993,registered,true,782183,,CC BY-SA 3.0,,143,92,2,0,0,4,true,false,false,true,true,true,52,11,true,0.006,0.0012,6421,2009,4,15,Thursday,false,false,false,true,false,false,false
4486787,"Jackson with JSON: Unrecognized field, not marked as ignorable","I need to convert a certain JSON string to a Java object. I am using Jackson for JSON handling. I have no control over the input JSON (I read from a web service). This is my input JSON:
{""wrapper"":[{""id"":""13"",""name"":""Fred""}]}
Here is a simplified use case:
private void tryReading() {
String jsonStr = ""{\""wrapper\""\:[{\""id\"":\""13\"",\""name\"":\""Fred\""}]}"";
ObjectMapper mapper = new ObjectMapper();
Wrapper wrapper = null;
try {
wrapper = mapper.readValue(jsonStr , Wrapper.class);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(""wrapper = "" + wrapper);
}
My entity class is:
public Class Student {
private String name;
private String id;
//getters & setters for name & id here
}
My Wrapper class is basically a container object to get my list of students:
public Class Wrapper {
private List<Student> students;
//getters & setters here
}
I keep getting this error and ""wrapper"" returns null. I am not sure what's missing. Can someone help please?
org.codehaus.jackson.map.exc.UnrecognizedPropertyException:
Unrecognized field ""wrapper"" (Class Wrapper), not marked as ignorable
at [Source: java.io.StringReader@1198891; line: 1, column: 13]
(through reference chain: Wrapper[""wrapper""])
at org.codehaus.jackson.map.exc.UnrecognizedPropertyException
.from(UnrecognizedPropertyException.java:53)
",https://stackoverflow.com/questions/4486787/jackson-with-json-unrecognized-field-not-marked-as-ignorable,1053,1532222.0,54.0,,,2010-12-20 04:02:51,2024-12-02 10:15:37,2017-08-16 07:22:50,,,java;json;data-binding;jackson,jshree,10601,548167,registered,true,,,CC BY-SA 3.0,2018-08-08 19:03:52,1595,1427,6,0,0,4,false,false,false,true,true,true,62,9,false,0.035,0.0007,5815,2010,12,4,Monday,false,false,false,true,false,false,false
338206,Why can't I use switch statement on a String?,"Is this functionality going to be put into a later Java version?
Can someone explain why I can't do this, as in, the technical way Java's switch statement works?
",https://stackoverflow.com/questions/338206/why-cant-i-use-switch-statement-on-a-string,1050,776455.0,14.0,,,2008-12-03 18:23:57,2022-09-22 02:19:10,2018-07-09 21:52:21,,,java;string;switch-statement,Alex Beardsley,21253,14007,registered,true,338230,,CC BY-SA 4.0,2014-12-16 03:11:37,190,163,1,0,0,3,true,false,false,true,true,true,49,9,true,0.018,0.0014,6562,2008,12,18,Wednesday,false,false,false,true,false,false,false
180158,How do I time a method's execution in Java?,"
- How do I get a method's execution time?
- Is there a
Timer utility class for things like timing how long a task takes, etc?
Most of the searches on Google return results for timers that schedule threads and tasks, which is not what I want.
",https://stackoverflow.com/questions/180158/how-do-i-time-a-methods-execution-in-java,1049,1000171.0,43.0,,,2008-10-07 20:10:25,2026-01-06 18:15:51,2020-05-25 08:13:18,,,java;timing;execution-time,Ogre Psalm33,22164,13140,registered,true,180191,,CC BY-SA 4.0,2015-09-18 23:01:43,292,245,1,0,0,3,true,false,false,true,true,true,47,9,true,0.043,0.001,6619,2008,10,20,Tuesday,false,false,false,true,false,false,false
24885223,Why doesn't RecyclerView have onItemClickListener()?,"I was exploring RecyclerView and I was surprised to see that RecyclerView does not have onItemClickListener().
I've two question.
Main Question
I want to know why Google removed onItemClickListener()?
Is there a performance issue or something else?
Secondary Question
I solved my problem by writing onClick in my RecyclerView.Adapter:
public static class ViewHolder extends RecyclerView.ViewHolder implements OnClickListener {
public TextView txtViewTitle;
public ImageView imgViewIcon;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
txtViewTitle = (TextView) itemLayoutView.findViewById(R.id.item_title);
imgViewIcon = (ImageView) itemLayoutView.findViewById(R.id.item_icon);
}
@Override
public void onClick(View v) {
}
}
Is this ok / is there any better way?
",https://stackoverflow.com/questions/24885223/why-doesnt-recyclerview-have-onitemclicklistener,1048,444677.0,31.0,,,2014-07-22 10:43:39,2024-11-26 10:07:09,2019-12-11 14:47:54,2025-06-18 18:13:14,Opinion-based,java;android;android-recyclerview,T_V,17094,2424999,registered,true,24933117,,,,1006,844,7,0,0,3,true,true,false,true,true,true,56,5,true,0.07,0.0024,4505,2014,7,10,Tuesday,false,false,false,true,false,false,false
11461607,Can't start Eclipse - Java was started but returned exit code=13,"I am trying to get my first taste of Android development using Eclipse. I ran into this problem when trying to run Eclipse, having installed version 4.2 only minutes ago.
After first trying to start Eclipse without any parameters to specify the Java VM, I got an error message saying it couldn't find a Java VM called javaw.exe inside the Eclipse folder, so I found where Java was installed and specified that location as the parameter in the shortcut's target. Now I get a different error, Java was started but returned exit code=13.
Similar questions seem to indicate that it's a 32-bit/64-bit conflict, but I'm 99% positive that I downloaded 64-bit versions of both Eclipse and Java (RE 7u5), which I chose because I have 64-bit Windows 7.
- If anyone knows how to confirm that my Eclipse and Java are 64-bit,
that'd be appreciated.
- If you think my problem is a different one, please help!
- Please speak as plainly as you can, as I am totally new to Eclipse
and Java.
Shortcut Target: ""C:\Program Files\Eclipse-SDK-4.2-win32-x86_64\eclipse\eclipse.exe"" -vm ""C:\Program Files (x86)\Java\jre7\bin\javaw.exe""
Full error code...:
Java was started but returned exit code=13
C:\Program Files (x86)\Java\jre7\bin\javaw.exe
-Xms40m
-Xmx512m
-XX:MaxPermSize=256m
-jar C:\Program Files\Eclipse-SDK-4.2-win32-x86_64\eclipse\\plugins/org.eclipse.equinox.launcher_1.30v20120522-1813.jar
-os win32
-ws win32
-arch x86_64
-showsplash C:\Program Files\Eclipse-SDK-4.2-win32-x86_64\eclipse\\plugins\org.eclipse.platform_4.2.0.v201206081400\splash.bmp
-launcher C:\Program Files\Eclipse-SDK-4.2-win32-x86_64\eclipse\eclipse.exe
-name Eclipse
--launcher.library C:\Program Files\Eclipse-SDK-4.2-win32-x86_64\eclipse\\plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.200.v201205221813\eclipse_1503.dll
-startup C:\Program Files\Eclipse-SDK-4.2-win32-x86_64\eclipse\\plugins/org.eclipse.equinox.launcher_1.30v20120522-1813.jar
--launcher.overrideVmargs
-exitdata 1e30_5c
-vm C:\Program Files (x86)\Java\jre7\bin\javaw.exe
-vmargs
-Xms40m
-Xmx512m
-XX:MaxPermSize=256m
-jar C:\Program Files\Eclipse-SDK-4.2-win32-x86_64\eclipse\\plugins/org.eclipse.equinox.launcher_1.30v20120522-1813.jar
",https://stackoverflow.com/questions/11461607/cant-start-eclipse-java-was-started-but-returned-exit-code-13,1046,1738356.0,44.0,,,2012-07-12 22:23:31,2022-02-15 14:56:35,2019-01-02 19:46:52,,,java;android;windows;eclipse;32bit-64bit,Ben E.,10632,1522092,registered,true,41441870,,CC BY-SA 4.0,2013-07-06 06:49:34,2381,2192,5,0,0,5,true,false,false,true,true,true,68,11,false,0.025,0.0006,5245,2012,7,22,Thursday,false,false,false,true,false,false,false
1264709,Convert InputStream to byte array in Java,"How do I read an entire InputStream into a byte array?
",https://stackoverflow.com/questions/1264709/convert-inputstream-to-byte-array-in-java,1026,1255839.0,35.0,,,2009-08-12 07:27:22,2024-09-17 14:11:45,2014-09-10 10:09:09,,,java;arrays;inputstream,JGC,13123,140962,registered,true,1264756,,CC BY-SA 3.0,2017-01-31 22:33:04,75,55,1,0,0,3,true,false,false,true,true,true,41,7,false,0.028,0.0008,6310,2009,8,7,Wednesday,false,false,false,true,false,false,false
5915992,How to reference a method in javadoc?,"How can I use the @link tag to link to a method?
I want to change:
/**
* Returns the Baz object owned by the Bar object owned by Foo owned by this.
* A convenience method, equivalent to getFoo().getBar().getBaz()
* @return baz
*/
public Baz fooBarBaz()
to:
/**
* Returns the Baz object owned by the Bar object owned by Foo owned by this.
* A convenience method, equivalent to {@link getFoo()}.{@link getBar()}.{@link getBaz()}
* @return baz
*/
public Baz fooBarBaz()
but I don't know how to format the @link tag correctly.
",https://stackoverflow.com/questions/5915992/how-to-reference-a-method-in-javadoc,1025,604891.0,3.0,,,2011-05-06 19:15:05,2026-01-10 18:57:39,2020-04-17 17:54:44,,,java;hyperlink;javadoc,Jason S,191310,44330,registered,true,5916098,,CC BY-SA 4.0,2017-01-12 21:45:37,657,538,4,0,0,3,true,false,false,true,true,true,37,7,true,0.005,0.0017,5678,2011,5,19,Friday,false,false,false,true,false,false,false
5868369,How can I read a large text file line by line using Java?,"I need to read a large text file of around 5-6 GB line by line using Java.
How can I do this quickly?
",https://stackoverflow.com/questions/5868369/how-can-i-read-a-large-text-file-line-by-line-using-java,1021,1507840.0,22.0,,,2011-05-03 10:53:24,2026-05-04 23:45:47,2022-12-18 15:06:59,,,java;performance;file-io;io;text-files,manoj singh,10283,735982,unregistered,true,,,CC BY-SA 4.0,2017-09-28 07:11:07,117,103,0,0,0,5,false,false,false,true,true,true,57,13,true,0.015,0.0007,5681,2011,5,10,Tuesday,false,false,false,true,false,false,false
4216745,Java string to date conversion,"What is the best way to convert a String in the format 'January 2, 2010' to a Date in Java?
Ultimately, I want to break out the month, the day, and the year as integers so that I can use
Date date = new Date();
date.setMonth()..
date.setYear()..
date.setDay()..
date.setlong currentTime = date.getTime();
to convert the date into time.
",https://stackoverflow.com/questions/4216745/java-string-to-date-conversion,1020,2546191.0,18.0,,,2010-11-18 15:53:01,2025-11-25 08:56:49,2018-06-25 13:53:42,,,java;string;date;time;data-conversion,littleK,20349,123891,registered,true,4216767,,CC BY-SA 4.0,2013-05-09 16:43:42,411,340,3,0,0,5,true,false,false,true,true,true,30,5,false,0.007,0.0004,5847,2010,11,15,Thursday,false,false,false,true,false,false,false
21076179,"PKIX path building failed" and "unable to find valid certification path to requested target","I'm trying to get tweets using twitter4j library for my java project,
which uses under the covers java.net.HttpURLConnection (as can be seen in stack trace).
On my first run I got an error about certificate sun.security.validator.ValidatorException and sun.security.provider.certpath.SunCertPathBuilderException.
Then I added the twitter certificate by:
C:\Program Files\Java\jdk1.7.0_45\jre\lib\security>keytool -importcert -trustcacerts -file PathToCert -alias ca_alias -keystore "C:\Program Files\Java\jdk1.7.0_45\jre\lib\security\cacerts"
but without success.
Here is the procedure to get tweets:
public static void main(String[] args) throws TwitterException {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("myConsumerKey")
.setOAuthConsumerSecret("myConsumerSecret")
.setOAuthAccessToken("myAccessToken")
.setOAuthAccessTokenSecret("myAccessTokenSecret");
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
try {
Query query = new Query("iphone");
QueryResult result;
result = twitter.search(query);
System.out.println("Total amount of tweets: " + result.getTweets().size());
List<Status> tweets = result.getTweets();
for (Status tweet : tweets) {
System.out.println("@" + tweet.getUser().getScreenName() + " : " + tweet.getText());
}
} catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to search tweets: " + te.getMessage());
}
And here is the error:
sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
Relevant discussions can be found on the Internet at:
http://www.google.co.jp/search?q=d35baff5 or
http://www.google.co.jp/search?q=1446302e
TwitterException{exceptionCode=[d35baff5-1446302e 43208640-747fd158 43208640-747fd158 43208640-747fd158], statusCode=-1, message=null, code=-1, retryAfter=-1, rateLimitStatus=null, version=3.0.5}
at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:177)
at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:61)
at twitter4j.internal.http.HttpClientWrapper.get(HttpClientWrapper.java:81)
at twitter4j.TwitterImpl.get(TwitterImpl.java:1929)
at twitter4j.TwitterImpl.search(TwitterImpl.java:306)
at jku.cc.servlets.TweetsAnalyzer.main(TweetsAnalyzer.java:38)
Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.ssl.Alerts.getSSLException(Unknown Source)
at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)
at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
at sun.security.ssl.ClientHandshaker.serverCertificate(Unknown Source)
at sun.security.ssl.ClientHandshaker.processMessage(Unknown Source)
at sun.security.ssl.Handshaker.processLoop(Unknown Source)
at sun.security.ssl.Handshaker.process_record(Unknown Source)
at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.HttpURLConnection.getResponseCode(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(Unknown Source)
at twitter4j.internal.http.HttpResponseImpl.<init>(HttpResponseImpl.java:34)
at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:141)
... 5 more
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.validator.PKIXValidator.doBuild(Unknown Source)
at sun.security.validator.PKIXValidator.engineValidate(Unknown Source)
at sun.security.validator.Validator.validate(Unknown Source)
at sun.security.ssl.X509TrustManagerImpl.validate(Unknown Source)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(Unknown Source)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
... 20 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(Unknown Source)
at java.security.cert.CertPathBuilder.build(Unknown Source)
... 26 more
Failed to search tweets: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
",https://stackoverflow.com/questions/21076179/pkix-path-building-failed-and-unable-to-find-valid-certification-path-to-requ,1019,4133605.0,65.0,,,2014-01-12 15:04:45,2026-01-18 17:11:13,2025-05-05 12:02:40,,,java;ssl-certificate;httpurlconnection,bofanda,12226,1130672,registered,true,36427118,,CC BY-SA 4.0,2017-07-15 04:15:13,5653,5494,6,0,0,3,true,false,false,true,true,true,113,14,false,0.016,0.0002,4696,2014,1,15,Sunday,true,false,false,true,false,false,false
7421612,SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder","My application is to be deployed on both tcServer and WebSphere 6.1. This application uses ehCache and so requires slf4j as a dependency.
As a result I've added the slf4j-api.jar (1.6) jar to my war file bundle.
The application works fine in tcServer except for the following error:
SLF4J: Failed to load class ""org.slf4j.impl.StaticLoggerBinder"".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
However, when I deploy in WebSphere I get a java.lang.NoClassDefFoundError: org.slf4j.impl.StaticLoggerBinder.
Also accompanied by Failed to load class ""org.slf4j.impl.StaticMDCBinder""
I've checked the classpaths of both application servers and there is no other slf4j jar.
Does anyone have any ideas what may be happening here?
",https://stackoverflow.com/questions/7421612/slf4j-failed-to-load-class-org-slf4j-impl-staticloggerbinder,1015,1938681.0,40.0,,,2011-09-14 19:03:46,2024-12-20 10:14:15,2019-12-18 16:09:33,,,java;websphere;slf4j,DJ180,20134,777906,registered,true,9919375,,CC BY-SA 4.0,2015-04-11 02:24:26,921,829,3,0,0,3,true,false,false,true,true,true,73,6,false,0.021,0.0005,5547,2011,9,19,Wednesday,false,false,false,true,false,false,false
1816673,How do I check if a file exists in Java?,"How can I check whether a file exists, before opening it for reading in Java (the equivalent of Perl's -e $filename)?
The only similar question on SO deals with writing the file and was thus answered using FileWriter which is obviously not applicable here.
If possible I'd prefer a real API call returning true/false as opposed to some "Call API to open a file and catch when it throws an exception which you check for 'no file' in the text", but I can live with the latter.
",https://stackoverflow.com/questions/1816673/how-do-i-check-if-a-file-exists-in-java,1009,1539464.0,19.0,,,2009-11-29 20:32:39,2026-04-19 15:36:26,2024-10-16 11:47:33,,,java;file-io;io;file-exists,DVK,130265,119280,registered,true,1816676,,CC BY-SA 4.0,2019-01-02 12:57:51,656,485,2,1,0,4,true,false,false,true,true,true,40,10,true,0.012,0.0007,6201,2009,11,20,Sunday,true,false,false,true,false,false,false
504103,How do I write a correct micro-benchmark in Java?,"How do you write (and run) a correct micro-benchmark in Java?
I'm looking for some code samples and comments illustrating various things to think about.
Example: Should the benchmark measure time/iteration or iterations/time, and why?
Related: Is stopwatch benchmarking acceptable?
",https://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java,997,151155.0,11.0,,,2009-02-02 17:39:41,2024-01-18 13:59:37,2019-03-23 07:01:33,,,java;jvm;benchmarking;jvm-hotspot;microbenchmark,John Nilsson,17395,24243,registered,true,513259,,CC BY-SA 4.0,2011-02-01 14:07:15,407,285,0,1,0,5,true,false,false,true,true,true,49,9,true,0.073,0.0066,6501,2009,2,17,Monday,false,false,false,true,false,false,false
26684562,What's the difference between map() and flatMap() methods in Java 8?,"In Java 8, what's the difference between Stream.map() and Stream.flatMap() methods?
",https://stackoverflow.com/questions/26684562/whats-the-difference-between-map-and-flatmap-methods-in-java-8,994,665579.0,21.0,,,2014-10-31 22:53:15,2023-05-23 11:48:49,2019-11-26 14:38:07,,,java;java-8;java-stream,cassiomolin,132885,1426227,registered,true,26684710,,CC BY-SA 4.0,2018-06-19 12:25:27,389,84,2,2,0,3,true,false,false,true,true,true,72,11,true,0.032,0.0015,4404,2014,10,22,Friday,false,false,false,true,false,false,false
817856,When and how should I use a ThreadLocal variable?,"When should I use a ThreadLocal variable?
How is it used?
",https://stackoverflow.com/questions/817856/when-and-how-should-i-use-a-threadlocal-variable,989,392523.0,26.0,,,2009-05-03 19:59:20,2022-10-02 18:57:48,2019-05-09 01:34:23,,,java;multithreading;concurrency;thread-local;thread-confinement,Sasha,,,does_not_exist,true,817926,,CC BY-SA 4.0,,186,59,1,1,0,5,true,false,false,true,false,true,49,9,true,0.066,0.0025,6411,2009,5,19,Sunday,true,false,false,true,false,false,false
13102045,Scanner is skipping nextLine() after using next() or nextFoo()?,"I am using the Scanner methods nextInt() and nextLine() for reading input.
It looks like this:
System.out.println(""Enter numerical value"");
int option;
option = input.nextInt(); // Read numerical value from input
System.out.println(""Enter 1st string"");
String string1 = input.nextLine(); // Read 1st string (this is skipped)
System.out.println(""Enter 2nd string"");
String string2 = input.nextLine(); // Read 2nd string (this appears right after reading numerical value)
The problem is that after entering the numerical value, the first input.nextLine() is skipped and the second input.nextLine() is executed, so that my output looks like this:
Enter numerical value
3 // This is my input
Enter 1st string // The program is supposed to stop here and wait for my input, but is skipped
Enter 2nd string // ...and this line is executed and waits for my input
I tested my application and it looks like the problem lies in using input.nextInt(). If I delete it, then both string1 = input.nextLine() and string2 = input.nextLine() are executed as I want them to be.
",https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo,975,916150.0,25.0,,,2012-10-27 16:37:01,2024-08-07 21:33:32,2018-04-04 13:31:32,,,java;io;java.util.scanner,blekione,10630,1779488,registered,true,13102066,,CC BY-SA 3.0,2015-04-19 09:05:46,1260,1080,10,0,0,3,true,false,false,true,true,true,63,9,true,0.027,0.0011,5138,2012,10,16,Saturday,true,false,false,true,false,false,false
7352493,Failed to load the JNI shared Library (JDK),"When I try opening Eclipse, a pop-up dialog states:
Failed to load the JNI shared library "C:/JDK/bin/client/jvm.dll".
Following this, Eclipse force closes.
Here are a few points I'd like to make:
- I checked to see if anything exists on that path. It does exist.
- My Eclipse and Java SE Development Kit are both 64-bit. I checked my system, and it can handle 64-bit.
- I've searched for this problem on Google and StackOverflow, and the only answer I found was to download the 32-bit versions of JDK and Eclipse.
Downloading the 32-bit versions is something I only want to do as a very last resort.
What would be suggested to solve this issue?
",https://stackoverflow.com/questions/7352493/failed-to-load-the-jni-shared-library-jdk,974,1625813.0,39.0,,,2011-09-08 18:02:15,2024-08-28 13:21:49,2024-08-28 13:21:49,,,java;windows;eclipse;java-native-interface,Mxyk,10696,834063,registered,true,7385128,,CC BY-SA 4.0,2012-12-04 12:08:10,894,652,1,2,0,4,true,false,false,true,true,true,43,8,false,0.024,0.0006,5553,2011,9,18,Thursday,false,false,false,true,false,false,false
1393486,Error java.lang.OutOfMemoryError: GC overhead limit exceeded,"I get this error message as I execute my JUnit tests:
java.lang.OutOfMemoryError: GC overhead limit exceeded
I know what an OutOfMemoryError is, but what does GC overhead limit mean? How can I solve this?
",https://stackoverflow.com/questions/1393486/error-java-lang-outofmemoryerror-gc-overhead-limit-exceeded,972,1367703.0,24.0,,,2009-09-08 11:34:28,2025-06-12 09:58:00,2021-08-23 09:17:47,,,java;garbage-collection;out-of-memory;heap-memory,Mnementh,51529,21005,registered,true,1393503,,CC BY-SA 4.0,2013-09-13 13:17:04,270,206,3,0,0,4,true,false,false,true,true,true,60,6,false,0.018,0.0007,6283,2009,9,11,Tuesday,false,false,false,true,false,false,false
12862659,How to verify that a specific method was not called using Mockito?,"How to verify that a method is not called on an object's dependency?
For example:
public interface Dependency {
void someMethod();
}
public class Foo {
public bar(final Dependency d) {
...
}
}
With the Foo test:
public class FooTest {
@Test
public void dependencyIsNotCalled() {
final Foo foo = new Foo(...);
final Dependency dependency = mock(Dependency.class);
foo.bar(dependency);
**// verify here that someMethod was not called??**
}
}
",https://stackoverflow.com/questions/12862659/how-to-verify-that-a-specific-method-was-not-called-using-mockito,970,714278.0,7.0,,,2012-10-12 15:44:46,2023-06-05 12:23:15,2021-10-27 16:16:01,,,java;unit-testing;junit;mockito;tdd,beluchin,12862,614800,registered,true,12863072,,CC BY-SA 4.0,,597,511,2,0,0,5,true,false,false,true,true,true,66,12,true,0.01,0.0014,5153,2012,10,15,Friday,false,false,false,true,false,false,false
29888592,Error:java: javacTask: source release 8 requires target release 1.8,"Using IntelliJ IDE can't compile any projects. Screenshots of settings below:
Used JDK:
Project SDK and Language level:
Language Level:
Anybody have any ideas?
",https://stackoverflow.com/questions/29888592/errorjava-javactask-source-release-8-requires-target-release-1-8,968,536799.0,26.0,,,2015-04-27 06:24:28,2024-05-10 07:12:03,2018-04-24 08:16:23,,,java;intellij-idea;java-8,Hobbyist,16302,4111710,registered,true,30524848,,CC BY-SA 3.0,2018-10-26 09:52:09,661,170,0,3,3,3,true,false,false,true,true,true,67,9,false,0.048,0.0018,4226,2015,4,6,Monday,false,false,false,true,false,false,false
2041778,How to initialize HashSet values by construction?,"I need to create a Set with initial values.
Set<String> h = new HashSet<String>();
h.add(""a"");
h.add(""b"");
Is there a way to do this in one line of code? For instance, it's useful for a final static field.
",https://stackoverflow.com/questions/2041778/how-to-initialize-hashset-values-by-construction,965,1233839.0,25.0,,,2010-01-11 12:31:50,2024-04-13 03:56:51,2018-11-03 22:47:57,,,java;collections;constructor;initialization;hashset,Serg,14166,105037,registered,true,2041810,,CC BY-SA 4.0,2023-04-13 11:13:38,272,221,2,0,0,5,true,false,false,true,true,true,49,7,true,0.02,0.0008,6158,2010,1,12,Monday,false,false,false,true,false,false,false
2684630,Making a mocked method return an argument that was passed to it,"Consider a method signature like:
public String myFunction(String abc);
Can Mockito help return the same string that the method received?
",https://stackoverflow.com/questions/2684630/making-a-mocked-method-return-an-argument-that-was-passed-to-it,964,606246.0,10.0,,,2010-04-21 16:11:41,2022-06-01 07:33:13,2019-05-10 15:16:33,,,java;mockito,Abhijeet Kashnia,12990,189974,registered,true,2711553,,CC BY-SA 4.0,2016-01-20 21:15:59,179,141,1,0,0,2,true,false,false,true,true,true,63,12,false,0.016,0.0016,6058,2010,4,16,Wednesday,false,false,false,true,false,false,false
8172420,How to convert a char to a String?,"I have a char and I need a String. How do I convert from one to the other?
",https://stackoverflow.com/questions/8172420/how-to-convert-a-char-to-a-string,958,1314692.0,14.0,,,2011-11-17 18:37:19,2023-12-02 23:21:16,2017-02-27 18:45:35,,,java;string;char;type-conversion,Landon Kuhn,79121,1785,registered,true,,,CC BY-SA 3.0,2015-02-21 18:14:01,108,75,2,0,0,4,false,false,false,true,true,true,34,8,true,0.011,0.0007,5483,2011,11,18,Thursday,false,false,false,true,false,false,false
1104975,A for-loop to iterate over an enum in Java,"I have an enum in Java for the cardinal and intermediate directions:
public enum Direction {
NORTH,
NORTHEAST,
EAST,
SOUTHEAST,
SOUTH,
SOUTHWEST,
WEST,
NORTHWEST
}
How can I write a for loop that iterates through each of these enum values?
",https://stackoverflow.com/questions/1104975/a-for-loop-to-iterate-over-an-enum-in-java,956,543769.0,9.0,,,2009-07-09 16:24:03,2023-11-20 23:56:08,2022-05-08 17:38:57,,,java;loops;for-loop;enums,Nick Meyer,40790,135178,registered,true,1104994,,CC BY-SA 4.0,2014-11-12 11:51:29,342,265,4,0,0,4,true,false,false,true,true,true,42,9,false,0.017,0.0018,6344,2009,7,16,Thursday,false,false,false,true,false,false,false
858980,File to byte[] in Java,"How do I convert a java.io.File to a byte[]?
",https://stackoverflow.com/questions/858980/file-to-byte-in-java,942,1475605.0,26.0,,,2009-05-13 16:30:33,2021-07-09 16:38:08,2014-03-27 11:32:56,,,java;file-io,Ben Noland,35168,32899,registered,true,859076,,CC BY-SA 3.0,2015-12-07 13:10:32,78,45,2,0,0,2,true,false,false,true,true,true,22,5,false,0.018,0.0006,6401,2009,5,16,Wednesday,false,false,false,true,false,false,false
869033,How do I copy an object in Java?,"Consider the code below:
DummyBean dum = new DummyBean();
dum.setDummy(""foo"");
System.out.println(dum.getDummy()); // prints 'foo'
DummyBean dumtwo = dum;
System.out.println(dumtwo.getDummy()); // prints 'foo'
dum.setDummy(""bar"");
System.out.println(dumtwo.getDummy()); // prints 'bar' but it should print 'foo'
So, I want to copy the dum to dumtwo and change dum without affecting the dumtwo. But the code above is not doing that. When I change something in dum, the same change is happening in dumtwo also.
I guess, when I say dumtwo = dum, Java copies the reference only. So, is there any way to create a fresh copy of dum and assign it to dumtwo?
",https://stackoverflow.com/questions/869033/how-do-i-copy-an-object-in-java,937,1600360.0,23.0,,,2009-05-15 14:30:26,2024-05-01 19:59:39,2017-12-23 19:15:19,,,java;object;copy;clone,Veera,33382,42372,registered,true,869078,,CC BY-SA 3.0,2013-10-11 15:39:04,836,657,10,0,0,4,true,false,false,true,true,true,32,8,true,0.014,0.0006,6399,2009,5,14,Friday,false,false,false,true,false,false,false
2213340,What is a daemon thread in Java?,"Can anybody tell me what daemon threads are in Java?
",https://stackoverflow.com/questions/2213340/what-is-a-daemon-thread-in-java,937,576974.0,26.0,,,2010-02-06 14:08:37,2024-08-27 16:51:21,2021-07-26 03:22:31,,,java;multithreading,rocker,11665,236586,registered,true,,,CC BY-SA 4.0,2013-08-25 12:21:34,60,53,0,0,0,2,false,false,false,true,true,true,32,7,true,0.045,0.0016,6132,2010,2,14,Saturday,true,false,false,true,false,false,false
1082050,Linking to an external URL in Javadoc?,"Something like:
/**
* See {@linktourl http://google.com}
*/
",https://stackoverflow.com/questions/1082050/linking-to-an-external-url-in-javadoc,936,331274.0,4.0,,,2009-07-04 11:44:32,2026-03-27 09:04:42,2010-10-27 02:50:31,,,java;url;javadoc;hyperlink,ripper234,232304,11236,registered,true,10683345,,CC BY-SA 2.5,2018-10-05 17:39:29,95,64,1,0,0,4,true,false,false,true,true,true,38,7,true,0.012,0.0028,6349,2009,7,11,Saturday,true,false,false,true,false,false,false
2723397,What is PECS (Producer Extends Consumer Super)?,"I came across PECS (short for Producer extends and Consumer super) while reading up on generics.
Can someone explain to me how to use PECS to resolve confusion between extends and super?
",https://stackoverflow.com/questions/2723397/what-is-pecs-producer-extends-consumer-super,935,187265.0,17.0,,,2010-04-27 17:16:40,2024-05-24 18:36:39,2016-04-05 14:59:01,,,java;generics;super;bounded-wildcard;pecs,peakit,29673,133830,registered,true,2723538,,CC BY-SA 3.0,2015-06-16 16:34:44,264,189,4,0,0,5,true,false,false,true,true,true,47,7,true,0.091,0.005,6052,2010,4,17,Tuesday,false,false,false,true,false,false,false
1051640,Correct way to add external jars (lib/*.jar) to an IntelliJ IDEA project,"When creating a new Java project in IntelliJ IDEA, the following directories and files are created:
./projectname.iml
./projectname.ipr
./projectname.iws
./src/
I want to configure IntelliJ IDEA to include my dependency JARs in ./lib/*.jar to the project.
What is the correct way to achieve this in IntelliJ IDEA?
",https://stackoverflow.com/questions/1051640/correct-way-to-add-external-jars-lib-jar-to-an-intellij-idea-project,930,1401984.0,14.0,,,2009-06-26 22:58:35,2025-08-10 19:16:49,2024-01-05 07:49:49,,,java;intellij-idea;build;dependency-management,knorv,50505,58394,registered,true,1051705,,CC BY-SA 4.0,2018-06-03 17:41:21,372,315,2,0,0,4,true,false,false,true,true,true,72,12,false,0.01,0.0007,6357,2009,6,22,Friday,false,false,false,true,false,false,false
858572,How to make a new List in Java,"We create a Set as:
Set myset = new HashSet()
How do we create a List in Java?
",https://stackoverflow.com/questions/858572/how-to-make-a-new-list-in-java,929,2750440.0,25.0,,,2009-05-13 15:12:45,2022-03-29 12:13:41,2019-10-05 09:57:47,,,java;list;collections,user93796,1,93796,registered,true,858590,,CC BY-SA 4.0,2013-08-06 19:27:31,146,82,3,0,0,3,true,false,false,true,true,true,30,8,false,0.009,0.0003,6401,2009,5,15,Wednesday,false,false,false,true,false,false,false
2302802,How to fix the Hibernate "object references an unsaved transient instance - save the transient instance before flushing" error,"I receive following error when I save the object using Hibernate
object references an unsaved transient instance - save the transient instance before flushing
",https://stackoverflow.com/questions/2302802/how-to-fix-the-hibernate-object-references-an-unsaved-transient-instance-save,928,1176305.0,35.0,,,2010-02-20 16:17:45,2024-12-17 02:24:28,2020-01-02 18:04:28,,,java;hibernate;jpa;orm;entity,Tushar Ahirrao,13225,196480,registered,true,2302814,,CC BY-SA 4.0,2018-09-07 12:43:11,193,162,1,0,0,5,true,false,false,true,true,true,136,19,false,0.03,0.0008,6118,2010,2,16,Saturday,true,false,false,true,false,false,false
3437897,How do I get a class instance of generic type T?,"I have a generics class, Foo<T>. In a method of Foo, I want to get the class instance of type T, but I just can't call T.class.
What is the preferred way to get around it using T.class?
",https://stackoverflow.com/questions/3437897/how-do-i-get-a-class-instance-of-generic-type-t,927,1039558.0,25.0,,,2010-08-09 06:58:45,2024-01-15 07:18:52,2020-03-18 12:47:51,,,java;generics,robinmag,18290,448452,registered,true,3437930,,CC BY-SA 4.0,,272,193,5,0,0,2,true,false,false,true,true,true,48,11,true,0.024,0.0009,5948,2010,8,6,Monday,false,false,false,true,false,false,false
3072173,How to call a method after a delay in Android,"I want to be able to call the following method after a specified delay.
In objective c there was something like:
[self performSelector:@selector(DoSomething) withObject:nil afterDelay:5];
Is there an equivalent of this method in android with java?
For example I need to be able to call a method after 5 seconds.
public void DoSomething()
{
//do something here
}
",https://stackoverflow.com/questions/3072173/how-to-call-a-method-after-a-delay-in-android,923,866116.0,37.0,,,2010-06-18 18:24:19,2024-07-05 07:32:17,2014-09-04 07:31:52,,,java;android;handler;delay,aryaxt,77976,242769,registered,true,9166354,,CC BY-SA 3.0,2013-03-18 08:46:05,435,373,2,0,0,4,true,false,false,true,true,true,45,10,false,0.043,0.0011,6000,2010,6,18,Friday,false,false,false,true,false,false,false
299659,What's the difference between SoftReference and WeakReference in Java?,"What's the difference between java.lang.ref.WeakReference and java.lang.ref.SoftReference ?
",https://stackoverflow.com/questions/299659/whats-the-difference-between-softreference-and-weakreference-in-java,923,266694.0,12.0,,,2008-11-18 18:26:37,2021-10-18 20:48:26,2021-10-18 20:48:26,,,java;reference;weak-references;soft-references,driekken,11653,24982,registered,true,299702,,CC BY-SA 4.0,,375,92,2,2,0,4,true,false,false,true,true,true,74,9,true,0.045,0.0035,6577,2008,11,18,Tuesday,false,false,false,true,false,false,false
30571,How do I tell Maven to use the latest version of a dependency?,"In Maven, dependencies are usually set up like this:
<dependency>
<groupId>wonderful-inc</groupId>
<artifactId>dream-library</artifactId>
<version>1.2.3</version>
</dependency>
Now, if you are working with libraries that have frequent releases, constantly updating the <version> tag can be somewhat annoying. Is there any way to tell Maven to always use the latest available version (from the repository)?
",https://stackoverflow.com/questions/30571/how-do-i-tell-maven-to-use-the-latest-version-of-a-dependency,922,817327.0,13.0,,,2008-08-27 16:17:02,2026-07-23 09:12:31,2017-02-23 11:35:59,,,java;maven;dependencies;maven-2;maven-metadata,Anders Sandvig,21064,1709,registered,true,1172371,,CC BY-SA 3.0,2018-10-26 13:56:24,546,470,1,0,0,5,true,false,false,true,true,true,62,13,true,0.016,0.0011,6660,2008,8,16,Wednesday,false,false,false,true,false,false,false
2745265,Is List<Dog> a subclass of List<Animal>? Why are Java generics not implicitly polymorphic?,"I'm a bit confused about how Java generics handle inheritance / polymorphism.
Assume the following hierarchy -
Animal (Parent)
Dog - Cat (Children)
So suppose I have a method doSomething(List<Animal> animals). By all the rules of inheritance and polymorphism, I would assume that a List<Dog> is a List<Animal> and a List<Cat> is a List<Animal> - and so either one could be passed to this method. Not so. If I want to achieve this behavior, I have to explicitly tell the method to accept a list of any subclass of Animal by saying doSomething(List<? extends Animal> animals).
I understand that this is Java's behavior. My question is why? Why is polymorphism generally implicit, but when it comes to generics it must be specified?
",https://stackoverflow.com/questions/2745265/is-listdog-a-subclass-of-listanimal-why-are-java-generics-not-implicitly-po,921,144487.0,19.0,,,2010-04-30 14:39:39,2024-01-15 13:17:34,2018-11-20 09:22:14,,,java;generics;inheritance;polymorphism,froadie,83910,259541,registered,true,2745301,,CC BY-SA 4.0,2015-10-02 18:51:54,970,772,6,0,0,4,true,false,false,true,true,true,102,13,true,0.131,0.0064,6049,2010,4,14,Friday,false,false,false,true,false,false,false
3348816,IntelliJ IDEA: never use wildcard imports,"Is there a way to tell IntelliJ never to use wildcard imports?
Under Settings > Code Style > Imports, I can see that you can specify the 'class count' prior to IntelliJ using wildcard imports. However, if I never want to use wildcard imports can I turn this functionality off?
I have tried putting -1 or leaving the field blank but that just tells IntelliJ to always use wildcard imports. Obviously a not-so-nice solution would be to put a ridiculously high number so that you never encounter wildcard imports but I was hoping there was a nicer way to just turn it off.
",https://stackoverflow.com/questions/3348816/intellij-idea-never-use-wildcard-imports,915,415407.0,16.0,,,2010-07-27 23:36:33,2026-05-08 14:13:11,2025-04-13 22:15:57,,,java;intellij-idea;settings,digiarnie,23755,30563,registered,true,3348855,,CC BY-SA 4.0,,633,577,2,0,0,3,true,false,false,true,true,true,41,6,false,0.039,0.0022,5961,2010,7,23,Tuesday,false,false,false,true,false,false,false
924285,Efficiency of Java "Double Brace Initialization"?,"In Hidden Features of Java the top answer mentions Double Brace Initialization, with a very enticing syntax:
Set<String> flavors = new HashSet<String>() {{
add(""vanilla"");
add(""strawberry"");
add(""chocolate"");
add(""butter pecan"");
}};
This idiom creates an anonymous inner class with just an instance initializer in it, which ""can use any [...] methods in the containing scope"".
Main question: Is this as inefficient as it sounds? Should its use be limited to one-off initializations? (And of course showing off!)
Second question: The new HashSet must be the ""this"" used in the instance initializer ... can anyone shed light on the mechanism?
Third question: Is this idiom too obscure to use in production code?
Summary: Very, very nice answers, thanks everyone. On question (3), people felt the syntax should be clear (though I'd recommend an occasional comment, especially if your code will pass on to developers who may not be familiar with it).
On question (1), the generated code should run quickly. The extra .class files do cause jar file clutter, and slow program startup slightly (thanks to @coobird for measuring that). @Thilo pointed out that garbage collection can be affected, and the memory cost for the extra loaded classes may be a factor in some cases.
Question (2) turned out to be most interesting to me. If I understand the answers, what's happening in DBI is that the anonymous inner class extends the class of the object being constructed by the new operator, and hence has a ""this"" value referencing the instance being constructed. Very neat.
Overall, DBI strikes me as something of an intellectual curiousity. Coobird and others point out you can achieve the same effect with Arrays.asList, varargs methods, Google Collections, and the proposed Java 7 Collection literals. Newer JVM languages like Scala, JRuby, and Groovy also offer concise notations for list construction, and interoperate well with Java. Given that DBI clutters up the classpath, slows down class loading a bit, and makes the code a tad more obscure, I'd probably shy away from it. However, I plan to spring this on a friend who's just gotten his SCJP and loves good natured jousts about Java semantics! ;-) Thanks everyone!
7/2017: Baeldung has a good summary of double brace initialization and considers it an anti-pattern.
12/2017: @Basil Bourque notes that in the new Java 9 you can say:
Set<String> flavors = Set.of(""vanilla"", ""strawberry"", ""chocolate"", ""butter pecan"");
That's for sure the way to go. If you're stuck with an earlier version, take a look at Google Collections' ImmutableSet.
",https://stackoverflow.com/questions/924285/efficiency-of-java-double-brace-initialization,915,156150.0,15.0,,,2009-05-29 03:40:13,2020-02-22 00:46:27,2017-12-10 23:02:18,,,java;performance;collections;initialization,Jim Ferrans,31082,45935,registered,true,924326,,CC BY-SA 3.0,2018-10-26 07:46:36,3228,2655,2,4,0,4,true,false,false,true,true,true,59,6,true,0.096,0.0059,6385,2009,5,3,Friday,false,false,false,true,false,false,false
53452713,Why is 2 * (i * i) faster than 2 * i * i in Java?,"The following Java program takes on average between 0.50 secs and 0.55 secs to run:
public static void main(String[] args) {
long startTime = System.nanoTime();
int n = 0;
for (int i = 0; i < 1000000000; i++) {
n += 2 * (i * i);
}
System.out.println(
(double) (System.nanoTime() - startTime) / 1000000000 + " s");
System.out.println("n = " + n);
}
If I replace 2 * (i * i) with 2 * i * i, it takes between 0.60 and 0.65 secs to run. How come?
I ran each version of the program 15 times, alternating between the two. Here are the results:
2*(i*i) │ 2*i*i
──────────┼──────────
0.5183738 │ 0.6246434
0.5298337 │ 0.6049722
0.5308647 │ 0.6603363
0.5133458 │ 0.6243328
0.5003011 │ 0.6541802
0.5366181 │ 0.6312638
0.515149 │ 0.6241105
0.5237389 │ 0.627815
0.5249942 │ 0.6114252
0.5641624 │ 0.6781033
0.538412 │ 0.6393969
0.5466744 │ 0.6608845
0.531159 │ 0.6201077
0.5048032 │ 0.6511559
0.5232789 │ 0.6544526
The fastest run of 2 * i * i took longer than the slowest run of 2 * (i * i). If they had the same efficiency, the probability of this happening would be less than 1/2^15 * 100% = 0.00305%.
",https://stackoverflow.com/questions/53452713/why-is-2-i-i-faster-than-2-i-i-in-java,912,255487.0,10.0,,,2018-11-23 20:40:10,2022-07-16 13:14:30,2022-07-16 13:14:30,,,java;performance;benchmarking;bytecode;jit,Stefan,5102,10339589,registered,true,53453588,,CC BY-SA 4.0,2018-12-07 10:23:12,1382,1163,7,0,0,5,true,false,false,true,true,true,49,16,true,0.039,0.0036,2920,2018,11,20,Friday,false,false,false,true,false,false,false
3495926,Can I catch multiple Java exceptions in the same catch clause?,"In Java, I want to do something like this:
try {
...
} catch (/* code to catch IllegalArgumentException, SecurityException,
IllegalAccessException, and NoSuchFieldException at the same time */) {
someCode();
}
...instead of:
try {
...
} catch (IllegalArgumentException e) {
someCode();
} catch (SecurityException e) {
someCode();
} catch (IllegalAccessException e) {
someCode();
} catch (NoSuchFieldException e) {
someCode();
}
Is there any way to do this?
",https://stackoverflow.com/questions/3495926/can-i-catch-multiple-java-exceptions-in-the-same-catch-clause,907,762429.0,11.0,,,2010-08-16 18:07:03,2023-04-23 17:31:12,2018-11-01 20:16:41,,,java;exception;try-catch;multi-catch,froadie,83910,259541,registered,true,3495968,,CC BY-SA 4.0,,582,513,2,0,0,4,true,false,false,true,true,true,62,11,true,0.014,0.0012,5941,2010,8,18,Monday,false,false,false,true,false,false,false
15826202,Where is Java Installed on Mac OS X?,"I downloaded Java 7u17 on Mac OS 10.7.5 from here and successfully installed it. To do some JNI programming, I need to know where Java is installed on my Mac.
I thought that inside the /Library/Java/JavaVirtualMachines/ folder, there would be a folder called 1.7.0.jdk or something, but then I found the folder empty. This was confirmed by running ls /Library/Java/JavaVirtualMachines/ in the Terminal. I've tried searching for it to find out if it was installed somewhere, but that doesn't seem to be turning anything up.
Could someone please tell me where Java is installed on my Mac?
",https://stackoverflow.com/questions/15826202/where-is-java-installed-on-mac-os-x,901,1213662.0,21.0,,,2013-04-05 04:58:29,2024-02-28 09:57:53,2023-07-13 15:36:58,,,java;macos,Thunderforge,20895,531762,registered,true,15826712,,CC BY-SA 4.0,2019-02-11 06:14:07,737,587,3,1,0,2,true,false,false,true,true,true,36,8,true,0.017,0.0007,4978,2013,4,4,Friday,false,false,false,true,false,false,false
11757487,How to tell Jackson to ignore a field during serialization if its value is null?,"How can Jackson be configured to ignore a field value during serialization if that field's value is null.
For example:
public class SomeClass {
// what jackson annotation causes jackson to skip over this value if it is null but will
// serialize it otherwise
private String someValue;
}
",https://stackoverflow.com/questions/11757487/how-to-tell-jackson-to-ignore-a-field-during-serialization-if-its-value-is-null,901,962899.0,23.0,,,2012-08-01 10:40:31,2026-01-27 17:09:27,2015-07-17 04:30:30,,,java;jackson,ams,63532,438319,registered,true,11761975,,CC BY-SA 3.0,,341,303,1,0,0,2,true,false,false,true,true,true,80,15,true,0.024,0.0009,5225,2012,8,10,Wednesday,false,false,false,true,false,false,false
2736389,How to pass an object from one activity to another on Android,"I am trying to work on sending an object of my customer class from one Activity and displaying it in another Activity.
The code for the customer class:
public class Customer {
private String firstName, lastName, address;
int age;
public Customer(String fname, String lname, int age, String address) {
firstName = fname;
lastName = lname;
age = age;
address = address;
}
public String printValues() {
String data = null;
data = "First Name :" + firstName + " Last Name :" + lastName
+ " Age : " + age + " Address : " + address;
return data;
}
}
I want to send its object from one Activity to another and then display the data on the other Activity.
How can I achieve that?
",https://stackoverflow.com/questions/2736389/how-to-pass-an-object-from-one-activity-to-another-on-android,900,866574.0,35.0,,,2010-04-29 10:06:52,2023-11-05 03:30:46,2022-07-25 10:54:24,,,java;android;object;android-intent;android-activity,Adil Bhatty,17360,328518,registered,true,2736612,,CC BY-SA 4.0,2017-07-21 17:02:16,921,808,5,0,0,5,true,false,false,true,true,true,61,12,false,0.04,0.001,6050,2010,4,10,Thursday,false,false,false,true,false,false,false
4597850,Gradle build without tests,"I want to execute gradle build without executing the unit tests. I tried:
gradle -Dskip.tests build
That doesn't seem to do anything. Is there some other command I could use?
",https://stackoverflow.com/questions/4597850/gradle-build-without-tests,892,702499.0,12.0,,,2011-01-04 20:01:23,2023-12-09 12:42:12,2023-12-09 12:42:12,,,java;gradle;testing,Dave,14298,3095,registered,true,4714118,,CC BY-SA 4.0,2019-09-18 13:27:19,266,176,2,0,0,3,true,false,false,true,true,true,26,4,false,0.017,0.0013,5800,2011,1,20,Tuesday,false,false,false,true,false,false,false
23353173,Unfortunately MyApp has stopped. How can I solve this?,"I am developing an application, and everytime I run it, I get the message:
Unfortunately, MyApp has stopped.
What can I do to solve this?
About this question - obviously inspired by What is a stack trace, and how can I use it to debug my application errors?, there are lots of questions stating that their application has crashed, without any further detail. This question aims to instruct novice Android programmers on how to try and fix their problems themselves, or ask the right questions.
",https://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this,888,566277.0,23.0,,,2014-04-28 23:55:14,2024-12-23 06:20:01,2020-07-21 22:35:10,,,java;android;debugging;kotlin,nhaarman,100739,675383,registered,true,23353174,,CC BY-SA 4.0,2014-05-12 18:06:16,702,503,0,1,0,4,true,false,false,true,true,true,54,9,true,0.041,0.0016,4590,2014,4,23,Monday,false,false,false,true,false,false,false
2095397,"What is the difference between JSF, Servlet and JSP?","I have some questions. These are :
- How are JSP and Servlet related to each other?
- Is JSP some kind of Servlet?
- How are JSP and JSF related to each other?
- Is JSF some kind of Pre-Build UI based JSP like ASP.NET-MVC?
",https://stackoverflow.com/questions/2095397/what-is-the-difference-between-jsf-servlet-and-jsp,886,461278.0,16.0,,,2010-01-19 17:15:41,2024-01-05 07:44:37,2020-05-25 05:10:03,,,java;jsp;jsf;servlets;jakarta-ee,Cheung,15572,83952,registered,true,2097732,,CC BY-SA 4.0,2013-06-20 12:41:30,289,220,0,0,0,5,true,false,false,true,true,true,52,9,true,0.035,0.0019,6150,2010,1,17,Tuesday,false,false,false,true,false,false,false
1217228,What is the Java equivalent for LINQ?,"What is Java equivalent for LINQ?
",https://stackoverflow.com/questions/1217228/what-is-the-java-equivalent-for-linq,876,382935.0,34.0,,,2009-08-01 18:53:26,2019-10-18 22:37:50,2014-09-27 06:30:59,2016-02-11 12:28:35,Not suitable for this site,java;linq,Ahmed Atia,17990,14118,registered,true,1217229,,,2015-06-24 15:33:46,41,34,0,0,0,2,true,true,false,true,true,true,37,7,true,0.089,0.0023,6321,2009,8,18,Saturday,true,false,false,true,false,false,false
5175728,How to get the current date/time in Java,"What's the best way to get the current date/time in Java?
",https://stackoverflow.com/questions/5175728/how-to-get-the-current-date-time-in-java,874,2611144.0,28.0,,,2011-03-03 01:48:09,2023-10-27 01:53:51,2018-05-03 05:44:17,2020-04-30 22:00:12,Duplicate,java;datetime,user496949,86741,496949,registered,true,5175900,,,2013-08-22 18:15:49,65,58,0,0,0,2,true,true,false,true,true,true,40,8,false,0.011,0.0003,5742,2011,3,1,Thursday,false,false,false,true,false,false,false
25147094,How can I turn a List of Lists into a List in Java 8?,"If I have a List<List<Object>>, how can I turn that into a List<Object> that contains all the objects in the same iteration order by using the features of Java 8?
",https://stackoverflow.com/questions/25147094/how-can-i-turn-a-list-of-lists-into-a-list-in-java-8,872,764817.0,12.0,,,2014-08-05 19:48:00,2022-06-10 15:45:48,2018-02-28 10:22:11,,,java;collections;java-8,Sarah Szabo,10923,2058221,registered,true,25147125,,CC BY-SA 3.0,,214,181,2,0,0,3,true,false,false,true,true,true,53,14,true,0.016,0.0011,4491,2014,8,19,Tuesday,false,false,false,true,false,false,false
106591,What is the volatile keyword useful for?,"I came across the volatile keyword in Java. Not being very familiar with it, I found this explanation.
Volatile variables are a simpler -- but weaker -- form of synchronization than locking, which in some cases offers better performance or scalability than intrinsic locking. If you follow the conditions for using volatile safely -- that the variable is truly independent of both other variables and its own prior values -- you can sometimes simplify code by using volatile instead of synchronized. However, code using volatile is often more fragile than code using locking. The patterns offered here cover the most common cases where volatile is a sensible alternative to synchronized. Following these patterns -- taking care not to push them beyond their limits -- should help you safely cover the majority of cases where volatile variables are a win.
Given the detail in which that article explains the keyword in question, do you ever use it or could you ever see a case in which you could use this keyword in the correct manner?
",https://stackoverflow.com/questions/106591/what-is-the-volatile-keyword-useful-for,860,431389.0,26.0,,,2008-09-20 00:41:02,2025-11-12 15:33:06,2025-05-26 01:03:22,,,java;multithreading;keyword;volatile,Richard,10592,16759,registered,true,106787,,CC BY-SA 4.0,2015-06-23 08:33:22,1229,1037,1,1,0,4,true,false,false,true,true,true,40,7,true,0.06,0.002,6636,2008,9,0,Saturday,true,false,false,true,false,false,false
70689,What is an efficient way to implement a singleton pattern in Java?,"What is an efficient way to implement a singleton design pattern in Java?
",https://stackoverflow.com/questions/70689/what-is-an-efficient-way-to-implement-a-singleton-pattern-in-java,858,346397.0,29.0,,,2008-09-16 09:24:28,2021-08-15 05:14:41,2021-08-15 05:14:41,2018-09-15 04:35:00,Needs more focus,java;singleton;design-patterns,Riyaz Mohammed Ibrahim,9605,11581,registered,true,71399,,,2019-03-21 06:38:41,81,74,0,0,0,3,true,true,false,true,true,true,66,12,true,0.084,0.0025,6640,2008,9,9,Tuesday,false,false,false,true,false,false,false
3064423,How to convert an Array to a Set in Java,"I would like to convert an array to a Set in Java. There are some obvious ways of doing this (i.e. with a loop) but I would like something a bit neater, something like:
java.util.Arrays.asList(Object[] a);
Any ideas?
",https://stackoverflow.com/questions/3064423/how-to-convert-an-array-to-a-set-in-java,854,860233.0,19.0,,,2010-06-17 18:23:56,2023-10-18 05:25:00,2016-04-11 20:23:08,,,java;collections;arrays;set,user130076,,,does_not_exist,true,3064447,,CC BY-SA 3.0,2019-03-25 11:39:55,258,220,1,0,0,4,true,false,false,true,false,true,40,10,false,0.022,0.001,6001,2010,6,18,Thursday,false,false,false,true,false,false,false
5455794,Removing whitespace from strings in Java,"I have a string like this:
mysz = ""name=john age=13 year=2001"";
I want to remove the whitespaces in the string. I tried trim() but this removes only whitespaces before and after the whole string. I also tried replaceAll(""\\W"", """") but then the = also gets removed.
How can I achieve a string with:
mysz2 = ""name=johnage=13year=2001""
",https://stackoverflow.com/questions/5455794/removing-whitespace-from-strings-in-java,853,1757470.0,36.0,,,2011-03-28 07:22:01,2024-02-04 10:06:57,2011-03-28 07:29:38,,,java;whitespace,zyamat,8551,662159,unregistered,true,,,CC BY-SA 2.5,2018-12-20 04:42:24,448,340,5,0,0,2,false,false,false,true,true,true,40,6,false,0.02,0.0005,5717,2011,3,7,Monday,false,false,false,true,false,false,false
860187,Access restriction on class due to restriction on required library rt.jar?,"I'm attempting to compile Java 1.4 code that was created by IBM's WSDL2Java on Java5 without recreating the stubs and saw this error in Eclipse.
I'm under the assumption that the stubs generated should just compile as long as the runtime jars are available (they are).
Access restriction: The type QName is not accessible due to restriction on required library C:\Program Files\Java\jdk1.5.0_16\jre\lib\rt.jar
The full class name is javax.xml.namespace.QName
What exactly is going on here? Is this a case where I am trying to refactor a pig from sausage? Am I better off recreating the stubs?
",https://stackoverflow.com/questions/860187/access-restriction-on-class-due-to-restriction-on-required-library-rt-jar,847,685055.0,15.0,,,2009-05-13 20:16:26,2021-08-18 19:58:29,2020-04-17 18:15:15,,,java;eclipse;wsdl;stub;wsdl2java,sal,23703,13753,registered,true,2174607,,CC BY-SA 4.0,2010-08-08 18:17:40,781,600,3,0,0,5,true,false,false,true,true,true,74,11,true,0.022,0.0012,6401,2009,5,20,Wednesday,false,false,false,true,false,false,false
20700053,How to add local .jar file dependency to build.gradle file?,"I have tried to add my local .jar file dependency to my build.gradle file:
apply plugin: 'java'
sourceSets {
main {
java {
srcDir 'src/model'
}
}
}
dependencies {
runtime files('libs/mnist-tools.jar', 'libs/gson-2.2.4.jar')
runtime fileTree(dir: 'libs', include: '*.jar')
}
And you can see that I added the .jar files into the referencedLibraries folder here: https://github.com/WalnutiQ/wAlnut/tree/version-2.3.1/referencedLibraries
But the problem is that when I run the command: gradle build on the command line I get the following error:
error: package com.google.gson does not exist
import com.google.gson.Gson;
Here is my entire repo: https://github.com/WalnutiQ/wAlnut/tree/version-2.3.1
",https://stackoverflow.com/questions/20700053/how-to-add-local-jar-file-dependency-to-build-gradle-file,846,1024562.0,23.0,,,2013-12-20 09:14:44,2024-10-17 12:03:40,2022-11-11 14:15:19,,,java;gradle;dependency-management;build.gradle;gradle-eclipse,letter Q,15585,1495015,registered,true,20700183,,CC BY-SA 4.0,,1010,744,2,2,0,5,true,false,false,true,true,true,59,10,true,0.022,0.0008,4719,2013,12,9,Friday,false,false,false,true,false,false,false
10786042,Java URL encoding of query string parameters,"Say I have a URL
http://example.com/query?q=
and I have a query entered by the user such as:
random word £500 bank $
I want the result to be a properly encoded URL:
http://example.com/query?q=random%20word%20%A3500%20bank%20%24
What's the best way to achieve this? I tried URLEncoder and creating URI/URL objects but none of them come out quite right.
",https://stackoverflow.com/questions/10786042/java-url-encoding-of-query-string-parameters,843,1259531.0,12.0,,,2012-05-28 14:10:45,2025-08-12 14:10:33,2022-11-27 22:27:56,,,java;http;url;encoding;urlencode,user1277546,8832,1277546,registered,true,10786112,,CC BY-SA 4.0,2018-07-27 10:27:32,555,356,3,0,0,5,true,false,false,true,true,true,44,7,false,0.01,0.0007,5290,2012,5,14,Monday,false,false,false,true,false,false,false
22358071,Differences between Oracle JDK and OpenJDK,"
NOTE: This question is from 2014. As of Java 11 OpenJDK and Oracle
JDK are converging.
Are there any crucial differences between Oracle and OpenJDK?
For example, are the garbage collection and other JVM parameters the same?
Does GC work differently between the two?
",https://stackoverflow.com/questions/22358071/differences-between-oracle-jdk-and-openjdk,842,712492.0,14.0,,,2014-03-12 16:36:32,2026-06-10 17:05:39,2019-01-31 23:33:27,,,java;difference,user1340582,19869,1340582,registered,true,38685948,,CC BY-SA 4.0,,330,277,0,0,0,2,true,false,false,true,true,true,42,6,false,0.02,0.0012,4637,2014,3,16,Wednesday,false,false,false,true,false,false,false
2298208,How do I discover memory usage of my application in Android?,"How can I find the memory used on my Android application, programmatically?
I hope there is a way to do it. Plus, how do I get the free memory of the phone too?
",https://stackoverflow.com/questions/2298208/how-do-i-discover-memory-usage-of-my-application-in-android,841,358327.0,10.0,,,2010-02-19 17:12:35,2022-09-28 12:02:56,2014-10-27 21:25:51,,,java;android;memory;memory-management,Andrea Baccega,27713,314407,registered,true,2299813,,CC BY-SA 3.0,2014-02-01 00:34:21,176,162,0,0,0,4,true,false,false,true,true,true,60,11,true,0.028,0.0023,6119,2010,2,17,Friday,false,false,false,true,false,false,false
10839131,Implements vs extends: When to use? What's the difference?,"Please explain in an easy to understand language or a link to some article.
",https://stackoverflow.com/questions/10839131/implements-vs-extends-when-to-use-whats-the-difference,840,1349688.0,19.0,,,2012-05-31 18:25:47,2025-11-18 17:12:16,2017-09-05 04:16:59,,,java;inheritance;interface;extends;implements,Saad Masood,11476,434407,registered,true,10839155,,CC BY-SA 3.0,,83,76,0,0,0,5,true,false,false,true,true,true,62,9,true,0.014,0.0006,5287,2012,5,18,Thursday,false,false,false,true,false,false,false
9655181,Java: convert a byte array to a hex string?,"I have a byte array filled with hex numbers and printing it the easy way is pretty pointless because there are many unprintable elements. What I need is the exact hexcode in the form of: 3a5f771c
",https://stackoverflow.com/questions/9655181/java-convert-a-byte-array-to-a-hex-string,833,1076544.0,34.0,,,2012-03-11 13:06:24,2024-01-29 11:13:17,2023-08-03 07:26:51,,,java;arrays;hex,Andre,9220,107544,registered,true,9855338,,CC BY-SA 4.0,2015-11-19 11:18:13,216,196,1,0,0,3,true,false,false,true,true,true,43,9,true,0.032,0.0008,5368,2012,3,13,Sunday,true,false,false,true,false,false,false
1026723,How do I convert a Map to List in Java?,"How do I convert a Map<key,value> to a List<value>? Should I iterate over all map values and insert them into a list?
",https://stackoverflow.com/questions/1026723/how-do-i-convert-a-map-to-list-in-java,828,1111176.0,13.0,,,2009-06-22 11:45:28,2023-11-14 01:59:43,2022-06-05 05:17:02,,,java;list;dictionary;collections,Javaa,8319,60173,registered,true,1026736,,CC BY-SA 4.0,2021-07-01 03:31:39,163,130,2,0,0,4,true,false,false,true,true,true,39,10,true,0.012,0.0007,6361,2009,6,11,Monday,false,false,false,true,false,false,false
1053467,How do I save a String to a text file using Java?,"In Java, I have text from a text field in a String variable called ""text"".
How can I save the contents of the ""text"" variable to a file?
",https://stackoverflow.com/questions/1053467/how-do-i-save-a-string-to-a-text-file-using-java,826,1488826.0,24.0,,,2009-06-27 19:37:28,2026-04-12 15:45:15,2014-07-01 06:12:07,,,java;file;file-io;text-files,Justin White,8493,126680,registered,true,,,CC BY-SA 3.0,2014-01-10 09:27:44,152,138,0,0,0,4,false,false,false,true,true,true,49,12,true,0.016,0.0006,6356,2009,6,19,Saturday,true,false,false,true,false,false,false
1459656,How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?,"The code below gives me the current time. But it does not tell anything about milliseconds.
public static String getCurrentTimeStamp() {
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//dd/MM/yyyy
Date now = new Date();
String strDate = sdfDate.format(now);
return strDate;
}
I have a date in the format YYYY-MM-DD HH:MM:SS (2009-09-22 16:47:08).
But I want to retrieve the current time in the format YYYY-MM-DD HH:MM:SS.MS (2009-09-22 16:47:08.128, where 128 are the milliseconds).
SimpleTextFormat will work fine. Here the lowest unit of time is second, but how do I get millisecond as well?
",https://stackoverflow.com/questions/1459656/how-to-get-the-current-time-in-yyyy-mm-dd-hhmisec-millisecond-format-in-java,824,1721866.0,18.0,,,2009-09-22 12:00:50,2024-08-09 05:03:22,2021-02-07 12:36:27,,,java;date,Sunil Kumar Sahoo,53694,111988,registered,true,1459683,,CC BY-SA 4.0,,775,645,7,0,0,2,true,false,false,true,true,true,79,12,true,0.01,0.0005,6269,2009,9,12,Tuesday,false,false,false,true,false,false,false
2770321,What is a raw type and why shouldn't we use it?,"Questions:
- What are raw types in Java, and why do I often hear that they shouldn't be used in new code?
- What is the alternative if we can't use raw types, and how is it better?
",https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it,823,380354.0,15.0,,,2010-05-05 02:48:53,2022-12-07 15:19:15,2017-03-22 16:13:06,,,java;generics;raw-types,polygenelubricants,385712,276101,registered,true,,,CC BY-SA 3.0,2013-10-12 17:37:04,216,180,0,0,0,3,false,false,false,true,true,true,51,11,true,0.039,0.0022,6044,2010,5,2,Wednesday,false,false,false,true,false,false,false
11677572,Dealing with "Xerces hell" in Java/Maven?,"In my office, the mere mention of the word Xerces is enough to incite murderous rage from developers. A cursory glance at the other Xerces questions on SO seem to indicate that almost all Maven users are "touched" by this problem at some point. Unfortunately, understanding the problem requires a bit of knowledge about the history of Xerces...
History
Xerces is the most widely used XML parser in the Java ecosystem. Almost every library or framework written in Java uses Xerces in some capacity (transitively, if not directly).
The Xerces jars included in the official binaries are, to this day, not versioned. For example, the Xerces 2.11.0 implementation jar is named xercesImpl.jar and not xercesImpl-2.11.0.jar.
The Xerces team does not use Maven, which means they do not
upload an official release to Maven Central.
Xerces used to be released as a single jar (xerces.jar), but was split into two jars, one containing the API (xml-apis.jar) and one containing the implementations of those APIs (xercesImpl.jar). Many older Maven POMs still declare a dependency on xerces.jar. At some point in the past, Xerces was also released as xmlParserAPIs.jar, which some older POMs also depend on.
The versions assigned to the xml-apis and xercesImpl jars by those who deploy their jars to Maven repositories are often different. For example, xml-apis might be given version 1.3.03 and xercesImpl might be given version 2.8.0, even though both are from Xerces 2.8.0. This is because people often tag the xml-apis jar with the version of the specifications that it implements. There is a very nice, but incomplete breakdown of this here.
To complicate matters, Xerces is the XML parser used in the reference implementation of the Java API for XML Processing (JAXP), included in the JRE. The implementation classes are repackaged under the com.sun.* namespace, which makes it dangerous to access them directly, as they may not be available in some JREs. However, not all of the Xerces functionality is exposed via the java.* and javax.* APIs; for example, there is no API that exposes Xerces serialization.
Adding to the confusing mess, almost all servlet containers (JBoss, Jetty, Glassfish, Tomcat, etc.), ship with Xerces in one or more of their /lib folders.
Problems
Conflict Resolution
For some -- or perhaps all -- of the reasons above, many
organizations publish and consume custom builds of Xerces in their
POMs. This is not really a problem if you have a small application and are only using Maven Central, but it quickly becomes an issue for enterprise software where Artifactory or Nexus is proxying multiple repositories (JBoss, Hibernate, etc.):
![]()
For example, organization A might publish xml-apis as:
<groupId>org.apache.xerces</groupId>
<artifactId>xml-apis</artifactId>
<version>2.9.1</version>
Meanwhile, organization B might publish the same jar as:
<groupId>xml-apis</groupId>
<artifactId>xml-apis</artifactId>
<version>1.3.04</version>
Although B's jar is a lower version than A's jar, Maven does not know
that they are the same artifact because they have different
groupIds. Thus, it cannot perform conflict resolution and both
jars will be included as resolved dependencies:
![]()
Classloader Hell
As mentioned above, the JRE ships with Xerces in the JAXP RI. While it would be nice to mark all Xerces Maven dependencies as <exclusion>s or as <provided>, the third-party code you depend on may or may not work with the version provided in JAXP of the JDK you're using. In addition, you have the Xerces jars shipped in your servlet container to contend with. This leaves you with a number of choices: Do you delete the servlet version and hope that your container runs on the JAXP version? Is it better to leave the servlet version, and hope that your application frameworks run on the servlet version? If one or two of the unresolved conflicts outlined above manage to slip into your product (easy to happen in a large organization), you quickly find yourself in classloader hell, wondering which version of Xerces the classloader is picking at runtime and whether or not it will pick the same jar in Windows and Linux (probably not).
Solutions?
We've tried marking all Xerces Maven dependencies as <provided> or as an <exclusion>, but this is difficult to enforce (especially with a large team) given that the artifacts have so many aliases (xml-apis, xerces, xercesImpl, xmlParserAPIs, etc.). Additionally, our third party libs/frameworks may not run on the JAXP version or the version provided by a servlet container.
How can we best address this problem with Maven? Do we have to exercise such fine-grained control over our dependencies, and then rely on tiered classloading? Is there some way to globally exclude all Xerces dependencies, and force all of our frameworks/libs to use the JAXP version?
UPDATE: Joshua Spiewak has uploaded a patched version of the Xerces build scripts to XERCESJ-1454 that allows for upload to Maven Central. Vote/watch/contribute to this issue and let's fix this problem once and for all.
",https://stackoverflow.com/questions/11677572/dealing-with-xerces-hell-in-java-maven,822,169482.0,11.0,,,2012-07-26 20:32:59,2019-12-12 15:03:28,2020-06-20 09:12:55,,,java;maven;classloader;dependency-management;xerces,Justin Garrick,14967,311304,registered,true,,,CC BY-SA 4.0,2018-09-03 05:22:03,6651,5171,27,6,2,5,false,false,false,true,true,true,51,6,true,0.065,0.0049,5231,2012,7,20,Thursday,false,false,false,true,false,false,false
7142622,What is the difference between @Inject and @Autowired in Spring Framework? Which one to use under what condition?,"I am going through some blogs on SpringSource and in one of the blogs, the author is using @Inject and I suppose he can also use @Autowired.
Here is the piece of code:
@Inject private CustomerOrderService customerOrderService;
So what is the difference between using @Inject and @Autowired and would appreciate it if someone explained their difference and which one to use under what situation.
",https://stackoverflow.com/questions/7142622/what-is-the-difference-between-inject-and-autowired-in-spring-framework-which,820,419245.0,12.0,,,2011-08-22 02:30:42,2026-05-19 13:31:35,2024-01-04 09:14:16,,,java;spring;dependency-injection;autowired;inject,Rachel,104509,164299,registered,true,7144137,,CC BY-SA 4.0,2018-09-07 12:08:16,488,395,5,0,0,5,true,false,false,true,true,true,113,18,true,0.029,0.002,5570,2011,8,2,Monday,false,false,false,true,false,false,false
1235179,Simple way to repeat a string,"I'm looking for a simple commons method or operator that allows me to repeat some string n times. I know I could write this using a for loop, but I wish to avoid for loops whenever necessary and a simple direct method should exist somewhere.
String str = "abc";
String repeated = str.repeat(3);
repeated.equals("abcabcabc");
Related to:
repeat string javascript
Create NSString by repeating another string a given number of times
Edited
I try to avoid for loops when they are not completely necessary because:
They add to the number of lines of code even if they are tucked away in another function.
Someone reading my code has to figure out what I am doing in that for loop. Even if it is commented and has meaningful variables names, they still have to make sure it is not doing anything "clever".
Programmers love to put clever things in for loops, even if I write it to "only do what it is intended to do", that does not preclude someone coming along and adding some additional clever "fix".
They are very often easy to get wrong. For loops involving indexes tend to generate off by one bugs.
For loops often reuse the same variables, increasing the chance of really hard to find scoping bugs.
For loops increase the number of places a bug hunter has to look.
",https://stackoverflow.com/questions/1235179/simple-way-to-repeat-a-string,817,864802.0,33.0,,,2009-08-05 19:14:38,2025-03-05 03:32:16,2020-11-05 12:42:42,,,java;string,Ethan Heilman,17018,74359,registered,true,49065337,,CC BY-SA 4.0,,1738,1324,1,2,0,2,true,false,false,true,true,true,29,6,false,0.038,0.0009,6317,2009,8,19,Wednesday,false,false,false,true,false,false,false
2201925,Converting ISO 8601-compliant String to java.util.Date,"I am trying to convert an ISO 8601 formatted String to a java.util.Date.
I found the pattern yyyy-MM-dd'T'HH:mm:ssZ to be ISO8601-compliant if used with a Locale (compare sample).
However, using the java.text.SimpleDateFormat, I cannot convert the correctly formatted String 2010-01-01T12:00:00+01:00. I have to convert it first to 2010-01-01T12:00:00+0100, without the colon.
So, the current solution is
SimpleDateFormat ISO8601DATEFORMAT = new SimpleDateFormat(""yyyy-MM-dd'T'HH:mm:ssZ"", Locale.GERMANY);
String date = ""2010-01-01T12:00:00+01:00"".replaceAll(""\\+0([0-9]){1}\\:00"", ""+0$100"");
System.out.println(ISO8601DATEFORMAT.parse(date));
which obviously isn't that nice. Am I missing something or is there a better solution?
Answer
Thanks to JuanZe's comment, I found the Joda-Time magic, it is also described here.
So, the solution is
DateTimeFormatter parser2 = ISODateTimeFormat.dateTimeNoMillis();
String jtdate = ""2010-01-01T12:00:00+01:00"";
System.out.println(parser2.parseDateTime(jtdate));
Or more simply, use the default parser via the constructor:
DateTime dt = new DateTime( ""2010-01-01T12:00:00+01:00"" ) ;
To me, this is nice.
",https://stackoverflow.com/questions/2201925/converting-iso-8601-compliant-string-to-java-util-date,814,911767.0,31.0,,,2010-02-04 17:52:39,2025-09-18 20:46:56,2018-07-12 08:31:17,,,java;date;iso8601,Ice09,9131,157229,registered,true,2202300,,CC BY-SA 4.0,2017-09-02 20:03:13,1761,1164,8,3,0,3,true,false,false,true,true,true,54,6,false,0.034,0.0009,6134,2010,2,17,Thursday,false,false,false,true,false,false,false
3988788,"What is a stack trace, and how can I use it to debug my application errors?","Sometimes when I run my application it gives me an error that looks like:
Exception in thread ""main"" java.lang.NullPointerException
at com.example.myproject.Book.getTitle(Book.java:16)
at com.example.myproject.Author.getBookTitles(Author.java:25)
at com.example.myproject.Bootstrap.main(Bootstrap.java:14)
People have referred to this as a ""stack trace"". What is a stack trace? What can it tell me about the error that's happening in my program?
About this question - quite often I see a question come through where a novice programmer is ""getting an error"", and they simply paste their stack trace and some random block of code without understanding what the stack trace is or how they can use it. This question is intended as a reference for novice programmers who might need help understanding the value of a stack trace.
",https://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug-my-application-errors,812,695783.0,7.0,,,2010-10-21 14:52:24,2022-10-03 11:46:41,2017-03-22 16:16:53,,,java;debugging;stack-trace,Rob Hruska,121020,29995,registered,true,3988794,,CC BY-SA 3.0,2016-02-14 16:30:14,931,855,1,0,0,3,true,false,false,true,true,true,75,16,true,0.01,0.0012,5875,2010,10,14,Thursday,false,false,false,true,false,false,false
687833,How to get the last value of an ArrayList,"How can I get the last value of an ArrayList?
",https://stackoverflow.com/questions/687833/how-to-get-the-last-value-of-an-arraylist,810,1157547.0,15.0,,,2009-03-26 22:38:57,2026-09-16 02:52:01,2022-03-25 18:21:38,,,java;arraylist,Jessy,15739,80796,registered,true,687842,,CC BY-SA 4.0,2025-01-13 07:30:48,53,46,0,0,0,2,true,false,false,true,true,true,41,9,false,0.013,0.0007,6449,2009,3,22,Thursday,false,false,false,true,false,false,false
4157972,"How to update a value, given a key in a hashmap?","Suppose we have a HashMap<String, Integer> in Java.
How do I update (increment) the integer-value of the string-key for each existence of the string I find?
One could remove and reenter the pair, but overhead would be a concern.
Another way would be to just put the new pair and the old one would be replaced.
In the latter case, what happens if there is a hashcode collision with a new key I am trying to insert? The correct behavior for a hashtable would be to assign a different place for it, or make a list out of it in the current bucket.
",https://stackoverflow.com/questions/4157972/how-to-update-a-value-given-a-key-in-a-hashmap,806,1420123.0,17.0,,,2010-11-11 18:34:01,2020-05-31 07:09:24,2019-06-26 18:28:32,,,java;key;hashmap,laertis,8527,297032,registered,true,4158002,,CC BY-SA 4.0,2018-12-28 22:13:37,598,553,1,0,0,3,true,false,false,true,true,true,48,11,true,0.012,0.0006,5854,2010,11,18,Thursday,false,false,false,true,false,false,false
16467685,Difference between @Mock and @InjectMocks,"What is the difference between @Mock and @InjectMocks in Mockito framework?
",https://stackoverflow.com/questions/16467685/difference-between-mock-and-injectmocks,804,687504.0,13.0,,,2013-05-09 17:33:30,2022-08-21 18:29:11,2015-02-23 15:54:39,,,java;unit-testing;mocking;mockito,user2249972,8045,2249972,registered,true,,,CC BY-SA 3.0,2019-05-19 12:10:59,109,76,2,0,0,4,false,false,false,true,true,true,41,5,false,0.019,0.0012,4944,2013,5,17,Thursday,false,false,false,true,false,false,false
1429860,Easiest way to convert a List to a Set in Java,"What is the easiest way to convert a List to a Set in Java?
",https://stackoverflow.com/questions/1429860/easiest-way-to-convert-a-list-to-a-set-in-java,803,812318.0,18.0,,,2009-09-15 22:02:35,2024-04-28 15:57:07,2016-05-26 11:23:19,,,java;collections,OHHAI,8285,160189,registered,true,1429869,,CC BY-SA 3.0,,93,60,2,0,0,2,true,false,false,true,true,true,46,11,false,0.022,0.001,6276,2009,9,22,Tuesday,false,false,false,true,false,false,false
1844688,How can I read all files in a folder from Java?,"How can I read all the files in a folder through Java? It doesn't matter which API.
",https://stackoverflow.com/questions/1844688/how-can-i-read-all-files-in-a-folder-from-java,801,1486940.0,35.0,,,2009-12-04 03:39:37,2024-02-16 05:52:37,2024-02-16 05:43:09,,,java;file;io;directory,M.J.,16806,197831,registered,true,1846349,,CC BY-SA 4.0,2019-05-03 20:23:05,91,84,0,0,0,4,true,false,false,true,true,true,47,11,true,0.024,0.0005,6196,2009,12,3,Friday,false,false,false,true,false,false,false
7520432,What is the difference between == and equals() in Java?,"I wanted to clarify if I understand this correctly:
== is a reference comparison, i.e. both objects point to the same memory location
.equals() evaluates to the comparison of values in the objects
",https://stackoverflow.com/questions/7520432/what-is-the-difference-between-and-equals-in-java,801,860648.0,27.0,,,2011-09-22 19:36:43,2023-12-29 07:44:13,2019-11-22 07:33:10,,,java;identity;equality;object-comparison,brainydexter,20544,280924,registered,true,7520464,,CC BY-SA 4.0,2015-03-24 13:54:31,260,200,2,0,0,4,true,false,false,true,true,true,55,10,true,0.031,0.0009,5539,2011,9,19,Thursday,false,false,false,true,false,false,false
960431,How can I convert List<Integer> to int[] in Java?,"How can I convert a List<Integer> to int[] in Java?
I'm confused because List.toArray() actually returns an Object[], which can be cast to neither Integer[] nor int[].
Right now I'm using a loop to do so:
int[] toIntArray(List<Integer> list) {
int[] ret = new int[list.size()];
for(int i = 0; i < ret.length; i++)
ret[i] = list.get(i);
return ret;
}
Is there's a better way to do this?
This is similar to the question
How can I convert int[] to Integer[] in Java?.
",https://stackoverflow.com/questions/960431/how-can-i-convert-listinteger-to-int-in-java,793,861352.0,16.0,,,2009-06-06 20:20:18,2023-04-10 09:08:17,2022-12-28 23:49:53,2018-10-24 11:51:00,Duplicate,java;arrays;collections,unknown,,,does_not_exist,true,960449,,,2013-09-03 19:20:52,733,491,7,1,0,3,true,true,false,true,false,true,55,9,true,0.019,0.0009,6377,2009,6,20,Saturday,true,false,false,true,false,false,false
50683786,Why does array[idx++]+="a" increase idx once in Java 8 but twice in Java 9 and 10?,"For a challenge, a fellow code golfer wrote the following code:
import java.util.*;
public class Main {
public static void main(String[] args) {
int size = 3;
String[] array = new String[size];
Arrays.fill(array, "");
for (int i = 0; i <= 100;) {
array[i++ % size] += i + " ";
}
for (String element: array) {
System.out.println(element);
}
}
}
When running this code in Java 8, we get the following result:
1 4 7 10 13 16 19 22 25 28 31 34 37 40 43 46 49 52 55 58 61 64 67 70 73 76 79 82 85 88 91 94 97 100
2 5 8 11 14 17 20 23 26 29 32 35 38 41 44 47 50 53 56 59 62 65 68 71 74 77 80 83 86 89 92 95 98 101
3 6 9 12 15 18 21 24 27 30 33 36 39 42 45 48 51 54 57 60 63 66 69 72 75 78 81 84 87 90 93 96 99
When running this code in Java 10, we get the following result:
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 100 102
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 100
The numbering is entirely off using Java 10. So what is happening here? Is it a bug in Java 10?
Follow ups from the comments:
The issue appears when compiled with Java 9 or later (we found it in Java 10). Compiling this code on Java 8, then running in Java 9 or any later version, including Java 11 early access, gives the expected result.
This kind of code is non-standard, but is valid according to the spec. It was found by Kevin Cruijssen in a discussion in a golfing challenge, hence the weird use case encountered.
Didier L simplified the issue with this much smaller and more understandable code:
class Main {
public static void main(String[] args) {
String[] array = { "" };
array[test()] += "a";
}
static int test() {
System.out.println("evaluated");
return 0;
}
}
Result when compiled in Java 8:
evaluated
Result when compiled in Java 9 and 10:
evaluated
evaluated
The issue seems to be limited to the string concatenation and assignment operator (+=) with an expression with side effect(s) as the left operand, like in array[test()]+="a", array[ix++]+="a", test()[index]+="a", or test().field+="a". To enable string concatenation, at least one of the sides must have type String. Trying to reproduce this on other types or constructs failed.
",https://stackoverflow.com/questions/50683786/why-does-arrayidx-a-increase-idx-once-in-java-8-but-twice-in-java-9-and-1,792,76100.0,1.0,,,2018-06-04 15:16:14,2026-01-20 15:14:58,2021-11-04 12:46:52,,,java;java-8;javac;java-9;java-10,Olivier Grégoire,35874,180719,registered,true,50686658,,CC BY-SA 4.0,,4638,2666,12,9,0,5,true,false,false,true,true,true,92,16,true,0.013,0.0104,3092,2018,6,15,Monday,false,false,false,true,false,false,false
9572795,Convert list to array in Java,"How can I convert a List to an Array in Java?
Check the code below:
ArrayList<Tienda> tiendas;
List<Tienda> tiendasList;
tiendas = new ArrayList<Tienda>();
Resources res = this.getBaseContext().getResources();
XMLParser saxparser = new XMLParser(marca,res);
tiendasList = saxparser.parse(marca,res);
tiendas = tiendasList.toArray();
this.adaptador = new adaptadorMarca(this, R.layout.filamarca, tiendas);
setListAdapter(this.adaptador);
I need to populate the array tiendas with the values of tiendasList.
",https://stackoverflow.com/questions/9572795/convert-list-to-array-in-java,791,1544695.0,11.0,,,2012-03-05 19:37:28,2020-11-02 09:36:23,2020-01-14 16:41:21,2018-12-18 16:43:09,Duplicate,java;arrays;list;arraylist,colymore,12516,988283,registered,true,9572820,,,,632,535,5,0,0,4,true,true,false,true,true,true,29,6,false,0.007,0.0005,5374,2012,3,19,Monday,false,false,false,true,false,false,false
5905896,IntelliJ inspection gives "Cannot resolve symbol" but still compiles code,"Platform: IntelliJ Community Edition 10.0.3
SDK: jdk1.6.0_21
OS: Windows 7
So I have a strange situation with IntelliJ that has me completely stumped. I setup a Maven project and add log4j as a dependency in the pom.xml file. The IDEA inspections run fine and my unit tests all compile and run.
I then added hunnysoft's jmime library to my local maven repository using the mvn install:install-file as follows.
mvn install:install-file -Dfile=jmime.jar -DgroupId=jmime \
-DartifactId=jmime -Dversion=3.1.1e -Dpackaging=jar
Maven installed the jar file just fine into my local repository.
I then went into IntelliJ's Settings => Maven => Repository Services and Updated my local repository (so that IntelliJ would reindex the repository contents).
Finally, I added the following dependency to my pom.xml file (just above the log4j dependency).
<dependency>
<groupId>jmime</groupId>
<artifactId>jmime</artifactId>
<version>3.1.1e</version>
</dependency>
I now create a new class as follows:
package com.stackoverflow.question;
import org.apache.log4j.Logger;
import com.hunnysoft.jmime.ByteString;
import com.hunnysoft.jmime.Field;
import com.hunnysoft.jmime.FieldBody;
public class StackOverflowQuestion {
public Field create(String name, String text) {
Logger.getLogger(getClass()).debug(""create entered"");
FieldBody body = new FieldBody();
body.setText(new ByteString(text));
Field field = new Field();
field.setFieldName(name);
field.setFieldBody(body);
return field;
}
}
Now for the weirdness. IntelliJ's intention mechanism picks up and recognizes the Logger import in the maven pom file just fine. However, for all of the hunnysoft imports it reports: ""Cannot resolve symbol 'ByteString/Field/FieldBody'"", BUT Build => Compile 'StackOverflowQuestion.java' compiles everything correctly and the unit test I created for this class runs fine (though the intentions mark the call to create() as a problem area too).
So somewhere, somehow IntelliJ is ignoring the jmime.jar file for the intention subsystem. I'm confused because the log4j dependency works fine and everything compiles and runs fine. F12 (""Go To Declaration"") works on the Logger import, but breaks on all the jmime imports.
Oh, one other thing, if I go to the 'Packages' view in the ""Projects"" window the ""com.hunnysoft.jmime"" package appears and I can see ALL of the classes I imported in the code snippet above under ""Libraries"". Removing the above dependency from the pom.xml file causes this package to disappear and the compilation breaks.
It appears that the inspection's classpath is broken, but there does not seem to be a setting for this anywhere in the Settings => Intentions | Compiler areas (not that I expected any such settings, I believe the IDEA should already know the correct classpath based on the pom file and JDK).
As a final experiment I created a brand new standard J2SE application project (without using maven) and added the jmime.jar file directly to the project as one of its libraries. I run into exactly the same problems as described above in this new project.
Here is the MANIFEST.MF from the jmime jar file.
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.5.4
Created-By: 10.0-b23 (Sun Microsystems Inc.)
Name: com/hunnysoft/jmime/
Sealed: true
Specification-Title: Hunny JMIME
Specification-Version: 3.1.1
Specification-Vendor: Hunny Software, Inc.
Implementation-Title: com.hunnysoft.jmime
Implementation-Version: 3.1.1E
Implementation-Vendor: Hunny Software, Inc.
I don't see anything unusual in this jar file.
My best guess is that perhaps the problem might be a missing dependency issue. But AFAIK jmime is supposed to be self contained (JarAnalyzer doesn't come up with anything, but I'm not sure it would if a dependency jar is missing).
So, anyone have any IDEAs?
",https://stackoverflow.com/questions/5905896/intellij-inspection-gives-cannot-resolve-symbol-but-still-compiles-code,790,886483.0,67.0,,,2011-05-06 01:24:08,2025-01-20 19:47:51,2018-03-06 11:03:40,,,java;maven;intellij-idea;intellij-inspections,Kevin Sitze,8320,740904,registered,true,5905931,,CC BY-SA 3.0,2018-10-26 09:52:27,4155,3930,4,0,0,4,true,false,false,true,true,true,83,10,false,0.076,0.0009,5678,2011,5,1,Friday,false,false,false,true,false,false,false
19896870,Why is my Spring @Autowired field null?,"Note: This is intended to be a canonical answer for a common problem.
I have a Spring @Service class (MileageFeeCalculator) that has an @Autowired field (rateService), but the field is null when I try to use it. The logs show that both the MileageFeeCalculator bean and the MileageRateService bean are being created, but I get a NullPointerException whenever I try to call the mileageCharge method on my service bean. Why isn't Spring autowiring the field?
Controller class:
@Controller
public class MileageFeeController {
@RequestMapping("/mileage/{miles}")
@ResponseBody
public float mileageFee(@PathVariable int miles) {
MileageFeeCalculator calc = new MileageFeeCalculator();
return calc.mileageCharge(miles);
}
}
Service class:
@Service
public class MileageFeeCalculator {
@Autowired
private MileageRateService rateService; // <--- should be autowired, is null
public float mileageCharge(final int miles) {
return (miles * rateService.ratePerMile()); // <--- throws NPE
}
}
Service bean that should be autowired in MileageFeeCalculator but it isn't:
@Service
public class MileageRateService {
public float ratePerMile() {
return 0.565f;
}
}
When I try to GET /mileage/3, I get this exception:
java.lang.NullPointerException: null
at com.chrylis.example.spring_autowired_npe.MileageFeeCalculator.mileageCharge(MileageFeeCalculator.java:13)
at com.chrylis.example.spring_autowired_npe.MileageFeeController.mileageFee(MileageFeeController.java:14)
...
",https://stackoverflow.com/questions/19896870/why-is-my-spring-autowired-field-null,788,786700.0,23.0,,,2013-11-11 00:05:03,2026-02-02 11:40:47,2024-01-04 17:01:25,,,java;spring;null;nullpointerexception;autowired,chrylis -cautiouslyoptimistic-,77527,1189885,registered,true,19896871,,CC BY-SA 4.0,2014-05-08 15:21:22,1854,1564,15,0,0,5,true,false,false,true,true,true,39,7,true,0.029,0.001,4758,2013,11,0,Monday,false,false,false,true,false,false,false
4105331,How do I convert from int to String?,"I'm working on a project where all conversions from int to String are done like this:
int i = 5;
String strI = """" + i;
I'm not familiar with Java.
Is this usual practice or is something wrong, as I suppose?
",https://stackoverflow.com/questions/4105331/how-do-i-convert-from-int-to-string,786,2318220.0,21.0,,,2010-11-05 11:11:21,2023-09-28 22:52:28,2020-04-19 17:46:12,,,java;string;type-conversion,Denis Palnitsky,18397,238123,registered,true,4105406,,CC BY-SA 4.0,2013-07-09 17:52:47,283,212,3,0,0,3,true,false,false,true,true,true,36,8,true,0.009,0.0003,5860,2010,11,11,Friday,false,false,false,true,false,false,false
1249973,How to decompile DEX into Java source code?,"How can one decompile Android DEX (VM bytecode) files into corresponding Java source code?
",https://stackoverflow.com/questions/1249973/how-to-decompile-dex-into-java-source-code,786,692195.0,18.0,,,2009-08-08 21:39:45,2026-02-28 07:43:43,2022-10-26 17:45:07,,,java;android;reverse-engineering;decompiler;dex,Will,76141,15721,registered,true,4177581,,CC BY-SA 4.0,2013-05-12 20:01:18,98,91,0,0,0,5,true,false,false,true,true,true,43,8,true,0.026,0.0011,6314,2009,8,21,Saturday,true,false,false,true,false,false,false
160970,How do I invoke a Java method when given the method name as a string?,"If I have two variables:
Object obj;
String methodName = ""getName"";
Without knowing the class of obj, how can I call the method identified by methodName on it?
The method being called has no parameters, and a String return value. It's a getter for a Java bean.
",https://stackoverflow.com/questions/160970/how-do-i-invoke-a-java-method-when-given-the-method-name-as-a-string,784,1122087.0,23.0,,,2008-10-02 05:15:43,2023-06-25 09:52:53,2013-01-24 08:20:50,,,java;reflection;invoke,brasskazoo,79876,6340,registered,true,161005,,CC BY-SA 3.0,2023-02-14 21:05:59,358,265,4,0,0,3,true,false,false,true,true,true,69,15,true,0.02,0.0007,6624,2008,10,5,Thursday,false,false,false,true,false,false,false
5455014,Ignoring new fields on JSON objects using Jackson,"I'm using Jackson JSON library to convert some JSON objects to POJO classes on an android application. The problem is, the JSON objects might change and have new fields added while the application is published, but currently it will break even when a simple String field is added, which can safely be ignored.
Is there any way to tell Jackson to ignore newly added fields? (e.g. non-existing on the POJO objects)? A global ignore would be great.
",https://stackoverflow.com/questions/5455014/ignoring-new-fields-on-json-objects-using-jackson,783,816417.0,12.0,,,2011-03-28 05:26:16,2021-03-02 13:19:05,2017-07-19 10:29:10,2018-11-12 16:49:53,Duplicate,java;json;jackson,Hadi Eskandari,26564,54538,registered,true,5455563,,,,462,448,0,0,0,3,true,true,false,true,true,true,49,8,false,0.015,0.001,5717,2011,3,5,Monday,false,false,false,true,false,false,false
1625234,How to append text to an existing file in Java?,"I need to append text repeatedly to an existing file in Java. How do I do that?
",https://stackoverflow.com/questions/1625234/how-to-append-text-to-an-existing-file-in-java,781,1268752.0,31.0,,,2009-10-26 14:43:50,2024-04-22 09:33:18,2020-08-13 20:37:33,,,java;file-io;io;text-files,flyingfromchina,9721,193304,registered,true,1625263,,CC BY-SA 4.0,2018-08-26 09:41:31,87,80,0,0,0,4,true,false,false,true,true,true,47,10,true,0.024,0.0006,6235,2009,10,14,Monday,false,false,false,true,false,false,false
122105,How to filter a Java Collection (based on predicate)?,"I want to filter a java.util.Collection based on a predicate.
",https://stackoverflow.com/questions/122105/how-to-filter-a-java-collection-based-on-predicate,777,910266.0,29.0,,,2008-09-23 16:26:26,2024-04-13 19:56:58,2021-08-27 07:29:40,,,java;collections;filter,Kevin Wong,14962,4792,registered,true,1385698,,CC BY-SA 4.0,2015-06-16 21:34:04,82,62,1,0,0,3,true,false,false,true,true,true,53,9,true,0.032,0.0009,6633,2008,9,16,Tuesday,false,false,false,true,false,false,false
6115896,Understanding checked vs unchecked exceptions in Java,"Joshua Bloch in ""Effective Java"" said that
Use checked exceptions for
recoverable conditions and runtime
exceptions for programming errors
(Item 58 in 2nd edition)
Let's see if I understand this correctly.
Here is my understanding of a checked exception:
try{
String userInput = //read in user input
Long id = Long.parseLong(userInput);
}catch(NumberFormatException e){
id = 0; //recover the situation by setting the id to 0
}
1. Is the above considered a checked exception?
2. Is RuntimeException an unchecked exception?
Here is my understanding of an unchecked exception:
try{
File file = new File(""my/file/path"");
FileInputStream fis = new FileInputStream(file);
}catch(FileNotFoundException e){
//3. What should I do here?
//Should I ""throw new FileNotFoundException(""File not found"");""?
//Should I log?
//Or should I System.exit(0);?
}
4. Now, couldn't the above code also be a checked exception? I can try to recover the situation like this? Can I? (Note: my 3rd question is inside the catch above)
try{
String filePath = //read in from user input file path
File file = new File(filePath);
FileInputStream fis = new FileInputStream(file);
}catch(FileNotFoundException e){
//Kindly prompt the user an error message
//Somehow ask the user to re-enter the file path.
}
5. Why do people do this?
public void someMethod throws Exception{
}
Why do they let the exception bubble up? Isn't handling the error sooner better? Why bubble up?
6. Should I bubble up the exact exception or mask it using Exception?
Below are my readings
In Java, when should I create a checked exception, and when should it be a runtime exception?
When to choose checked and unchecked exceptions
",https://stackoverflow.com/questions/6115896/understanding-checked-vs-unchecked-exceptions-in-java,775,370989.0,21.0,,,2011-05-24 19:38:31,2026-01-12 02:12:36,2019-10-07 14:18:19,,,java;exception;runtimeexception;checked-exceptions;unchecked-exception,Thang Pham,38793,240337,registered,true,6116020,,CC BY-SA 4.0,2013-08-05 13:00:57,2348,1764,5,2,0,5,true,false,false,true,true,true,53,7,false,0.057,0.0021,5660,2011,5,19,Tuesday,false,false,false,true,false,false,false
5192512,How can I clear or empty a StringBuilder?,"I'm using a StringBuilder in a loop and every x iterations I want to empty it and start with an empty StringBuilder, but I can't see any method similar to the .NET StringBuilder.Clear in the documentation, just the delete method which seems overly complicated.
So what is the best way to clean out a StringBuilder in Java?
",https://stackoverflow.com/questions/5192512/how-can-i-clear-or-empty-a-stringbuilder,769,777199.0,9.0,,,2011-03-04 10:26:19,2021-04-13 08:09:38,2018-02-08 01:15:35,2015-10-14 02:34:07,Duplicate,java;stringbuilder,Hans Olsson,55137,306651,registered,true,5192545,,,2018-02-08 19:02:43,713,324,2,3,0,2,true,true,false,true,true,true,41,8,true,0.012,0.001,5741,2011,3,10,Friday,false,false,false,true,false,false,false
2990799,Difference between FetchType LAZY and EAGER in Java Persistence API?,"What is the difference between FetchType.LAZY and FetchType.EAGER in Java Persistence API?
",https://stackoverflow.com/questions/2990799/difference-between-fetchtype-lazy-and-eager-in-java-persistence-api,763,824600.0,18.0,,,2010-06-07 15:28:44,2024-09-04 01:04:10,2023-01-10 00:10:26,,,java;hibernate;jpa;orm,leon,10455,324968,registered,true,2991015,,CC BY-SA 4.0,,324,91,2,2,0,4,true,false,false,true,true,true,68,10,true,0.022,0.0009,6011,2010,6,15,Monday,false,false,false,true,false,false,false
1873995,Run a single test method with maven,"I know you can run all the tests in a certain class using:
mvn test -Dtest=classname
But I want to run an individual method and -Dtest=classname.methodname doesn't seem to work.
",https://stackoverflow.com/questions/1873995/run-a-single-test-method-with-maven,762,592474.0,14.0,,,2009-12-09 13:44:44,2025-10-15 09:46:54,2020-09-25 03:14:27,,,java;maven;unit-testing;maven-2;maven-3,BillMan,10244,227986,registered,true,5988315,,CC BY-SA 4.0,2020-09-24 08:09:57,220,182,1,0,0,5,true,false,false,true,true,true,35,7,false,0.024,0.0013,6191,2009,12,13,Wednesday,false,false,false,true,false,false,false
1386275,Why is Java Vector (and Stack) class considered obsolete or deprecated?,"Why is Java Vector considered a legacy class, obsolete or deprecated?
Isn't its use valid when working with concurrency?
And if I don't want to manually synchronize objects and just want to use a thread-safe collection without needing to make fresh copies of the underlying array (as CopyOnWriteArrayList does), then is it fine to use Vector?
What about Stack, which is a subclass of Vector, what should I use instead of it?
",https://stackoverflow.com/questions/1386275/why-is-java-vector-and-stack-class-considered-obsolete-or-deprecated,756,254595.0,5.0,,,2009-09-06 18:04:09,2020-03-06 11:32:47,2018-05-16 00:28:39,,,java;vector;stack;deprecated;obsolete,fjsj,11300,145349,registered,true,1386288,,CC BY-SA 4.0,2013-10-28 11:59:08,508,428,4,0,0,5,true,false,false,true,true,true,71,11,true,0.02,0.003,6285,2009,9,18,Sunday,true,false,false,true,false,false,false
2758224,What are assertions in Java and when should they be used?,"What are some real life examples to understand the key role of the Java assert keyword?
",https://stackoverflow.com/questions/2758224/what-are-assertions-in-java-and-when-should-they-be-used,755,634126.0,20.0,,,2010-05-03 13:11:56,2024-08-09 06:57:24,2023-04-15 18:04:45,,,java;assertion,Praveen,91355,267269,registered,true,2758645,,CC BY-SA 4.0,2013-04-30 09:08:01,125,88,1,0,0,2,true,false,false,true,true,true,57,11,true,0.032,0.0012,6046,2010,5,13,Monday,false,false,false,true,false,false,false
10604298,Spring: @Component versus @Bean,"I understand that @Component annotation was introduced in Spring 2.5 to get rid of XML bean definition by using classpath scanning.
@Bean was introduced in spring 3.0 and can be used with @Configuration to fully get rid of XML file and use Java config instead.
Would it have been possible to re-use the @Component annotation instead of introducing the @Bean annotation? My understanding is that the final goal is to create beans in both cases.
",https://stackoverflow.com/questions/10604298/spring-component-versus-bean,753,520178.0,17.0,,,2012-05-15 15:45:46,2025-06-19 05:23:26,2024-01-04 11:30:43,,,java;spring;annotations;autowired,user1396576,7651,1396576,registered,true,,,CC BY-SA 4.0,,543,444,6,0,0,4,false,false,false,true,true,true,31,4,false,0.033,0.0014,5303,2012,5,15,Tuesday,false,false,false,true,false,false,false
1751844,Java: convert List<String> to a join()d String,"JavaScript has Array.join()
js>["Bill","Bob","Steve"].join(" and ")
Bill and Bob and Steve
Does Java have anything like this? I know I can cobble something up myself with StringBuilder:
static public String join(List<String> list, String conjunction)
{
StringBuilder sb = new StringBuilder();
boolean first = true;
for (String item : list)
{
if (first)
first = false;
else
sb.append(conjunction);
sb.append(item);
}
return sb.toString();
}
.. but there's no point in doing this if something like it is already part of the JDK.
",https://stackoverflow.com/questions/1751844/java-convert-liststring-to-a-joind-string,749,639204.0,23.0,,,2009-11-17 21:15:14,2025-11-04 09:29:49,2021-08-24 17:32:51,,,java;string;list,Jason S,191310,44330,registered,true,22577565,,CC BY-SA 4.0,2013-09-02 21:21:21,727,632,4,0,0,3,true,false,false,true,true,true,52,7,false,0.036,0.0012,6213,2009,11,21,Tuesday,false,false,false,true,false,false,false
1168345,Why do this() and super() have to be the first statement in a constructor?,"Java requires that if you call this() or super() in a constructor, it must be the first statement. Why?
For example:
public class MyClass {
public MyClass(int x) {}
}
public class MySubClass extends MyClass {
public MySubClass(int a, int b) {
int c = a + b;
super(c); // COMPILE ERROR
}
}
The Sun compiler says, call to super must be first statement in constructor. The Eclipse compiler says, Constructor call must be the first statement in a constructor.
However, you can get around this by re-arranging the code a little bit:
public class MySubClass extends MyClass {
public MySubClass(int a, int b) {
super(a + b); // OK
}
}
Here is another example:
public class MyClass {
public MyClass(List list) {}
}
public class MySubClassA extends MyClass {
public MySubClassA(Object item) {
// Create a list that contains the item, and pass the list to super
List list = new ArrayList();
list.add(item);
super(list); // COMPILE ERROR
}
}
public class MySubClassB extends MyClass {
public MySubClassB(Object item) {
// Create a list that contains the item, and pass the list to super
super(Arrays.asList(new Object[] { item })); // OK
}
}
So, it is not stopping you from executing logic before the call to super(). It is just stopping you from executing logic that you can't fit into a single expression.
There are similar rules for calling this(). The compiler says, call to this must be first statement in constructor.
Why does the compiler have these restrictions? Can you give a code example where, if the compiler did not have this restriction, something bad would happen?
",https://stackoverflow.com/questions/1168345/why-do-this-and-super-have-to-be-the-first-statement-in-a-constructor,749,361872.0,23.0,,,2009-07-22 21:25:15,2025-10-01 05:18:59,2022-06-23 10:18:34,,,java;constructor,Joe Daley,46608,31563,registered,true,,,CC BY-SA 4.0,,1928,1692,10,0,0,2,false,false,false,true,true,true,74,14,true,0.064,0.0021,6331,2009,7,21,Wednesday,false,false,false,true,false,false,false
260666,Can an abstract class have a constructor?,"Can an abstract class have a constructor?
If so, how can it be used and for what purposes?
",https://stackoverflow.com/questions/260666/can-an-abstract-class-have-a-constructor,747,819724.0,22.0,,,2008-11-04 02:46:21,2021-10-29 12:09:15,2016-10-17 13:41:23,,,java;constructor;abstract-class,Szere Dyeri,15334,33885,registered,true,260755,,CC BY-SA 3.0,2015-09-14 10:42:34,106,92,0,0,0,3,true,false,false,true,true,true,41,7,true,0.027,0.0009,6591,2008,11,2,Tuesday,false,false,false,true,false,false,false
8215308,Using context in a fragment,"How can I get the context in a fragment?
I need to use my database whose constructor takes in the context, but getApplicationContext() and FragmentClass.this don't work so what can I do?
Database constructor
public Database(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
",https://stackoverflow.com/questions/8215308/using-context-in-a-fragment,746,657016.0,30.0,,,2011-11-21 16:46:29,2022-07-22 11:10:41,2022-07-22 11:09:29,,,java;android;android-fragments;android-context,tyczj,74905,599346,registered,true,8215398,,CC BY-SA 4.0,2018-07-27 18:43:17,381,310,3,0,0,4,true,false,false,true,true,true,27,5,false,0.046,0.0011,5479,2011,11,16,Monday,false,false,false,true,false,false,false
364114,Can I add JAR files to Maven 2 build classpath without installing them?,"Maven 2 is driving me crazy during the experimentation / quick and dirty mock-up phase of development.
I have a pom.xml file that defines the dependencies for the web application framework I want to use, and I can quickly generate starter projects from that file.
However, sometimes I want to link to a third-party library that doesn't already have a pom.xml file defined, so rather than create the pom.xml file for the third-party library by hand and install it, and add the dependency to my pom.xml file, I would just like to tell Maven: "In addition to my defined dependencies, include any JAR files that are in /lib too."
It seems like this ought to be simple, but if it is, I am missing something.
Any pointers on how to do this are greatly appreciated. Short of that, if there is a simple way to point Maven to a /lib directory and easily create a pom.xml with all the enclosed JAR files mapped to a single dependency which I could then name / install and link to in one fell swoop would also suffice.
",https://stackoverflow.com/questions/364114/can-i-add-jar-files-to-maven-2-build-classpath-without-installing-them,746,466706.0,25.0,,,2008-12-12 20:57:31,2025-07-29 20:11:31,2025-07-29 16:45:49,,,java;maven-2,purple,,,does_not_exist,true,,,CC BY-SA 4.0,2011-01-12 19:09:58,1226,1018,4,1,0,2,false,false,false,true,false,true,71,13,true,0.054,0.0016,6553,2008,12,20,Friday,false,false,false,true,false,false,false
1154008,Any way to declare an array in-line?,"Let's say I have a method m() that takes an array of strings as an argument. Is there a way I can just declare this array in-line when I make the call, i.e. instead of
String[] strs = {"blah", "hey", "yo"};
m(strs);
Can I just replace this with one line, and avoid declaring a named variable that I'm never going to use?
",https://stackoverflow.com/questions/1154008/any-way-to-declare-an-array-in-line,738,485936.0,8.0,,,2009-07-20 14:44:51,2025-02-11 19:22:53,2025-02-11 19:22:53,,,java;arrays,DivideByHero,20445,60006,registered,true,1154027,,CC BY-SA 4.0,,403,352,2,0,0,2,true,false,false,true,true,true,36,7,true,0.016,0.0015,6333,2009,7,14,Monday,false,false,false,true,false,false,false
18410035,Ways to iterate over a list in Java,"Being somewhat new to the Java language I'm trying to familiarize myself with all the ways (or at least the non-pathological ones) that one might iterate through a list (or perhaps other collections) and the advantages or disadvantages of each.
Given a List<E> list object, I know of the following ways to loop through all elements:
Basic for loop (of course, there're equivalent while / do while loops as well)
// Not recommended (see below)!
for (int i = 0; i < list.size(); i++) {
E element = list.get(i);
// 1 - can call methods of element
// 2 - can use 'i' to make index-based calls to methods of list
// ...
}
Note: As @amarseillan pointed out, this form is a poor choice
for iterating over Lists, because the actual implementation of
the get method may not be as efficient as when using an Iterator.
For example, LinkedList implementations must traverse all of
the elements preceding i to get the i-th element.
In the above example there's no way for the List implementation to
""save its place"" to make future iterations more efficient.
For an ArrayList it doesn't really matter, because the complexity/cost of get is constant time (O(1)) whereas for a LinkedList is it proportional to the size of the list (O(n)).
For more information about the computational complexity of the built-in Collections implementations, check out this question.
Enhanced for loop (nicely explained in this question)
for (E element : list) {
// 1 - can call methods of element
// ...
}
Iterator
for (Iterator<E> iter = list.iterator(); iter.hasNext(); ) {
E element = iter.next();
// 1 - can call methods of element
// 2 - can use iter.remove() to remove the current element from the list
// ...
}
ListIterator
for (ListIterator<E> iter = list.listIterator(); iter.hasNext(); ) {
E element = iter.next();
// 1 - can call methods of element
// 2 - can use iter.remove() to remove the current element from the list
// 3 - can use iter.add(...) to insert a new element into the list
// between element and iter->next()
// 4 - can use iter.set(...) to replace the current element
// ...
}
Functional Java
list.stream().map(e -> e + 1); // Can apply a transformation function for e
Iterable.forEach, Stream.forEach, ...
(A map method from Java 8's Stream API (see @i_am_zero's answer).)
In Java 8 collection classes that implement Iterable (for example, all Lists) now have a forEach method, which can be used instead of the for loop statement demonstrated above. (Here is another question that provides a good comparison.)
Arrays.asList(1,2,3,4).forEach(System.out::println);
// 1 - can call methods of an element
// 2 - would need reference to containing object to remove an item
// (TODO: someone please confirm / deny this)
// 3 - functionally separates iteration from the action
// being performed with each item.
Arrays.asList(1,2,3,4).stream().forEach(System.out::println);
// Same capabilities as above plus potentially greater
// utilization of parallelism
// (caution: consequently, order of execution is not guaranteed,
// see [Stream.forEachOrdered][stream-foreach-ordered] for more
// information about this).
What other ways are there, if any?
(BTW, my interest does not stem at all from a desire to optimize performance; I just want to know what forms are available to me as a developer.)
",https://stackoverflow.com/questions/18410035/ways-to-iterate-over-a-list-in-java,733,1422604.0,13.0,,,2013-08-23 19:00:14,2025-05-02 13:23:54,2018-02-23 17:22:48,,,java;loops;collections;iteration,jacobq,11683,1171509,registered,true,18410489,,CC BY-SA 3.0,2014-11-23 03:32:38,5239,3426,21,13,0,4,true,false,false,true,true,true,35,8,false,0.009,0.0005,4838,2013,8,19,Friday,false,false,false,true,false,false,false
6992608,Why there is no ConcurrentHashSet against ConcurrentHashMap,"HashSet is based on HashMap.
If we look at HashSet<E> implementation, everything is been managed under HashMap<E,Object>.
<E> is used as a key of HashMap.
And we know that HashMap is not thread safe. That is why we have ConcurrentHashMap in Java.
Based on this, I am confused that why we don't have a ConcurrentHashSet which should be based on the ConcurrentHashMap?
Is there anything else that I am missing? I need to use Set in a multi-threaded environment.
Also, If I want to create my own ConcurrentHashSet can I achieve it by just replacing the HashMap to ConcurrentHashMap and leaving the rest as is?
",https://stackoverflow.com/questions/6992608/why-there-is-no-concurrenthashset-against-concurrenthashmap,731,355796.0,11.0,,,2011-08-09 07:14:29,2024-03-01 12:13:00,2013-11-25 17:57:17,,,java;collections;concurrency;hashmap;hashset,Talha Ahmed Khan,15671,358163,registered,true,6992643,,CC BY-SA 3.0,,840,631,11,0,0,5,true,false,false,true,true,true,59,7,false,0.031,0.0021,5583,2011,8,7,Tuesday,false,false,false,true,false,false,false
7026507,Why are static variables considered evil?,"I am a Java programmer who is new to the corporate world. Recently I've developed an application using Groovy and Java. All through the code I wrote used quite a good number of statics. I was asked by the senior technical lot to cut down on the number of statics used. I've googled about the same, and I find that many programmers are fairly against using static variables.
I find static variables more convenient to use. And I presume that they are efficient too (please correct me if I am wrong), because if I had to make 10,000 calls to a function within a class, I would be glad to make the method static and use a straightforward Class.methodCall() on it instead of cluttering the memory with 10,000 instances of the class, right?
Moreover statics reduce the inter-dependencies on the other parts of the code. They can act as perfect state holders. Adding to this I find that statics are widely implemented in some languages like Smalltalk and Scala. So why is this opposition to statics prevalent among programmers (especially in the world of Java)?
PS: please do correct me if my assumptions about statics are wrong.
",https://stackoverflow.com/questions/7026507/why-are-static-variables-considered-evil,730,314363.0,32.0,,,2011-08-11 13:14:37,2024-11-02 23:57:59,2021-07-29 04:44:50,,,java;static,Vamsi Emani,10362,619361,registered,true,7026563,,CC BY-SA 4.0,,1423,1124,1,3,0,2,true,false,false,true,true,true,41,6,true,0.102,0.0023,5581,2011,8,13,Thursday,false,false,false,true,false,false,false
1560788,How to check internet access on Android? InetAddress never times out,"I got a AsyncTask that is supposed to check the network access to a host name. But the doInBackground() is never timed out. Anyone have a clue?
public class HostAvailabilityTask extends AsyncTask<String, Void, Boolean> {
private Main main;
public HostAvailabilityTask(Main main) {
this.main = main;
}
protected Boolean doInBackground(String... params) {
Main.Log(""doInBackground() isHostAvailable():""+params[0]);
try {
return InetAddress.getByName(params[0]).isReachable(30);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean... result) {
Main.Log(""onPostExecute()"");
if(result[0] == false) {
main.setContentView(R.layout.splash);
return;
}
main.continueAfterHostCheck();
}
}
",https://stackoverflow.com/questions/1560788/how-to-check-internet-access-on-android-inetaddress-never-times-out,729,523479.0,64.0,,,2009-10-13 14:59:51,2023-01-03 16:29:05,2021-03-07 17:28:26,,,java;android;android-asynctask;android-networking,Vidar Vestnes,43064,133858,registered,true,27312494,,CC BY-SA 4.0,2016-11-27 22:56:52,1043,986,3,0,0,4,true,false,false,true,true,true,68,11,false,0.122,0.0014,6248,2009,10,14,Tuesday,false,false,false,true,false,false,false
23696317,Find first element by predicate,"I've just started playing with Java 8 lambdas and I'm trying to implement some of the things that I'm used to in functional languages.
For example, most functional languages have some kind of find function that operates on sequences, or lists that returns the first element, for which the predicate is true. The only way I can see to achieve this in Java 8 is:
lst.stream()
.filter(x -> x > 5)
.findFirst()
However this seems inefficient to me, as the filter will scan the whole list, at least to my understanding (which could be wrong). Is there a better way?
",https://stackoverflow.com/questions/23696317/find-first-element-by-predicate,729,688864.0,9.0,,,2014-05-16 13:28:19,2024-07-28 14:52:30,2017-09-06 19:44:57,,,java;java-8;java-stream,siki,9557,2163864,registered,true,23696571,,CC BY-SA 3.0,2020-12-03 15:13:15,639,581,2,0,0,3,true,false,false,true,true,true,31,5,false,0.013,0.0011,4572,2014,5,13,Friday,false,false,false,true,false,false,false
3144940,Set ImageView width and height programmatically?,"How can I set an ImageView's width and height programmatically?
",https://stackoverflow.com/questions/3144940/set-imageview-width-and-height-programmatically,726,648164.0,15.0,,,2010-06-29 21:36:28,2020-10-14 06:59:36,2020-01-23 15:15:21,,,java;android;android-emulator;android-widget,praveenb,10677,341443,registered,true,5257851,,CC BY-SA 4.0,,84,64,1,0,0,4,true,false,false,true,true,true,48,6,true,0.023,0.0011,5989,2010,6,21,Tuesday,false,false,false,true,false,false,false
19655184,No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?,"I'm compiling a project in Eclipse using m2eclipse. I set the JDK path in Eclipse like this:
Windows-->preferences-->installed jres--> jdk1.7.xx path
But this is showing an error
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
[INFO] 1 error
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.424s
[INFO] Finished at: Tue Oct 29 15:21:01 IST 2013
[INFO] Final Memory: 5M/15M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler- plugin:3.1:compile (default-compile) on project TEST-WEB: Compilation failure
[ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
",https://stackoverflow.com/questions/19655184/no-compiler-is-provided-in-this-environment-perhaps-you-are-running-on-a-jre-ra,725,1562519.0,38.0,,,2013-10-29 10:11:50,2022-06-15 08:32:13,2016-12-31 00:59:38,,,java;eclipse;maven;java-7;m2eclipse,Sai prateek,11956,2841472,registered,true,21279068,,CC BY-SA 3.0,2014-09-10 05:41:33,1166,1104,2,0,0,5,true,false,false,true,true,true,96,18,true,0.024,0.0005,4771,2013,10,10,Tuesday,false,false,false,true,false,false,false
509076,How do I address unchecked cast warnings?,"Eclipse is giving me a warning of the following form:
Type safety: Unchecked cast from Object to HashMap
This is from a call to an API that I have no control over which returns Object:
HashMap<String, String> getItems(javax.servlet.http.HttpSession session) {
HashMap<String, String> theHash = (HashMap<String, String>)session.getAttribute(""attributeKey"");
return theHash;
}
I'd like to avoid Eclipse warnings, if possible, since theoretically they indicate at least a potential code problem. I haven't found a good way to eliminate this one yet, though. I can extract the single line involved out to a method by itself and add @SuppressWarnings(""unchecked"") to that method, thus limiting the impact of having a block of code where I ignore warnings. Any better options? I don't want to turn these warnings off in Eclipse.
Before I came to the code, it was simpler, but still provoked warnings:
HashMap getItems(javax.servlet.http.HttpSession session) {
HashMap theHash = (HashMap)session.getAttribute(""attributeKey"");
return theHash;
}
Problem was elsewhere when you tried to use the hash you'd get warnings:
HashMap items = getItems(session);
items.put(""this"", ""that"");
Type safety: The method put(Object, Object) belongs to the raw type HashMap. References to generic type HashMap<K,V> should be parameterized.
",https://stackoverflow.com/questions/509076/how-do-i-address-unchecked-cast-warnings,725,566972.0,22.0,,,2009-02-03 21:57:47,2022-09-02 12:08:53,2017-03-28 21:27:11,,,java;generics;warnings,skiphoppy,104505,18103,registered,true,509230,,CC BY-SA 3.0,2022-09-03 12:37:56,1519,1367,4,0,0,3,true,false,false,true,true,true,41,7,true,0.039,0.0013,6500,2009,2,21,Tuesday,false,false,false,true,false,false,false
7414794,Difference between <context:annotation-config> and <context:component-scan>,"I'm learning Spring 3 and I don't seem to grasp the functionality behind <context:annotation-config> and <context:component-scan>.
From what I've read they seem to handle different annotations (@Required, @Autowired etc vs @Component, @Repository, @Service etc), but also from what I've read, they register the same bean post processor classes.
To confuse me even more, there is an annotation-config attribute on <context:component-scan>.
Can someone shed some light on these tags? What's similar and what's different, is one superseded by the other, do they complete each other, do I need one of them or both?
",https://stackoverflow.com/questions/7414794/difference-between-contextannotation-config-and-contextcomponent-scan,724,357483.0,15.0,,,2011-09-14 10:28:33,2024-01-04 11:23:59,2024-01-04 11:23:59,,,java;configuration;annotations;spring-3,user938214097,7241,944383,unregistered,true,,,CC BY-SA 4.0,2018-09-07 12:08:09,814,629,10,0,0,4,false,false,false,true,true,true,87,5,false,0.042,0.002,5547,2011,9,10,Wednesday,false,false,false,true,false,false,false
513832,How do I compare strings in Java?,"I've been using the == operator in my program to compare all my strings so far.
However, I ran into a bug, changed one of them into .equals() instead, and it fixed the bug.
Is == bad? When should it and should it not be used? What's the difference?
",https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java,723,4857413.0,23.0,,,2009-02-04 23:17:07,2023-11-20 14:05:47,2013-01-23 13:36:07,,,java;string;equality,Nathan H,49811,25645,registered,true,513839,,CC BY-SA 3.0,2014-01-31 05:20:23,303,250,3,0,0,3,true,false,false,true,true,true,33,7,true,0.005,0.0001,6499,2009,2,23,Wednesday,false,false,false,true,false,false,false
9170832,List of Java class file format major version numbers?,"I saw this list of major version numbers for Java in another post:
Java
Major version
26
70
25
69
24
68
23
67
22
66
21
65
20
64
19
63
18
62
17
61
16
60
15
59
14
58
13
57
12
56
11
55
10
54
9
53
8
52
7
51
6
50
5
49
1.4
48
1.3
47
1.2
46
1.1
45
1.0.2
45
Where does this list come from? Is there a specific reference for this? Preferably something that shows minor versions too?
",https://stackoverflow.com/questions/9170832/list-of-java-class-file-format-major-version-numbers,720,715517.0,7.0,,,2012-02-07 04:01:07,2026-04-04 20:25:02,2026-04-04 20:25:02,,,java;version,Robert Mark Bram,10169,257233,registered,true,9170852,,CC BY-SA 4.0,2021-04-23 04:04:29,2788,436,0,0,0,2,true,false,false,true,true,true,53,9,true,0.01,0.001,5401,2012,2,4,Tuesday,false,false,false,true,false,false,false
156275,"What is the equivalent of the C++ Pair<L,R> in Java?","Is there a good reason why there is no Pair<L,R> in Java? What would be the equivalent of this C++ construct? I would rather avoid reimplementing my own.
It seems that 1.6 is providing something similar (AbstractMap.SimpleEntry<K,V>), but this looks quite convoluted.
",https://stackoverflow.com/questions/156275/what-is-the-equivalent-of-the-c-pairl-r-in-java,718,509654.0,34.0,,,2008-10-01 04:48:41,2023-03-20 15:29:38,2019-03-04 13:04:18,,,java;tuples;std-pair,David Segonds,85273,13673,registered,true,156685,,CC BY-SA 4.0,2018-09-24 20:20:10,338,281,2,0,0,3,true,false,false,true,true,true,58,10,true,0.067,0.0014,6625,2008,10,4,Wednesday,false,false,false,true,false,false,false
5181578,What is the point of "final class" in Java?,"I am reading a book about Java and it says that you can declare the whole class as final. I cannot think of anything where I'd use this.
I am just new to programming and I am wondering if programmers actually use this on their programs. If they do, when do they use it so I can understand it better and know when to use it.
If Java is object oriented, and you declare a class final, doesn't it stop the idea of class having the characteristics of objects?
",https://stackoverflow.com/questions/5181578/what-is-the-point-of-final-class-in-java,712,638008.0,25.0,,,2011-03-03 13:52:23,2024-12-02 02:44:30,2018-05-22 08:10:34,,,java;final,newbie,15048,525965,registered,true,5181618,,CC BY-SA 4.0,2016-06-06 17:51:56,524,460,2,0,0,2,true,false,false,true,true,true,53,9,true,0.039,0.0011,5742,2011,3,13,Thursday,false,false,false,true,false,false,false
450807,How do I make the method return type generic?,"Consider this example (typical in OOP books):
I have an Animal class, where each Animal can have many friends.
And subclasses like Dog, Duck, Mouse etc which add specific behavior like bark(), quack() etc.
Here's the Animal class:
public class Animal {
private Map<String,Animal> friends = new HashMap<>();
public void addFriend(String name, Animal animal){
friends.put(name,animal);
}
public Animal callFriend(String name){
return friends.get(name);
}
}
And here's some code snippet with lots of typecasting:
Mouse jerry = new Mouse();
jerry.addFriend(""spike"", new Dog());
jerry.addFriend(""quacker"", new Duck());
((Dog) jerry.callFriend(""spike"")).bark();
((Duck) jerry.callFriend(""quacker"")).quack();
Is there any way I can use generics for the return type to get rid of the typecasting, so that I can say
jerry.callFriend(""spike"").bark();
jerry.callFriend(""quacker"").quack();
Here's some initial code with return type conveyed to the method as a parameter that's never used.
public<T extends Animal> T callFriend(String name, T unusedTypeObj){
return (T)friends.get(name);
}
Is there a way to figure out the return type at runtime without the extra parameter using instanceof? Or at least by passing a class of the type instead of a dummy instance.
I understand generics are for compile time type-checking, but is there a workaround for this?
",https://stackoverflow.com/questions/450807/how-do-i-make-the-method-return-type-generic,711,963410.0,19.0,,,2009-01-16 15:43:08,2021-09-26 09:52:37,2016-05-16 09:40:02,,,java;generics;return-value,Sathish,21120,51402,registered,true,450874,,CC BY-SA 3.0,,1705,1435,13,0,0,3,true,false,false,true,true,true,45,9,true,0.02,0.0007,6518,2009,1,15,Friday,false,false,false,true,false,false,false
23699371,Distinct by property,"In Java 8, how can I filter a collection using the Stream API by checking the distinctness of a property of each object?
For example, I have a list of Person objects and I want to remove people with the same name:
persons.stream().distinct();
will use the default equality check for a Person object, so I need something like:
persons.stream().distinct(p -> p.getName());
Unfortunately, the distinct() method has no such overload. Without modifying the equality check inside the Person class, is it possible to do this succinctly?
",https://stackoverflow.com/questions/23699371/distinct-by-property,709,629979.0,36.0,,,2014-05-16 15:40:12,2026-07-20 20:16:57,2025-03-06 14:28:02,,,java;collections;java-8;java-stream;distinct-values,RichK,11932,255231,registered,true,27872852,,CC BY-SA 4.0,2019-09-18 12:35:18,676,535,7,0,0,5,true,false,false,true,true,true,20,3,false,0.057,0.0011,4572,2014,5,15,Friday,false,false,false,true,false,false,false
31922866,Why should Java 8's Optional not be used in arguments,"I've read on many Web sites Optional should be used as a return type only, and not used in method arguments. I'm struggling to find a logical reason why. For example I have a piece of logic which has 2 optional parameters. Therefore I think it would make sense to write my method signature like this (solution 1):
public int calculateSomething(Optional<String> p1, Optional<BigDecimal> p2) {
// my logic
}
Many web pages specify Optional should not be used as method arguments. With this in mind, I could use the following method signature and add a clear Javadoc comment to specify that the arguments may be null, hoping future maintainers will read the Javadoc and therefore always carry out null checks prior to using the arguments (solution 2):
public int calculateSomething(String p1, BigDecimal p2) {
// my logic
}
Alternatively I could replace my method with four public methods to provide a nicer interface and make it more obvious p1 and p2 are optional (solution 3):
public int calculateSomething() {
calculateSomething(null, null);
}
public int calculateSomething(String p1) {
calculateSomething(p1, null);
}
public int calculateSomething(BigDecimal p2) {
calculateSomething(null, p2);
}
public int calculateSomething(String p1, BigDecimal p2) {
// my logic
}
Now I try writing the code of the class which invokes this piece of logic for each approach. I first retrieve the two input parameters from another object which returns Optionals and then, I invoke calculateSomething. Therefore, if solution 1 is used the calling code would look like this:
Optional<String> p1 = otherObject.getP1();
Optional<BigInteger> p2 = otherObject.getP2();
int result = myObject.calculateSomething(p1, p2);
if solution 2 is used, the calling code would look like this:
Optional<String> p1 = otherObject.getP1();
Optional<BigInteger> p2 = otherObject.getP2();
int result = myObject.calculateSomething(p1.orElse(null), p2.orElse(null));
if solution 3 is applied, I could use the code above or I could use the following (but it's significantly more code):
Optional<String> p1 = otherObject.getP1();
Optional<BigInteger> p2 = otherObject.getP2();
int result;
if (p1.isPresent()) {
if (p2.isPresent()) {
result = myObject.calculateSomething(p1, p2);
} else {
result = myObject.calculateSomething(p1);
}
} else {
if (p2.isPresent()) {
result = myObject.calculateSomething(p2);
} else {
result = myObject.calculateSomething();
}
}
So my question is: Why is it considered bad practice to use Optionals as method arguments (see solution 1)? It looks like the most readable solution to me and makes it most obvious that the parameters could be empty/null to future maintainers. (I'm aware the designers of Optional intended it to only be used as a return type, but I can't find any logical reasons not to use it in this scenario).
",https://stackoverflow.com/questions/31922866/why-should-java-8s-optional-not-be-used-in-arguments,705,379762.0,28.0,,,2015-08-10 14:58:00,2024-10-11 23:04:48,2023-02-04 08:56:56,,,java;java-8;option-type,Neil Stevens,7475,3918862,registered,true,31923105,,CC BY-SA 4.0,,3221,2959,10,0,0,3,true,false,false,true,true,true,57,10,false,0.074,0.0019,4121,2015,8,14,Monday,false,false,false,true,false,false,false
2020088,Sending Email in Android using JavaMail API without using the default/built-in app,"I am trying to create a mail sending application in Android.
If I use:
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
This will launch the built-in Android application; I'm trying to send the mail on button click directly without using this application.
",https://stackoverflow.com/questions/2020088/sending-email-in-android-using-javamail-api-without-using-the-default-built-in-a,704,480161.0,25.0,,,2010-01-07 12:04:43,2023-03-14 09:10:15,2019-10-21 16:58:00,,,java;android;email;android-intent;jakarta-mail,Vinayak Bevinakatti,40583,28557,registered,true,2033124,,CC BY-SA 4.0,2011-06-12 04:35:55,344,282,1,0,0,5,true,false,false,true,true,true,82,12,false,0.052,0.0015,6162,2010,1,12,Thursday,false,false,false,true,false,false,false
367706,How do I parse command line arguments in Java?,"What is a good way of parsing command line arguments in Java?
",https://stackoverflow.com/questions/367706/how-do-i-parse-command-line-arguments-in-java,700,506364.0,21.0,,,2008-12-15 07:46:10,2025-05-11 14:26:13,2021-03-27 17:38:08,,,java;command-line;command-line-arguments,lindelof,35526,1428,registered,true,367714,,CC BY-SA 4.0,2019-09-24 11:50:52,69,62,0,0,0,3,true,false,false,true,true,true,46,9,true,0.041,0.0014,6550,2008,12,7,Monday,false,false,false,true,false,false,false
3758606,How can I convert byte size into a human-readable format in Java?,"How can I convert byte size into a human-readable format in Java?
Like 1024 should become "1 Kb" and 1024*1024 should become "1 Mb".
I am kind of sick of writing this utility method for each project. Is there a static method in Apache Commons for this?
",https://stackoverflow.com/questions/3758606/how-can-i-convert-byte-size-into-a-human-readable-format-in-java,697,380260.0,31.0,,,2010-09-21 08:42:59,2024-09-09 10:42:35,2020-08-12 18:33:00,,,java;formatting;apache-commons,Igor Mukhin,15566,404615,registered,true,3758880,,CC BY-SA 4.0,2019-12-04 18:02:28,353,273,0,1,0,3,true,false,false,true,true,true,65,12,true,0.082,0.0018,5905,2010,9,8,Tuesday,false,false,false,true,false,false,false
8405087,What is this date format? 2011-08-12T20:17:46.384Z,"I have the following date: 2011-08-12T20:17:46.384Z. What format is this? I'm trying to parse it with Java 1.4 via DateFormat.getDateInstance().parse(dateStr) and I'm getting
java.text.ParseException: Unparseable date: ""2011-08-12T20:17:46.384Z""
I think I should be using SimpleDateFormat for parsing, but I have to know the format string first. All I have for that so far is yyyy-MM-dd, because I don't know what the T means in this string--something time zone-related? This date string is coming from the lcmis:downloadedOn tag shown on Files CMIS download history media type.
",https://stackoverflow.com/questions/8405087/what-is-this-date-format-2011-08-12t201746-384z,693,970011.0,12.0,,,2011-12-06 18:45:57,2024-07-02 16:25:54,,,,java;date;time;format;simpledateformat,cheshire137,31851,38743,registered,true,8405125,,CC BY-SA 3.0,,925,590,5,2,0,5,true,false,false,true,true,false,50,6,false,0.012,0.0007,5464,2011,12,18,Tuesday,false,false,false,true,false,false,false
34413,Why am I getting a NoClassDefFoundError in Java?,"I am getting a NoClassDefFoundError when I run my Java application. What is typically the cause of this?
",https://stackoverflow.com/questions/34413/why-am-i-getting-a-noclassdeffounderror-in-java,691,1225524.0,33.0,,,2008-08-29 14:59:30,2024-08-07 07:00:24,2014-04-11 10:38:15,,,java;noclassdeffounderror,John Meagher,25538,3535,registered,true,34419,,CC BY-SA 3.0,2015-01-18 11:55:43,126,106,1,0,0,2,true,false,false,true,true,true,48,8,true,0.027,0.0006,6658,2008,8,14,Friday,false,false,false,true,false,false,false
6112561,Clearing coverage highlighting in Eclipse,"After running coverage reports in Eclipse (using cobertura or an EMMA plugin), my source code files get highlighted in green, red and yellow depending on which lines of code were covered by tests.
How can I clear this highlighting after I'm done?
",https://stackoverflow.com/questions/6112561/clearing-coverage-highlighting-in-eclipse,690,323454.0,11.0,,,2011-05-24 15:03:24,2025-06-07 06:56:28,2020-01-29 17:15:47,,,java;eclipse;code-coverage;cobertura;emma,Charbel,14777,334179,registered,true,6121432,,CC BY-SA 4.0,,262,248,0,0,0,5,true,false,false,true,true,true,41,5,false,0.034,0.0021,5660,2011,5,15,Tuesday,false,false,false,true,false,false,false
22489398,Unsupported major.minor version 52.0,"Pictures:
Command Prompt showing versions
Picture of error
Hello.java
import java.applet.Applet;
import java.awt.*;
public class Hello extends Applet {
// Java applet to draw ""Hello World""
public void paint (Graphics page) {
page.drawString (""Hello World!"", 50, 50);
}
}
Hello.html
<HTML>
<HEAD>
<TITLE>HelloWorld Applet</TITLE>
</HEAD>
<BODY>
<APPLET CODE=""Hello.class"" WIDTH=300 HEIGHT=150>
</APPLET>
</BODY>
</HTML>
Error
Hello : Unsupported major.minor version 52.0
What may the problem be?
",https://stackoverflow.com/questions/22489398/unsupported-major-minor-version-52-0,689,1952698.0,26.0,,,2014-03-18 19:40:48,2021-04-13 18:01:34,2017-01-14 16:45:05,2016-07-20 06:47:24,Duplicate,java;applet;version;unsupported-class-version,user3397452,7051,3397452,registered,true,,,,2015-06-21 23:31:02,963,632,3,0,2,4,false,true,false,true,true,true,36,4,false,0.013,0.0004,4631,2014,3,19,Tuesday,false,false,false,true,false,false,false
52353,How to determine the size of an object in Java,"I have an application that reads a CSV file with piles of data rows. I give the user a summary of the number of rows based on types of data, but I want to make sure that I don't read in too many rows of data and cause OutOfMemoryErrors. Each row translates into an object. Is there a way to find out the size of that object programmatically? Is there a reference that defines how large primitive types and object references are for a VM?
Right now, I have code that says read up to 32,000 rows, but I'd also like to have code that says read as many rows as possible until I've used 32MB of memory.
",https://stackoverflow.com/questions/52353/how-to-determine-the-size-of-an-object-in-java,688,387923.0,29.0,,,2008-09-09 17:07:03,2025-05-08 08:39:10,2023-02-16 16:10:19,,,java;memory,Jay R.,32209,5074,registered,true,52682,,CC BY-SA 4.0,2020-02-12 15:11:48,672,598,2,0,0,2,true,false,false,true,true,true,46,10,false,0.075,0.0018,6647,2008,9,17,Tuesday,false,false,false,true,false,false,false
12893995,How to check certificate name and alias in keystore files?,"I have a bunch of .keystore files and need to find one with specific CN and alias. Is there a way to do it with keytool, jarsigner or some other tool? I found a way to check if specific keystore was used to sign a specific apk, but I also need to get the alias and certificate name in each of the files.
",https://stackoverflow.com/questions/12893995/how-to-check-certificate-name-and-alias-in-keystore-files,687,1892393.0,12.0,,,2012-10-15 10:46:17,2024-06-04 11:46:52,,,,java;android;keystore,Malthan,7855,117696,registered,true,12894334,,CC BY-SA 3.0,2015-09-11 06:43:28,311,304,0,0,0,3,true,false,false,true,true,false,58,10,true,0.006,0.0004,5150,2012,10,10,Monday,false,false,false,true,false,false,false
216894,Get an OutputStream into a String,"What's the best way to pipe the output from an java.io.OutputStream to a String in Java?
Say I have the method:
writeToStream(Object o, OutputStream out)
Which writes certain data from the object to the given stream. However, I want to get this output into a String as easily as possible.
I'm considering writing a class like this (untested):
class StringOutputStream extends OutputStream {
StringBuilder mBuf;
public void write(int byte) throws IOException {
mBuf.append((char) byte);
}
public String getString() {
return mBuf.toString();
}
}
But is there a better way? I only want to run a test!
",https://stackoverflow.com/questions/216894/get-an-outputstream-into-a-string,686,761750.0,6.0,,,2008-10-19 20:03:23,2022-09-06 08:49:47,2009-06-07 15:16:40,,,java;string;io;stream,Adrian Mouat,47146,4332,registered,true,216913,,CC BY-SA 2.5,,712,629,2,0,0,4,true,false,false,true,true,true,33,6,false,0.008,0.0009,6607,2008,10,20,Sunday,true,false,false,true,false,false,false
1082580,How can I build JAR files from IntelliJ IDEA properly?,"I have a project that contains a single module, and some dependencies.
I'd like to create a JAR file, in a separate directory, that contains the compiled module. In addition, I would like to have the dependencies present beside my module.
No matter how I twist IntelliJ IDEA's "build JAR" file process, the output of my module appears empty (besides a META-INF file).
",https://stackoverflow.com/questions/1082580/how-can-i-build-jar-files-from-intellij-idea-properly,685,974931.0,25.0,,,2009-07-04 17:05:35,2025-05-24 18:27:54,2025-05-24 13:14:17,,,java;intellij-idea;build;jar;artifact,ripper234,232304,11236,registered,true,4901370,,CC BY-SA 4.0,2018-08-16 17:09:06,412,378,1,0,0,5,true,false,false,true,true,true,54,10,true,0.026,0.0007,6349,2009,7,17,Saturday,true,false,false,true,false,false,false
370962,Why can't static methods be abstract in Java?,"The question is in Java why can't I define an abstract static method? for example
abstract class foo {
abstract void bar( ); // <-- this is ok
abstract static void bar2(); //<-- this isn't why?
}
",https://stackoverflow.com/questions/370962/why-cant-static-methods-be-abstract-in-java,685,360992.0,29.0,,,2008-12-16 10:45:27,2023-03-10 05:21:34,2020-06-07 14:12:41,,,java;abstract-class;static-methods,hhafez,39984,42303,registered,true,372544,,CC BY-SA 4.0,,243,212,1,0,0,3,true,false,false,true,true,true,49,8,true,0.08,0.0019,6549,2008,12,10,Tuesday,false,false,false,true,false,false,false
1612334,"Difference between DTO, VO, POJO, JavaBeans?","Have seen some similar questions:
- What is the difference between a JavaBean and a POJO?
- What is the Difference Between POJO (Plain Old Java Object) and DTO (Data Transfer Object)?
Can you also please tell me the contexts in which they are used? Or the purpose of them?
",https://stackoverflow.com/questions/1612334/difference-between-dto-vo-pojo-javabeans,685,590415.0,10.0,,,2009-10-23 09:30:36,2024-12-01 14:05:29,2017-05-23 11:47:36,,,java;terminology;javabeans;dto;pojo,jai,22005,157705,registered,true,1612671,,CC BY-SA 3.0,2019-11-25 16:27:05,527,273,0,2,0,5,true,false,false,true,true,true,44,6,true,0.017,0.0012,6238,2009,10,9,Friday,false,false,false,true,false,false,false
6615516,IntelliJ show JavaDocs tooltip on mouse over,"In Eclipse, when hovering over a method, variable, etc. a tooltip is displayed with the corresponding JavaDocs. Is there such a feature in IntelliJ?
",https://stackoverflow.com/questions/6615516/intellij-show-javadocs-tooltip-on-mouse-over,681,192513.0,22.0,,,2011-07-07 18:42:32,2023-04-10 14:47:08,2018-09-25 17:10:00,,,java;eclipse;ide;intellij-idea,Steve Kuo,63353,24396,registered,true,20746942,,CC BY-SA 4.0,2018-10-26 09:52:17,156,149,0,0,0,4,true,false,false,true,true,true,44,7,false,0.114,0.0035,5616,2011,7,18,Thursday,false,false,false,true,false,false,false
171952,Is there a destructor for Java?,"Is there a destructor for Java? I don't seem to be able to find any documentation on this. If there isn't, how can I achieve the same effect?
To make my question more specific, I am writing an application that deals with data and the specification say that there should be a 'reset' button that brings the application back to its original just launched state. However, all data have to be 'live' unless the application is closed or reset button is pressed.
Being usually a C/C++ programmer, I thought this would be trivial to implement. (And hence I planned to implement it last.) I structured my program such that all the 'reset-able' objects would be in the same class so that I can just destroy all 'live' objects when a reset button is pressed.
I was thinking if all I did was just to dereference the data and wait for the garbage collector to collect them, wouldn't there be a memory leak if my user repeatedly entered data and pressed the reset button? I was also thinking since Java is quite mature as a language, there should be a way to prevent this from happening or gracefully tackle this.
",https://stackoverflow.com/questions/171952/is-there-a-destructor-for-java,681,699347.0,25.0,,,2008-10-05 13:12:25,2024-11-02 22:22:21,2021-11-03 23:55:13,,,java;garbage-collection;destructor;finalize,wai,9163,18500,registered,true,171957,,CC BY-SA 4.0,,1132,1104,0,0,0,4,true,false,false,true,true,true,31,6,true,0.036,0.001,6621,2008,10,13,Sunday,true,false,false,true,false,false,false
1196586,Calling remove in foreach loop in Java,"In Java, is it legal to call remove on a collection when iterating through the collection using a foreach loop? For instance:
List<String> names = ....
for (String name : names) {
// Do something
names.remove(name).
}
As an addendum, is it legal to remove items that have not been iterated over yet? For instance,
//Assume that the names list as duplicate entries
List<String> names = ....
for (String name : names) {
// Do something
while (names.remove(name));
}
",https://stackoverflow.com/questions/1196586/calling-remove-in-foreach-loop-in-java,679,572809.0,11.0,,,2009-07-28 20:39:07,2015-11-22 03:37:30,2009-07-30 20:16:30,2014-11-19 00:03:06,Duplicate,java;loops;iterator;foreach,Michael Bobick,9017,3425,registered,true,1196612,,,,559,497,2,0,0,4,true,true,false,true,true,true,38,7,false,0.019,0.0012,6325,2009,7,20,Tuesday,false,false,false,true,false,false,false
9881611,What's the difference between JPA and Hibernate?,"I understand that JPA 2 is a specification and Hibernate is a tool for ORM. Also, I understand that Hibernate has more features than JPA 2. But from a practical point of view, what really is the difference?
I have experience using iBatis and now I'm trying to learn either Hibernate or JPA2. I picked up Pro JPA2 book and it keeps referring to ""JPA provider"". For example:
If you think a feature should be standardized, you should speak up
and request it from your JPA provider
This confuses me so I have a few questions:
- Using JPA2 alone can I fetch data from DB by simply annotating my POJO's
- Is JPA2 supposed to be used with a ""JPA Provider"" e.g TopLink or Hibernate? If so, then what's the benefit of using JPA2 + Hibernate as compared to JPA2 alone, or compared to Hibernate alone ?
- Can you recommend a good practical JPA2 book. ""Pro JPA2"" seems more like a bible and reference on JPA2 (It doesn't get into Queries until the later half of the book). Is there a book that takes a problem/solution approach to JPA2?
",https://stackoverflow.com/questions/9881611/whats-the-difference-between-jpa-and-hibernate,678,613279.0,22.0,,,2012-03-27 00:04:39,2018-03-20 18:12:20,2018-03-20 18:12:20,2018-04-04 11:30:43,Opinion-based,java;hibernate;jpa;jakarta-ee;orm,Anthony,36462,654203,registered,true,,,,2015-05-19 13:47:43,1121,1032,0,0,0,5,false,true,false,true,true,true,52,7,true,0.036,0.0011,5352,2012,3,0,Tuesday,false,false,false,true,false,false,false
3403909,Get generic type of class at runtime,"How can I achieve this?
public class GenericClass<T>
{
public Type getMyType()
{
//How do I return the type of T?
}
}
Everything I have tried so far always returns type Object rather than the specific type used.
",https://stackoverflow.com/questions/3403909/get-generic-type-of-class-at-runtime,678,902808.0,31.0,,,2010-08-04 08:44:44,2025-10-14 13:00:39,2015-12-26 16:56:03,2025-11-10 12:45:49,Duplicate,java;generics;reflection,Glenn,6795,410543,unregistered,true,,,,2017-09-05 08:14:08,292,241,2,0,0,3,false,true,false,true,true,true,36,7,false,0.034,0.0008,5953,2010,8,8,Wednesday,false,false,false,true,false,false,false
24471109,RecyclerView onClick,"Has anyone using RecyclerView found a way to set an onClickListener to items in the RecyclerView?
I thought of setting a listener to each of the layouts for each item but that seems a little too much hassle
I'm sure there is a way for the RecyclerView to listen for the onClick event but I can't quite figure it out.
",https://stackoverflow.com/questions/24471109/recyclerview-onclick,677,811718.0,49.0,,,2014-06-28 21:27:43,2022-12-27 18:41:39,2020-03-05 19:13:17,,,java;android;android-recyclerview;onclick;onclicklistener,CurtJRees,6788,1354811,registered,true,24471410,,CC BY-SA 4.0,2015-12-12 21:33:27,389,317,5,0,0,5,true,false,false,true,true,true,20,2,false,0.06,0.0008,4529,2014,6,21,Saturday,true,false,false,true,false,false,false
1673841,Examples of GoF Design Patterns in Java's core libraries,"I am learning GoF Java Design Patterns and I want to see some real life examples of them. What are some good examples of these Design Patterns in Java's core libraries?
",https://stackoverflow.com/questions/1673841/examples-of-gof-design-patterns-in-javas-core-libraries,672,572176.0,7.0,,,2009-11-04 13:45:52,2019-08-09 07:36:31,2015-04-11 03:40:40,,,oop;design-patterns;java,unj2,53936,82368,registered,true,2707195,,CC BY-SA 3.0,,176,169,0,0,0,3,true,false,false,true,true,true,60,9,false,0.012,0.0012,6226,2009,11,13,Wednesday,false,false,false,true,false,false,false
7488643,How to convert comma-separated String to List?,"Is there any built-in method in Java which allows us to convert comma separated String to some container (e.g array, List or Vector)? Or do I need to write custom code for that?
String commaSeparated = "item1 , item2 , item3";
List<String> items = //method that converts above string into list??
",https://stackoverflow.com/questions/7488643/how-to-convert-comma-separated-string-to-list,670,1340594.0,28.0,,,2011-09-20 16:40:02,2026-01-06 07:54:26,2020-07-16 20:35:00,,,java;string;collections;split,Jame,22484,586528,registered,true,7488676,,CC BY-SA 4.0,2022-09-07 04:04:26,344,313,1,0,0,4,true,false,false,true,true,true,46,7,true,0.021,0.0005,5541,2011,9,16,Tuesday,false,false,false,true,false,false,false
20375176,Should I always use a parallel stream when possible?,"With Java 8 and lambdas, it's easy to iterate over collections as streams, and just as easy to use a parallel stream. Two examples from the documentation, the second one using parallelStream:
myShapesCollection.stream()
.filter(e -> e.getColor() == Color.RED)
.forEach(e -> System.out.println(e.getName()));
myShapesCollection.parallelStream() // <-- This one uses parallel
.filter(e -> e.getColor() == Color.RED)
.forEach(e -> System.out.println(e.getName()));
As long as I don't care about the order, would it always be beneficial to use the parallel? One would think it is faster dividing the work on more cores.
Are there other considerations? When should parallel stream be used and when should the nonparallel be used?
(This question is asked to trigger a discussion about how and when to use parallel streams, not because I think always using them is a good idea.)
",https://stackoverflow.com/questions/20375176/should-i-always-use-a-parallel-stream-when-possible,669,259111.0,6.0,,,2013-12-04 12:17:46,2026-03-10 21:43:22,2026-03-10 20:06:23,,,java;parallel-processing;java-8;java-stream,Matsemann,22069,923847,registered,true,20375622,,CC BY-SA 4.0,,1086,905,1,1,0,4,true,false,false,true,true,true,52,9,true,0.023,0.0026,4735,2013,12,12,Wednesday,false,false,false,true,false,false,false
428918,How can I increment a date by one day in Java?,"I'm working with a date in this format: yyyy-mm-dd.
How can I increment this date by one day?
",https://stackoverflow.com/questions/428918/how-can-i-increment-a-date-by-one-day-in-java,668,1201918.0,32.0,,,2009-01-09 17:20:09,2022-11-12 12:57:45,2018-01-24 16:57:44,,,java;date,user48094,10691,48094,registered,true,,,CC BY-SA 3.0,2021-07-20 11:12:13,122,95,1,0,0,2,false,false,false,true,true,true,46,11,true,0.027,0.0006,6525,2009,1,17,Friday,false,false,false,true,false,false,false
835889,java.util.Date to XMLGregorianCalendar,"Isn't there a convenient way of getting from a java.util.Date to a XMLGregorianCalendar?
",https://stackoverflow.com/questions/835889/java-util-date-to-xmlgregoriancalendar,668,719396.0,10.0,,,2009-05-07 17:05:03,2025-05-29 12:07:23,2017-05-25 14:25:14,,,java;xml;date;xmlgregoriancalendar,mac,10115,53943,registered,true,56313273,,CC BY-SA 3.0,,96,89,0,0,0,4,true,false,false,true,true,true,38,3,false,0.014,0.0009,6407,2009,5,17,Thursday,false,false,false,true,false,false,false
75175,Create instance of generic type in Java?,"Is it possible to create an instance of a generic type in Java? I'm thinking based on what I've seen that the answer is no (due to type erasure), but I'd be interested if anyone can see something I'm missing:
class SomeContainer<E>
{
E createContents()
{
return what???
}
}
EDIT: It turns out that Super Type Tokens could be used to resolve my issue, but it requires a lot of reflection-based code, as some of the answers below have indicated.
I'll leave this open for a little while to see if anyone comes up with anything dramatically different than Ian Robertson's Artima Article.
",https://stackoverflow.com/questions/75175/create-instance-of-generic-type-in-java,664,638768.0,29.0,,,2008-09-16 18:04:28,2022-12-05 12:57:33,2012-04-06 11:29:12,,,java;generics,David Citron,43669,5309,registered,true,,,CC BY-SA 3.0,,857,614,2,2,0,2,false,false,false,true,true,true,40,7,true,0.045,0.001,6640,2008,9,18,Tuesday,false,false,false,true,false,false,false
4591206,ArithmeticException: "Non-terminating decimal expansion; no exact representable decimal result","Why does the following code raise the exception shown below?
BigDecimal a = new BigDecimal(""1.6"");
BigDecimal b = new BigDecimal(""9.2"");
a.divide(b) // results in the following exception.
Exception:
java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
",https://stackoverflow.com/questions/4591206/arithmeticexception-non-terminating-decimal-expansion-no-exact-representable,662,516745.0,9.0,,,2011-01-04 06:34:37,2022-09-01 20:38:47,2020-01-10 13:13:26,,,java;bigdecimal;arithmeticexception,Jason,12959,472897,registered,true,4591216,,CC BY-SA 4.0,,371,309,2,0,0,3,true,false,false,true,true,true,105,9,false,0.017,0.0013,5800,2011,1,6,Tuesday,false,false,false,true,false,false,false
908489,Eclipse/Java code completion not working,"I've downloaded, unzipped and setup Eclipse 3.4.2 with some plugins (noteable, EPIC, Clearcase, QuantumDB, MisterQ).
Now I find when I'm editing Java projects the code completion is not working. If I type String. and press ctrl+space a popup shows ""No Default Proposals"" and the status bar at the bottom shows ""No completions available"".
Any ideas?
",https://stackoverflow.com/questions/908489/eclipse-java-code-completion-not-working,660,465144.0,25.0,,,2009-05-26 00:43:45,2022-01-12 18:37:28,2014-02-13 19:16:05,,,java;eclipse;ide,Robert Brown,10996,14952,registered,true,908930,,CC BY-SA 3.0,2011-05-16 11:31:48,409,353,1,0,0,3,true,false,false,true,true,true,40,5,false,0.054,0.0014,6388,2009,5,0,Tuesday,false,false,false,true,false,false,false
320542,How to get the path of a running JAR file?,"My code runs inside a JAR file, say foo.jar, and I need to know, in the code, in which folder the running foo.jar is.
So, if foo.jar is in C:\FOO\, I want to get that path no matter what my current working directory is.
",https://stackoverflow.com/questions/320542/how-to-get-the-path-of-a-running-jar-file,659,648081.0,33.0,,,2008-11-26 12:30:38,2023-05-22 16:10:45,2020-03-06 13:15:08,,,java;path;jar;executable-jar,Thiago Chaves,9533,16873,registered,true,320595,,CC BY-SA 4.0,2016-09-07 23:20:56,299,221,1,0,0,4,true,false,false,true,true,true,42,10,true,0.051,0.001,6569,2008,11,12,Wednesday,false,false,false,true,false,false,false
520328,Can you find all classes in a package using reflection?,"Is it possible to find all classes or interfaces in a given package? (Quickly looking at e.g. Package, it would seem like no.)
",https://stackoverflow.com/questions/520328/can-you-find-all-classes-in-a-package-using-reflection,658,544631.0,30.0,,,2009-02-06 13:43:16,2024-05-18 12:51:23,2015-06-29 14:30:59,,,java;reflection;package,Jonik,82166,56285,registered,true,520339,,CC BY-SA 3.0,,239,127,1,1,0,3,true,false,false,true,true,true,55,10,true,0.055,0.0012,6497,2009,2,13,Friday,false,false,false,true,false,false,false
1061717,What exactly is Spring Framework for?,"I hear a lot about Spring, people are saying all over the web that Spring is a good framework for web development. What exactly is Spring Framework for in a nutshell? Why should I used it over just plain Java.
",https://stackoverflow.com/questions/1061717/what-exactly-is-spring-framework-for,658,298894.0,17.0,,,2009-06-30 04:25:00,2022-12-22 10:35:15,2021-05-07 17:25:27,2018-03-26 19:42:51,Needs more focus,java;spring;frameworks,Maksim,17001,51230,registered,true,1064562,,,2012-01-24 04:35:10,267,210,0,1,0,3,true,true,false,true,true,true,37,6,true,0.057,0.0022,6353,2009,6,4,Tuesday,false,false,false,true,false,false,false
878573,Does Java have support for multiline strings?,"Coming from Perl, I sure am missing the ""here-document"" means of creating a multi-line string in source code:
$string = <<""EOF"" # create a three-line string
text
text
text
EOF
In Java, I have to have cumbersome quotes and plus signs on every line as I concatenate my multiline string from scratch.
What are some better alternatives? Define my string in a properties file?
Edit: Two answers say StringBuilder.append() is preferable to the plus notation. Could anyone elaborate as to why they think so? It doesn't look more preferable to me at all. I'm looking for a way around the fact that multiline strings are not a first-class language construct, which means I definitely don't want to replace a first-class language construct (string concatenation with plus) with method calls.
Edit: To clarify my question further, I'm not concerned about performance at all. I'm concerned about maintainability and design issues.
",https://stackoverflow.com/questions/878573/does-java-have-support-for-multiline-strings,657,832548.0,44.0,,,2009-05-18 16:28:47,2026-04-13 19:47:11,2021-08-26 16:21:35,,,java;string;multiline,skiphoppy,104505,18103,registered,true,,,CC BY-SA 4.0,2016-02-24 14:33:42,1030,937,1,0,0,3,false,false,false,true,true,true,45,7,true,0.053,0.0008,6396,2009,5,16,Monday,false,false,false,true,false,false,false
1099300,"What's the difference between getPath(), getAbsolutePath(), and getCanonicalPath() in Java?","What's the difference between getPath(), getAbsolutePath(), and getCanonicalPath() in Java?
And when do I use each one?
",https://stackoverflow.com/questions/1099300/whats-the-difference-between-getpath-getabsolutepath-and-getcanonicalpath,656,432816.0,6.0,,,2009-07-08 16:53:51,2020-10-28 21:43:23,2013-05-17 08:51:43,,,java,knt,7653,122358,registered,true,1099370,,CC BY-SA 3.0,,174,121,3,0,0,1,true,false,false,true,true,true,95,10,true,0.014,0.0015,6345,2009,7,16,Wednesday,false,false,false,true,false,false,false
14970516,Use Mockito to mock some methods but not others,"Is there any way, using Mockito, to mock some methods in a class, but not others?
For example, in this (admittedly contrived) Stock class I want to mock the getPrice() and getQuantity() return values (as shown in the test snippet below) but I want the getValue() to perform the multiplication as coded in the Stock class
public class Stock {
private final double price;
private final int quantity;
Stock(double price, int quantity) {
this.price = price;
this.quantity = quantity;
}
public double getPrice() {
return price;
}
public int getQuantity() {
return quantity;
}
public double getValue() {
return getPrice() * getQuantity();
}
@Test
public void getValueTest() {
Stock stock = mock(Stock.class);
when(stock.getPrice()).thenReturn(100.00);
when(stock.getQuantity()).thenReturn(200);
double value = stock.getValue();
// Unfortunately the following assert fails, because the mock Stock getValue() method does not perform the Stock.getValue() calculation code.
assertEquals(""Stock value not correct"", 100.00*200, value, .00001);
}
",https://stackoverflow.com/questions/14970516/use-mockito-to-mock-some-methods-but-not-others,655,762047.0,5.0,,,2013-02-20 00:59:08,2022-11-21 21:59:30,2019-10-21 10:55:32,,,java;mocking;mockito,Victor Grazi,16640,522729,registered,true,14970545,,CC BY-SA 4.0,2019-04-24 09:07:37,1212,1109,6,0,0,3,true,false,false,true,true,true,47,9,false,0.007,0.0009,5022,2013,2,0,Wednesday,false,false,false,true,false,false,false
510632,What's the difference between ConcurrentHashMap and Collections.synchronizedMap(Map)?,"I have a Map which is to be modified by several threads concurrently.
There seem to be three different synchronized Map implementations in the Java API:
Hashtable
Collections.synchronizedMap(Map)
ConcurrentHashMap
From what I understand, Hashtable is an old implementation (extending the obsolete Dictionary class), which has been adapted later to fit the Map interface. While it is synchronized, it seems to have serious scalability issues and is discouraged for new projects.
But what about the other two? What are the differences between Maps returned by Collections.synchronizedMap(Map) and ConcurrentHashMaps? Which one fits which situation?
",https://stackoverflow.com/questions/510632/whats-the-difference-between-concurrenthashmap-and-collections-synchronizedmap,654,350669.0,19.0,,,2009-02-04 09:22:46,2021-07-25 08:12:27,2016-09-06 07:11:28,,,java;dictionary;concurrency,Henning,11745,29549,registered,true,510654,,CC BY-SA 3.0,,925,654,8,1,0,3,true,false,false,true,true,true,89,7,true,0.054,0.0019,6499,2009,2,9,Wednesday,false,false,false,true,false,false,false
18198176,Java 8 Lambda function that throws exception?,"I know how to create a reference to a method that has a String parameter and returns an int, it's:
Function<String, Integer>
However, this doesn't work if the function throws an exception, say it's defined as:
Integer myMethod(String s) throws IOException
How would I define this reference?
",https://stackoverflow.com/questions/18198176/java-8-lambda-function-that-throws-exception,652,557250.0,28.0,,,2013-08-12 23:16:36,2024-01-31 10:22:08,2018-07-02 09:13:08,,,java;lambda;java-8,Rocky Pulley,23469,428916,registered,true,18198349,,CC BY-SA 4.0,2018-11-06 09:20:29,398,303,4,0,0,3,true,false,false,true,true,true,45,7,true,0.05,0.0012,4849,2013,8,23,Monday,false,false,false,true,false,false,false
541920,Multiple line code example in Javadoc comment,"I have a small code example I want to include in the Javadoc comment for a method.
/**
* -- ex: looping through List of Map objects --
* <code>
* for (int i = 0; i < list.size(); i++) {
* Map map = (Map)list.get(i);
* System.out.println(map.get(""wordID""));
* System.out.println(map.get(""word""));
* }
* </code>
*
* @param query - select statement
* @return List of Map objects
*/
The problem is the code example shows up in the Javadoc with no line breaks making it hard to read.
-- ex: looping through List of Map objects -- for (int i = 0; i list.size(); i++) { Map map = (Map)list.get(i); System.out.println(map.get(""wordID"")); System.out.println(map.get(""word"")); }
Parameters
query - - select statement
Returns:
List of Map objects
I guess I am wrong in assuming the code tag would handle line breaks. What is the best way to format code examples in Javadoc comments ?
",https://stackoverflow.com/questions/541920/multiple-line-code-example-in-javadoc-comment,651,279798.0,19.0,,,2009-02-12 15:52:42,2025-09-05 18:28:33,2009-02-12 15:59:08,,,java;html;javadoc,Mark,17350,50262,registered,true,542142,,CC BY-SA 2.5,2017-04-26 16:53:37,999,930,2,0,0,3,true,false,false,true,true,true,45,7,false,0.068,0.0023,6491,2009,2,15,Thursday,false,false,false,true,false,false,false
30969455,Android changing Floating Action Button color,"I have been trying to change Material's Floating Action Button color, but without success.
<android.support.design.widget.FloatingActionButton
android:id=""@+id/profile_edit_fab""
android:layout_width=""wrap_content""
android:layout_height=""wrap_content""
android:layout_gravity=""end|bottom""
android:layout_margin=""16dp""
android:clickable=""true""
android:src=""@drawable/ic_mode_edit_white_24dp"" />
I have tried to add:
android:background=""@color/mycolor""
or via code:
FloatingActionButton fab = (FloatingActionButton) rootView.findViewById(R.id.profile_edit_fab);
fab.setBackgroundColor(Color.parseColor(""#mycolor""));
or
fab.setBackgroundDrawable(new ColorDrawable(Color.parseColor(""#mycolor"")));
But none of the above worked. I have also tried the solutions in the proposed duplicate question, but none of them works; the button remained green and also became a square.
P.S. It would be also nice to know how to add ripple effect, couldn't understand that either.
",https://stackoverflow.com/questions/30969455/android-changing-floating-action-button-color,650,488968.0,28.0,,,2015-06-21 21:20:22,2023-09-05 09:03:04,2020-02-15 15:24:50,,,java;android;android-5.0-lollipop;floating-action-button,Jjang,11486,1334761,registered,true,31179286,,CC BY-SA 4.0,2020-07-18 11:56:17,1144,1006,4,0,0,4,true,false,false,true,true,true,45,6,false,0.057,0.0013,4171,2015,6,21,Sunday,true,false,false,true,false,false,false
11938253,JPA JoinColumn vs mappedBy,"What is the difference between:
@Entity
public class Company {
@OneToMany(cascade = CascadeType.ALL , fetch = FetchType.LAZY)
@JoinColumn(name = "companyIdRef", referencedColumnName = "companyId")
private List<Branch> branches;
...
}
and
@Entity
public class Company {
@OneToMany(cascade = CascadeType.ALL , fetch = FetchType.LAZY,
mappedBy = "companyIdRef")
private List<Branch> branches;
...
}
",https://stackoverflow.com/questions/11938253/jpa-joincolumn-vs-mappedby,649,641069.0,9.0,,,2012-08-13 16:17:29,2023-11-07 08:37:57,2021-04-13 21:45:41,,,java;hibernate;jpa;orm,Mykhaylo Adamovych,21454,448078,registered,true,11939045,,CC BY-SA 4.0,2015-06-03 22:35:10,537,475,2,0,0,4,true,false,false,true,true,true,26,4,false,0.014,0.001,5213,2012,8,16,Monday,false,false,false,true,false,false,false
10268583,Downloading Java JDK on Linux via wget is shown license page instead,"When I try to download Java from Oracle I instead end up downloading a page telling me that I need agree to the OTN license terms.
Sorry!
In order to download products from Oracle Technology Network you must agree to the OTN license terms.
Be sure that...
- Your browser has ""cookies"" and JavaScript enabled.
- You clicked on ""Accept License"" for the product you wish to download.
- You attempt the download within 30 minutes of accepting the license.
How can I download and install Java?
",https://stackoverflow.com/questions/10268583/downloading-java-jdk-on-linux-via-wget-is-shown-license-page-instead,648,562557.0,30.0,,,2012-04-22 14:03:10,2022-11-30 15:55:13,2015-07-14 19:32:20,,,java;linux;installation;wget,thejartender,9385,835806,registered,true,10959815,,CC BY-SA 3.0,2015-01-24 02:04:37,612,514,0,0,0,4,true,false,false,true,true,true,68,12,false,0.053,0.0012,5326,2012,4,14,Sunday,true,false,false,true,false,false,false
8725387,Why is there no SortedList in Java?,"In Java there are the SortedSet and SortedMap interfaces. Both belong to the Java Collections framework and provide a sorted way to access the elements.
However, in my understanding there is no SortedList in Java. You can use java.util.Collections.sort() to sort a list.
Any idea why it is designed like that?
",https://stackoverflow.com/questions/8725387/why-is-there-no-sortedlist-in-java,648,699844.0,16.0,,,2012-01-04 10:35:53,2026-01-19 17:35:23,2020-04-18 20:39:53,,,java;sorting;collections,Jijoy,12904,83501,registered,true,8725470,,CC BY-SA 4.0,2013-07-12 12:12:13,848,313,4,4,0,3,true,false,false,true,true,true,35,7,true,0.023,0.0009,5435,2012,1,10,Wednesday,false,false,false,true,false,false,false
9619030,Resolving javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed Error?,"Edit : I tried to format the question and accepted answer in more presentable way at my blog.
Here is the original issue.
I am getting this error:
detailed message sun.security.validator.ValidatorException: PKIX path
building failed:
sun.security.provider.certpath.SunCertPathBuilderException: unable to
find valid certification path to requested target
cause javax.net.ssl.SSLHandshakeException:
sun.security.validator.ValidatorException: PKIX path building
failed: sun.security.provider.certpath.SunCertPathBuilderException:
unable to find valid certification path to requested target
I am using Tomcat 6 as webserver. I have two HTTPS web applications installed on different Tomcats on different ports but on the same machine. Say App1 (port 8443) and App2 (port 443). App1 connects to App2. When App1 connects to App2 I get the above error. I know this is a very common error so came across many solutions on different forums and sites. I have the below entry in server.xml of both Tomcats:
keystoreFile="c:/.keystore"
keystorePass="changeit"
Every site says the same reason that certificate given by app2 is not in the trusted store of app1 jvm. This seems to be true also when I tried to hit the same URL in IE browser, it works (with warming, There is a problem with this web site's security certificate. Here I say continue to this website). But when same URL is hit by Java client (in my case) I get the above error. So to put it in the truststore I tried these three options:
Option 1
System.setProperty("javax.net.ssl.trustStore", "C:/.keystore");
System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
Option 2
Setting below in environment variable
CATALINA_OPTS -- param name
-Djavax.net.ssl.trustStore=C:\.keystore -Djavax.net.ssl.trustStorePassword=changeit ---param value
Option 3
Setting below in environment variable
JAVA_OPTS -- param name
-Djavax.net.ssl.trustStore=C:\.keystore -Djavax.net.ssl.trustStorePassword=changeit ---param value
Result
But nothing worked.
What at last worked is executing the Java approach suggested in How to handle invalid SSL certificates with Apache HttpClient? by Pascal Thivent i.e. executing the program InstallCert.
But this approach is fine for devbox setup but I can not use it at production environment.
I am wondering why three approaches mentioned above did not work when I have mentioned the same values in server.xml of App2 server and same values in truststore by setting
System.setProperty("javax.net.ssl.trustStore", "C:/.keystore") and System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
in App1 program.
For more information this is how I am making the connection:
URL url = new URL(urlStr);
URLConnection conn = url.openConnection();
if (conn instanceof HttpsURLConnection) {
HttpsURLConnection conn1 = (HttpsURLConnection) url.openConnection();
conn1.setHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
reply.load(conn1.getInputStream());
",https://stackoverflow.com/questions/9619030/resolving-javax-net-ssl-sslhandshakeexception-sun-security-validator-validatore,648,2427019.0,38.0,,,2012-03-08 14:17:14,2025-05-20 11:20:26,2021-08-16 11:30:35,,,java;ssl;https,M Sach,34660,802050,registered,true,9619478,,CC BY-SA 4.0,2015-04-21 09:18:53,3739,3150,8,2,0,3,true,false,false,true,true,true,122,8,true,0.016,0.0003,5371,2012,3,14,Thursday,false,false,false,true,false,false,false
15156857,Mockito test a void method throws an exception,"I have a method with a void return type. It can also throw a number of exceptions so I'd like to test those exceptions being thrown. All attempts have failed with the same reason:
The method when(T) in the type Stubber is not applicable for the arguments (void)
Any ideas how I can get the method to throw a specified exception?
doThrow(new Exception()).when(mockedObject.methodReturningVoid(...));
",https://stackoverflow.com/questions/15156857/mockito-test-a-void-method-throws-an-exception,647,563978.0,4.0,,,2013-03-01 11:40:33,2024-08-01 11:24:04,2015-08-26 14:40:30,,,java;exception;mocking;mockito,edwardmlyte,16717,509213,registered,true,15157021,,CC BY-SA 3.0,,490,407,2,0,0,4,true,false,false,true,true,true,46,8,false,0.007,0.0011,5013,2013,3,11,Friday,false,false,false,true,false,false,false
24511052,How to convert an Iterator to a Stream?,"I am looking for a concise way to convert an Iterator to a Stream or more specifically to ""view"" the iterator as a stream.
For performance reason, I would like to avoid a copy of the iterator in a new list:
Iterator<String> sourceIterator = Arrays.asList(""A"", ""B"", ""C"").iterator();
Collection<String> copyList = new ArrayList<String>();
sourceIterator.forEachRemaining(copyList::add);
Stream<String> targetStream = copyList.stream();
Based on the some suggestions in the comments, I have also tried to use Stream.generate:
public static void main(String[] args) throws Exception {
Iterator<String> sourceIterator = Arrays.asList(""A"", ""B"", ""C"").iterator();
Stream<String> targetStream = Stream.generate(sourceIterator::next);
targetStream.forEach(System.out::println);
}
However, I get a NoSuchElementException (since there is no invocation of hasNext)
Exception in thread ""main"" java.util.NoSuchElementException
at java.util.AbstractList$Itr.next(AbstractList.java:364)
at Main$$Lambda$1/1175962212.get(Unknown Source)
at java.util.stream.StreamSpliterators$InfiniteSupplyingSpliterator$OfRef.tryAdvance(StreamSpliterators.java:1351)
at java.util.Spliterator.forEachRemaining(Spliterator.java:326)
at java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:580)
at Main.main(Main.java:20)
I have looked at StreamSupport and Collections but I didn't find anything.
",https://stackoverflow.com/questions/24511052/how-to-convert-an-iterator-to-a-stream,647,386441.0,13.0,,,2014-07-01 13:05:15,2025-03-18 05:46:32,2021-09-17 00:21:04,,,java;iterator;java-8,gontard,29790,1594933,registered,true,24511534,,CC BY-SA 4.0,,2247,1463,10,5,0,3,true,false,false,true,true,true,39,8,true,0.034,0.0017,4526,2014,7,13,Tuesday,false,false,false,true,false,false,false
19431234,Converting between java.time.LocalDateTime and java.util.Date,"Java 8 has a completely new API for date and time. One of the most useful classes in this API is LocalDateTime, for holding a timezone-independent date-with-time value.
There are probably millions of lines of code using the legacy class java.util.Date for this purpose. As such, when interfacing old and new code there will be a need for converting between the two. As there seems to be no direct methods for accomplishing this, how can it be done?
",https://stackoverflow.com/questions/19431234/converting-between-java-time-localdatetime-and-java-util-date,646,733556.0,10.0,,,2013-10-17 15:40:54,2024-10-16 10:31:26,2014-10-19 21:27:58,,,java;datetime;java-8;java-time,Knut Arne Vedaa,15822,50572,registered,true,23885950,,CC BY-SA 3.0,,491,451,2,0,0,4,true,false,false,true,true,true,61,5,false,0.014,0.0009,4783,2013,10,15,Thursday,false,false,false,true,false,false,false
228477,How do I programmatically determine operating system in Java?,"I would like to determine the operating system of the host that my Java program is running programmatically (for example: I would like to be able to load different properties based on whether I am on a Windows or Unix platform). What is the safest way to do this with 100% reliability?
",https://stackoverflow.com/questions/228477/how-do-i-programmatically-determine-operating-system-in-java,645,496582.0,22.0,,,2008-10-23 03:47:05,2025-05-19 11:55:04,2019-05-08 11:34:30,,,java;operating-system,karlgrz,14901,318,registered,true,228481,,CC BY-SA 4.0,2019-05-08 11:34:40,293,286,0,0,0,2,true,false,false,true,true,true,61,9,true,0.044,0.0013,6603,2008,10,3,Thursday,false,false,false,true,false,false,false
19998454,"When to use: Java 8+ interface default method, vs. abstract method","Java 8 allows for default implementation of methods in interfaces called Default Methods.
I am confused between when would I use that sort of interface default method, instead of an abstract class (with abstract method(s)).
So when should interface with default methods be used and when should an abstract class (with abstract method(s)) be used? Are the abstract classes still useful in that scenario?
",https://stackoverflow.com/questions/19998454/when-to-use-java-8-interface-default-method-vs-abstract-method,645,175474.0,16.0,,,2013-11-15 10:06:01,2023-05-08 10:36:42,2020-05-12 18:39:01,,,java;interface;java-8;abstract-class;default-method,Narendra Pathai,42055,1719067,registered,true,19998827,,CC BY-SA 4.0,2018-04-16 11:20:20,559,408,3,1,0,5,true,false,false,true,true,true,66,11,false,0.091,0.0037,4754,2013,11,10,Friday,false,false,false,true,false,false,false
23318109,Is it possible to use Java 8 for Android development?,"Searching the web, it is not clear if Java 8 is supported for Android development or not.
Before I download/setup Java 8, can some one point me at any ""official"" documentation that says Java 8 is or is not supported for Android development.
",https://stackoverflow.com/questions/23318109/is-it-possible-to-use-java-8-for-android-development,636,299370.0,28.0,,,2014-04-27 00:40:43,2021-11-03 18:54:18,2017-08-26 05:02:26,,,java;android;java-8;android-gradle-plugin,nPn,16880,2612259,registered,true,23318269,,CC BY-SA 3.0,2015-06-21 04:42:28,256,242,0,0,0,4,true,false,false,true,true,true,53,10,true,0.094,0.0021,4591,2014,4,0,Sunday,true,false,false,true,false,false,false
2279030,Type List vs type ArrayList in Java,"(1) List<?> myList = new ArrayList<?>();
(2) ArrayList<?> myList = new ArrayList<?>();
I understand that with (1), implementations of the List interface can be swapped. It seems that (1) is typically used in an application regardless of need (myself I always use this).
I am wondering if anyone uses (2)?
Also, how often (and can I please get an example) does the situation actually require using (1) over (2) (i.e. where (2) wouldn't suffice..aside coding to interfaces and best practices etc.)
",https://stackoverflow.com/questions/2279030/type-list-vs-type-arraylist-in-java,636,480026.0,15.0,,,2010-02-17 07:40:13,2021-11-01 05:37:45,2017-03-02 06:59:58,2020-04-06 06:47:19,Duplicate,java;list;interface;decoupling,kji,6761,275030,unregistered,true,2279059,,,,644,530,1,0,0,4,true,true,false,true,true,true,35,7,false,0.031,0.0013,6121,2010,2,7,Wednesday,false,false,false,true,false,false,false
13670991,Can we instantiate an abstract class?,"During one of my interview, I was asked ""If we can instantiate an abstract class?""
My reply was ""No. we can't"". But, interviewer told me ""Wrong, we can.""
I argued a bit on this. Then he told me to try this myself at home.
abstract class my {
public void mymethod() {
System.out.print(""Abstract"");
}
}
class poly {
public static void main(String a[]) {
my m = new my() {};
m.mymethod();
}
}
Here, I'm creating instance of my class and calling method of abstract class. Can anyone please explain this to me? Was I really wrong during my interview?
",https://stackoverflow.com/questions/13670991/can-we-instantiate-an-abstract-class,635,341612.0,16.0,,,2012-12-02 16:01:58,2019-11-24 12:16:23,2019-06-07 18:02:21,,,java;oop;class;object;abstract,Ravi,31587,1162620,registered,true,13671003,,CC BY-SA 4.0,2013-07-02 12:12:00,646,594,1,0,0,5,true,false,false,true,true,true,37,6,true,0.047,0.0019,5102,2012,12,16,Sunday,true,false,false,true,false,false,false
625433,"How to convert Milliseconds to "X mins, x seconds" in Java?","I want to record the time using System.currentTimeMillis() when a user begins something in my program. When he finishes, I will subtract the current System.currentTimeMillis() from the start variable, and I want to show them the time elapsed using a human readable format such as ""XX hours, XX mins, XX seconds"" or even ""XX mins, XX seconds"" because its not likely to take someone an hour.
What's the best way to do this?
",https://stackoverflow.com/questions/625433/how-to-convert-milliseconds-to-x-mins-x-seconds-in-java,634,686842.0,31.0,,,2009-03-09 08:41:06,2024-03-27 13:15:53,,,,java;time,Ali,268320,49153,registered,true,625624,,CC BY-SA 2.5,2012-05-05 11:27:22,476,423,3,0,0,2,true,false,false,true,true,false,69,11,true,0.045,0.0009,6466,2009,3,8,Monday,false,false,false,true,false,false,false
4334970,Hibernate throws MultipleBagFetchException - cannot simultaneously fetch multiple bags,"Hibernate throws this exception during SessionFactory creation:
org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags
This is my test case:
Parent.java
@Entity
public Parent {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
@OneToMany(mappedBy=""parent"", fetch=FetchType.EAGER)
// @IndexColumn(name=""INDEX_COL"") if I had this the problem solve but I retrieve more children than I have, one child is null.
private List<Child> children;
}
Child.java
@Entity
public Child {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
@ManyToOne
private Parent parent;
}
How about this problem? What can I do?
EDIT
OK, the problem I have is that another ""parent"" entity is inside my parent, my real behavior is this:
Parent.java
@Entity
public Parent {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
@ManyToOne
private AnotherParent anotherParent;
@OneToMany(mappedBy=""parent"", fetch=FetchType.EAGER)
private List<Child> children;
}
AnotherParent.java
@Entity
public AnotherParent {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
@OneToMany(mappedBy=""parent"", fetch=FetchType.EAGER)
private List<AnotherChild> anotherChildren;
}
Hibernate doesn't like two collections with FetchType.EAGER, but this seems to be a bug, I'm not doing unusual things...
Removing FetchType.EAGER from Parent or AnotherParent solves the problem, but I need it, so real solution is to use @LazyCollection(LazyCollectionOption.FALSE) instead of FetchType (thanks to Bozho for the solution).
",https://stackoverflow.com/questions/4334970/hibernate-throws-multiplebagfetchexception-cannot-simultaneously-fetch-multipl,634,516159.0,18.0,,,2010-12-02 12:28:19,2024-06-05 13:20:02,2020-04-29 16:42:12,,,java;hibernate;jpa;one-to-many;bag,blow,13269,195176,registered,true,4335514,,CC BY-SA 4.0,,2090,1659,10,1,0,5,true,false,false,true,true,true,86,9,false,0.035,0.0012,5833,2010,12,12,Thursday,false,false,false,true,false,false,false
703396,How to nicely format floating numbers to string without unnecessary decimal 0's,"A 64-bit double can represent integer +/- 253 exactly.
Given this fact, I choose to use a double type as a single type for all my types, since my largest integer is an unsigned 32-bit number.
But now I have to print these pseudo integers, but the problem is they are also mixed in with actual doubles.
So how do I print these doubles nicely in Java?
I have tried String.format("%f", value), which is close, except I get a lot of trailing zeros for small values.
Here's an example output of of %f
232.00000000
0.18000000000
1237875192.0
4.5800000000
0.00000000
1.23450000
What I want is:
232
0.18
1237875192
4.58
0
1.2345
Sure I can write a function to trim those zeros, but that's lot of performance loss due to string manipulation. Can I do better with other format code?
The answers by Tom E. and Jeremy S. are unacceptable as they both arbitrarily rounds to two decimal places. Please understand the problem before answering.
Please note that String.format(format, args...) is locale-dependent (see answers below).
",https://stackoverflow.com/questions/703396/how-to-nicely-format-floating-numbers-to-string-without-unnecessary-decimal-0s,633,874356.0,29.0,,,2009-03-31 22:54:29,2023-02-03 18:29:43,2020-12-08 10:23:30,,,java;string;floating-point;format;double,Pyrolistical,28174,21838,registered,true,14126736,,CC BY-SA 4.0,2013-02-15 17:18:05,1212,1034,3,0,0,5,true,false,false,true,true,true,83,12,false,0.033,0.0007,6444,2009,3,22,Tuesday,false,false,false,true,false,false,false
2965747,Why do I get an UnsupportedOperationException when trying to remove an element from a List?,"I have this code:
public static String SelectRandomFromTemplate(String template,int count) {
String[] split = template.split(""|"");
List<String> list=Arrays.asList(split);
Random r = new Random();
while( list.size() > count ) {
list.remove(r.nextInt(list.size()));
}
return StringUtils.join(list, "", "");
}
I get this:
06-03 15:05:29.614: ERROR/AndroidRuntime(7737): java.lang.UnsupportedOperationException
06-03 15:05:29.614: ERROR/AndroidRuntime(7737): at java.util.AbstractList.remove(AbstractList.java:645)
How would be this the correct way? Java.15
",https://stackoverflow.com/questions/2965747/why-do-i-get-an-unsupportedoperationexception-when-trying-to-remove-an-element-f,632,719251.0,17.0,,,2010-06-03 12:08:43,2021-11-05 07:55:50,2017-05-10 06:11:38,,,java;exception;list;arraylist,Pentium10,208930,243782,registered,true,2965808,,CC BY-SA 3.0,,664,595,2,0,0,4,true,false,false,true,true,true,91,15,true,0.024,0.0009,6015,2010,6,12,Thursday,false,false,false,true,false,false,false
275944,How do I count the number of occurrences of a char in a String?,"I have the string
a.b.c.d
I want to count the occurrences of '.' in an idiomatic way, preferably a one-liner.
(Previously I had expressed this constraint as ""without a loop"", in case you're wondering why everyone's trying to answer without using a loop).
",https://stackoverflow.com/questions/275944/how-do-i-count-the-number-of-occurrences-of-a-char-in-a-string,631,1072545.0,49.0,,,2008-11-09 14:07:09,2024-11-15 22:08:45,2018-09-02 17:32:38,,,java;string,Bart,11061,4343,registered,true,1816989,,CC BY-SA 4.0,2021-03-20 15:55:37,305,260,1,0,0,2,true,false,false,true,true,true,63,14,true,0.046,0.0006,6586,2008,11,14,Sunday,true,false,false,true,false,false,false
8892360,Convert Set to List without creating new List,"I am using this code to convert a Set to a List:
Map<String, List<String>> mainMap = new HashMap<>();
for (int i=0; i < something.size(); i++) {
Set<String> set = getSet(...); //returns different result each time
List<String> listOfNames = new ArrayList<>(set);
mainMap.put(differentKeyName, listOfNames);
}
I want to avoid creating a new list in each iteration of the loop. Is that possible?
",https://stackoverflow.com/questions/8892360/convert-set-to-list-without-creating-new-list,628,1174619.0,15.0,,,2012-01-17 09:40:05,2024-05-21 08:11:48,2020-05-08 12:48:12,,,java;performance;list;set,Muhammad Imran Tariq,23462,420613,registered,true,8892424,,CC BY-SA 4.0,,506,442,3,0,0,4,true,false,false,true,true,true,45,8,false,0.013,0.0005,5422,2012,1,9,Tuesday,false,false,false,true,false,false,false
541749,How to determine an object's class?,"If class B and class C extend class A and I have an object of type B or C, how can I determine of which type it is an instance?
",https://stackoverflow.com/questions/541749/how-to-determine-an-objects-class,626,887762.0,14.0,,,2009-02-12 15:18:24,2024-02-18 21:09:30,2018-01-22 20:30:43,,,java;inheritance,carrier,33306,20498,registered,true,541769,,CC BY-SA 3.0,,200,128,5,0,0,2,true,false,false,true,true,true,39,6,true,0.016,0.0007,6491,2009,2,15,Thursday,false,false,false,true,false,false,false
6784463,Error - trustAnchors parameter must be non-empty,"I'm trying to configure my e-mail on Jenkins/Hudson, and I constantly receive the error:
java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be
non-empty
I've seen a good amount of information online about the error, but I have not gotten any to work. I'm using Sun's JDK on Fedora Linux (not OpenJDK).
Here are a few things I've tried. I tried following the advice from this post, but copying the cacerts from Windows over to my Fedora box hosting Jenkins didn't work. I tried following this guide as I'm trying to configure Gmail as my SMTP server, but it didn't work either. I also tried to download and move those cacert files manually and move them over to my Java folder using a variation of the commands on this guide.
I am open to any suggestions as I'm currently stuck right now. I have gotten it to work from a Windows Hudson server, but I am struggling on Linux.
",https://stackoverflow.com/questions/6784463/error-trustanchors-parameter-must-be-non-empty,626,1086499.0,52.0,,,2011-07-22 00:35:02,2025-11-24 14:18:13,2018-07-21 18:39:34,,,java;hudson;jakarta-mail;jenkins,David Gill,8691,586907,registered,true,6788682,,CC BY-SA 4.0,2017-11-16 23:20:59,1242,914,1,3,0,4,true,false,false,true,true,true,48,7,false,0.048,0.0006,5601,2011,7,0,Friday,false,false,false,true,false,false,false
5971964,When should I use File.separator and when File.pathSeparator?,"In the File class there are two strings, separator and pathSeparator.
What's the difference? When should I use one over the other?
",https://stackoverflow.com/questions/5971964/when-should-i-use-file-separator-and-when-file-pathseparator,626,501705.0,3.0,,,2011-05-12 00:08:19,2021-06-14 15:00:04,2020-08-13 18:43:59,,,java;file;path-separator,icnhzabot,10321,743534,registered,true,,,CC BY-SA 4.0,,388,131,3,2,0,3,false,false,false,true,true,true,61,8,true,0.006,0.0012,5672,2011,5,0,Thursday,false,false,false,true,false,false,false
21242110,Convert java.util.Date to java.time.LocalDate,"What is the best way to convert a java.util.Date object to the new JDK 8/JSR-310 java.time.LocalDate?
Date input = new Date();
LocalDate date = ???
",https://stackoverflow.com/questions/21242110/convert-java-util-date-to-java-time-localdate,625,690276.0,14.0,,,2014-01-20 19:06:42,2024-06-24 16:59:54,2014-10-19 21:29:42,,,java;datetime;java-8;java-time,JodaStephen,64083,38896,registered,true,21242111,,CC BY-SA 3.0,2018-11-06 09:20:05,207,150,3,0,0,4,true,false,false,true,true,true,45,4,false,0.02,0.0009,4688,2014,1,19,Monday,false,false,false,true,false,false,false
683518,Java Class that implements Map and keeps insertion order?,"I'm looking for a class in java that has key-value association, but without using hashes. Here is what I'm currently doing:
- Add values to a
Hashtable.
- Get an iterator for the
Hashtable.entrySet().
- Iterate through all values and:
- Get a
Map.Entry for the iterator.
- Create an object of type
Module (a custom class) based on the value.
- Add the class to a JPanel.
- Show the panel.
The problem with this is that I do not have control over the order that I get the values back, so I cannot display the values in the a given order (without hard-coding the order).
I would use an ArrayList or Vector for this, but later in the code I need to grab the Module object for a given Key, which I can't do with an ArrayList or Vector.
Does anyone know of a free/open-source Java class that will do this, or a way to get values out of a Hashtable based on when they were added?
Thanks!
",https://stackoverflow.com/questions/683518/java-class-that-implements-map-and-keeps-insertion-order,625,456121.0,11.0,,,2009-03-25 21:22:04,2025-08-31 09:13:45,2016-11-03 20:25:38,,,java;dictionary;key-value,Shane,6335,33725,registered,true,683524,,CC BY-SA 3.0,,1125,879,10,0,0,3,true,false,false,true,true,true,57,9,true,0.024,0.0014,6450,2009,3,21,Wednesday,false,false,false,true,false,false,false
2329358,Is there anything like .NET's NotImplementedException in Java?,"Is there anything like .NET's NotImplementedException in Java?
",https://stackoverflow.com/questions/2329358/is-there-anything-like-nets-notimplementedexception-in-java,625,206265.0,6.0,,,2010-02-24 20:44:28,2024-10-10 02:05:01,2013-04-06 11:07:36,,,java;.net;exception,devoured elysium,106194,130758,registered,true,2329389,,CC BY-SA 3.0,,83,63,1,0,0,3,true,false,false,true,true,true,66,8,true,0.029,0.003,6114,2010,2,20,Wednesday,false,false,false,true,false,false,false
3591784,View's getWidth() and getHeight() returns 0,"I am creating all of the elements in my android project dynamically. I am trying to get the width and height of a button so that I can rotate that button around. I am just trying to learn how to work with the android language. However, it returns 0.
I did some research and I saw that it needs to be done somewhere other than in the onCreate() method. If someone can give me an example of how to do it, that would be great.
Here is my current code:
package com.animation;
import android.app.Activity;
import android.os.Bundle;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.LinearLayout;
public class AnimateScreen extends Activity {
//Called when the activity is first created.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout ll = new LinearLayout(this);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(30, 20, 30, 0);
Button bt = new Button(this);
bt.setText(String.valueOf(bt.getWidth()));
RotateAnimation ra = new RotateAnimation(0,360,bt.getWidth() / 2,bt.getHeight() / 2);
ra.setDuration(3000L);
ra.setRepeatMode(Animation.RESTART);
ra.setRepeatCount(Animation.INFINITE);
ra.setInterpolator(new LinearInterpolator());
bt.startAnimation(ra);
ll.addView(bt,layoutParams);
setContentView(ll);
}
",https://stackoverflow.com/questions/3591784/views-getwidth-and-getheight-returns-0,624,426281.0,28.0,,,2010-08-28 17:47:02,2024-07-13 17:43:23,2023-03-18 20:19:55,,,java;android;android-layout;getter,ngreenwood6,8236,160463,registered,true,3594216,,CC BY-SA 4.0,,1675,1617,2,0,0,4,true,false,false,true,true,true,47,6,false,0.066,0.0015,5929,2010,8,17,Saturday,true,false,false,true,false,false,false
4493001,What are the best use cases for Akka framework,"I have heard lots of raving about Akka framework (Java/Scala service platform), but so far have not seen many actual examples of use cases it would be good for. So I would be interested in hearing about things developers have used it succesfully.
Only one limitation: please do not include case of writing a chat server.
(why? since this has been overused as an example for lots of similar things)
",https://stackoverflow.com/questions/4493001/what-are-the-best-use-cases-for-akka-framework,622,180418.0,12.0,,,2010-12-20 19:15:54,2022-05-18 15:29:45,2022-05-18 15:29:45,2013-08-18 00:38:17,Opinion-based,java;scala;asynchronous;akka,StaxMan,117202,59501,registered,true,4494522,,,,461,400,0,1,0,4,true,true,false,true,true,true,46,9,false,0.067,0.0034,5815,2010,12,19,Monday,false,false,false,true,false,false,false
24437564,Update Eclipse with Android development tools v. 23,"I updated Eclipse with the new SDK tools (rev. 23), but now when Eclipse starts I receive the error:
This Android SDK requires Android Developer Toolkit version 23.0.0 or above. Current version is 22.6.3.v201404151837-1123206. Please update ADT to the latest version.
No updates were found with ""Check for updates"". If I try ""Install new software"", I can see version 23, but I can't upgrade due to the following error:
Cannot complete the install because of a conflicting dependency.
Software being installed: Android Development Tools 23.0.0.1245622 (com.android.ide.eclipse.adt.feature.feature.group 23.0.0.1245622)
Software currently installed: Android Developer Tools 22.2.1.v201309180102-833290 (com.android.ide.eclipse.adt.package.product 22.2.1.v201309180102-833290)
Only one of the following can be installed at once:
ADT Package 22.6.3.v201404151837-1123206 (com.android.ide.eclipse.adt.package 22.6.3.v201404151837-1123206)
ADT Package 23.0.0.1245622 (com.android.ide.eclipse.adt.package 23.0.0.1245622)
Cannot satisfy dependency:
From: Android Development Tools 23.0.0.1245622 (com.android.ide.eclipse.adt.feature.feature.group 23.0.0.1245622)
To: com.android.ide.eclipse.adt.package [23.0.0.1245622]
Cannot satisfy dependency:
From: Android Development Tools 22.6.3.v201404151837-1123206 (com.android.ide.eclipse.adt.feature.group 22.6.3.v201404151837-1123206)
To: com.android.ide.eclipse.adt.package [22.6.3.v201404151837-1123206]
Cannot satisfy dependency:
From: ADT Package 22.2.1.v201309180102-833290 (com.android.ide.eclipse.adt.package.feature.group 22.2.1.v201309180102-833290)
To: com.android.ide.eclipse.adt.feature.group 22.2.0
Cannot satisfy dependency:
From: Android Developer Tools 22.2.1.v201309180102-833290 (com.android.ide.eclipse.adt.package.product 22.2.1.v201309180102-833290)
To: com.android.ide.eclipse.adt.package.feature.group [22.2.1.v201309180102-833290]
After download of the last ADT from the web site, it seems there's another problem.
With SDK Tools rev. 23 proguard is not installed, the folder SDK dir/tools/proguard is missing, and other tools are missing. This version contains several bugs.
",https://stackoverflow.com/questions/24437564/update-eclipse-with-android-development-tools-v-23,620,231341.0,43.0,,,2014-06-26 18:21:46,2017-01-22 20:38:10,2017-01-22 19:55:40,,,java;android;eclipse;adt,greywolf82,22273,2944616,registered,true,24455640,,CC BY-SA 3.0,2014-06-27 19:38:01,2320,2189,2,0,0,4,true,false,false,true,true,true,51,8,false,0.186,0.0027,4531,2014,6,18,Thursday,false,false,false,true,false,false,false
328496,When would you use the Builder Pattern?,"What are some common, real world examples of using the Builder Pattern? What does it buy you? Why not just use a Factory Pattern?
",https://stackoverflow.com/questions/328496/when-would-you-use-the-builder-pattern,619,310569.0,13.0,,,2008-11-30 05:41:23,2020-12-05 14:24:39,2014-09-28 16:50:38,2015-05-22 17:03:47,Needs more focus,java;design-patterns;builder,Charles Graham,24923,7705,registered,true,328506,,,2013-07-27 13:18:44,157,132,0,0,0,3,true,true,false,true,true,true,39,7,true,0.042,0.002,6565,2008,11,5,Sunday,true,false,false,true,false,false,false
1594667,.war vs .ear file,"What is the difference between a .war and .ear file?
",https://stackoverflow.com/questions/1594667/war-vs-ear-file,619,387901.0,9.0,,,2009-10-20 13:38:28,2020-06-08 04:57:27,2018-06-30 17:19:03,,,java;jakarta-ee;deployment,ria,7964,23414,registered,true,1594723,,CC BY-SA 4.0,2013-05-10 17:01:42,60,53,0,0,0,3,true,false,false,true,true,true,17,4,false,0.023,0.0016,6241,2009,10,13,Tuesday,false,false,false,true,false,false,false
147454,What are the dangers of using a wild card with a Java import statement?,"It is much more convenient and cleaner to use a single statement like
import java.awt.*;
than to import a bunch of individual classes
import java.awt.Panel;
import java.awt.Graphics;
import java.awt.Canvas;
...
What are the dangers with using a wildcard in the import statement?
",https://stackoverflow.com/questions/147454/what-are-the-dangers-of-using-a-wild-card-with-a-java-import-statement,617,302409.0,18.0,,,2008-09-29 03:55:51,2025-08-15 18:55:11,2025-08-15 18:55:11,2025-08-16 10:30:22,Opinion-based,java;import;wildcard,jnancheta,7484,22807,registered,true,147461,,,2018-12-13 10:16:58,363,281,3,0,0,3,true,true,false,true,true,true,71,14,true,0.06,0.002,6627,2008,9,3,Monday,false,false,false,true,false,false,false
27581,What issues should be considered when overriding equals and hashCode in Java?,"What issues / pitfalls must be considered when overriding equals and hashCode?
",https://stackoverflow.com/questions/27581/what-issues-should-be-considered-when-overriding-equals-and-hashcode-in-java,616,613490.0,11.0,,,2008-08-26 08:50:26,2017-01-26 11:00:31,2014-08-11 19:02:45,,,java;overriding;equals;hashcode,Matt Sheppard,118363,797,registered,true,27609,,CC BY-SA 3.0,2014-01-12 19:30:49,112,79,2,0,0,4,true,false,false,true,true,true,77,12,true,0.018,0.001,6661,2008,8,8,Tuesday,false,false,false,true,false,false,false
24104313,How do I make a delay in Java?,"I am trying to do something in Java and I need something to wait / delay for an amount of seconds in a while loop.
while (true) {
if (i == 3) {
i = 0;
}
ceva[i].setSelected(true);
// I need to wait here
ceva[i].setSelected(false);
// I need to wait here
i++;
}
I want to build a step sequencer.
How do I make a delay in Java?
",https://stackoverflow.com/questions/24104313/how-do-i-make-a-delay-in-java,616,2346950.0,8.0,,,2014-06-08 08:26:21,2025-02-25 14:16:52,2022-12-29 00:31:02,,,java;wait;sleep;thread-sleep,ardb,6573,3387622,registered,true,24104427,,CC BY-SA 4.0,2020-09-06 15:24:14,413,368,1,0,0,4,true,false,false,true,true,true,30,8,true,0.003,0.0003,4549,2014,6,8,Sunday,true,false,false,true,false,false,false
3076078,Check if at least two out of three booleans are true,"An interviewer recently asked me this question: given three boolean variables, a, b, and c, return true if at least two out of the three are true.
My solution follows:
boolean atLeastTwo(boolean a, boolean b, boolean c) {
if ((a && b) || (b && c) || (a && c)) {
return true;
}
else{
return false;
}
}
He said that this can be improved further, but how?
",https://stackoverflow.com/questions/3076078/check-if-at-least-two-out-of-three-booleans-are-true,615,209566.0,65.0,,,2010-06-19 15:46:02,2024-10-30 05:54:03,2013-01-25 22:30:37,,,java;boolean;boolean-logic,user282886,3205,282886,registered,true,3076081,,CC BY-SA 3.0,2012-01-30 16:35:28,458,413,1,0,0,3,true,false,false,true,true,true,52,11,false,0.31,0.0029,5999,2010,6,15,Saturday,true,false,false,true,false,false,false
13950338,How to make an Android device vibrate? with different frequency?,"I wrote an Android application. Now, I want to make the device vibrate when a certain action occurs. How can I do this?
",https://stackoverflow.com/questions/13950338/how-to-make-an-android-device-vibrate-with-different-frequency,615,433037.0,15.0,,,2012-12-19 10:32:05,2024-05-07 15:41:47,2021-01-06 13:58:02,,,java;android;kotlin;vibration;android-vibration,Billie,9176,1798362,registered,true,13950364,,CC BY-SA 4.0,2015-12-30 00:19:08,127,120,0,0,0,5,true,false,false,true,true,true,64,10,true,0.035,0.0014,5085,2012,12,10,Wednesday,false,false,false,true,false,false,false
7438612,How to remove the last character from a string?,"I want to remove the last character from a string. I've tried doing this:
public String method(String str) {
if (str.charAt(str.length()-1)=='x'){
str = str.replace(str.substring(str.length()-1), """");
return str;
} else{
return str;
}
}
Getting the length of the string - 1 and replacing the last letter with nothing (deleting it), but every time I run the program, it deletes middle letters that are the same as the last letter.
For example, the word is ""admirer""; after I run the method, I get ""admie."" I want it to return the word admire.
",https://stackoverflow.com/questions/7438612/how-to-remove-the-last-character-from-a-string,614,1482953.0,37.0,,,2011-09-15 23:16:03,2024-11-23 05:13:53,2015-08-21 07:17:17,,,java;string,duaprog137,,,does_not_exist,true,7438613,,,2022-05-03 11:39:31,627,582,1,0,0,2,true,false,false,true,false,true,47,9,true,0.025,0.0004,5546,2011,9,23,Thursday,false,false,false,true,false,false,false
2062020,How can I tell if I'm running in 64-bit JVM or 32-bit JVM (from within a program)?,"How can I tell if the JVM in which my application runs is 32 bit or 64-bit? Specifically, what functions or properties I can used to detect this within the program?
",https://stackoverflow.com/questions/2062020/how-can-i-tell-if-im-running-in-64-bit-jvm-or-32-bit-jvm-from-within-a-program,614,762170.0,14.0,,,2010-01-14 03:38:29,2024-06-15 22:28:03,2019-03-23 07:29:35,,,java;jvm;java-native-interface;64-bit;32-bit,BobMcGee,20190,95122,registered,true,2062036,,CC BY-SA 4.0,2019-03-23 07:47:50,173,166,0,0,0,5,true,false,false,true,true,true,86,17,true,0.018,0.0008,6155,2010,1,3,Thursday,false,false,false,true,false,false,false
1642028,What is the '-->' operator in C/C++?,"After reading Hidden Features and Dark Corners of C++/STL on comp.lang.c++.moderated, I was completely surprised that the following snippet compiled and worked in both Visual Studio 2008 and G++ 4.4. I would assume this is also valid C since it works in GCC as well.
Here's the code:
#include <stdio.h>
int main()
{
int x = 10;
while (x --> 0) // x goes to 0
{
printf("%d ", x);
}
}
Output:
9 8 7 6 5 4 3 2 1 0
Where is this defined in the standard, and where has it come from?
",https://stackoverflow.com/questions/1642028/what-is-the-operator-in-c-c,10270,1062595.0,26.0,,,2009-10-29 06:57:45,2026-08-26 03:44:03,2023-03-30 14:11:04,,,c++;c;operators;code-formatting;standards-compliance,GManNickG,507447,87234,registered,true,1642035,,CC BY-SA 4.0,2011-02-10 06:48:02,719,523,3,1,0,5,true,false,false,true,true,true,47,7,true,0.024,0.0097,6232,2009,10,6,Thursday,false,false,false,false,false,false,false
1711631,Improve INSERT-per-second performance of SQLite,"Optimizing SQLite is tricky. Bulk-insert performance of a C application can vary from 85 inserts per second to over 96,000 inserts per second!
Background: We are using SQLite as part of a desktop application. We have large amounts of configuration data stored in XML files that are parsed and loaded into an SQLite database for further processing when the application is initialized. SQLite is ideal for this situation because it's fast, it requires no specialized configuration, and the database is stored on disk as a single file.
Rationale: Initially I was disappointed with the performance I was seeing. It turns out that the performance of SQLite can vary significantly (both for bulk-inserts and selects) depending on how the database is configured and how you're using the API. It was not a trivial matter to figure out what all of the options and techniques were, so I thought it was prudent to create this community wiki entry to share the results with Stack Overflow readers in order to save others the trouble of the same investigations.
The experiment: Rather than simply talking about performance tips in the general sense (i.e. "Use a transaction!"), I thought it was best to write some C code and actually measure the impact of various options. We're going to start with some simple data:
- A 28 MiB TSV text file (approximately 865,000 records) of the complete transit schedule for the city of Toronto
- My test machine is a 3.60 GHz P4 running Windows XP.
- The code is compiled with Visual C++ 2005 x32 as "Release" with "Full Optimization" (
/Ox) and Favor Fast Code (/Ot).
- I'm using the SQLite "Amalgamation", compiled directly into my test application. The SQLite version I happen to have is a bit older (3.6.7), but I suspect these results will be comparable to the latest release (please leave a comment if you think otherwise).
Let's write some code!
The code: A simple C program that reads the text file line-by-line, splits the string into values and then inserts the data into an SQLite database. In this "baseline" version of the code, the database is created, but we won't actually insert data:
/*************************************************************
Baseline code to experiment with SQLite performance.
Input data is a 28 MiB TSV text file of the
complete Toronto Transit System schedule/route info
from http://www.toronto.ca/open/datasets/ttc-routes/
**************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include "sqlite3.h"
#define INPUTDATA "C:\\TTC_schedule_scheduleitem_10-27-2009.txt"
#define DATABASE "c:\\TTC_schedule_scheduleitem_10-27-2009.sqlite"
#define TABLE "CREATE TABLE IF NOT EXISTS TTC (id INTEGER PRIMARY KEY, Route_ID TEXT, Branch_Code TEXT, Version INTEGER, Stop INTEGER, Vehicle_Index INTEGER, Day Integer, Time TEXT)"
#define BUFFER_SIZE 256
int main(int argc, char **argv) {
sqlite3 * db;
sqlite3_stmt * stmt;
char * sErrMsg = 0;
char * tail = 0;
int nRetCode;
int n = 0;
clock_t cStartClock;
FILE * pFile;
char sInputBuf [BUFFER_SIZE] = "\0";
char * sRT = 0; /* Route */
char * sBR = 0; /* Branch */
char * sVR = 0; /* Version */
char * sST = 0; /* Stop Number */
char * sVI = 0; /* Vehicle */
char * sDT = 0; /* Date */
char * sTM = 0; /* Time */
char sSQL [BUFFER_SIZE] = "\0";
/*********************************************/
/* Open the Database and create the Schema */
sqlite3_open(DATABASE, &db);
sqlite3_exec(db, TABLE, NULL, NULL, &sErrMsg);
/*********************************************/
/* Open input file and import into Database*/
cStartClock = clock();
pFile = fopen (INPUTDATA,"r");
while (!feof(pFile)) {
fgets (sInputBuf, BUFFER_SIZE, pFile);
sRT = strtok (sInputBuf, "\t"); /* Get Route */
sBR = strtok (NULL, "\t"); /* Get Branch */
sVR = strtok (NULL, "\t"); /* Get Version */
sST = strtok (NULL, "\t"); /* Get Stop Number */
sVI = strtok (NULL, "\t"); /* Get Vehicle */
sDT = strtok (NULL, "\t"); /* Get Date */
sTM = strtok (NULL, "\t"); /* Get Time */
/* ACTUAL INSERT WILL GO HERE */
n++;
}
fclose (pFile);
printf("Imported %d records in %4.2f seconds\n", n, (clock() - cStartClock) / (double)CLOCKS_PER_SEC);
sqlite3_close(db);
return 0;
}
The "control"
Running the code as-is doesn't actually perform any database operations, but it will give us an idea of how fast the raw C file I/O and string processing operations are.
Imported 864913 records in 0.94 seconds
Great! We can do 920,000 inserts per second, provided we don't actually do any inserts :-)
The "worst-case-scenario"
We're going to generate the SQL string using the values read from the file and invoke that SQL operation using sqlite3_exec:
sprintf(sSQL, "INSERT INTO TTC VALUES (NULL, '%s', '%s', '%s', '%s', '%s', '%s', '%s')", sRT, sBR, sVR, sST, sVI, sDT, sTM);
sqlite3_exec(db, sSQL, NULL, NULL, &sErrMsg);
This is going to be slow because the SQL will be compiled into VDBE code for every insert and every insert will happen in its own transaction. How slow?
Imported 864913 records in 9933.61
seconds
Yikes! 2 hours and 45 minutes! That's only 85 inserts per second.
Using a transaction
By default, SQLite will evaluate every INSERT/UPDATE statement within a unique transaction. If performing a large number of inserts, it's advisable to wrap your operation in a transaction:
sqlite3_exec(db, "BEGIN TRANSACTION", NULL, NULL, &sErrMsg);
pFile = fopen (INPUTDATA,"r");
while (!feof(pFile)) {
...
}
fclose (pFile);
sqlite3_exec(db, "END TRANSACTION", NULL, NULL, &sErrMsg);
Imported 864913 records in 38.03 seconds
That's better. Simply wrapping all of our inserts in a single transaction improved our performance to 23,000 inserts per second.
Using a prepared statement
Using a transaction was a huge improvement, but recompiling the SQL statement for every insert doesn't make sense if we using the same SQL over-and-over. Let's use sqlite3_prepare_v2 to compile our SQL statement once and then bind our parameters to that statement using sqlite3_bind_text:
/* Open input file and import into the database */
cStartClock = clock();
sprintf(sSQL, "INSERT INTO TTC VALUES (NULL, @RT, @BR, @VR, @ST, @VI, @DT, @TM)");
sqlite3_prepare_v2(db, sSQL, BUFFER_SIZE, &stmt, &tail);
sqlite3_exec(db, "BEGIN TRANSACTION", NULL, NULL, &sErrMsg);
pFile = fopen (INPUTDATA,"r");
while (!feof(pFile)) {
fgets (sInputBuf, BUFFER_SIZE, pFile);
sRT = strtok (sInputBuf, "\t"); /* Get Route */
sB",https://stackoverflow.com/questions/1711631/improve-insert-per-second-performance-of-sqlite,3424,533203.0,12.0,,,2009-11-10 22:16:43,2026-03-29 18:18:07,2025-08-24 07:27:17,,,c;performance;sqlite;optimization,Mike Willekes,6210,203690,registered,true,1712873,,CC BY-SA 4.0,2018-04-27 06:47:06,16496,14514,36,3,0,4,true,false,false,true,true,true,47,5,false,0.023,0.0064,6220,2009,11,22,Tuesday,false,false,false,false,false,false,false
47981,"How to set, clear, and toggle a single bit","How can I set, clear, and toggle a bit?
",https://stackoverflow.com/questions/47981/how-to-set-clear-and-toggle-a-single-bit,3175,1737781.0,27.0,,,2008-09-07 00:42:17,2025-09-02 10:24:09,2023-08-21 23:05:40,,,c++;c;bit-manipulation;bitwise-operators,JeffV,54929,445087,registered,true,47990,,CC BY-SA 4.0,2021-08-13 09:06:59,47,40,0,0,0,4,true,false,false,true,true,true,42,9,false,0.016,0.0018,6649,2008,9,0,Sunday,true,false,false,false,false,false,false
21593,What is the difference between #include <filename> and #include "filename"?,"What is the difference between using angle brackets and quotes in an include directive?
#include <filename>
#include "filename"
",https://stackoverflow.com/questions/21593/what-is-the-difference-between-include-filename-and-include-filename,3167,972191.0,30.0,,,2008-08-22 01:40:06,2022-08-11 13:53:34,2022-07-04 21:45:52,,,c++;c;include;header-files;c-preprocessor,quest49,51398,2399,registered,true,,,CC BY-SA 4.0,2014-04-28 14:17:29,219,146,3,0,0,5,false,false,false,true,true,true,91,10,true,0.031,0.0033,6665,2008,8,1,Friday,false,false,false,false,false,false,false
605845,Should I cast the result of malloc (in C)?,"In this question, someone suggested in a comment that I should not cast the result of malloc. i.e., I should do this:
int *sieve = malloc(sizeof(*sieve) * length);
rather than:
int *sieve = (int *) malloc(sizeof(*sieve) * length);
Why would this be the case?
",https://stackoverflow.com/questions/605845/should-i-cast-the-result-of-malloc-in-c,2835,427271.0,30.0,,,2009-03-03 10:13:02,2024-07-17 11:44:48,2024-03-28 15:12:17,,,c;malloc;casting,Patrick McDonald,65789,61989,registered,true,605858,,CC BY-SA 4.0,2013-09-25 04:39:50,630,261,3,2,0,3,true,false,false,true,true,true,42,9,true,0.07,0.0066,6472,2009,3,10,Tuesday,false,false,false,false,false,false,false
7825055,What does the ??!??! operator do in C?,"I saw a line of C that looked like this:
!ErrorHasOccured() ??!??! HandleError();
It compiled correctly and seems to run ok. It seems like it's checking if an error has occurred, and if it has, it handles it. But I'm not really sure what it's actually doing or how it's doing it. It does look like the programmer is trying express their feelings about errors.
I have never seen the ??!??! before in any programming language, and I can't find documentation for it anywhere. (Google doesn't help with search terms like ??!??!). What does it do and how does the code sample work?
",https://stackoverflow.com/questions/7825055/what-does-the-operator-do-in-c,2575,407091.0,4.0,,,2011-10-19 16:56:59,2025-06-05 04:00:18,2020-05-15 02:44:35,,,c;operators;trigraphs,Peter Olson,143557,546661,registered,true,7825075,,CC BY-SA 4.0,2018-04-27 07:12:43,652,581,3,0,0,3,true,false,false,true,true,true,38,8,true,0.01,0.0063,5512,2011,10,16,Wednesday,false,false,false,false,false,false,false
1041866,What is the effect of `extern "C"` in C++?,"What exactly does putting extern ""C"" into C++ code do?
For example:
extern ""C"" {
void foo();
}
",https://stackoverflow.com/questions/1041866/what-is-the-effect-of-extern-c-in-c,2194,1358699.0,18.0,,,2009-06-25 02:10:07,2026-11-13 13:15:37,2026-11-13 13:15:37,,,c++;c;linkage;name-mangling;extern-c,Litherum,23530,125848,registered,true,1041880,,CC BY-SA 4.0,2017-03-09 07:41:42,152,101,2,0,0,5,true,false,false,true,true,true,52,9,true,0.013,0.0016,6358,2009,6,2,Thursday,false,false,false,false,false,false,false
1143262,"What is the difference between const int*, const int * const, and int * const?","I always mess up how to use const int *, const int * const, and int * const correctly. Is there a set of rules defining what you can and cannot do?
I want to know all the do's and all don'ts in terms of assignments, passing to the functions, etc.
",https://stackoverflow.com/questions/1143262/what-is-the-difference-between-const-int-const-int-const-and-int-const,1874,803818.0,23.0,,,2009-07-17 13:28:09,2025-08-22 09:06:24,2024-06-11 20:39:18,,,c++;c;pointers;constants;c++-faq,ultraman,,,does_not_exist,true,1143272,,CC BY-SA 4.0,2019-07-19 13:01:01,300,247,3,0,0,5,true,false,false,true,false,true,78,15,true,0.029,0.0023,6336,2009,7,13,Friday,false,false,false,false,false,false,false
381542,"With arrays, why is it the case that a[5] == 5[a]?","As Joel points out in Stack Overflow podcast #34, in C Programming Language (aka: K & R), there is mention of this property of arrays in C: a[5] == 5[a]
Joel says that it's because of pointer arithmetic but I still don't understand. Why does a[5] == 5[a]?
",https://stackoverflow.com/questions/381542/with-arrays-why-is-it-the-case-that-a5-5a,1829,142815.0,20.0,,,2008-12-19 17:01:33,2026-02-16 20:00:46,2018-10-21 07:55:14,,,c;arrays;pointers;pointer-arithmetic,Dinah,54427,356,registered,true,381549,,CC BY-SA 4.0,2013-05-18 13:13:48,496,261,2,2,0,4,true,false,false,true,true,true,50,11,true,0.14,0.0128,6546,2008,12,17,Friday,false,false,false,false,false,false,false
9229601,What is ':-!!' in C?,"I bumped into this strange macro code in /usr/include/linux/kernel.h:
/* Force a compilation error if condition is true, but also produce a
result (of value 0 and type size_t), so the expression can be used
e.g. in a structure initializer (or where-ever else comma expressions
aren't permitted). */
#define BUILD_BUG_ON_ZERO(e) (sizeof(struct { int:-!!(e); }))
#define BUILD_BUG_ON_NULL(e) ((void *)sizeof(struct { int:-!!(e); }))
What does :-!! do?
Update: In recent times, the macro has been moved to /usr/include/linux/build_bug.h
",https://stackoverflow.com/questions/9229601/what-is-in-c,1812,211412.0,6.0,,,2012-02-10 14:50:08,2026-11-19 05:19:27,2023-08-25 21:25:56,,,c;linux;macros;operators,chmurli,15170,883147,registered,true,9229793,,CC BY-SA 4.0,2013-06-10 05:15:51,933,545,4,2,0,4,true,false,false,true,true,true,28,5,true,0.028,0.0086,5398,2012,2,14,Friday,false,false,false,false,false,false,false
12135518,Is < faster than <=?,"Is if (a < 901) faster than if (a <= 900)?
Not exactly as in this simple example, but there are slight performance changes on loop complex code. I suppose this has to do something with generated machine code in case it's even true.
",https://stackoverflow.com/questions/12135518/is-faster-than,1787,161037.0,15.0,,,2012-08-27 02:10:12,2026-01-06 05:36:38,2021-11-26 10:29:52,,,c++;c;performance;assembly;relational-operators,Vinícius,15826,1513286,registered,true,12135533,,CC BY-SA 4.0,2019-03-21 01:39:28,278,238,2,0,0,5,true,false,false,true,true,true,26,5,true,0.093,0.0111,5199,2012,8,2,Monday,false,false,false,false,false,false,false
36827659,Compiling an application for use in highly radioactive environments,"We are compiling an embedded C++ application that is deployed in a shielded device in an environment bombarded with ionizing radiation. We are using GCC and cross-compiling for ARM. When deployed, our application generates some erroneous data and crashes more often than we would like. The hardware is designed for this environment, and our application has run on this platform for several years.
Are there changes we can make to our code, or compile-time improvements that can be made to identify/correct soft errors and memory-corruption caused by single event upsets? Have any other developers had success in reducing the harmful effects of soft errors on a long-running application?
",https://stackoverflow.com/questions/36827659/compiling-an-application-for-use-in-highly-radioactive-environments,1646,874119.0,24.0,,,2016-04-24 19:09:40,2026-10-15 11:59:08,2020-11-24 14:07:15,,,c++;c;gcc;embedded;fault-tolerance,rook,67256,183528,registered,true,36831344,,CC BY-SA 4.0,2016-04-27 23:55:23,933,687,0,3,0,5,true,false,false,true,true,true,67,9,false,0.027,0.0019,3863,2016,4,19,Sunday,true,false,false,false,false,false,false
840501,How do function pointers in C work?,"I had some experience lately with function pointers in C.
So going on with the tradition of answering your own questions, I decided to make a small summary of the very basics, for those who need a quick dive-in to the subject.
",https://stackoverflow.com/questions/840501/how-do-function-pointers-in-c-work,1554,1120445.0,12.0,,,2009-05-08 15:49:17,2022-10-18 14:51:38,,,,c;function-pointers,Yuval Adam,166180,24545,registered,true,840504,,CC BY-SA 2.5,2015-05-16 11:45:07,242,228,0,0,0,2,true,false,false,true,true,false,35,7,true,0.011,0.0014,6406,2009,5,15,Friday,false,false,false,false,false,false,false
572547,What does "static" mean in C?,"I've seen the word static used in different places in C code; is this like a static function/class in C# (where the implementation is shared across objects)?
",https://stackoverflow.com/questions/572547/what-does-static-mean-in-c,1464,1296144.0,22.0,,,2009-02-21 06:47:52,2024-08-23 15:58:24,2017-10-29 15:42:25,,,c;syntax;static,David,,,does_not_exist,true,572550,,CC BY-SA 3.0,2016-04-27 15:16:59,180,160,1,0,0,3,true,false,false,true,false,true,39,6,true,0.017,0.0011,6482,2009,2,6,Saturday,true,false,false,false,false,false,false
37538,How do I determine the size of my array in C?,"How do I determine the size of my array in C?
That is, the number of elements the array can hold?
",https://stackoverflow.com/questions/37538/how-do-i-determine-the-size-of-my-array-in-c,1442,3416916.0,22.0,,,2008-09-01 06:49:22,2025-05-28 12:43:28,2023-01-20 16:31:07,,,arrays;c,Mark Harrison,306839,116,registered,true,37539,,CC BY-SA 4.0,2015-10-28 00:30:41,114,100,0,0,0,2,true,false,false,true,true,true,45,11,true,0.006,0.0004,6655,2008,9,6,Monday,false,false,false,false,false,false,false
1433204,How do I use extern to share variables between source files?,"I know that global variables in C sometimes have the extern keyword. What is an extern variable? What is the declaration like? What is its scope?
This is related to sharing variables across source files, but how does that work precisely? Where do I use extern?
",https://stackoverflow.com/questions/1433204/how-do-i-use-extern-to-share-variables-between-source-files,1283,1043227.0,19.0,,,2009-09-16 14:08:40,2023-05-17 04:03:37,2022-10-17 03:54:42,,,c++;c;global-variables;extern,shilpa,,,does_not_exist,true,,,CC BY-SA 4.0,2015-08-26 14:18:41,315,262,3,0,0,4,false,false,false,true,false,true,60,11,true,0.018,0.0012,6275,2009,9,14,Wednesday,false,false,false,false,false,false,false
24853,What is the difference between ++i and i++?,"In C, what is the difference between using ++i and i++, and which should be used in the incrementation block of a for loop?
",https://stackoverflow.com/questions/24853/what-is-the-difference-between-i-and-i,1204,1856596.0,18.0,,,2008-08-24 05:19:19,2026-06-05 12:02:40,2021-03-15 10:32:30,,,c;for-loop;post-increment;pre-increment,The.Anti.9,45226,2128,registered,true,24858,,CC BY-SA 4.0,2015-03-03 16:00:52,170,124,3,0,0,4,true,false,false,true,true,true,43,8,true,0.01,0.0006,6663,2008,8,5,Sunday,true,false,false,false,false,false,false
201101,How can I initialize all members of an array to the same value?,"I have a large array in C (not C++ if that makes a difference). I want to initialize all members of the same value.
I could swear I once knew a simple way to do this. I could use memset() in my case, but isn't there a way to do this that is built right into the C syntax?
",https://stackoverflow.com/questions/201101/how-can-i-initialize-all-members-of-an-array-to-the-same-value,1191,2328265.0,27.0,,,2008-10-14 13:13:40,2025-02-27 21:10:15,2025-02-27 19:16:58,,,c;arrays;initialization;array-initialize,Matt,89117,17693,registered,true,201116,,CC BY-SA 4.0,2012-09-21 21:12:49,299,272,1,0,0,4,true,false,false,true,true,true,63,13,true,0.012,0.0005,6612,2008,10,13,Tuesday,false,false,false,false,false,false,false
19210935,Why does the C preprocessor interpret the word "linux" as the constant "1"?,"Why does the C preprocessor in GCC interpret the word linux (small letters) as the constant 1?
test.c:
#include <stdio.h>
int main(void)
{
int linux = 5;
return 0;
}
Result of $ gcc -E test.c (stop after the preprocessing stage):
....
int main(void)
{
int 1 = 5;
return 0;
}
Which of course yields an error.
(BTW: There is no #define linux in the stdio.h file.)
",https://stackoverflow.com/questions/19210935/why-does-the-c-preprocessor-interpret-the-word-linux-as-the-constant-1,1113,139247.0,5.0,,,2013-10-06 16:09:48,2023-03-29 22:09:31,2020-04-16 11:01:24,,,c;linux;gcc;c-preprocessor,ahmedaly50,7855,2851929,registered,true,19214007,,CC BY-SA 4.0,2013-10-09 14:47:49,598,399,7,0,0,4,true,false,false,true,true,true,95,13,true,0.036,0.008,4794,2013,10,16,Sunday,true,false,false,false,false,false,false
1410563,What is the difference between a definition and a declaration?,"The meaning of both eludes me.
",https://stackoverflow.com/questions/1410563/what-is-the-difference-between-a-definition-and-a-declaration,1079,513474.0,27.0,,,2009-09-11 12:27:12,2023-09-24 15:35:26,2023-09-24 15:35:26,,,c++;c;declaration;terminology;c++-faq,Maciek,20182,142168,registered,true,1410632,,CC BY-SA 4.0,2011-09-02 19:07:20,38,31,0,0,0,5,true,false,false,true,true,true,62,10,true,0.053,0.0021,6280,2009,9,12,Friday,false,false,false,false,false,false,false
1675351,typedef struct vs struct definitions,"I'm a beginner in C programming, but I was wondering what's the difference between using typedef when defining a structure versus not using typedef. It seems to me like there's really no difference, they accomplish the same goal.
struct myStruct{
int one;
int two;
};
vs.
typedef struct{
int one;
int two;
}myStruct;
",https://stackoverflow.com/questions/1675351/typedef-struct-vs-struct-definitions,1059,1078830.0,12.0,,,2009-11-04 17:21:57,2021-11-29 10:20:25,2018-12-04 16:22:30,2016-06-05 22:23:48,Duplicate,c;struct;typedef,user69514,27927,69514,registered,true,1675446,,,2016-06-04 05:56:31,426,338,4,0,0,3,true,true,false,true,true,true,36,5,false,0.011,0.001,6226,2009,11,17,Wednesday,false,false,false,false,false,false,false
98650,What is the strict aliasing rule?,"When asking about common undefined behavior in C, people sometimes refer to the strict aliasing rule.
What are they talking about?
",https://stackoverflow.com/questions/98650/what-is-the-strict-aliasing-rule,1048,339550.0,12.0,,,2008-09-19 01:30:27,2026-07-10 17:58:18,2026-02-17 15:50:29,,,c++;c;undefined-behavior;strict-aliasing;type-punning,Benoit,39630,10703,registered,true,99010,,CC BY-SA 4.0,2016-11-30 09:27:44,272,131,0,1,0,5,true,false,false,true,true,true,33,6,true,0.035,0.0031,6637,2008,9,1,Friday,false,false,false,false,false,false,false
15393441,Obfuscated C Code Contest 2006. Please explain sykes2.c,"How does this C program work?
main(_){_^448&&main(-~_);putchar(--_%64?32|-~7[__TIME__-_/8%8]["">'txiZ^(~z?""-48]>>"";;;====~$::199""[_*2&8|_/64]/(_&2?1:8)%8&1:10);}
It compiles as it is (tested on gcc 4.6.3). It prints the time when compiled. On my system:
!! !!!!!! !! !!!!!! !! !!!!!!
!! !! !! !! !! !! !! !!
!! !! !! !! !! !! !! !!
!! !!!!!! !! !! !! !! !! !!!!!!
!! !! !! !! !! !! !!
!! !! !! !! !! !! !!
!! !!!!!! !! !! !! !!!!!!
Source: sykes2 - A clock in one line, sykes2 author hints
Some hints: No compile warnings per default. Compiled with -Wall, the following warnings are emitted:
sykes2.c:1:1: warning: return type defaults to ‘int’ [-Wreturn-type]
sykes2.c: In function ‘main’:
sykes2.c:1:14: warning: value computed is not used [-Wunused-value]
sykes2.c:1:1: warning: implicit declaration of function ‘putchar’ [-Wimplicit-function-declaration]
sykes2.c:1:1: warning: suggest parentheses around arithmetic in operand of ‘|’ [-Wparentheses]
sykes2.c:1:1: warning: suggest parentheses around arithmetic in operand of ‘|’ [-Wparentheses]
sykes2.c:1:1: warning: control reaches end of non-void function [-Wreturn-type]
",https://stackoverflow.com/questions/15393441/obfuscated-c-code-contest-2006-please-explain-sykes2-c,997,86126.0,4.0,,,2013-03-13 18:22:49,2020-04-27 20:27:22,2020-04-27 20:27:22,,,c;obfuscation;deobfuscation,corny,7874,2143551,registered,true,15395030,,CC BY-SA 4.0,2013-03-20 05:12:15,1711,1435,5,2,0,3,true,false,false,true,true,true,55,8,false,0.046,0.0116,5001,2013,3,18,Wednesday,false,false,false,false,false,false,false
1538420,Difference between malloc and calloc?,"What is the difference between doing:
ptr = malloc(MAXELEMS * sizeof(char *));
And:
ptr = calloc(MAXELEMS, sizeof(char*));
When is it a good idea to use calloc over malloc or vice versa?
",https://stackoverflow.com/questions/1538420/difference-between-malloc-and-calloc,979,692196.0,14.0,,,2009-10-08 15:04:33,2023-02-03 01:06:03,2023-02-03 01:06:03,,,c;malloc;calloc,user105033,19768,105033,registered,true,1538427,,CC BY-SA 4.0,2016-11-06 16:15:49,284,189,4,0,0,3,true,false,false,true,true,true,37,5,true,0.02,0.0014,6253,2009,10,15,Thursday,false,false,false,false,false,false,false
154136,Why use apparently meaningless do-while and if-else statements in macros?,"In many C/C++ macros I'm seeing the code of the macro wrapped in what seems like a meaningless do while loop. Here are examples.
#define FOO(X) do { f(X); g(X); } while (0)
#define FOO(X) if (1) { f(X); g(X); } else
I can't see what the do while is doing. Why not just write this without it?
#define FOO(X) f(X); g(X)
",https://stackoverflow.com/questions/154136/why-use-apparently-meaningless-do-while-and-if-else-statements-in-macros,972,126583.0,9.0,,,2008-09-30 17:36:24,2026-02-12 20:30:00,2024-12-10 10:21:33,,,c++;c;c-preprocessor;c++-faq,jfm3,38292,11138,registered,true,154138,,CC BY-SA 4.0,2015-03-31 09:39:13,486,322,4,0,0,4,true,false,false,true,true,true,73,10,true,0.071,0.0077,6626,2008,9,17,Tuesday,false,false,false,false,false,false,false
65820,Unit Testing C Code,"I worked on an embedded system this summer written in straight C. It was an existing project that the company I work for had taken over. I have become quite accustomed to writing unit tests in Java using JUnit but was at a loss as to the best way to write unit tests for existing code (which needed refactoring) as well as new code added to the system.
Are there any projects out there that make unit testing plain C code as easy as unit testing Java code with JUnit? Any insight that would apply specifically to embedded development (cross-compiling to arm-linux platform) would be greatly appreciated.
",https://stackoverflow.com/questions/65820/unit-testing-c-code,968,577062.0,31.0,,,2008-09-15 19:12:00,2020-11-21 06:02:40,2019-08-08 15:42:42,2015-04-18 10:21:15,Not suitable for this site,c;unit-testing;testing;embedded,Paul Osborne,5154,7049,registered,true,65845,,,2019-07-17 09:00:08,622,608,0,0,0,4,true,true,false,true,true,true,19,4,false,0.054,0.0017,6641,2008,9,19,Monday,false,false,false,false,false,false,false
949433,Why are these constructs using pre and post-increment undefined behavior?,"#include <stdio.h>
int main(void)
{
int i = 0;
i = i++ + ++i;
printf(""%d\n"", i); // 3
i = 1;
i = (i++);
printf(""%d\n"", i); // 2 Should be 1, no ?
volatile int u = 0;
u = u++ + ++u;
printf(""%d\n"", u); // 1
u = 1;
u = (u++);
printf(""%d\n"", u); // 2 Should also be one, no ?
register int v = 0;
v = v++ + ++v;
printf(""%d\n"", v); // 3 (Should be the same as u ?)
int w = 0;
printf(""%d %d\n"", ++w, w); // shouldn't this print 1 1
int x[2] = { 5, 8 }, y = 0;
x[y] = y ++;
printf(""%d %d\n"", x[0], x[1]); // shouldn't this print 0 8? or 5 0?
}
",https://stackoverflow.com/questions/949433/why-are-these-constructs-using-pre-and-post-increment-undefined-behavior,928,109197.0,15.0,,,2009-06-04 09:17:52,2024-08-26 11:46:10,2019-08-17 07:31:59,,,c;increment;undefined-behavior;operator-precedence;sequence-points,PiX,9955,44988,registered,true,949443,,CC BY-SA 4.0,2013-05-28 11:01:48,634,610,1,0,0,5,true,false,false,true,true,true,73,10,true,0.137,0.0085,6379,2009,6,9,Thursday,false,false,false,false,false,false,false
2346806,What is a segmentation fault?,"What is a segmentation fault? Is it different in C and C++? How are segmentation faults and dangling pointers related?
",https://stackoverflow.com/questions/2346806/what-is-a-segmentation-fault,909,1155914.0,17.0,,,2010-02-27 09:23:14,2026-04-16 04:21:01,2016-06-01 02:40:25,,,c++;c;segmentation-fault,Rajendra Uppal,20242,277734,registered,true,2346849,,CC BY-SA 3.0,2016-04-18 07:36:39,126,119,0,0,0,3,true,false,false,true,true,true,29,5,true,0.015,0.0008,6111,2010,2,9,Saturday,true,false,false,false,false,false,false
16931770,makefile:4: *** missing separator. Stop,"This is my makefile:
all:ll
ll:ll.c
gcc -c -Wall -Werror -02 c.c ll.c -o ll $@ $<
clean :
\rm -fr ll
When I try to make clean or make make, I get this error:
:makefile:4: *** missing separator. Stop.
How can I fix it?
",https://stackoverflow.com/questions/16931770/makefile4-missing-separator-stop,890,1049218.0,19.0,,,2013-06-05 04:48:50,2023-08-30 00:35:44,2013-06-05 05:20:53,,,c;makefile,Rahul Reddy,13323,2384801,registered,true,16945143,,CC BY-SA 3.0,2019-07-18 16:12:08,338,243,4,0,0,2,true,false,false,true,true,true,39,5,false,0.018,0.0008,4917,2013,6,4,Wednesday,false,false,false,false,false,false,false
1921539,Using Boolean values in C,"C doesn't have any built-in Boolean types. What's the best way to use them in C?
",https://stackoverflow.com/questions/1921539/using-boolean-values-in-c,890,1661091.0,19.0,,,2009-12-17 12:46:49,2024-01-17 20:26:14,2023-06-15 12:05:32,,,c;boolean,neuromancer,56059,209512,registered,true,1921557,,CC BY-SA 4.0,2016-04-26 17:24:43,88,81,0,0,0,2,true,false,false,true,true,true,25,5,false,0.011,0.0005,6183,2009,12,12,Thursday,false,false,false,false,false,false,false
119123,Why isn't sizeof for a struct equal to the sum of sizeof of each member?,"Why does the sizeof operator return a size larger for a structure than the total sizes of the structure's members?
",https://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member,884,313797.0,13.0,,,2008-09-23 04:24:47,2022-04-26 07:39:19,2018-09-23 09:09:20,,,c++;c;struct;sizeof;c++-faq,Kevin,26337,6386,registered,true,119128,,CC BY-SA 4.0,2016-04-26 17:27:38,135,115,1,0,0,5,true,false,false,true,true,true,76,15,true,0.041,0.0028,6633,2008,9,4,Tuesday,false,false,false,false,false,false,false
204476,What should main() return in C and C++?,"What is the correct (most efficient) way to define the main() function in C and C++ — int main() or void main() — and why? And how about the arguments?
If int main() then return 1 or return 0?
",https://stackoverflow.com/questions/204476/what-should-main-return-in-c-and-c,857,488139.0,19.0,,,2008-10-15 12:13:48,2025-02-15 19:14:08,2023-09-26 13:20:52,,,c++;c;return-value;program-entry-point;return-type,Joel,15666,25632,registered,true,204483,,CC BY-SA 4.0,2011-09-22 12:03:18,278,193,6,0,0,5,true,false,false,true,true,true,39,8,true,0.039,0.0018,6611,2008,10,12,Wednesday,false,false,false,false,false,false,false
2550774,What is size_t in C?,"I am getting confused with size_t in C. I know that it is returned by the sizeof operator. But what exactly is it? Is it a data type?
Let's say I have a for loop:
for(i = 0; i < some_size; i++)
Should I use int i; or size_t i;?
",https://stackoverflow.com/questions/2550774/what-is-size-t-in-c,847,1132094.0,15.0,,,2010-03-31 05:51:55,2023-12-31 12:58:49,2013-12-11 11:35:34,,,c;int;size-t,Vijay,67869,134713,registered,true,2550799,,CC BY-SA 3.0,2017-10-16 07:54:04,345,235,6,0,0,3,true,false,false,true,true,true,20,5,true,0.013,0.0007,6079,2010,3,5,Wednesday,false,false,false,false,false,false,false
9410,How do you pass a function as a parameter in C?,"I want to create a function that performs a function passed by parameter on a set of data. How do you pass a function as a parameter in C?
",https://stackoverflow.com/questions/9410/how-do-you-pass-a-function-as-a-parameter-in-c,840,858592.0,10.0,,,2008-08-13 02:16:32,2023-07-31 12:15:11,2016-07-29 19:09:28,,,c;function;pointers;syntax;parameters,andrewrk,31571,432,registered,true,9413,,CC BY-SA 3.0,2016-04-26 17:31:59,146,139,0,0,0,5,true,false,false,true,true,true,47,11,true,0.012,0.001,6674,2008,8,2,Wednesday,false,false,false,false,false,false,false
612097,How can I get the list of files in a directory using C or C++?,"How can I determine the list of files in a directory from inside my C or C++ code?
I'm not allowed to execute the ls command and parse the results from within my program.
",https://stackoverflow.com/questions/612097/how-can-i-get-the-list-of-files-in-a-directory-using-c-or-c,831,1401597.0,33.0,,,2009-03-04 19:35:58,2023-07-25 23:37:48,2018-10-07 01:59:17,,,c++;c;file;directory,foobarfuzzbizz,59253,39036,registered,true,612176,,CC BY-SA 4.0,2021-11-16 17:08:05,199,172,1,0,0,4,true,false,false,true,true,true,62,15,true,0.024,0.0006,6471,2009,3,19,Wednesday,false,false,false,false,false,false,false
63166,How to determine CPU and memory consumption from inside a process,"I once had the task of determining the following performance parameters from inside a running application:
- Total virtual memory available
- Virtual memory currently used
- Virtual memory currently used by my process
- Total RAM available
- RAM currently used
- RAM currently used by my process
- % CPU currently used
- % CPU currently used by my process
The code had to run on Windows and Linux. Even though this seems to be a standard task, finding the necessary information in the manuals (WIN32 API, GNU docs) as well as on the Internet took me several days, because there's so much incomplete/incorrect/outdated information on this topic to be found out there.
In order to save others from going through the same trouble, I thought it would be a good idea to collect all the scattered information plus what I found by trial and error here in one place.
",https://stackoverflow.com/questions/63166/how-to-determine-cpu-and-memory-consumption-from-inside-a-process,787,484840.0,10.0,,,2008-09-15 14:04:43,2023-09-26 06:43:24,2021-07-05 11:49:52,,,c++;c;memory;cpu,Lanzelot,16705,7381,registered,true,,,CC BY-SA 4.0,2024-01-06 19:47:43,955,845,0,0,0,4,false,false,false,true,true,true,65,11,false,0.021,0.0016,6641,2008,9,14,Monday,false,false,false,false,false,false,false
19902828,Why does ENOENT mean "No such file or directory"?,"What does the ENT mean in ENOENT?
Shouldn't the error:
No such file or directory
just be named by ENOFILE?
Is there any story or reason?
",https://stackoverflow.com/questions/19902828/why-does-enoent-mean-no-such-file-or-directory,760,474732.0,4.0,,,2013-11-11 09:25:40,2023-09-12 14:23:27,2019-09-27 22:54:34,,,c;linux;unix,mingchaoyan,8794,1699828,registered,true,19902850,,CC BY-SA 4.0,2018-06-19 13:29:13,244,145,3,0,0,3,true,false,false,true,true,true,59,9,true,0.008,0.0016,4758,2013,11,9,Monday,false,false,false,false,false,false,false
199333,How do I detect unsigned integer overflow?,"I was writing a program in C++ to find all solutions of ab = c, where a, b and c together use all the digits 0-9 exactly once. The program looped over values of a and b, and it ran a digit-counting routine each time on a, b and ab to check if the digits condition was satisfied.
However, spurious solutions can be generated when ab overflows the integer limit. I ended up checking for this using code like:
unsigned long b, c, c_test;
...
c_test=c*b; // Possible overflow
if (c_test/b != c) {/* There has been an overflow*/}
else c=c_test; // No overflow
Is there any issue with this way of testing for overflow? I know that some chips have an internal flag that is set when overflow occurs, but I've never seen it accessed through C or C++.
",https://stackoverflow.com/questions/199333/how-do-i-detect-unsigned-integer-overflow,760,495351.0,30.0,,,2008-10-13 22:53:21,2026-05-22 15:51:50,2026-05-22 15:51:50,,,c++;c;integer-overflow,Chris Johnson,10820,23732,registered,true,,,CC BY-SA 4.0,2013-10-04 00:35:48,951,756,1,0,0,3,false,false,false,true,true,true,42,7,true,0.061,0.0015,6613,2008,10,22,Monday,false,false,false,false,false,false,false
1653958,Why are #ifndef and #define used in C++ header files?,"I have been seeing code like this usually in the start of header files:
#ifndef HEADERFILE_H
#define HEADERFILE_H
And at the end of the file is
#endif
What is the purpose of this?
",https://stackoverflow.com/questions/1653958/why-are-ifndef-and-define-used-in-c-header-files,758,799783.0,5.0,,,2009-10-31 10:06:34,2023-11-15 19:41:26,2019-07-25 01:41:04,,,c++;c;c-preprocessor,Asad Khan,11989,197688,registered,true,1653965,,CC BY-SA 4.0,2015-09-25 15:41:51,255,186,2,0,0,3,true,false,false,true,true,true,53,10,true,0.006,0.0009,6230,2009,10,10,Saturday,true,false,false,false,false,false,false
6964392,Speed comparison with Project Euler: C vs Python vs Erlang vs Haskell,"I have taken Problem #12 from Project Euler as a programming exercise and to compare my (surely not optimal) implementations in C, Python, Erlang and Haskell. In order to get some higher execution times, I search for the first triangle number with more than 1000 divisors instead of 500 as stated in the original problem.
The result is the following:
C:
lorenzo@enzo:~/erlang$ gcc -lm -o euler12.bin euler12.c
lorenzo@enzo:~/erlang$ time ./euler12.bin
842161320
real 0m11.074s
user 0m11.070s
sys 0m0.000s
Python:
lorenzo@enzo:~/erlang$ time ./euler12.py
842161320
real 1m16.632s
user 1m16.370s
sys 0m0.250s
Python with PyPy:
lorenzo@enzo:~/Downloads/pypy-c-jit-43780-b590cf6de419-linux64/bin$ time ./pypy /home/lorenzo/erlang/euler12.py
842161320
real 0m13.082s
user 0m13.050s
sys 0m0.020s
Erlang:
lorenzo@enzo:~/erlang$ erlc euler12.erl
lorenzo@enzo:~/erlang$ time erl -s euler12 solve
Erlang R13B03 (erts-5.7.4) [source] [64-bit] [smp:4:4] [rq:4] [async-threads:0] [hipe] [kernel-poll:false]
Eshell V5.7.4 (abort with ^G)
1> 842161320
real 0m48.259s
user 0m48.070s
sys 0m0.020s
Haskell:
lorenzo@enzo:~/erlang$ ghc euler12.hs -o euler12.hsx
[1 of 1] Compiling Main ( euler12.hs, euler12.o )
Linking euler12.hsx ...
lorenzo@enzo:~/erlang$ time ./euler12.hsx
842161320
real 2m37.326s
user 2m37.240s
sys 0m0.080s
Summary:
- C: 100%
- Python: 692% (118% with PyPy)
- Erlang: 436% (135% thanks to RichardC)
- Haskell: 1421%
I suppose that C has a big advantage as it uses long for the calculations and not arbitrary length integers as the other three. Also it doesn't need to load a runtime first (Do the others?).
Question 1:
Do Erlang, Python and Haskell lose speed due to using arbitrary length integers or don't they as long as the values are less than MAXINT?
Question 2:
Why is Haskell so slow? Is there a compiler flag that turns off the brakes or is it my implementation? (The latter is quite probable as Haskell is a book with seven seals to me.)
Question 3:
Can you offer me some hints how to optimize these implementations without changing the way I determine the factors? Optimization in any way: nicer, faster, more "native" to the language.
EDIT:
Question 4:
Do my functional implementations permit LCO (last call optimization, a.k.a tail recursion elimination) and hence avoid adding unnecessary frames onto the call stack?
I really tried to implement the same algorithm as similar as possible in the four languages, although I have to admit that my Haskell and Erlang knowledge is very limited.
Source codes used:
#include <stdio.h>
#include <math.h>
int factorCount (long n)
{
double square = sqrt (n);
int isquare = (int) square;
int count = isquare == square ? -1 : 0;
long candidate;
for (candidate = 1; candidate <= isquare; candidate ++)
if (0 == n % candidate) count += 2;
return count;
}
int main ()
{
long triangle = 1;
int index = 1;
while (factorCount (triangle) < 1001)
{
index ++;
triangle += index;
}
printf ("%ld\n", triangle);
}
#! /usr/bin/env python3.2
import math
def factorCount (n):
square = math.sqrt (n)
isquare = int (square)
count = -1 if isquare == square else 0
for candidate in range (1, isquare + 1):
if not n % candidate: count += 2
return count
triangle = 1
index = 1
while factorCount (triangle) < 1001:
index += 1
triangle += index
print (triangle)
-module (euler12).
-compile (export_all).
factorCount (Number) -> factorCount (Number, math:sqrt (Number), 1, 0).
factorCount (_, Sqrt, Candidate, Count) when Candidate > Sqrt -> Count;
factorCount (_, Sqrt, Candidate, Count) when Candidate == Sqrt -> Count + 1;
factorCount (Number, Sqrt, Candidate, Count) ->
case Number rem Candidate of
0 -> factorCount (Number, Sqrt, Candidate + 1, Count + 2);
_ -> factorCount (Number, Sqrt, Candidate + 1, Count)
end.
nextTriangle (Index, Triangle) ->
Count = factorCount (Triangle),
if
Count > 1000 -> Triangle;
true -> nextTriangle (Index + 1, Triangle + Index + 1)
end.
solve () ->
io:format ("~p~n", [nextTriangle (1, 1) ] ),
halt (0).
factorCount number = factorCount' number isquare 1 0 - (fromEnum $ square == fromIntegral isquare)
where square = sqrt $ fromIntegral number
isquare = floor square
factorCount' number sqrt candidate count
| fromIntegral candidate > sqrt = count
| number `mod` candidate == 0 = factorCount' number sqrt (candidate + 1) (count + 2)
| otherwise = factorCount' number sqrt (candidate + 1) count
nextTriangle index triangle
| factorCount triangle > 1000 = triangle
| otherwise = nextTriangle (index + 1) (triangle + index + 1)
main = print $ nextTriangle 1 1
",https://stackoverflow.com/questions/6964392/speed-comparison-with-project-euler-c-vs-python-vs-erlang-vs-haskell,746,163885.0,17.0,,,2011-08-06 02:34:14,2023-06-01 20:19:52,2021-12-20 01:32:06,,,python;c;performance;haskell;erlang,Hyperboreus,32629,763505,registered,true,6964760,,CC BY-SA 4.0,2019-07-13 13:21:42,5996,4903,10,2,0,5,true,false,false,true,true,true,69,12,false,0.104,0.0046,5586,2011,8,2,Saturday,true,true,false,false,false,false,false
17307275,What is the printf format specifier for bool?,"Since ANSI C99 there is _Bool or bool via stdbool.h. But is there also a printf format specifier for bool?
I mean something like in that pseudo code:
bool x = true;
printf(""%B\n"", x);
which would print:
true
",https://stackoverflow.com/questions/17307275/what-is-the-printf-format-specifier-for-bool,738,1467978.0,8.0,,,2013-06-25 20:50:17,2023-02-21 20:05:22,2022-08-19 13:13:46,,,c;boolean;printf,maxschlepzig,40596,427158,registered,true,17307307,,CC BY-SA 4.0,2018-10-19 20:01:59,335,214,6,0,0,3,true,false,false,true,true,true,45,8,true,0.005,0.0005,4897,2013,6,20,Tuesday,false,false,false,false,false,false,false
822323,How to generate a random int in C?,"Is there a function to generate a random int number in C? Or will I have to use a third party library?
",https://stackoverflow.com/questions/822323/how-to-generate-a-random-int-in-c,737,2566460.0,34.0,,,2009-05-04 22:07:59,2024-09-09 05:23:27,2018-07-14 16:39:11,,,c;random,Kredns,37341,56555,registered,true,822368,,CC BY-SA 4.0,2015-07-04 20:07:09,111,104,0,0,0,2,true,false,false,true,true,true,34,8,true,0.013,0.0003,6410,2009,5,22,Monday,false,false,false,false,false,false,false
12887700,Can code that is valid in both C and C++ produce different behavior when compiled in each language?,"C and C++ have many differences, and not all valid C code is valid C++ code.
(By ""valid"" I mean standard code with defined behavior, i.e. not implementation-specific/undefined/etc.)
Is there any scenario in which a piece of code valid in both C and C++ would produce different behavior when compiled with a standard compiler in each language?
To make it a reasonable/useful comparison (I'm trying to learn something practically useful, not to try to find obvious loopholes in the question), let's assume:
- Nothing preprocessor-related (which means no hacks with
#ifdef __cplusplus, pragmas, etc.)
- Anything implementation-defined is the same in both languages (e.g. numeric limits, etc.)
- We're comparing reasonably recent versions of each standard (e.g. say, C++98 and C90 or later)
If the versions matter, then please mention which versions of each produce different behavior.
",https://stackoverflow.com/questions/12887700/can-code-that-is-valid-in-both-c-and-c-produce-different-behavior-when-compile,726,55021.0,20.0,,,2012-10-14 23:54:26,2025-12-10 17:22:13,2012-10-16 23:53:47,,,c++;c,user541686,213473,541686,registered,true,12887719,,CC BY-SA 3.0,2012-10-27 22:55:49,970,883,1,0,0,2,true,false,false,true,true,true,99,18,true,0.363,0.0132,5151,2012,10,23,Sunday,true,false,false,false,false,false,false
1716296,Why does printf not flush after the call unless a newline is in the format string?,"Why does printf not flush after the call unless a newline is in the format string? Is this POSIX behavior? How might I have printf immediately flush every time?
",https://stackoverflow.com/questions/1716296/why-does-printf-not-flush-after-the-call-unless-a-newline-is-in-the-format-strin,717,548550.0,10.0,,,2009-11-11 16:22:39,2025-05-14 10:35:23,2018-07-24 17:18:33,,,c;printf;flush,Crazy Chenz,13370,71865,registered,true,1716621,,CC BY-SA 4.0,,194,161,2,0,0,3,true,false,false,true,true,true,82,16,true,0.018,0.0013,6219,2009,11,16,Wednesday,false,false,false,false,false,false,false
2649334,Difference between static and shared libraries?,"What is the difference between static and shared libraries?
I use Eclipse and there are several project types including Static Libraries and Shared Libraries? Does one have an advantage over the other?
",https://stackoverflow.com/questions/2649334/difference-between-static-and-shared-libraries,713,332281.0,9.0,,,2010-04-15 22:08:01,2024-11-15 15:19:44,2012-04-06 05:30:43,,,c++;c;shared-libraries;static-libraries,Mohit Deshpande,55597,200477,registered,true,2649430,,CC BY-SA 3.0,2015-04-07 14:44:33,217,203,0,0,0,4,true,false,false,true,true,true,47,6,true,0.027,0.0021,6064,2010,4,22,Thursday,false,false,false,false,false,false,false
4955198,What does 'dereferencing' a pointer mean in C/C++?,"Please include an example with the explanation.
",https://stackoverflow.com/questions/4955198/what-does-dereferencing-a-pointer-mean-in-c-c,713,863965.0,6.0,,,2011-02-10 09:16:22,2023-03-30 14:25:51,2023-03-30 14:25:51,,,c++;c;pointers;dereference;c++-faq,asir,13629,606344,unregistered,true,4955297,,CC BY-SA 4.0,2015-05-13 16:50:35,55,48,0,0,0,5,true,false,false,true,true,true,58,8,true,0.007,0.0008,5763,2011,2,9,Thursday,false,false,false,false,false,false,false
11694546,"Divide a number by 3 without using *, /, +, -, % operators","How would you divide a number by 3 without using *, /, +, -, %, operators?
The number may be signed or unsigned.
",https://stackoverflow.com/questions/11694546/divide-a-number-by-3-without-using-operators,702,156781.0,42.0,,,2012-07-27 19:34:31,2026-08-12 10:20:40,2023-03-30 14:23:29,,,c;math;bit-manipulation;division;divide,Green goblin,9990,1347366,registered,true,11694778,,CC BY-SA 4.0,2014-03-14 13:27:55,194,115,5,0,0,5,true,false,false,true,true,true,58,13,false,0.268,0.0045,5230,2012,7,19,Friday,false,false,false,false,false,false,false
558122,What is a "static" function in C?,"The question was about plain c functions, not c++ static methods, as clarified in comments.
I understand what a static variable is, but what is a static function?
And why is it that if I declare a function, let's say void print_matrix, in let's say a.c (WITHOUT a.h) and include ""a.c"" - I get ""print_matrix@@....) already defined in a.obj"", BUT if I declare it as static void print_matrix then it compiles?
UPDATE Just to clear things up - I know that including .c is bad, as many of you pointed out. I just do it to temporarily clear space in main.c until I have a better idea of how to group all those functions into proper .h and .c files. Just a temporary, quick solution.
",https://stackoverflow.com/questions/558122/what-is-a-static-function-in-c,700,795045.0,11.0,,,2009-02-17 18:26:02,2024-12-02 20:48:35,2019-11-03 22:48:41,,,c;function;static;terminology,Slava V,17414,37141,registered,true,558132,,CC BY-SA 4.0,2018-10-27 18:03:29,1109,681,13,2,0,4,true,false,false,true,true,true,43,7,true,0.014,0.0009,6486,2009,2,18,Tuesday,false,false,false,false,false,false,false
2397984,"Undefined, unspecified and implementation-defined behavior","What is undefined behavior (UB) in C and C++? What about unspecified behavior and implementation-defined behavior? What is the difference between them?
",https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior,688,106380.0,10.0,,,2010-03-07 21:10:30,2025-03-30 12:33:46,2021-11-22 03:19:14,,,c++;c;undefined-behavior;unspecified-behavior;implementation-defined-behavior,Zolomon,9997,182153,registered,true,4105123,,CC BY-SA 4.0,2014-03-25 09:53:53,188,154,0,0,0,5,true,false,false,true,true,true,58,5,false,0.094,0.0065,6103,2010,3,21,Sunday,true,false,false,false,false,false,false
5431941,Why is “while( !feof(file) )” always wrong?,"What is wrong with using feof() to control a read loop? For example:
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char **argv)
{
char *path = "stdin";
FILE *fp = argc > 1 ? fopen(path=argv[1], "r") : stdin;
if( fp == NULL ){
perror(path);
return EXIT_FAILURE;
}
while( !feof(fp) ){ /* THIS IS WRONG */
/* Read and process data from file… */
}
if( fclose(fp) != 0 ){
perror(path);
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
What is wrong with this loop?
",https://stackoverflow.com/questions/5431941/why-is-while-feoffile-always-wrong,685,307727.0,6.0,,,2011-03-25 11:42:33,2023-10-21 16:39:04,2022-06-13 18:12:26,,,c;file;while-loop;eof;feof,William Pursell,215352,140750,registered,true,26557243,,CC BY-SA 4.0,2014-03-25 09:53:18,637,586,2,0,0,5,true,false,false,true,true,true,43,7,true,0.019,0.0022,5720,2011,3,11,Friday,false,false,false,false,false,false,false
1674032,"static const" vs "#define" vs "enum","Which one is better to use among the below statements in C?
static const int var = 5;
or
#define var 5
or
enum { var = 5 };
",https://stackoverflow.com/questions/1674032/static-const-vs-define-vs-enum,677,394516.0,17.0,,,2009-11-04 14:19:24,2023-08-14 15:37:52,2016-01-01 17:55:08,,,c;constants,Vijay,67869,134713,registered,true,1674459,,CC BY-SA 3.0,2019-01-11 11:12:42,226,133,3,0,0,2,true,false,false,true,true,true,67,6,false,0.043,0.0017,6226,2009,11,14,Wednesday,false,false,false,false,false,false,false
654754,What REALLY happens when you don't free after malloc before program termination?,"We are all taught that you must free every pointer that is allocated. I'm a bit curious, though, about the real cost of not freeing memory. In some obvious cases, like when malloc() is called inside a loop or part of a thread execution, it's very important to free, so there aren't any memory leaks. But consider the following two examples:
First, if I have code that's something like this:
int main()
{
char *a = malloc(1024);
/* Do some arbitrary stuff with 'a' (no alloc functions) */
return 0;
}
What's the real result here? My thinking is that the process dies and then the heap space is gone anyway, so there isn't any harm in missing the call to free (however, I do recognize the importance of having it anyway for closure, maintainability, and good practice). Am I right in this thinking?
Second, let's say I have a program that acts a bit like a shell. Users can declare variables like aaa = 123 and those are stored in some dynamic data structure for later use. Clearly, it seems obvious that you'd use some solution that will calls some *alloc function (hashmap, linked list, something like that).
For this kind of program, it doesn't make sense to ever free after calling malloc, because these variables must be present at all times during the program's execution and there isn't any good way (that I can see) to implement this with statically allocated space. Is it bad design to have a bunch of memory that's allocated, but only freed as part of the process ending? If so, what's the alternative?
",https://stackoverflow.com/questions/654754/what-really-happens-when-you-dont-free-after-malloc-before-program-termination,669,184966.0,20.0,,,2009-03-17 15:29:09,2025-08-18 21:22:21,2025-08-18 20:41:56,,,c;malloc;free,Scott,10807,67491,registered,true,654766,,CC BY-SA 4.0,2018-04-29 08:09:11,1652,1532,5,0,0,3,true,false,false,true,true,true,84,12,true,0.108,0.0036,6458,2009,3,15,Tuesday,false,false,false,false,false,false,false
12774207,"Fastest way to check if a file exists using standard C++/C++11,14,17/C?","I would like to find the fastest way to check if a file exists in standard C++11, 14, 17, or C. I have thousands of files and before doing something on them I need to check if all of them exist. What can I write instead of /* SOMETHING */ in the following function?
inline bool exist(const std::string& name)
{
/* SOMETHING */
}
",https://stackoverflow.com/questions/12774207/fastest-way-to-check-if-a-file-exists-using-standard-c-c11-14-17-c,663,1064828.0,23.0,,,2012-10-08 01:10:11,2023-06-11 11:42:07,2022-01-31 03:15:07,,,c++;c;file;stream,Vincent,61459,882932,registered,true,12774387,,CC BY-SA 4.0,,382,338,2,0,0,4,true,false,false,true,true,true,71,11,true,0.022,0.0006,5157,2012,10,1,Monday,false,false,false,false,false,false,false
330793,How to initialize a struct in accordance with C programming language standards,"I want to initialize a struct element, split in declaration and initialization. This is what I have:
typedef struct MY_TYPE {
bool flag;
short int value;
double stuff;
} MY_TYPE;
void function(void) {
MY_TYPE a;
...
a = { true, 15, 0.123 }
}
Is this the way to declare and initialize a local variable of MY_TYPE in accordance with C programming language standards (C89, C90, C99, C11, etc.)? Or is there anything better or at least working?
Update I ended up having a static initialization element where I set every subelement according to my needs.
",https://stackoverflow.com/questions/330793/how-to-initialize-a-struct-in-accordance-with-c-programming-language-standards,652,1409365.0,18.0,,,2008-12-01 13:13:17,2025-09-03 12:56:13,2018-12-13 02:46:20,,,c;struct;initialization,cringe,14150,834,registered,true,330867,,CC BY-SA 4.0,2019-07-18 13:08:19,642,567,2,0,0,3,true,false,false,true,true,true,78,12,false,0.013,0.0005,6564,2008,12,13,Monday,false,false,false,false,false,false,false
34732,How do I list the symbols in a .so file,"How do I list the symbols being exported from a .so file? If possible, I'd also like to know their source (e.g. if they are pulled in from a static library).
I'm using gcc 4.0.2, if that makes a difference.
",https://stackoverflow.com/questions/34732/how-do-i-list-the-symbols-in-a-so-file,639,641582.0,11.0,,,2008-08-29 16:57:47,2024-09-20 07:16:14,2019-01-10 11:53:00,,,c++;c;gcc;symbols;name-mangling,Moe,30090,3051,registered,true,34796,,CC BY-SA 4.0,2014-11-04 15:35:05,223,209,0,0,0,5,true,false,false,true,true,true,39,10,false,0.017,0.001,6658,2008,8,16,Friday,false,false,false,false,false,false,false
38561,What is the conversion specifier for printf that formats a long?,"The printf function takes an argument type, such as %d or %i for a signed int. However, I don't see anything for a long value.
",https://stackoverflow.com/questions/38561/what-is-the-conversion-specifier-for-printf-that-formats-a-long,630,1183318.0,7.0,,,2008-09-01 22:45:25,2022-12-19 01:40:04,2022-11-04 21:01:45,,,c;printf;long-integer,Thomas Owens,116701,572,registered,true,38570,,CC BY-SA 4.0,2019-07-18 13:06:46,199,127,5,0,0,3,true,false,false,true,true,true,64,11,true,0.006,0.0005,6655,2008,9,22,Monday,false,false,false,false,false,false,false
111928,Is there a printf converter to print in binary format?,"I can print with printf as a hex or octal number. Is there a format tag to print as binary, or arbitrary base?
I am running gcc.
printf("%d %x %o\n", 10, 10, 10); //prints "10 A 12\n"
printf("%b\n", 10); // prints "%b\n"
",https://stackoverflow.com/questions/111928/is-there-a-printf-converter-to-print-in-binary-format,626,1389842.0,62.0,,,2008-09-21 20:04:58,2025-06-17 14:47:48,2022-12-07 01:48:38,,,c;printf,Brian,8934,8959,registered,true,,,CC BY-SA 4.0,2011-08-21 14:02:07,314,263,2,0,0,2,false,false,false,true,true,true,54,10,true,0.045,0.0005,6635,2008,9,20,Sunday,true,false,false,false,false,false,false
24848359,Which is faster: while(1) or while(2)?,"This was an interview question asked by a senior manager.
Which is faster?
while(1) {
// Some code
}
or
while(2) {
//Some code
}
I said that both have the same execution speed, as the expression inside while should finally evaluate to true or false. In this case, both evaluate to true and there are no extra conditional instructions inside the while condition. So, both will have the same speed of execution and I prefer while (1).
But the interviewer said confidently:
"Check your basics. while(1) is faster than while(2)."
(He was not testing my confidence)
Is this true?
",https://stackoverflow.com/questions/24848359/which-is-faster-while1-or-while2,617,101572.0,24.0,,,2014-07-20 07:32:49,2025-07-16 17:31:44,2024-05-17 10:01:38,,,c;performance;while-loop,Nikole ,4739,616705,registered,true,,,CC BY-SA 4.0,2014-07-27 01:46:32,776,595,9,0,0,3,false,false,false,true,true,true,38,6,true,0.236,0.0061,4507,2014,7,7,Sunday,true,false,false,false,false,false,false
246127,Why is volatile needed in C?,"Why is volatile needed in C? What is it used for? What will it do?
",https://stackoverflow.com/questions/246127/why-is-volatile-needed-in-c,615,489429.0,19.0,,,2008-10-29 08:36:39,2024-02-05 15:40:56,2015-05-27 17:57:13,,,c;declaration;volatile,thomas,,,does_not_exist,true,,,CC BY-SA 3.0,2012-09-05 18:36:37,87,67,1,0,0,3,false,false,false,true,false,true,28,6,true,0.039,0.0013,6597,2008,10,8,Wednesday,false,false,false,false,false,false,false
4264127,Correct format specifier for double in printf,"What is the correct format specifier for double in printf? Is it %f or is it %lf? I believe it's %f, but I am not sure.
Code sample
#include <stdio.h>
int main()
{
double d = 1.4;
printf("%lf", d); // Is this wrong?
}
",https://stackoverflow.com/questions/4264127/correct-format-specifier-for-double-in-printf,615,1600420.0,5.0,,,2010-11-24 06:45:28,2024-03-24 13:08:24,2024-03-24 13:08:24,,,c;floating-point;printf;double;format-specifiers,Leopard,6151,518402,unregistered,true,4264154,,CC BY-SA 4.0,2018-07-15 04:54:36,347,242,6,0,0,5,true,false,false,true,true,true,45,7,false,0.003,0.0004,5841,2010,11,6,Wednesday,false,false,false,false,false,false,false
145270,Calling C/C++ from Python?,"What would be the quickest way to construct a Python binding to a C or C++ library?
(I am using Windows if this matters.)
",https://stackoverflow.com/questions/145270/calling-c-c-from-python,613,579990.0,12.0,,,2008-09-28 05:34:20,2021-06-17 21:41:02,2017-10-04 22:55:55,2020-10-25 04:34:29,Needs more focus,c++;python;c,shoosh,79702,9611,registered,true,145436,,,,137,123,0,0,0,3,true,true,false,true,true,true,26,4,true,0.021,0.0011,6628,2008,9,5,Sunday,true,true,false,false,false,false,false
5029840,Convert char to int in C and C++,"How do I convert a char to an int in C and C++?
",https://stackoverflow.com/questions/5029840/convert-char-to-int-in-c-and-c,609,2935382.0,14.0,,,2011-02-17 13:57:37,2024-11-11 23:02:54,2011-02-17 14:11:04,,,c++;c;gcc,mainajaved,8209,621510,registered,true,,,CC BY-SA 2.5,2013-08-13 15:24:25,81,48,2,0,0,3,false,false,false,true,true,true,32,8,false,0.005,0.0002,5756,2011,2,13,Thursday,false,false,false,false,false,false,false
7724569,Debug vs Release in CMake,"In a GCC compiled project,
- How do I run CMake for each build configuration type (debug/release)?
- How do I specify debug and release C/C++ flags using CMake?
- How do I express that the main executable will be compiled with
g++ and one nested library with gcc?
",https://stackoverflow.com/questions/7724569/debug-vs-release-in-cmake,609,875881.0,6.0,,,2011-10-11 10:26:54,2025-08-01 09:20:08,2025-08-01 09:20:08,2025-08-01 09:20:42,Needs more focus,c++;c;gcc;cmake,Cartesius00,24730,684534,registered,true,7725055,,,,329,260,2,0,0,4,true,true,false,true,true,true,25,5,false,0.007,0.0007,5520,2011,10,10,Tuesday,false,false,false,false,false,false,false
131803,unsigned int vs. size_t,"I notice that modern C and C++ code seems to use size_t instead of int/unsigned int pretty much everywhere - from parameters for C string functions to the STL. I am curious as to the reason for this and the benefits it brings.
",https://stackoverflow.com/questions/131803/unsigned-int-vs-size-t,603,310826.0,8.0,,,2008-09-25 07:00:03,2019-08-07 18:34:16,,,,c++;c;size-t,Rob,79348,9236,registered,true,131833,,CC BY-SA 2.5,2013-09-24 02:53:05,274,228,3,0,0,3,true,false,false,true,true,false,23,4,false,0.026,0.0019,6631,2008,9,7,Thursday,false,false,false,false,false,false,false
9809213,What are .a and .so files?,"I'm currently trying to port a C application to AIX and am getting confused. What are .a and .so files and how are they used when building/running an application?
",https://stackoverflow.com/questions/9809213/what-are-a-and-so-files,599,606646.0,5.0,,,2012-03-21 16:53:08,2023-11-20 04:33:01,2017-11-26 17:10:45,,,c;unix;compilation;shared-libraries;.a,Dunc,8154,563189,registered,true,9810368,,CC BY-SA 3.0,2018-08-01 05:14:47,239,163,0,1,0,5,true,false,false,true,true,true,26,6,true,0.008,0.001,5358,2012,3,16,Wednesday,false,false,false,false,false,false,false
1704407,What is the difference between char s[] and char *s?,"In C, one can use a string literal in a declaration like this:
char s[] = ""hello"";
or like this:
char *s = ""hello"";
So what is the difference? I want to know what actually happens in terms of storage duration, both at compile and run time.
",https://stackoverflow.com/questions/1704407/what-is-the-difference-between-char-s-and-char-s,594,401081.0,14.0,,,2009-11-09 22:34:21,2021-11-10 14:35:27,2017-12-22 09:04:00,,,c;string;char;constants,user188276,,,does_not_exist,true,1704433,,CC BY-SA 3.0,2012-04-20 18:12:33,316,247,2,0,0,4,true,false,false,true,false,true,52,10,true,0.035,0.0015,6221,2009,11,22,Monday,false,false,false,false,false,false,false
230062,What's the best way to check if a file exists in C?,"Is there a better way than simply trying to open the file?
int exists(const char *fname)
{
FILE *file;
if ((file = fopen(fname, ""r"")))
{
fclose(file);
return 1;
}
return 0;
}
",https://stackoverflow.com/questions/230062/whats-the-best-way-to-check-if-a-file-exists-in-c,589,873036.0,8.0,,,2008-10-23 14:57:24,2022-05-12 19:12:22,2019-02-22 00:48:25,,,c;filesystems;cross-platform,Dave Marshall,7635,1248,registered,true,230068,,CC BY-SA 4.0,2019-07-18 13:12:57,244,213,1,0,0,3,true,false,false,true,true,true,55,12,true,0.009,0.0007,6603,2008,10,14,Thursday,false,false,false,false,false,false,false
4295432,Typedef function pointer?,"I'm learning how to dynamically load DLL's but what I don't understand is this line
typedef void (*FunctionFunc)();
I have a few questions. If someone is able to answer them I would be grateful.
- Why is
typedef used?
- The syntax looks odd; after
void should there not be a function name or something? It looks like an anonymous function.
- Is a function pointer created to store the memory address of a function?
So I'm confused at the moment; can you clarify things for me?
",https://stackoverflow.com/questions/4295432/typedef-function-pointer,581,649217.0,6.0,,,2010-11-28 04:50:25,2024-09-14 13:21:16,2019-05-17 07:26:12,,,c++;c;pointers;typedef,Jack Harvin,6815,518544,unregistered,true,4295495,,CC BY-SA 4.0,2013-10-03 06:56:32,585,478,3,0,0,4,true,false,false,true,true,true,25,3,true,0.009,0.0009,5837,2010,11,4,Sunday,true,false,false,false,false,false,false
2670639,Why are hexadecimal numbers prefixed with 0x?,"Why are hexadecimal numbers prefixed as 0x?
I understand the usage of the prefix, but I don't understand the significance of why 0x was chosen.
",https://stackoverflow.com/questions/2670639/why-are-hexadecimal-numbers-prefixed-with-0x,575,445037.0,5.0,,,2010-04-19 20:33:01,2026-01-18 18:16:55,2025-08-28 18:12:53,,,c;syntax;hex,unj2,53936,82368,registered,true,4581351,,CC BY-SA 4.0,2018-10-19 18:31:59,184,144,2,0,0,3,true,false,false,true,true,true,45,7,true,0.011,0.0013,6060,2010,4,20,Monday,false,false,false,false,false,false,false
150355,Programmatically find the number of cores on a machine,"Is there a way to determine how many cores a machine has from C/C++ in a platform-independent way? If no such thing exists, what about determining it per-platform (Windows/*nix/Mac)?
",https://stackoverflow.com/questions/150355/programmatically-find-the-number-of-cores-on-a-machine,572,297417.0,21.0,,,2008-09-29 19:51:45,2023-11-25 07:57:45,2020-09-12 17:10:23,,,c++;c;multithreading;multiplatform,hazzen,17590,5066,registered,true,150971,,CC BY-SA 4.0,2015-01-04 19:33:33,190,183,0,0,0,4,true,false,false,true,true,true,54,9,false,0.071,0.0019,6627,2008,9,19,Monday,false,false,false,false,false,false,false
75191,What is an unsigned char?,"In C/C++, what is an unsigned char used for? How is it different from a regular char?
",https://stackoverflow.com/questions/75191/what-is-an-unsigned-char,565,775920.0,16.0,,,2008-09-16 18:05:18,2024-07-16 10:08:40,2024-07-16 10:08:40,,,c++;c;char,Landon Kuhn,79121,1785,registered,true,87648,,CC BY-SA 4.0,2015-10-13 08:27:46,119,86,2,0,0,3,true,false,false,true,true,true,25,5,true,0.021,0.0007,6640,2008,9,18,Tuesday,false,false,false,false,false,false,false
252780,Why should we typedef a struct so often in C?,"I have seen many programs consisting of structures like the one below
typedef struct
{
int i;
char k;
} elem;
elem user;
Why is it needed so often? Any specific reason or applicable area?
",https://stackoverflow.com/questions/252780/why-should-we-typedef-a-struct-so-often-in-c,561,692794.0,16.0,,,2008-10-31 07:14:03,2025-11-21 13:32:10,2016-03-18 01:28:49,,,c;struct;typedef,Manoj Doubts,14227,31116,registered,true,252810,,CC BY-SA 3.0,2019-07-18 16:10:29,239,201,1,0,0,3,true,false,false,true,true,true,45,10,true,0.023,0.0008,6595,2008,10,7,Friday,false,false,false,false,false,false,false
25789644,What is the difference between using a Makefile and CMake to compile the code?,"I code in C/C++ and use a (GNU) Makefile to compile the code. I can do the same with CMake and get a Makefile. However, what is the difference between using a Makefile and CMake to compile the code?
",https://stackoverflow.com/questions/25789644/what-is-the-difference-between-using-a-makefile-and-cmake-to-compile-the-code,561,328309.0,3.0,,,2014-09-11 14:07:47,2022-08-15 00:48:40,2022-04-15 12:25:36,,,c++;c;makefile;cmake,rish,6085,2024246,registered,true,25790020,,CC BY-SA 4.0,,206,199,0,0,0,4,true,false,false,true,true,true,78,14,true,0.009,0.0017,4454,2014,9,14,Thursday,false,false,false,false,false,false,false
2524611,How can one print a size_t variable portably using the printf family?,"I have a variable of type size_t, and I want to print it using printf(). What format specifier do I use to print it portably?
In 32-bit machine, %u seems right. I compiled with g++ -g -W -Wall -Werror -ansi -pedantic, and there was no warning. But when I compile that code in 64-bit machine, it produces warning.
size_t x = <something>;
printf(""size = %u\n"", x);
warning: format '%u' expects type 'unsigned int',
but argument 2 has type 'long unsigned int'
The warning goes away, as expected, if I change that to %lu.
The question is, how can I write the code, so that it compiles warning free on both 32- and 64- bit machines?
Edit: As a workaround, I guess one answer might be to ""cast"" the variable into an integer that is big enough, say unsigned long, and print using %lu. That would work in both cases. I am looking if there is any other idea.
",https://stackoverflow.com/questions/2524611/how-can-one-print-a-size-t-variable-portably-using-the-printf-family,552,477711.0,14.0,,,2010-03-26 15:52:25,2024-02-22 17:13:15,2020-05-25 04:30:55,,,c;printf,Arun,20653,278326,registered,true,2524675,,CC BY-SA 4.0,2015-08-25 10:56:23,1020,870,8,0,0,2,true,false,false,true,true,true,69,12,true,0.029,0.0012,6084,2010,3,15,Friday,false,false,false,false,false,false,false
1662909,Undefined reference to pthread_create in Linux,"I picked up the following demo off the web from https://computing.llnl.gov/tutorials/pthreads/
#include <pthread.h>
#include <stdio.h>
#define NUM_THREADS 5
void *PrintHello(void *threadid)
{
long tid;
tid = (long)threadid;
printf(""Hello World! It's me, thread #%ld!\n"", tid);
pthread_exit(NULL);
}
int main (int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
int rc;
long t;
for(t=0; t<NUM_THREADS; t++){
printf(""In main: creating thread %ld\n"", t);
rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
if (rc){
printf(""ERROR; return code from pthread_create() is %d\n"", rc);
exit(-1);
}
}
pthread_exit(NULL);
}
But when I compile it on my machine (running Ubuntu Linux 9.04) I get the following error:
corey@ubuntu:~/demo$ gcc -o term term.c
term.c: In function ‘main’:
term.c:23: warning: incompatible implicit declaration of built-in function ‘exit’
/tmp/cc8BMzwx.o: In function `main':
term.c:(.text+0x82): undefined reference to `pthread_create'
collect2: ld returned 1 exit status
This doesn't make any sense to me, because the header includes pthread.h, which should have the pthread_create function. Any ideas what's going wrong?
",https://stackoverflow.com/questions/1662909/undefined-reference-to-pthread-create-in-linux,549,996235.0,16.0,,,2009-11-02 18:40:52,2022-12-08 04:18:36,2017-03-09 06:30:29,,,c;linux;multithreading;pthreads,Ralph,6419,187770,unregistered,true,,,CC BY-SA 3.0,2011-10-11 16:15:39,1432,1259,4,1,0,4,false,false,false,true,true,true,46,6,false,0.016,0.0006,6228,2009,11,18,Monday,false,false,false,false,false,false,false
2386772,What is the difference between float and double?,"I've read about the difference between double precision and single precision. However, in most cases, float and double seem to be interchangeable, i.e. using one or the other does not seem to affect the results. Is this really the case? When are floats and doubles interchangeable? What are the differences between them?
",https://stackoverflow.com/questions/2386772/what-is-the-difference-between-float-and-double,548,1246394.0,14.0,,,2010-03-05 12:48:32,2023-12-15 17:42:16,2021-12-31 09:51:41,,,c++;c;floating-point;precision;ieee-754,VaioIsBorn,7951,281619,unregistered,true,2386882,,CC BY-SA 4.0,2017-09-24 23:25:57,354,321,2,0,0,5,true,false,false,true,true,true,48,8,true,0.011,0.0004,6105,2010,3,12,Friday,false,false,false,false,false,false,false
137038,How do you get assembler output from C/C++ source in GCC?,"How does one do this?
If I want to analyze how something is getting compiled, how would I get the emitted assembly code?
",https://stackoverflow.com/questions/137038/how-do-you-get-assembler-output-from-c-c-source-in-gcc,547,575121.0,17.0,,,2008-09-26 00:10:21,2023-04-28 07:07:56,2022-11-02 20:25:01,,,c++;c;assembly;gcc;disassembly,Doug T.,66039,8123,registered,true,137074,,CC BY-SA 4.0,2019-06-28 06:24:11,135,121,0,0,0,5,true,false,false,true,true,true,57,11,true,0.03,0.001,6630,2008,9,0,Friday,false,false,false,false,false,false,false
351733,How would one write object-oriented code in C?,"What are some ways to write object-oriented code in C? Especially with regard to polymorphism.
See also this Stack Overflow question Object-orientation in C.
",https://stackoverflow.com/questions/351733/how-would-one-write-object-oriented-code-in-c,547,414458.0,28.0,,,2008-12-09 04:02:40,2019-12-30 23:15:43,2019-12-30 23:15:43,2016-09-26 11:38:13,Needs more focus,c;oop;object,Dinah,54427,356,registered,true,,,,2013-01-08 08:06:08,270,161,0,1,0,3,false,true,false,true,true,true,46,8,true,0.068,0.0013,6556,2008,12,4,Tuesday,false,false,false,false,false,false,false
1518711,How does free know how much to free?,"In C programming, you can pass any kind of pointer you like as an argument to free, how does it know the size of the allocated memory to free? Whenever I pass a pointer to some function, I have to also pass the size (ie an array of 10 elements needs to receive 10 as a parameter to know the size of the array), but I do not have to pass the size to the free function. Why not, and can I use this same technique in my own functions to save me from needing to cart around the extra variable of the array's length?
",https://stackoverflow.com/questions/1518711/how-does-free-know-how-much-to-free,545,110817.0,11.0,,,2009-10-05 07:45:31,2024-06-24 18:28:14,2024-06-24 18:28:14,,,c;pointers;free,Joshua Cheek,32154,184212,registered,true,1518718,,CC BY-SA 4.0,2019-07-18 16:14:13,519,512,0,0,0,3,true,false,false,true,true,true,36,8,true,0.099,0.0049,6256,2009,10,7,Monday,false,false,false,false,false,false,false
1903954,"Is there a standard sign function (signum, sgn) in C/C++?","I want a function that returns -1 for negative numbers and +1 for positive numbers.
http://en.wikipedia.org/wiki/Sign_function
It's easy enough to write my own, but it seems like something that ought to be in a standard library somewhere.
Edit: Specifically, I was looking for a function working on floats.
",https://stackoverflow.com/questions/1903954/is-there-a-standard-sign-function-signum-sgn-in-c-c,539,619719.0,21.0,,,2009-12-14 22:27:15,2025-12-13 03:28:29,2009-12-24 02:40:14,,,c++;c;math,batty,7936,53602,registered,true,4609795,,CC BY-SA 2.5,2019-08-10 14:49:27,396,308,0,1,0,3,true,false,false,true,true,true,57,10,true,0.034,0.0009,6186,2009,12,22,Monday,false,false,false,false,false,false,false
24886,Is there a performance difference between i++ and ++i in C?,"Is there a performance difference between i++ and ++i if the resulting value is not used?
",https://stackoverflow.com/questions/24886/is-there-a-performance-difference-between-i-and-i-in-c,538,150492.0,14.0,,,2008-08-24 06:48:23,2023-06-08 11:52:36,2023-01-25 03:47:04,,,c;performance;oop;post-increment;pre-increment,Mark Harrison,306839,116,registered,true,24887,,CC BY-SA 4.0,2014-10-21 06:37:52,123,90,2,0,0,5,true,false,false,true,true,true,59,11,true,0.093,0.0036,6663,2008,8,6,Sunday,true,false,false,false,false,false,false
1775865,Preventing console window from closing on Visual Studio C/C++ Console application,"I've used Visual Studio for years, but this is the first time I've done any 'Console Application' development.
When I run my application the console window pops up, the program output appears and then the window closes as the application exits.
Is there a way to either keep it open until I have checked the output, or view the results after the window has closed?
",https://stackoverflow.com/questions/1775865/preventing-console-window-from-closing-on-visual-studio-c-c-console-applicatio,536,590492.0,25.0,,,2009-11-21 15:58:35,2025-01-13 08:42:38,2025-01-13 08:42:38,,,c;visual-studio;console,Martin,40551,770,registered,true,54084067,,CC BY-SA 4.0,2013-10-13 17:52:45,386,365,0,0,0,3,true,false,false,true,true,true,81,11,false,0.042,0.0009,6209,2009,11,15,Saturday,true,false,false,false,false,false,false
8225776,Why does sizeof(x++) not increment x?,"Here is the code compiled in Dev-C++ on Windows:
#include <stdio.h>
int main() {
int x = 5;
printf("%d and ", sizeof(x++)); // note 1
printf("%d\n", x); // note 2
return 0;
}
I expect x to be 6 after executing note 1. However, the output is:
4 and 5
Why does x not increment after note 1?
",https://stackoverflow.com/questions/8225776/why-does-sizeofx-not-increment-x,529,35952.0,10.0,,,2011-11-22 11:07:16,2023-10-03 18:54:37,2023-10-03 18:54:37,,,c;sizeof,Neigyl R. Noval,6058,559397,registered,true,8225835,,CC BY-SA 4.0,2019-07-18 11:50:13,584,334,4,1,0,2,true,false,false,true,true,true,37,6,true,0.278,0.0147,5478,2011,11,11,Tuesday,false,false,false,false,false,false,false
1018853,Why is the use of alloca() not considered good practice?,"alloca() allocates memory on the stack rather than on the heap, as in the case of malloc(). So, when I return from the routine the memory is freed. So, actually this solves my problem of freeing up dynamically allocated memory. Freeing of memory allocated through malloc() is a major headache and if somehow missed leads to all sorts of memory problems.
Why is the use of alloca() discouraged in spite of the above features?
",https://stackoverflow.com/questions/1018853/why-is-the-use-of-alloca-not-considered-good-practice,526,228500.0,26.0,,,2009-06-19 16:24:16,2025-02-19 11:39:32,2019-01-10 13:45:23,,,c;stack;malloc;allocation;alloca,Vaibhav,6087,120636,registered,true,1018865,,CC BY-SA 4.0,,492,426,4,0,0,5,true,false,false,true,true,true,56,10,true,0.114,0.0023,6364,2009,6,16,Friday,false,false,false,false,false,false,false
1993390,Static linking vs dynamic linking,"Are there any compelling performance reasons to choose static linking over dynamic linking or vice versa in certain situations? I've heard or read the following, but I don't know enough on the subject to vouch for its veracity.
1) The difference in runtime performance between static linking and dynamic linking is usually negligible.
2) (1) is not true if using a profiling compiler that uses profile data to optimize program hotpaths because with static linking, the compiler can optimize both your code and the library code. With dynamic linking only your code can be optimized. If most of the time is spent running library code, this can make a big difference. Otherwise, (1) still applies.
",https://stackoverflow.com/questions/1993390/static-linking-vs-dynamic-linking,511,341937.0,16.0,,,2010-01-03 00:06:12,2025-05-21 14:59:30,2017-01-11 20:22:44,,,c++;c;performance;static-linking;dynamic-linking,Eloff,22028,152580,registered,true,1993407,,CC BY-SA 3.0,2018-05-11 21:34:23,718,697,0,0,0,5,true,false,false,true,true,true,33,5,false,0.047,0.0015,6166,2010,1,0,Sunday,true,false,false,false,false,false,false
1461432,What is array-to-pointer conversion aka. decay?,"What is array-to-pointer conversion aka. decay? Is there any relation to array pointers?
",https://stackoverflow.com/questions/1461432/what-is-array-to-pointer-conversion-aka-decay,509,123266.0,11.0,,,2009-09-22 17:24:43,2023-09-25 23:15:21,2023-09-25 23:15:21,,,c++;c;arrays;pointers,Vamsi,6083,177303,registered,true,1461449,,CC BY-SA 4.0,2014-11-04 15:08:24,96,89,0,0,0,4,true,false,false,true,true,true,47,6,true,0.089,0.0041,6269,2009,9,17,Tuesday,false,false,false,false,false,false,false
859634,C pointer to array/array of pointers disambiguation,"What is the difference between the following declarations:
int* arr1[8];
int (*arr2)[8];
int *(arr3[8]);
What is the general rule for understanding more complex declarations?
",https://stackoverflow.com/questions/859634/c-pointer-to-array-array-of-pointers-disambiguation,507,405345.0,12.0,,,2009-05-13 18:35:12,2020-05-31 03:17:14,2014-12-12 06:12:51,,,c;arrays;pointers;variable-declaration,George,15709,48486,registered,true,859650,,CC BY-SA 3.0,2014-12-12 07:13:56,216,178,1,0,0,4,true,false,false,true,true,true,51,7,false,0.03,0.0013,6401,2009,5,18,Wednesday,false,false,false,false,false,false,false
577554,When is assembly faster than C?,"One of the stated reasons for knowing assembler is that, on occasion, it can be employed to write code that will be more performant than writing that code in a higher-level language, C in particular. However, I've also heard it stated many times that although that's not entirely false, the cases where assembler can actually be used to generate more performant code are both extremely rare and require expert knowledge of and experience with assembly.
This question doesn't even get into the fact that assembler instructions will be machine-specific and non-portable, or any of the other aspects of assembler. There are plenty of good reasons for knowing assembly besides this one, of course, but this is meant to be a specific question soliciting examples and data, not an extended discourse on assembler versus higher-level languages.
Can anyone provide some specific examples of cases where assembly will be faster than well-written C code using a modern compiler, and can you support that claim with profiling evidence? I am pretty confident these cases exist, but I really want to know exactly how esoteric these cases are, since it seems to be a point of some contention.
",https://stackoverflow.com/questions/577554/when-is-assembly-faster-than-c,502,156463.0,40.0,,,2009-02-23 13:03:26,2021-06-04 01:06:43,2018-01-03 15:58:37,2021-06-06 06:06:13,Needs more focus,c;performance;assembly,Adam Bellaire,111377,21632,registered,true,577856,,,,1241,1186,0,0,0,3,true,true,false,true,true,true,31,6,true,0.256,0.0032,6480,2009,2,13,Monday,false,false,false,false,false,false,false
426230,What is the LD_PRELOAD trick?,"I came across a reference to it recently on proggit and (as of now) it is not explained.
do you know that you have allocation performance issue?
If the LD_PRELOAD trick leads to considerable performance increases you might have one. Trying it is easy.
I suspect this might be it, but I don't know for sure.
",https://stackoverflow.com/questions/426230/what-is-the-ld-preload-trick,499,598661.0,10.0,,,2009-01-08 22:14:10,2025-07-21 17:39:27,2025-07-21 17:39:27,,,c;linux;environment-variables,Hank Gay,72583,4203,registered,true,426260,,CC BY-SA 4.0,,630,311,0,2,0,3,true,false,false,true,true,true,29,5,true,0.017,0.0008,6526,2009,1,22,Thursday,false,false,false,false,false,false,false
12717138,What is Linux’s native GUI API?,"Both Windows (Win32 API) and OS X (Cocoa) have their own APIs to handle windows, events and other OS stuff. I have never really got a clear answer as to what Linux’s equivalent is?
I have heard some people say GTK+, but GTK+ being cross platform. How can it be native?
",https://stackoverflow.com/questions/12717138/what-is-linux-s-native-gui-api,492,144298.0,11.0,,,2012-10-03 21:23:50,2021-01-01 20:02:21,2021-01-01 20:02:21,,,c++;c;linux;user-interface,DavidColson,8665,906367,registered,true,12717284,,CC BY-SA 4.0,2017-04-27 23:43:22,283,269,0,0,0,4,true,false,false,true,true,true,31,6,true,0.076,0.0034,5162,2012,10,21,Wednesday,false,false,false,false,false,false,false
238603,How can I get a file's size in C?,"How can I find out the size of a file I opened with an application written in C?
I would like to know the size because I want to put the content of the loaded file into a string, which I allocate using malloc().
Just writing malloc(10000*sizeof(char)); is IMHO a bad idea.
",https://stackoverflow.com/questions/238603/how-can-i-get-a-files-size-in-c,489,1176090.0,7.0,,,2008-10-26 20:54:57,2024-08-29 15:23:23,2024-08-29 15:23:23,2020-01-31 06:45:03,Duplicate,c;file;filesize,Nino,5541,25017,registered,true,238607,,,,320,273,2,0,0,3,true,true,false,true,true,true,37,9,true,0.006,0.0004,6600,2008,10,20,Sunday,true,false,false,false,false,false,false
109710,How do the likely/unlikely macros in the Linux kernel work and what is their benefit?,"I've been digging through some parts of the Linux kernel, and found calls like this:
if (unlikely(fd < 0))
{
/* Do something */
}
or
if (likely(!err))
{
/* Do something */
}
I've found the definition of them:
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
I know that they are for optimization, but how do they work? And how much performance/size decrease can be expected from using them? And is it worth the hassle (and losing the portability probably) at least in bottleneck code (in userspace, of course).
",https://stackoverflow.com/questions/109710/how-do-the-likely-unlikely-macros-in-the-linux-kernel-work-and-what-is-their-ben,482,243922.0,10.0,,,2008-09-20 23:04:16,2025-06-18 05:49:37,2023-07-27 18:23:16,,,c;gcc;linux-kernel;branch-prediction;likely-unlikely,terminus,14850,9232,registered,true,109721,,CC BY-SA 4.0,,678,578,3,0,0,5,true,false,false,true,true,true,85,15,true,0.041,0.002,6636,2008,9,23,Saturday,true,false,false,false,false,false,false
10087113,How many levels of pointers can we have?,"How many pointers (*) are allowed in a single variable?
Let's consider the following example.
int a = 10;
int *p = &a;
Similarly we can have
int **q = &p;
int ***r = &q;
and so on.
For example,
int ****************zz;
",https://stackoverflow.com/questions/10087113/how-many-levels-of-pointers-can-we-have,481,57575.0,15.0,,,2012-04-10 10:34:17,2025-07-04 06:03:22,2020-03-12 12:18:19,,,c++;c;pointers;language-lawyer;limit,Parag,8046,1297267,registered,true,,,CC BY-SA 4.0,2012-04-16 07:22:29,360,240,4,0,0,5,false,false,false,true,true,true,40,8,true,0.261,0.0084,5338,2012,4,10,Tuesday,false,false,false,false,false,false,false
233328,How do I print the full value of a long string in gdb?,"I want to print the full length of a C-string in GDB. By default it's being abbreviated, how do I force GDB to print the whole string?
",https://stackoverflow.com/questions/233328/how-do-i-print-the-full-value-of-a-long-string-in-gdb,481,306949.0,6.0,,,2008-10-24 12:36:01,2023-10-06 15:32:20,2011-10-06 21:11:12,,,c++;c;string;debugging;gdb,John Carter,55809,8331,registered,true,233339,,CC BY-SA 3.0,,143,136,0,0,0,5,true,false,false,true,true,true,54,13,true,0.02,0.0016,6602,2008,10,12,Friday,false,false,false,false,false,false,false
146159,Is Fortran easier to optimize than C for heavy calculations?,"From time to time I read that Fortran is or can be faster then C for heavy calculations. Is that really true? I must admit that I hardly know Fortran, but the Fortran code I have seen so far did not show that the language has features that C doesn't have.
If it is true, please tell me why. Please don't tell me what languages or libs are good for number crunching, I don't intend to write an app or lib to do that, I'm just curious.
",https://stackoverflow.com/questions/146159/is-fortran-easier-to-optimize-than-c-for-heavy-calculations,480,193648.0,23.0,,,2008-09-28 16:02:52,2022-05-02 14:01:49,2018-01-28 08:40:11,,,c;performance;fortran,quinmars,11661,18687,registered,true,146186,,CC BY-SA 3.0,2011-10-30 10:55:55,449,435,0,0,0,3,true,false,false,true,true,true,60,10,true,0.119,0.0025,6628,2008,9,16,Sunday,true,false,false,false,false,false,false
2844,How do you format an unsigned long long int using printf?,"#include <stdio.h>
int main() {
unsigned long long int num = 285212672; //FYI: fits in 29 bits
int normalInt = 5;
printf(""My number is %d bytes wide and its value is %ul. A normal number is %d.\n"", sizeof(num), num, normalInt);
return 0;
}
Output:
My number is 8 bytes wide and its value is 285212672l. A normal number is 0.
I assume this unexpected result is from printing the unsigned long long int. How do you printf() an unsigned long long int?
",https://stackoverflow.com/questions/2844/how-do-you-format-an-unsigned-long-long-int-using-printf,480,1067823.0,14.0,,,2008-08-05 20:59:29,2022-09-13 22:20:13,2018-09-14 02:32:40,,,c;syntax;printf;format-specifiers;long-long,andrewrk,31571,432,registered,true,2850,,CC BY-SA 4.0,2019-07-18 16:13:52,577,476,5,0,0,5,true,false,false,true,true,true,57,11,true,0.013,0.0004,6682,2008,8,20,Tuesday,false,false,false,false,false,false,false
3209909,How to printf "unsigned long" in C?,"I can never understand how to print unsigned long datatype in C.
Suppose unsigned_foo is an unsigned long, then I try:
printf(""%lu\n"", unsigned_foo)
printf(""%du\n"", unsigned_foo)
printf(""%ud\n"", unsigned_foo)
printf(""%ll\n"", unsigned_foo)
printf(""%ld\n"", unsigned_foo)
printf(""%dl\n"", unsigned_foo)
And all of them print some kind of -123123123 number instead of unsigned long that I have.
",https://stackoverflow.com/questions/3209909/how-to-printf-unsigned-long-in-c,478,1033023.0,7.0,,,2010-07-09 04:46:47,2018-10-11 15:17:45,2017-10-28 16:21:32,,,c;printf;long-integer;unsigned;format-specifiers,bodacydo,80807,257942,registered,true,3209915,,CC BY-SA 3.0,2019-07-18 16:15:36,622,395,11,0,0,5,true,false,false,true,true,true,45,7,true,0.007,0.0005,5979,2010,7,4,Friday,false,false,false,false,false,false,false
346536,Difference between a Structure and a Union,"Is there any good example to give the difference between a struct and a union?
Basically I know that struct uses all the memory of its member and union uses the largest members memory space. Is there any other OS level difference?
",https://stackoverflow.com/questions/346536/difference-between-a-structure-and-a-union,475,407561.0,18.0,,,2008-12-06 17:56:45,2024-10-06 22:50:02,2017-10-11 09:24:03,,,c;struct;unions,gagneet,37737,35416,registered,true,346541,,CC BY-SA 3.0,2014-07-13 11:17:34,291,232,4,0,0,3,true,false,false,true,true,true,42,7,false,0.044,0.0012,6559,2008,12,17,Saturday,true,false,false,false,false,false,false
227897,How to allocate aligned memory only using the standard library?,"I just finished a test as part of a job interview, and one question stumped me, even using Google for reference. I'd like to see what the StackOverflow crew can do with it:
The memset_16aligned function requires a 16-byte aligned pointer passed to it, or it will crash.
a) How would you allocate 1024 bytes of memory, and align it to a 16 byte boundary?
b) Free the memory after the memset_16aligned has executed.
{
void *mem;
void *ptr;
// answer a) here
memset_16aligned(ptr, 0, 1024);
// answer b) here
}
",https://stackoverflow.com/questions/227897/how-to-allocate-aligned-memory-only-using-the-standard-library,474,235433.0,17.0,,,2008-10-22 23:23:41,2024-06-23 00:46:37,2020-06-20 09:12:55,,,c;memory-management,JimDaniel,12797,63,registered,true,227900,,CC BY-SA 4.0,2015-11-24 21:29:04,639,537,3,0,0,2,true,false,false,true,true,true,63,10,true,0.072,0.002,6604,2008,10,23,Wednesday,false,false,false,false,false,false,false
162941,Why use pointers?,"I know this is a really basic question, but I've just started with some basic C++ programming after coding a few projects with high-level languages.
Basically I have three questions:
- Why use pointers over normal variables?
- When and where should I use pointers?
- How do you use pointers with arrays?
",https://stackoverflow.com/questions/162941/why-use-pointers,472,407365.0,17.0,,,2008-10-02 15:19:20,2020-11-19 20:46:53,2013-05-30 20:49:54,2013-05-30 22:11:05,not constructive,c++;c;pointers,Anonymous,,,does_not_exist,true,,,,,353,303,0,0,0,3,false,true,false,true,false,true,17,3,true,0.042,0.0012,6624,2008,10,15,Thursday,false,false,false,false,false,false,false
5727,What are the barriers to understanding pointers and what can be done to overcome them?,"Why are pointers such a leading factor of confusion for many new, and even old, college-level students in C or C++? Are there any tools or thought processes that helped you understand how pointers work at the variable, function, and beyond level?
What are some good practice things that can be done to bring somebody to the level of, "Ah-hah, I got it," without getting them bogged down in the overall concept? Basically, drill-like scenarios.
",https://stackoverflow.com/questions/5727/what-are-the-barriers-to-understanding-pointers-and-what-can-be-done-to-overcome,468,94688.0,28.0,,,2008-08-08 06:17:51,2024-01-09 11:13:24,2024-01-09 11:13:24,2014-02-08 22:14:29,Needs more focus,c++;c;pointers,David McGraw,5187,568,registered,true,5754,,,2011-05-04 11:25:57,469,455,0,0,0,3,true,true,false,true,true,true,86,15,true,0.296,0.0049,6679,2008,8,6,Friday,false,false,false,false,false,false,false
257418,do { ... } while (0) — what is it good for?,"I've been seeing that expression for over 10 years now. I've been trying to think what it's good for. Since I see it mostly in #defines, I assume it's good for inner scope variable declaration and for using breaks (instead of gotos.)
Is it good for anything else? Do you use it?
",https://stackoverflow.com/questions/257418/do-while-0-what-is-it-good-for,462,222504.0,5.0,,,2008-11-02 21:36:17,2022-06-03 23:04:14,2022-06-03 23:04:14,2020-10-24 17:39:08,Duplicate,c;loops,gilm,8160,31515,registered,true,257425,,,,293,279,0,0,0,2,true,true,false,true,true,true,43,12,true,0.022,0.0021,6593,2008,11,21,Sunday,true,false,false,false,false,false,false
2053029,How exactly does __attribute__((constructor)) work?,"It seems pretty clear that it is supposed to set things up.
- When exactly does it run?
- Why are there two parentheses?
- Is
__attribute__ a function? A macro? Syntax?
- Does this work in C? C++?
- Does the function it works with need to be static?
- When does
__attribute__((destructor)) run?
__attribute__((constructor))
static void initialize_navigationBarImages() {
navigationBarImages = [[NSMutableDictionary alloc] init];
}
__attribute__((destructor))
static void destroy_navigationBarImages() {
[navigationBarImages release];
}
",https://stackoverflow.com/questions/2053029/how-exactly-does-attribute-constructor-work,462,214716.0,5.0,,,2010-01-12 22:43:04,2024-11-27 06:38:55,2024-11-27 06:38:55,,,c++;c;objective-c;gcc;compiler-extension,Casebash,120331,165495,registered,true,2053078,,CC BY-SA 4.0,,815,559,3,1,0,5,true,false,false,true,true,true,51,5,true,0.023,0.0022,6157,2010,1,22,Tuesday,false,false,false,false,false,false,false
6261392,Printing all global variables/local variables?,"How can I print all global variables/local variables? Is that possible in gdb?
",https://stackoverflow.com/questions/6261392/printing-all-global-variables-local-variables,458,486871.0,4.0,,,2011-06-07 06:32:32,2025-09-22 08:36:28,2013-07-31 00:44:24,,,c;variables;gdb;global-variables,cpuer,7963,775627,unregistered,true,6261502,,CC BY-SA 3.0,,86,79,0,0,0,4,true,false,false,true,true,true,46,5,true,0.008,0.0009,5646,2011,6,6,Tuesday,false,false,false,false,false,false,false
3437404,MIN and MAX in C,"Where are MIN and MAX defined in C, if at all?
What is the best way to implement these, as generically and type safely as possible? (Compiler extensions/builtins for mainstream compilers preferred.)
",https://stackoverflow.com/questions/3437404/min-and-max-in-c,455,1308797.0,18.0,,,2010-08-09 04:49:40,2025-07-23 02:47:42,2015-04-01 04:28:36,,,c;max;min;c-preprocessor,Matt Joiner,120754,149482,registered,true,3437484,,CC BY-SA 3.0,2018-04-12 21:00:07,240,200,2,0,0,4,true,false,false,true,true,true,16,5,false,0.014,0.0003,5948,2010,8,4,Monday,false,false,false,false,false,false,false
45629176,Why do all the C files written by my lecturer start with a single # on the first line?,"I'm going through some C course notes, and every C program source file begins with a single # on the first line of the program.
Then there are blank lines, and following that other stuff followed by the main function.
What is the reason for the #?
(It's out of term now and I can't really ask the chap.)
Here's an example:
#
#include <stdio.h>
int main() {
printf(""Hello, World!"");
return 0;
}
",https://stackoverflow.com/questions/45629176/why-do-all-the-c-files-written-by-my-lecturer-start-with-a-single-on-the-first,444,23896.0,3.0,,,2017-08-11 07:17:56,2021-10-30 04:04:27,2019-04-10 05:01:31,,,c;c-preprocessor,The Main Man,2463,8449391,registered,true,45629209,,CC BY-SA 4.0,2019-04-10 05:16:34,556,413,4,0,0,2,true,false,false,true,true,true,86,19,true,0.126,0.0186,3389,2017,8,7,Friday,false,false,false,false,false,false,false
308695,How do I concatenate const/literal strings in C?,"I'm working in C, and I have to concatenate a few things.
Right now I have this:
message = strcat(""TEXT "", var);
message2 = strcat(strcat(""TEXT "", foo), strcat("" TEXT "", bar));
Now if you have experience in C I'm sure you realize that this gives you a segmentation fault when you try to run it. So how do I work around that?
",https://stackoverflow.com/questions/308695/how-do-i-concatenate-const-literal-strings-in-c,442,1410344.0,18.0,,,2008-11-21 13:06:54,2025-05-01 00:42:21,2017-05-22 17:41:31,,,c;string;concatenation,The.Anti.9,45226,2128,registered,true,308712,,CC BY-SA 3.0,2018-01-05 10:53:30,375,330,1,0,0,3,true,false,false,true,true,true,48,8,true,0.013,0.0003,6574,2008,11,13,Friday,false,false,false,false,false,false,false
153890,Printing leading 0's in C,"I'm trying to find a good way to print leading 0, such as 01001 for a ZIP Code. While the number would be stored as 1001, what is a good way to do it?
I thought of using either case statements or if to figure out how many digits the number is and then convert it to an char array with extra 0's for printing, but I can't help but think there may be a way to do this with the printf format syntax that is eluding me.
",https://stackoverflow.com/questions/153890/printing-leading-0s-in-c,438,565866.0,11.0,,,2008-09-30 16:34:43,2022-07-21 12:25:23,2021-02-13 16:44:35,,,c;printf,zxcv,7751,9628,registered,true,153895,,CC BY-SA 4.0,2015-12-06 11:50:04,604,416,8,1,0,2,true,false,false,true,true,true,29,5,false,0.019,0.0008,6626,2008,9,16,Tuesday,false,false,false,false,false,false,false
5134891,How do I use valgrind to find memory leaks?,"How do I use Valgrind to find the memory leaks in a program?
I am using Ubuntu 10.04 (Lucid Lynx), and I have a program, a.c.
",https://stackoverflow.com/questions/5134891/how-do-i-use-valgrind-to-find-memory-leaks,436,888094.0,4.0,,,2011-02-27 18:06:47,2026-06-29 23:04:55,2026-06-29 21:33:59,,,c;valgrind,user484457,5049,484457,registered,true,,,CC BY-SA 4.0,2018-07-18 03:41:31,276,126,0,1,0,2,false,false,false,true,true,true,43,9,true,0.005,0.0005,5746,2011,2,18,Sunday,true,false,false,false,false,false,false
2808398,Easily measure elapsed time,"I am trying to use time() to measure various points of my program.
What I don't understand is why the values in the before and after are the same? I understand this is not the best way to profile my program, I just want to see how long something take.
printf(""**MyProgram::before time= %ld\n"", time(NULL));
doSomthing();
doSomthingLong();
printf(""**MyProgram::after time= %ld\n"", time(NULL));
I have tried:
struct timeval diff, startTV, endTV;
gettimeofday(&startTV, NULL);
doSomething();
doSomethingLong();
gettimeofday(&endTV, NULL);
timersub(&endTV, &startTV, &diff);
printf(""**time taken = %ld %ld\n"", diff.tv_sec, diff.tv_usec);
How do I read a result of **time taken = 0 26339? Does that mean 26,339 nanoseconds = 26.3 msec?
What about **time taken = 4 45025, does that mean 4 seconds and 25 msec?
",https://stackoverflow.com/questions/2808398/easily-measure-elapsed-time,434,799714.0,26.0,,,2010-05-11 06:04:29,2023-06-03 22:06:25,2013-08-27 10:57:38,,,c++;c;linux;time;measurement,hap497,165381,128983,registered,true,,,CC BY-SA 3.0,2022-07-10 17:15:46,1032,845,4,1,0,5,false,false,false,true,true,true,27,4,false,0.033,0.0005,6038,2010,5,6,Tuesday,false,false,false,false,false,false,false
2094666,Pointers in C: when to use the ampersand and the asterisk?,"I'm just starting out with pointers, and I'm slightly confused. I know & means the address of a variable and that * can be used in front of a pointer variable to get the value of the object that is pointed to by the pointer. But things work differently when you're working with arrays, strings or when you're calling functions with a pointer copy of a variable. It's difficult to see a pattern of logic inside all of this.
When should I use & and *?
",https://stackoverflow.com/questions/2094666/pointers-in-c-when-to-use-the-ampersand-and-the-asterisk,431,358717.0,10.0,,,2010-01-19 15:41:06,2025-12-08 03:19:20,2012-04-07 23:42:13,,,c;pointers,Pieter,33231,217649,registered,true,2094715,,CC BY-SA 3.0,2016-09-17 19:52:29,525,459,4,0,0,2,true,false,false,true,true,true,58,11,true,0.028,0.0012,6150,2010,1,15,Tuesday,false,false,false,false,false,false,false
9225567,How to portably print a int64_t type in C,"C99 standard has integer types with bytes size like int64_t. I am using Windows's %I64d format currently (or unsigned %I64u), like:
#include <stdio.h>
#include <stdint.h>
int64_t my_int = 999999999999999999;
printf("This is my_int: %I64d\n", my_int);
and I get this compiler warning:
warning: format ‘%I64d’ expects type ‘int’, but argument 2 has type ‘int64_t’
I tried with:
printf("This is my_int: %lld\n", my_int); // long long decimal
But I get the same warning. I am using this compiler:
~/dev/c$ cc -v
Using built-in specs.
Target: i686-apple-darwin10
Configured with: /var/tmp/gcc/gcc-5664~89/src/configure --disable-checking --enable-werror --prefix=/usr --mandir=/share/man --enable-languages=c,objc,c++,obj-c++ --program-transform-name=/^[cg][^.-]*$/s/$/-4.2/ --with-slibdir=/usr/lib --build=i686-apple-darwin10 --program-prefix=i686-apple-darwin10- --host=x86_64-apple-darwin10 --target=i686-apple-darwin10 --with-gxx-include-dir=/include/c++/4.2.1
Thread model: posix
gcc version 4.2.1 (Apple Inc. build 5664)
Which format should I use to print my_int variable without having a warning?
",https://stackoverflow.com/questions/9225567/how-to-portably-print-a-int64-t-type-in-c,428,735666.0,6.0,,,2012-02-10 09:31:33,2023-10-25 22:01:24,2022-10-18 16:16:20,,,c;stdint,rtacconi,14865,87610,registered,true,9225648,,CC BY-SA 4.0,2019-07-19 10:40:42,1292,1135,6,0,0,2,true,false,false,true,true,true,41,9,false,0.008,0.0006,5398,2012,2,9,Friday,false,false,false,false,false,false,false
17095324,Fastest way to determine if an integer is between two integers (inclusive) with known sets of values,"Is there a faster way than x >= start && x <= end in C or C++ to test if an integer is between two integers?
UPDATE: My specific platform is iOS. This is part of a box blur function that restricts pixels to a circle in a given square.
UPDATE: After trying the accepted answer, I got an order of magnitude speedup on the one line of code over doing it the normal x >= start && x <= end way.
UPDATE: Here is the after and before code with assembler from XCode:
NEW WAY
// diff = (end - start) + 1
#define POINT_IN_RANGE_AND_INCREMENT(p, range) ((p++ - range.start) < range.diff)
Ltmp1313:
ldr r0, [sp, #176] @ 4-byte Reload
ldr r1, [sp, #164] @ 4-byte Reload
ldr r0, [r0]
ldr r1, [r1]
sub.w r0, r9, r0
cmp r0, r1
blo LBB44_30
OLD WAY
#define POINT_IN_RANGE_AND_INCREMENT(p, range) (p <= range.end && p++ >= range.start)
Ltmp1301:
ldr r1, [sp, #172] @ 4-byte Reload
ldr r1, [r1]
cmp r0, r1
bls LBB44_32
mov r6, r0
b LBB44_33
LBB44_32:
ldr r1, [sp, #188] @ 4-byte Reload
adds r6, r0, #1
Ltmp1302:
ldr r1, [r1]
cmp r0, r1
bhs LBB44_36
Pretty amazing how reducing or eliminating branching can provide such a dramatic speed up.
",https://stackoverflow.com/questions/17095324/fastest-way-to-determine-if-an-integer-is-between-two-integers-inclusive-with,424,106307.0,7.0,,,2013-06-13 19:21:42,2026-09-27 11:52:03,2017-05-23 12:09:54,,,c++;c;performance;math,jjxtra,21463,56079,registered,true,17095534,,CC BY-SA 3.0,,1492,1249,4,1,0,4,true,false,false,true,true,true,100,17,false,0.066,0.004,4909,2013,6,19,Thursday,false,false,false,false,false,false,false
10334688,How dangerous is it to compare floating point values?,"I know UIKit uses CGFloat because of the resolution independent coordinate system.
But every time I want to check if for example frame.origin.x is 0 it makes me feel sick:
if (theView.frame.origin.x == 0) {
// do important operation
}
Isn't CGFloat vulnerable to false positives when comparing with ==, <=, >=, <, >?
It is a floating point and they have unprecision problems: 0.0000000000041 for example.
Is Objective-C handling this internally when comparing or can it happen that a origin.x which reads as zero does not compare to 0 as true?
",https://stackoverflow.com/questions/10334688/how-dangerous-is-it-to-compare-floating-point-values,422,104969.0,12.0,,,2012-04-26 13:41:12,2022-09-01 22:35:05,2015-12-17 12:09:49,,,objective-c;ios;c;floating-point;floating-accuracy,Proud Member,40566,472300,registered,true,10335601,,CC BY-SA 3.0,2012-05-14 05:39:30,799,565,15,0,0,5,true,false,false,true,true,true,53,9,true,0.114,0.004,5322,2012,4,13,Thursday,false,false,false,false,false,false,false
10681375,Which is better option to use for dividing an integer number by 2?,"Which of the following techniques is the best option for dividing an integer by 2 and why?
Technique 1:
x = x >> 1;
Technique 2:
x = x / 2;
Here x is an integer.
",https://stackoverflow.com/questions/10681375/which-is-better-option-to-use-for-dividing-an-integer-number-by-2,419,80141.0,22.0,,,2012-05-21 07:54:36,2022-05-03 05:00:24,2016-07-29 17:29:34,2025-08-13 18:43:24,Opinion-based,c++;c;optimization;division;micro-optimization,Abhineet,6655,223622,registered,true,10681422,,,2012-05-29 21:53:39,264,175,3,0,0,5,true,true,false,true,true,true,66,13,true,0.275,0.0052,5297,2012,5,7,Monday,false,false,false,false,false,false,false
550195,Is It Possible to NSLog C Structs (Like CGRect or CGPoint)?,"I want to be able to debug C structures without having to explicitly type every property that they consist of.
i.e. I want to be able to do something like this:
CGPoint cgPoint = CGPointMake(0,0);
NSLog(@""%@"",cgPoint);
Obviously the '%@' won't work, hence the question.
",https://stackoverflow.com/questions/550195/is-it-possible-to-nslog-c-structs-like-cgrect-or-cgpoint,418,109558.0,9.0,,,2009-02-15 02:28:30,2022-11-08 14:14:08,,,,c;objective-c;cocoa;cocoa-touch,mazniak,5879,42523,registered,true,550243,,CC BY-SA 2.5,,320,275,1,0,0,4,true,false,false,true,true,false,59,11,true,0.082,0.0038,6488,2009,2,2,Sunday,true,false,false,false,false,false,false
8257714,How can I convert an int to a string in C?,"How do you convert an int (integer) to a string?
I'm trying to make a function that converts the data of a struct into a string to save it in a file.
",https://stackoverflow.com/questions/8257714/how-can-i-convert-an-int-to-a-string-in-c,415,1794130.0,11.0,,,2011-11-24 13:19:11,2023-07-19 20:38:45,2023-02-06 16:27:23,,,c;string;integer,Dic,4177,1063999,registered,true,8257754,,CC BY-SA 4.0,2016-10-15 13:07:46,190,150,2,0,0,3,true,false,false,true,true,true,42,11,true,0.006,0.0002,5476,2011,11,13,Thursday,false,false,false,false,false,false,false
9936132,Why does the order of the loops affect performance when iterating over a 2D array?,"Below are two nearly identical programs, where only the i and j for-loop order differs. Yet the first program runs slower than the second. Why?
Version 1 (slow)
#include <stdio.h>
#include <stdlib.h>
main () {
int i, j;
static int x[4000][4000];
for (i = 0; i < 4000; i++) {
for (j = 0; j < 4000; j++) {
x[j][i] = i + j; }
}
}
Version 2 (fast)
#include <stdio.h>
#include <stdlib.h>
main () {
int i, j;
static int x[4000][4000];
for (j = 0; j < 4000; j++) {
for (i = 0; i < 4000; i++) {
x[j][i] = i + j; }
}
}
",https://stackoverflow.com/questions/9936132/why-does-the-order-of-the-loops-affect-performance-when-iterating-over-a-2d-arra,415,63068.0,7.0,,,2012-03-30 02:17:32,2025-10-03 02:55:48,2025-10-03 02:32:13,,,c;performance;for-loop;optimization;cpu-cache,Mark,8748,295128,registered,true,9936656,,CC BY-SA 4.0,,687,592,4,0,0,5,true,false,false,true,true,true,82,15,true,0.111,0.0066,5349,2012,3,2,Friday,false,false,false,false,false,false,false
3789340,How does "#ifdef __cplusplus" work when combining C++ and C?,"I'm working on a project that has a lot of legacy C code. We've started writing in C++, with the intent to eventually convert the legacy code, as well. I'm a little confused about how the C and C++ interact. I understand that by wrapping the C code with extern "C" the C++ compiler will not mangle the C code's names, but I'm not entirely sure how to implement this.
So, at the top of each C header file (after the include guards), we have
#ifdef __cplusplus
extern "C" {
#endif
and at the bottom, we write
#ifdef __cplusplus
}
#endif
In between the two, we have all of our includes, typedefs, and function prototypes. I have a few questions, to see if I'm understanding this correctly:
If I have a C++ file A.hh which
includes a C header file B.h,
includes another C header file C.h,
how does this work? I think that
when the compiler steps into B.h,
__cplusplus will be defined, so it
will wrap the code with extern "C"
(and __cplusplus will not be
defined inside this block). So,
when it steps into C.h,
__cplusplus will not be defined
and the code will not be wrapped in
extern "C". Is this correct?
Is there anything wrong with
wrapping a piece of code with
extern "C" { extern "C" { .. } }?
What will the second extern "C"
do?
We don't put this wrapper around the .c files, just the .h files. So, what happens if a function doesn't have a prototype? Does the compiler think that it's a C++ function?
We are also using some third-party
code which is written in C, and does
not have this sort of wrapper around
it. Any time I include a header
from that library, I've been putting
an extern "C" around the #include.
Is this the right way to deal with
that?
Finally, is this set up a good idea?
Is there anything else we should do?
We're going to be mixing C and C++
for the foreseeable future, and I
want to make sure we're covering all
our bases.
",https://stackoverflow.com/questions/3789340/how-does-ifdef-cplusplus-work-when-combining-c-and-c,415,332048.0,5.0,,,2010-09-24 17:03:28,2026-09-30 21:25:41,2026-09-30 21:25:41,,,c++;c;c-preprocessor;extern-c,dublev,4485,157984,registered,true,3789553,,CC BY-SA 4.0,,2231,1949,11,0,0,4,true,false,false,true,true,true,70,10,true,0.015,0.0012,5902,2010,9,17,Friday,false,false,false,false,false,false,false
492384,How to find the size of an array (from a pointer pointing to the first element array)?,"First off, here is some code:
int main()
{
int days[] = {1,2,3,4,5};
int *ptr = days;
printf(""%u\n"", sizeof(days));
printf(""%u\n"", sizeof(ptr));
return 0;
}
Is there a way to find out the size of the array that ptr is pointing to (instead of just giving its size, which is four bytes on a 32-bit system)?
",https://stackoverflow.com/questions/492384/how-to-find-the-size-of-an-array-from-a-pointer-pointing-to-the-first-element-a,402,572410.0,18.0,,,2009-01-29 16:33:34,2025-08-31 12:40:20,2024-05-08 12:24:45,,,arrays;c;pointers;sizeof,jkidv,4577,33324,registered,true,492410,,CC BY-SA 4.0,2014-04-16 14:02:32,382,331,2,0,0,4,true,false,false,true,true,true,86,17,true,0.031,0.0007,6505,2009,1,16,Thursday,false,false,false,false,false,false,false
9688200,"Difference between shared objects (.so), static libraries (.a), and DLL's (.so)?","I have been involved in some debate with respect to libraries in Linux, and would like to confirm some things.
It is to my understanding (please correct me if I am wrong and I will edit my post later), that there are two ways of using libraries when building an application:
- Static libraries (.a files): At link time, a copy of the entire library is put into the final application so that the functions within the library are always available to the calling application
- Shared objects (.so files): At link time, the object is just verified against its API via the corresponding header (.h) file. The library isn't actually used until runtime, where it is needed.
The obvious advantage of static libraries is that they allow the entire application to be self-contained, while the benefit of dynamic libraries is that the ".so" file can be replaced (ie: in case it needs to be updated due to a security bug) without requiring the base application to be recompiled.
I have heard some people make a distinction between shared objects and dynamic link libraries (DLL's), even though they are both ".so" files. Is there any distinction between shared objects and DLLs when it comes to C/C++ development on Linux or any other POSIX compliant OS (ie: MINIX, UNIX, QNX, etc)? I am told that one key difference (so far) is that shared objects are just used at runtime, while DLL's must be opened first using the dlopen() call within the application.
Finally, I have also heard some developers mention "shared archives", which, to my understanding, are also static libraries themselves, but are never used by an application directly. Instead, other static libraries will link against the "shared archives" to pull some (but not all) functions/resources from the shared archive into the static library being built.
Update
In the context in which these terms were provided to me, it was effectively erroneous terms used by a team of Windows developers that had to learn Linux. I tried to correct them, but the (incorrect) language norms stuck.
- Shared Object: A library that is automatically linked into a program when the program starts, and exists as a standalone file. The library is included in the linking list at compile time (ie:
LDOPTS+=-lmylib for a library file named mylib.so). The library must be present at compile time, and when the application starts.
- Static Library: A library that is merged into the actual program itself at build time for a single (larger) application containing the application code and the library code that is automatically linked into a program when the program is built, and the final binary containing both the main program and the library itself exists as a single standalone binary file. The library is included in the linking list at compile time (ie:
LDOPTS+=-lmylib for a library file named mylib.a). The library must be present at compile time.
- DLL: Essentially the same as a shared object, but rather than being included in the linking list at compile time, the library is loaded via
dlopen()/dlsym() commands so that the library does not need to be present at build time for the program to compile. Also, the library does not need to be present (necessarily) at application startup or compile time, as it is only needed at the moment the dlopen/dlsym calls are made.
- Shared Archive: Essentially the same as a static library, but is compiled with the "export-shared" and "
-fPIC" flags. The library is included in the linking list at compile time (ie: LDOPTS+=-lmylibS for a library file named mylibS.a). The distinction between the two is that this additional flag is required if a shared object or DLL wants to statically link the shared archive into its own code AND be able to make the functions in the shared object available to other programs, rather than just using them internal to the DLL. This is useful in the case when someone provides you with a static library, and you wish to repackage it as an SO. The library must be present at compile time.
Additional Update
The distinction between "DLL" and "shared library" was just a (lazy, inaccurate) colloquialism in the company I worked in at the time (Windows developers being forced to shift to Linux development, and the term stuck), adhering to the descriptions noted above.
Additionally, the trailing "S" literal after the library name, in the case of "shared archives" was just a convention used at that company, and not in the industry in general.
",https://stackoverflow.com/questions/9688200/difference-between-shared-objects-so-static-libraries-a-and-dlls-so,400,269995.0,5.0,,,2012-03-13 16:37:53,2026-05-30 14:24:31,2023-09-12 11:39:36,,,c++;c;linux;dll;linker,Cloud,19531,1022889,registered,true,9688338,,CC BY-SA 4.0,,4971,4552,14,0,0,5,true,false,false,true,true,true,84,11,true,0.019,0.0015,5366,2012,3,16,Tuesday,false,false,false,false,false,false,false
13950642,Why does a function with no parameters (compared to the actual function definition) compile?,"I've just come across someone's C code that I'm confused as to why it is compiling. There are two points I don't understand.
The function prototype has no parameters compared to the actual function definition.
The parameter in the function definition does not have a type.
#include <stdio.h>
int func();
int func(param)
{
return param;
}
int main()
{
int bla = func(10);
printf("%d", bla);
}
Why does this work?
I have tested it in a couple of compilers, and it works fine.
",https://stackoverflow.com/questions/13950642/why-does-a-function-with-no-parameters-compared-to-the-actual-function-definiti,399,74966.0,11.0,,,2012-12-19 10:48:39,2021-04-22 03:57:30,2020-12-30 05:03:18,,,c;parameters;void;function-prototypes;function-parameter,AdmiralJonB,2142,791025,registered,true,13950800,,CC BY-SA 4.0,,634,515,1,0,0,5,true,false,false,true,true,true,92,14,true,0.147,0.0053,5085,2012,12,10,Wednesday,false,false,false,false,false,false,false
562303,The Definitive C Book Guide and List,"This question attempts to collect a community-maintained list of quality books on the c programming language, targeted at various skill levels.
C is a complex programming language that is difficult to pick up on-the-go by reading online tutorials. A comprehensive book is often the best way to learn the language, and finding a good book is the first step. It is important to avoid badly-written books, and even more importantly, books that contain serious technical errors.
Please suggest edits to the accepted answer to add quality books, with an approximate skill level and a short blurb/description about each book. (Note that the question is locked, so no new answers will be accepted. A single answer is being maintained with the list)
Feel free to debate book choices, quality, headings, summaries, skill levels, and anything else you see that is wrong. Books that are deemed satisfactory by the C community here will stick around on the list; the rest will be regularly removed.
For books that have reviews by the Association of C and C++ Users (ACCU), a link to those reviews should be added along with the book.
See also:
- Other C-related resources in the c tag wiki
- A similar list for c++: The Definitive C++ Book Guide and List
This question was discussed on Meta as part of the Deleted Questions Audit 2018.
The consensus was to keep it undeleted and actively maintained.
",https://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list,398,721066.0,1.0,,,2009-02-18 18:32:02,2024-04-21 13:48:19,2019-01-15 00:30:03,,,c,lillq,15503,2064,registered,true,,,CC BY-SA 4.0,2012-07-24 19:08:01,2131,1394,0,7,0,1,false,false,false,true,true,true,36,7,false,0.001,0.0006,6485,2009,2,18,Wednesday,false,false,false,false,false,false,false
1296843,"What is the difference between NULL, '\0' and 0?","In C, there appear to be differences between various values of zero -- NULL, NUL and 0.
I know that the ASCII character '0' evaluates to 48 or 0x30.
The NULL pointer is usually defined as:
#define NULL 0
Or
#define NULL (void *)0
In addition, there is the NUL character '\0' which seems to evaluate to 0 as well.
Are there times when these three values can not be equal?
Is this also true on 64 bit systems?
",https://stackoverflow.com/questions/1296843/what-is-the-difference-between-null-0-and-0,398,445824.0,11.0,,,2009-08-18 22:09:59,2021-02-23 07:05:01,2020-05-10 13:40:04,,,c;pointers;null,gnavi,26282,99317,registered,true,1296865,,CC BY-SA 4.0,2019-07-18 16:19:13,645,418,12,0,0,3,true,false,false,true,true,true,56,9,true,0.025,0.0009,6304,2009,8,22,Tuesday,false,false,false,false,false,false,false
2762568,C/C++ include header file order,"What order should include files be specified, i.e. what are the reasons for including one header before another?
For example, do the system files, STL, and Boost go before or after the local include files?
",https://stackoverflow.com/questions/2762568/c-c-include-header-file-order,396,193813.0,11.0,,,2010-05-04 03:09:22,2023-06-06 21:41:58,2023-04-08 01:14:44,2024-01-02 16:55:36,Opinion-based,c++;c;include,Anycorn,52013,206328,registered,true,2762596,,,,221,207,0,0,0,3,true,true,false,true,true,true,31,5,false,0.057,0.002,6045,2010,5,3,Tuesday,false,false,false,false,false,false,false
81656,Where do I find the current C or C++ standard documents?,"For many questions the answer seems to be found in ""the standard"". However, where do we find that? Preferably online.
Googling can sometimes feel futile, again especially for the C standards, since they are drowned in the flood of discussions on programming forums.
To get this started, since these are the ones I am searching for right now, where are there good online resources for:
- C89
- C99
- C11
- C++98
- C++03
- C++11
- C++14
- C++17
",https://stackoverflow.com/questions/81656/where-do-i-find-the-current-c-or-c-standard-documents,393,205286.0,11.0,,,2008-09-17 10:04:04,2026-11-06 15:53:58,2020-05-17 04:26:54,,,c++;c;standards;c++-faq,Christoffer,13008,15514,registered,true,83763,,CC BY-SA 4.0,2012-07-05 12:00:52,534,432,0,0,0,4,true,false,false,true,true,true,56,11,true,0.054,0.0019,6639,2008,9,10,Wednesday,false,false,false,false,false,false,false
2065912,"Core dumped, but the core file is not in the current directory","While running a C program, it says "(core dumped)", but I can't see any files under the current path.
I have set and verified the ulimit:
ulimit -c unlimited
ulimit -a
I also tried to find a file named "core", but it didn't get the core dumped file. Why?
Where is my core file?
",https://stackoverflow.com/questions/2065912/core-dumped-but-the-core-file-is-not-in-the-current-directory,392,559173.0,17.0,,,2010-01-14 16:59:47,2026-05-10 17:33:05,2026-05-10 15:40:48,,,c;linux;coredump,webminal.org,47894,246365,registered,true,2067406,,CC BY-SA 4.0,,441,299,2,1,0,3,true,false,false,true,true,true,62,12,false,0.03,0.0007,6155,2010,1,16,Thursday,false,false,false,false,false,false,false
17992553,Concept behind these four lines of tricky C code,"Why does this code give the output C++Sucks? What is the concept behind it?
#include <stdio.h>
double m[] = {7709179928849219.0, 771};
int main() {
m[1]--?m[0]*=2,main():printf((char*)m);
}
Test it here.
",https://stackoverflow.com/questions/17992553/concept-behind-these-four-lines-of-tricky-c-code,391,39851.0,9.0,,,2013-08-01 11:16:08,2019-03-18 04:20:29,2014-07-17 15:51:23,,,c;deobfuscation,codeslayer1,3686,2547190,registered,true,17992906,,CC BY-SA 3.0,2013-08-08 02:59:44,313,223,2,1,0,2,true,false,false,true,true,true,48,9,false,0.226,0.0098,4860,2013,8,11,Thursday,false,false,false,false,false,false,false
1345670,Stack smashing detected,"I am executing my a.out file. After execution the program runs for some time then exits with the message:
**** stack smashing detected ***: ./a.out terminated*
*======= Backtrace: =========*
*/lib/tls/i686/cmov/libc.so.6(__fortify_fail+0x48)Aborted*
What could be the possible reasons for this and how do I rectify it?
",https://stackoverflow.com/questions/1345670/stack-smashing-detected,391,835504.0,10.0,,,2009-08-28 08:17:50,2026-06-02 09:47:03,2012-09-18 03:00:22,,,c;exception;stack,Biswajyoti Das,8461,130423,registered,true,1347464,,CC BY-SA 3.0,2019-07-19 12:19:17,360,322,1,0,0,3,true,false,false,true,true,true,23,3,false,0.012,0.0005,6294,2009,8,8,Friday,false,false,false,false,false,false,false
890535,What is the difference between char * const and const char *?,"What's the difference between:
char * const
and
const char *
",https://stackoverflow.com/questions/890535/what-is-the-difference-between-char-const-and-const-char,389,283891.0,19.0,,,2009-05-20 22:16:22,2019-11-29 14:52:16,2012-11-27 15:46:26,,,c;pointers;constants,LB.,14282,59035,registered,true,890560,,CC BY-SA 3.0,2019-07-19 10:44:06,129,67,2,0,0,3,true,false,false,true,true,true,61,12,true,0.067,0.0014,6394,2009,5,22,Wednesday,false,false,false,false,false,false,false
797318,How to split a string literal across multiple lines in C / Objective-C?,"I have a pretty long sqlite query:
const char *sql_query = ""SELECT statuses.word_id FROM lang1_words, statuses WHERE statuses.word_id = lang1_words.word_id ORDER BY lang1_words.word ASC"";
How can I break it in a number of lines to make it easier to read?
If I do the following:
const char *sql_query = ""SELECT word_id
FROM table1, table2
WHERE table2.word_id = table1.word_id
ORDER BY table1.word ASC"";
I am getting an error.
Is there a way to write queries in multiple lines?
",https://stackoverflow.com/questions/797318/how-to-split-a-string-literal-across-multiple-lines-in-c-objective-c,388,337377.0,8.0,,,2009-04-28 11:01:50,2025-04-24 23:28:38,2021-07-23 03:59:37,,,c;objective-c;string-literals,Ilya Suzdalnitski,53700,77449,registered,true,797351,,CC BY-SA 4.0,2020-06-06 10:56:42,632,556,2,0,0,3,true,false,false,true,true,true,71,13,true,0.024,0.0012,6416,2009,4,11,Tuesday,false,false,false,false,false,false,false
1472138,C default arguments,"Is there a way to specify default arguments to a function in C?
",https://stackoverflow.com/questions/1472138/c-default-arguments,385,341886.0,26.0,,,2009-09-24 14:38:20,2026-11-03 14:25:49,2019-05-08 09:02:03,,,c;arguments;default-parameters,Nathaniel Flath,16241,41241,registered,true,1472151,,CC BY-SA 4.0,2019-07-19 10:44:53,71,64,0,0,0,3,true,false,false,true,true,true,19,3,false,0.076,0.0011,6267,2009,9,14,Thursday,false,false,false,false,false,false,false
212466,What is a bus error? Is it different from a segmentation fault?,"What does the "bus error" message mean, and how does it differ from a segmentation fault?
",https://stackoverflow.com/questions/212466/what-is-a-bus-error-is-it-different-from-a-segmentation-fault,383,595660.0,17.0,,,2008-10-17 14:48:44,2024-08-19 06:32:22,2021-08-22 09:04:14,,,c;unix;segmentation-fault;bus-error,raldi,22480,7598,registered,true,212585,,CC BY-SA 4.0,2017-05-23 11:31:22,187,100,0,1,0,4,true,false,false,true,true,true,63,12,true,0.029,0.0006,6609,2008,10,14,Friday,false,false,false,false,false,false,false
10289890,How to write iOS app purely in C,"I read here Learn C Before Objective-C?
Usually I then replace some Obj-C code with pure C code (after all you can mix them as much as you like, the content of an Obj-C method can be entirely, pure C code)
Is this true?
Is it possible to build an iPhone app purely in the C programming language?
",https://stackoverflow.com/questions/10289890/how-to-write-ios-app-purely-in-c,380,105665.0,4.0,,,2012-04-23 23:48:25,2015-08-17 11:17:56,2017-05-23 12:26:19,,,objective-c;ios;c;cocoa-touch;objective-c-runtime,001,65741,103264,registered,true,10290255,,CC BY-SA 3.0,2014-12-17 00:09:53,456,304,0,1,0,5,true,false,false,true,true,true,32,8,false,0.038,0.0036,5325,2012,4,23,Monday,false,false,false,false,false,false,false
3162030,Difference between angle bracket < > and double quotes " " while including header files in C++?,"
Possible Duplicate:
What is the difference between #include <filename> and #include “filename”?
What is the difference between angle bracket < > and double quotes "" "" while including header files in C++?
I mean which files are supposed to be included using eg: #include <QPushButton> and which files are to be included using eg: #include ""MyFile.h""???
",https://stackoverflow.com/questions/3162030/difference-between-angle-bracket-and-double-quotes-while-including-heade,377,246088.0,2.0,,,2010-07-01 22:07:54,2016-06-03 05:09:32,2017-05-23 12:10:28,2010-07-02 02:18:02,exact duplicate,c++;c;c++11,Sulla,8189,248643,registered,true,3162067,,,,626,382,4,1,0,3,true,true,false,true,true,true,111,17,true,0.008,0.0015,5987,2010,7,22,Thursday,false,false,false,false,false,false,false
614794,Detecting superfluous #includes in C/C++,"I often find that the headers section of a file gets larger and larger all the time, but it never gets smaller. Throughout the life of a source file, classes may have moved and been refactored and it's very possible that there are quite a few #includes that don't need to be there and anymore. Leaving them there only prolong the compile time and adds unnecessary compilation dependencies. Trying to figure out which are still needed can be quite tedious.
Is there some kind of tool that can detect superfluous #include directives and suggest which ones I can safely remove?
Does lint do this maybe?
",https://stackoverflow.com/questions/614794/detecting-superfluous-includes-in-c-c,373,166321.0,20.0,,,2009-03-05 13:43:53,2025-12-30 14:29:24,2025-12-30 14:29:24,2026-01-01 01:09:06,Not suitable for this site,c++;c;refactoring;include;dependencies,shoosh,79702,9611,registered,true,614925,,,,647,600,2,0,0,5,true,true,false,true,true,true,40,5,false,0.12,0.0022,6470,2009,3,13,Thursday,false,false,false,false,false,false,false
2693776,Removing trailing newline character from fgets() input,"I am trying to get some data from the user and send it to another function in gcc. The code is something like this.
printf(""Enter your Name: "");
if (!(fgets(Name, sizeof Name, stdin) != NULL)) {
fprintf(stderr, ""Error reading Name.\n"");
exit(1);
}
However, I find that it has a newline \n character in the end. So if I enter John it ends up sending John\n. How do I remove that \n and send a proper string.
",https://stackoverflow.com/questions/2693776/removing-trailing-newline-character-from-fgets-input,372,615121.0,16.0,,,2010-04-22 19:21:18,2024-12-27 15:33:56,2015-03-14 06:23:08,,,c;string;gcc;newline;fgets,sfactor,13172,213334,registered,true,2693826,,CC BY-SA 3.0,2018-06-14 19:44:08,508,418,5,0,0,5,true,false,false,true,true,true,54,7,false,0.026,0.0006,6057,2010,4,19,Thursday,false,false,false,false,false,false,false
2745074,Fast ceiling of an integer division in C / C++,"Given integer values x and y, C and C++ both return as the quotient q = x/y the floor of the floating point equivalent. I'm interested in a method of returning the ceiling instead. For example, ceil(10/5)=2 and ceil(11/5)=3.
The obvious approach involves something like:
q = x / y;
if (q * y < x) ++q;
This requires an extra comparison and multiplication; and other methods I've seen (used in fact) involve casting as a float or double. Is there a more direct method that avoids the additional multiplication (or a second division) and branch, and that also avoids casting as a floating point number?
",https://stackoverflow.com/questions/2745074/fast-ceiling-of-an-integer-division-in-c-c,372,296694.0,12.0,,,2010-04-30 14:16:53,2025-10-24 02:27:20,2023-03-26 13:32:42,,,c++;c;algorithm;math;integer-division,andand,17587,248123,registered,true,2745086,,CC BY-SA 4.0,,747,611,8,0,0,5,true,false,false,true,true,true,46,10,false,0.04,0.0013,6049,2010,4,14,Friday,false,false,false,false,false,false,false
258091,When should I use mmap for file access?,"POSIX environments provide at least two ways of accessing files. There's the standard system calls open(), read(), write(), and friends, but there's also the option of using mmap() to map the file into virtual memory.
When is it preferable to use one over the other? What're their individual advantages that merit including two interfaces?
",https://stackoverflow.com/questions/258091/when-should-i-use-mmap-for-file-access,371,147784.0,6.0,,,2008-11-03 07:56:03,2023-09-11 08:29:23,,,,c;file-io;posix;mmap,Peter Burns,45641,101,registered,true,258097,,CC BY-SA 2.5,2019-07-19 10:43:12,409,343,4,0,0,4,true,false,false,true,true,false,39,8,true,0.041,0.0025,6592,2008,11,7,Monday,false,false,false,false,false,false,false
5580761,Why use double indirection? or Why use pointers to pointers?,"When should a double indirection be used in C? Can anyone explain with a example?
What I know is that a double indirection is a pointer to a pointer. Why would I need a pointer to a pointer?
",https://stackoverflow.com/questions/5580761/why-use-double-indirection-or-why-use-pointers-to-pointers,368,307877.0,19.0,,,2011-04-07 12:08:56,2023-10-02 07:19:01,2019-05-23 08:27:59,,,c;pointers,manju,3681,696753,unregistered,true,5580952,,CC BY-SA 4.0,2019-05-23 08:27:31,207,193,0,0,0,2,true,false,false,true,true,true,60,10,true,0.062,0.0012,5707,2011,4,12,Thursday,false,false,false,false,false,false,false
205529,Passing variable number of arguments around,"Say I have a C function which takes a variable number of arguments: How can I call another function which expects a variable number of arguments from inside of it, passing all the arguments that got into the first function?
Example:
void format_string(char *fmt, ...);
void debug_print(int dbg_lvl, char *fmt, ...) {
format_string(fmt, /* how do I pass all the arguments from '...'? */);
fprintf(stdout, fmt);
}
",https://stackoverflow.com/questions/205529/passing-variable-number-of-arguments-around,368,217294.0,11.0,,,2008-10-15 16:58:12,2022-03-22 15:48:35,2014-08-26 20:44:38,,,c;variadic-functions,Vicent Marti,7353,4381,registered,true,205584,,CC BY-SA 3.0,,463,425,1,0,0,2,true,false,false,true,true,true,43,6,false,0.051,0.0017,6611,2008,10,16,Wednesday,false,false,false,false,false,false,false
231760,What does a type followed by _t (underscore-t) represent?,"This seems like a simple question, but I can't find it with the Stack Overflow search or Google. What does a type followed by a _t mean? Such as
int_t anInt;
I see it a lot in C code meant to deal closely with hardware—I can't help but think that they're related.
",https://stackoverflow.com/questions/231760/what-does-a-type-followed-by-t-underscore-t-represent,366,160701.0,11.0,,,2008-10-23 22:18:39,2024-10-24 18:31:20,2009-09-08 01:50:22,,,c;naming-conventions;types,Kevin Griffin,14852,26237,registered,true,231807,,CC BY-SA 2.5,,318,267,2,0,0,3,true,false,false,true,true,true,57,9,true,0.068,0.0023,6603,2008,10,22,Thursday,false,false,false,false,false,false,false
57842756,Why should I always enable compiler warnings?,"I often hear that when compiling C and C++ programs I should ""always enable compiler warnings"". Why is this necessary? How do I do that?
Sometimes I also hear that I should ""treat warnings as errors"". Should I? How do I do that?
",https://stackoverflow.com/questions/57842756/why-should-i-always-enable-compiler-warnings,361,46907.0,21.0,,,2019-09-08 14:20:35,2025-11-27 10:05:14,2019-10-08 18:13:10,,,c++;c;warnings;compiler-warnings;c++-faq,n.m.is-an-unemployed-ai-agent,126372,775806,registered,true,57842757,,CC BY-SA 4.0,,245,231,0,0,0,5,true,false,false,true,true,true,45,7,true,0.448,0.0077,2631,2019,9,14,Sunday,true,false,false,false,false,false,false
1088622,How do I create an array of strings in C?,"I am trying to create an array of strings in C. If I use this code:
char (*a[2])[14];
a[0]=""blah"";
a[1]=""hmm"";
gcc gives me ""warning: assignment from incompatible pointer type"". What is the correct way to do this?
edit: I am curious why this should give a compiler warning since if I do printf(a[1]);, it correctly prints ""hmm"".
",https://stackoverflow.com/questions/1088622/how-do-i-create-an-array-of-strings-in-c,358,1389858.0,15.0,,,2009-07-06 18:47:03,2023-07-28 13:01:58,2018-08-22 18:39:45,,,c;arrays;string,Charles,,,does_not_exist,true,,,CC BY-SA 4.0,2018-02-28 23:54:31,393,335,2,0,0,3,false,false,false,true,false,true,41,10,true,0.011,0.0003,6347,2009,7,18,Monday,false,false,false,false,false,false,false
5919996,"How to detect reliably Mac OS X, iOS, Linux, Windows in C preprocessor?","If there's some cross-platform C/C++ code that should be compiled on Mac OS X, iOS, Linux, Windows, how can I detect them reliably during preprocessor process?
",https://stackoverflow.com/questions/5919996/how-to-detect-reliably-mac-os-x-ios-linux-windows-in-c-preprocessor,354,222498.0,3.0,,,2011-05-07 08:37:51,2022-07-23 05:26:28,2016-03-10 11:13:04,2019-06-02 21:09:14,Duplicate,c++;c;cross-platform;c-preprocessor;os-detection,Cage,86979,246776,registered,true,5920028,,,,167,160,0,0,0,5,true,true,false,true,true,true,71,13,true,0.013,0.0016,5677,2011,5,8,Saturday,true,false,false,false,false,false,false
13366083,Why does the arrow (->) operator in C exist?,"The dot (.) operator is used to access a member of a struct, while the arrow operator (->) in C is used to access a member of a struct which is referenced by the pointer in question.
The pointer itself does not have any members which could be accessed with the dot operator (it's actually only a number describing a location in virtual memory so it doesn't have any members). So, there would be no ambiguity if we just defined the dot operator to automatically dereference the pointer if it is used on a pointer (an information which is known to the compiler at compile time afaik).
So why have the language creators decided to make things more complicated by adding this seemingly unnecessary operator? What is the big design decision?
",https://stackoverflow.com/questions/13366083/why-does-the-arrow-operator-in-c-exist,353,260570.0,4.0,,,2012-11-13 17:58:57,2023-04-25 12:31:39,2014-12-03 03:02:38,,,c;pointers;dereference,Askaga,6532,1753601,registered,true,13366168,,CC BY-SA 3.0,2015-08-06 10:40:43,789,742,2,0,0,3,true,false,false,true,true,true,47,9,true,0.015,0.0014,5121,2012,11,17,Tuesday,false,false,false,false,false,false,false
1860159,How to escape the % (percent) sign in C's printf,"How do you escape the % sign when using printf in C?
printf(""hello\%""); /* not like this */
",https://stackoverflow.com/questions/1860159/how-to-escape-the-percent-sign-in-cs-printf,352,398785.0,13.0,,,2009-12-07 14:02:08,2021-05-16 21:01:49,2021-05-16 14:27:25,,,c;printf;format-string,Chris_45,9143,163407,registered,true,1860164,,CC BY-SA 4.0,2019-07-19 10:42:02,138,94,2,0,0,3,true,false,false,true,true,true,52,10,false,0.033,0.0009,6193,2009,12,14,Monday,false,false,false,false,false,false,false
164194,"Why do I get a segmentation fault when writing to a "char *s" initialized with a string literal, but not "char s[]"?","The following code receives seg fault on line 2:
char *str = ""string"";
str[0] = 'z'; // could be also written as *str = 'z'
printf(""%s\n"", str);
While this works perfectly well:
char str[] = ""string"";
str[0] = 'z';
printf(""%s\n"", str);
Tested with MSVC and GCC.
",https://stackoverflow.com/questions/164194/why-do-i-get-a-segmentation-fault-when-writing-to-a-char-s-initialized-with-a,352,108512.0,21.0,,,2008-10-02 19:45:21,2025-10-31 09:32:30,2020-06-08 05:34:52,,,c;segmentation-fault;c-strings,Markus,3631,24622,registered,true,164258,,CC BY-SA 4.0,2014-04-10 13:41:07,338,269,2,0,0,3,true,false,false,true,true,true,136,22,true,0.194,0.0032,6624,2008,10,19,Thursday,false,false,false,false,false,false,false
2172943,Why is the size of a character sizeof('a') different in C and C++?,"#include <stdio.h>
int main(void)
{
printf("sizeof(char) = %zu\n", sizeof(char));
printf("sizeof('a') = %zu\n", sizeof('a'));
}
See https://godbolt.org/z/1eThqvMhx
When running this code in C, it prints
sizeof(char) = 1
sizeof('a') = 4
When running this code in C++, it prints
sizeof(char) = 1
sizeof('a') = 1
Why does the output differ between languages?
What is the size of a character in C and C++? As far as I know, the size of char is 1 byte in both C and C++.
",https://stackoverflow.com/questions/2172943/why-is-the-size-of-a-character-sizeofa-different-in-c-and-c,352,374925.0,4.0,,,2010-01-31 19:15:20,2024-01-15 11:58:08,2024-01-15 11:58:08,2024-01-15 12:04:55,Duplicate,c++;c;types;char;sizeof,whacko__Cracko,6762,211631,registered,true,2172948,,,,691,506,4,1,0,5,true,true,false,true,true,true,74,13,true,0.011,0.0009,6138,2010,1,19,Sunday,true,false,false,false,false,false,false
3378560,How to disable GCC warnings for a few lines of code,"In Visual C++, it's possible to use #pragma warning (disable: ...). Also I found that in GCC you can override per file compiler flags. How can I do this for ""next line"", or with push/pop semantics around areas of code using GCC?
",https://stackoverflow.com/questions/3378560/how-to-disable-gcc-warnings-for-a-few-lines-of-code,351,282627.0,9.0,,,2010-07-31 14:41:39,2024-04-05 12:34:16,2018-11-15 22:41:43,,,c;gcc;compiler-warnings;pragma,Matt Joiner,120754,149482,registered,true,3394268,,CC BY-SA 4.0,,453,229,1,2,0,4,true,false,false,true,true,true,51,11,false,0.032,0.0012,5957,2010,7,14,Saturday,true,false,false,false,false,false,false
7021725,How can I convert a string to integer in C?,"I am trying to find out if there is an alternative way of converting a string to an integer in C.
I regularly pattern the following in my code.
char s[] = "45";
int num = atoi(s);
Is there a better way or another way?
",https://stackoverflow.com/questions/7021725/how-can-i-convert-a-string-to-integer-in-c,351,1358114.0,14.0,,,2011-08-11 06:30:00,2026-10-10 20:15:06,2026-04-28 22:25:40,,,c;string;atoi,user618677,5161,618677,registered,true,7021750,,CC BY-SA 4.0,2014-03-15 21:52:36,275,230,1,0,0,3,true,false,false,true,true,true,43,10,true,0.01,0.0003,5581,2011,8,6,Thursday,false,false,false,false,false,false,false
2575048,Arrow operator (->) usage in C,"I am reading a book called ""Teach Yourself C in 21 Days"" (I have already learned Java and C# so I am moving at a much faster pace). I was reading the chapter on pointers and the -> (arrow) operator came up without explanation. I think that it is used to call members and functions (like the equivalent of the . (dot) operator, but for pointers instead of members). But I am not entirely sure.
Could I please get an explanation and a code sample?
",https://stackoverflow.com/questions/2575048/arrow-operator-usage-in-c,350,694284.0,11.0,,,2010-04-04 16:21:12,2024-05-20 03:58:20,2019-09-23 12:29:52,,,c;pointers;syntax,Mohit Deshpande,55597,200477,registered,true,2575050,,CC BY-SA 4.0,2019-07-19 12:12:58,499,450,2,0,0,3,true,false,false,true,true,true,33,6,false,0.016,0.0005,6075,2010,4,16,Sunday,true,false,false,false,false,false,false
1033898,Why do you have to link the math library in C?,"If I include <stdlib.h> or <stdio.h> in a C program, I don't have to link these when compiling, but I do have to link to <math.h>, using -lm with GCC, for example:
gcc test.c -o test -lm
What is the reason for this? Why do I have to explicitly link the math library, but not the other libraries?
",https://stackoverflow.com/questions/1033898/why-do-you-have-to-link-the-math-library-in-c,350,182046.0,14.0,,,2009-06-23 17:08:00,2024-03-07 16:49:28,2022-10-29 00:39:55,,,c;compilation;math.h,Nope,36360,41718,registered,true,1033940,,CC BY-SA 4.0,2024-03-10 13:30:58,523,315,4,1,0,3,true,false,false,true,true,true,46,11,true,0.077,0.0019,6360,2009,6,17,Tuesday,false,false,false,false,false,false,false
252782,strdup() - what does it do in C?,"What is the purpose of the strdup() function in C?
",https://stackoverflow.com/questions/252782/strdup-what-does-it-do-in-c,348,481434.0,11.0,,,2008-10-31 07:15:45,2024-10-21 11:12:53,2013-07-02 16:20:31,,,c;function;strdup,Manoj Doubts,14227,31116,registered,true,252802,,CC BY-SA 3.0,2017-05-29 06:55:00,71,51,1,0,0,3,true,false,false,true,true,true,32,8,true,0.023,0.0007,6595,2008,10,7,Friday,false,false,false,false,false,false,false
2310483,Purpose of Unions in C and C++,"I have used unions earlier comfortably; today I was alarmed when I read this post and came to know that this code
union ARGB
{
uint32_t colour;
struct componentsTag
{
uint8_t b;
uint8_t g;
uint8_t r;
uint8_t a;
} components;
} pixel;
pixel.colour = 0xff040201; // ARGB::colour is the active member from now on
// somewhere down the line, without any edit to pixel
if(pixel.components.a) // accessing the non-active member ARGB::components
is actually undefined behaviour I.e. reading from a member of the union other than the one recently written to leads to undefined behaviour. If this isn't the intended usage of unions, what is? Can some one please explain it elaborately?
Update:
I wanted to clarify a few things in hindsight.
- The answer to the question isn't the same for C and C++; my ignorant younger self tagged it as both C and C++.
- After scouring through C++11's standard I couldn't conclusively say that it calls out accessing/inspecting a non-active union member is undefined/unspecified/implementation-defined. All I could find was §9.5/1:
If a standard-layout union contains several standard-layout structs that share a common initial sequence, and if an object of this standard-layout union type contains one of the standard-layout structs, it is permitted to inspect the common initial sequence of any of standard-layout struct members. §9.2/19: Two standard-layout structs share a common initial sequence if corresponding members have layout-compatible types and either neither member is a bit-field or both are bit-fields with the same width for a sequence of one or more initial members.
- While in C, (C99 TC3 - DR 283 onwards) it's legal to do so (thanks to Pascal Cuoq for bringing this up). However, attempting to do it can still lead to undefined behavior, if the value read happens to be invalid (so called ""trap representation"") for the type it is read through. Otherwise, the value read is implementation defined.
C89/90 called this out under unspecified behavior (Annex J) and K&R's book says it's implementation defined. Quote from K&R:
This is the purpose of a union - a single variable that can legitimately hold any of one of several types. [...] so long as the usage is consistent: the type retrieved must be the type most recently stored. It is the programmer's responsibility to keep track of which type is currently stored in a union; the results are implementation-dependent if something is stored as one type and extracted as another.
Extract from Stroustrup's TC++PL (emphasis mine)
Use of unions can be essential for compatness of data [...] sometimes misused for ""type conversion"".
Above all, this question (whose title remains unchanged since my ask) was posed with an intention of understanding the purpose of unions AND not on what the standard allows E.g. Using inheritance for code reuse is, of course, allowed by the C++ standard, but it wasn't the purpose or the original intention of introducing inheritance as a C++ language feature. This is the reason Andrey's answer continues to remain as the accepted one.
",https://stackoverflow.com/questions/2310483/purpose-of-unions-in-c-and-c,346,186786.0,18.0,,,2010-02-22 11:17:19,2024-08-27 17:17:16,2017-05-23 12:25:51,,,c++;c;unions;type-punning,legends2k,33380,183120,registered,true,2313676,,CC BY-SA 3.0,,3800,3151,1,4,0,4,true,false,false,true,true,true,30,7,false,0.096,0.0019,6116,2010,2,11,Monday,false,false,false,false,false,false,false
15004944,max value of integer,"In C, the integer (for 32 bit machine) is 32 bits, and it ranges from -32,768 to +32,767.
In Java, the integer(long) is also 32 bits, but ranges from -2,147,483,648 to +2,147,483,647.
I do not understand how the range is different in Java, even though the number of bits is the same. Can someone explain this?
",https://stackoverflow.com/questions/15004944/max-value-of-integer,346,1272027.0,11.0,,,2013-02-21 14:37:41,2020-02-14 07:21:50,2020-02-14 07:21:50,,,java;c;integer;max;bit,stackuser,4233,1319100,registered,true,,,CC BY-SA 4.0,2019-05-03 04:26:18,325,311,0,0,0,5,false,false,false,true,true,true,20,4,false,0.009,0.0003,5021,2013,2,14,Thursday,false,false,false,true,false,false,false
5171502,.c vs .cc vs. .cpp vs .hpp vs .h vs .cxx,"
Possible Duplicates:
*.h or *.hpp for your class definitions
What is the difference between .cc and .cpp file suffix?
I used to think that it used to be that:
.h files are header files for C and C++, and usually only contain declarations.
.c files are C source code.
.cpp files are C++ source code (which can also be C source code).
then files like .hpp, .cc, and .cxx came along, and I got totally confused... what's the difference(s) between those? When do you use the "new" ones?
",https://stackoverflow.com/questions/5171502/c-vs-cc-vs-cpp-vs-hpp-vs-h-vs-cxx,345,368874.0,6.0,,,2011-03-02 18:04:59,2025-03-20 22:55:35,2023-10-11 19:34:52,2011-03-02 19:07:03,exact duplicate,c++;c;filenames;header-files;naming,user541686,213473,541686,registered,true,5171821,,,,893,498,6,2,0,5,true,true,false,true,true,true,40,11,false,0.016,0.0009,5743,2011,3,18,Wednesday,false,false,false,false,false,false,false
31739792,Is uninitialized local variable the fastest random number generator?,"I know the uninitialized local variable is undefined behaviour(UB), and also the value may have trap representations which may affect further operation, but sometimes I want to use the random number only for visual representation and will not further use them in other part of program, for example, set something with random color in a visual effect, for example:
void updateEffect(){
for(int i=0;i<1000;i++){
int r;
int g;
int b;
star[i].setColor(r%255,g%255,b%255);
bool isVisible;
star[i].setVisible(isVisible);
}
}
is it that faster than
void updateEffect(){
for(int i=0;i<1000;i++){
star[i].setColor(rand()%255,rand()%255,rand()%255);
star[i].setVisible(rand()%2==0?true:false);
}
}
and also faster than other random number generator?
",https://stackoverflow.com/questions/31739792/is-uninitialized-local-variable-the-fastest-random-number-generator,344,24342.0,21.0,,,2015-07-31 06:52:42,2020-02-18 20:28:31,2015-07-31 19:51:29,,,c++;c;undefined-behavior;garbage,ggrr,7927,4822120,registered,true,,,CC BY-SA 3.0,2015-08-01 08:50:23,910,832,2,0,0,4,false,false,false,true,true,true,68,9,true,0.863,0.0141,4131,2015,7,6,Friday,false,false,false,false,false,false,false
4306186,Structure padding and packing,"Consider:
struct mystruct_A
{
char a;
int b;
char c;
} x;
struct mystruct_B
{
int b;
char a;
} y;
The sizes of the structures are 12 and 8 respectively.
Are these structures padded or packed?
When does padding or packing take place?
",https://stackoverflow.com/questions/4306186/structure-padding-and-packing,343,553160.0,11.0,,,2010-11-29 17:16:12,2026-07-31 14:07:40,2016-09-01 15:57:25,,,c;struct;structure;padding;packing,Manu,5854,501778,registered,true,4306269,,CC BY-SA 3.0,,306,254,1,0,0,5,true,false,false,true,true,true,29,4,false,0.02,0.0006,5836,2010,11,17,Monday,false,false,false,false,false,false,false
12193170,What's the purpose of using braces (i.e. {}) for a single-line if or loop?,"I'm reading some lecture notes of my C++ lecturer and he wrote the following:
- Use Indentation // OK
- Never rely on operator precedence - Always use parentheses // OK
- Always use a { } block - even for a single line // not OK, why ???
- Const object on left side of comparison // OK
- Use unsigned for variables that are >= 0 // nice trick
- Set Pointer to NULL after deletion - Double delete protection // not bad
The 3rd technique is not clear to me: what would I gain by placing one line in
a { ... }?
For example, take this weird code:
int j = 0;
for (int i = 0 ; i < 100 ; ++i)
{
if (i % 2 == 0)
{
j++;
}
}
and replace it with:
int j = 0;
for (int i = 0 ; i < 100 ; ++i)
if (i % 2 == 0)
j++;
What's the benefit of using the 1st version?
",https://stackoverflow.com/questions/12193170/whats-the-purpose-of-using-braces-i-e-for-a-single-line-if-or-loop,342,55578.0,25.0,,,2012-08-30 08:50:09,2024-07-12 03:50:08,2014-06-24 05:43:09,,,c++;c;coding-style;curly-braces;defensive-programming,JAN,22063,779111,registered,true,12193202,,CC BY-SA 3.0,2014-10-18 08:53:32,1010,809,3,0,0,5,true,false,false,true,true,true,78,14,true,0.45,0.0062,5196,2012,8,8,Thursday,false,false,false,false,false,false,false
496448,How to correctly use the extern keyword in C,"My question is about when a function should be referenced with the extern keyword in C.
I am failing to see when this should be used in practice. As I am writing a program all of the functions that I use are made available through the header files I have included. So why would it be useful to extern to get access to something that was not exposed in the header file?
I could be thinking about how extern works incorrectly, and if so please correct me.
Also.. Should you extern something when it is the default declaration without the keyword in a header file?
",https://stackoverflow.com/questions/496448/how-to-correctly-use-the-extern-keyword-in-c,342,361417.0,11.0,,,2009-01-30 17:40:38,2025-04-27 09:42:50,2021-05-21 09:47:32,,,c,lillq,15503,2064,registered,true,496476,,CC BY-SA 4.0,2019-07-19 12:14:50,644,564,4,0,0,1,true,false,false,true,true,true,44,9,false,0.03,0.0009,6504,2009,1,17,Friday,false,false,false,false,false,false,false
6357038,Is multiplication and division using shift operators in C actually faster?,"Multiplication and division can be achieved using bit operators, for example
i*2 = i<<1
i*3 = (i<<1) + i;
i*10 = (i<<3) + (i<<1)
and so on.
Is it actually faster to use say (i<<3)+(i<<1) to multiply with 10 than using i*10 directly? Is there any sort of input that can't be multiplied or divided in this way?
",https://stackoverflow.com/questions/6357038/is-multiplication-and-division-using-shift-operators-in-c-actually-faster,337,155241.0,19.0,,,2011-06-15 11:31:04,2025-09-08 12:50:15,2011-06-16 03:57:06,,,c++;c;division;multiplication;bit-shift,eku,3447,669366,registered,true,6357114,,CC BY-SA 3.0,,420,349,3,0,0,5,true,false,false,true,true,true,74,11,true,0.122,0.0022,5638,2011,6,11,Wednesday,false,false,false,false,false,false,false
1119134,How do malloc() and free() work?,"I want to know how malloc and free work.
int main() {
unsigned char *p = (unsigned char*)malloc(4*sizeof(unsigned char));
memset(p,0,4);
strcpy((char*)p,""abcdabcd""); // **deliberately storing 8bytes**
cout << p;
free(p); // Obvious Crash, but I need how it works and why crash.
cout << p;
return 0;
}
I would be really grateful if the answer is in depth at memory level, if it's possible.
",https://stackoverflow.com/questions/1119134/how-do-malloc-and-free-work,336,228099.0,13.0,,,2009-07-13 12:22:18,2018-04-13 02:42:58,2018-04-13 02:42:58,,,c++;c;memory-management;malloc;free,Priyanka Mishra,10848,38038,registered,true,1119334,,CC BY-SA 3.0,2016-10-26 11:23:25,496,432,3,0,0,5,true,false,false,true,true,true,32,6,true,0.057,0.0015,6340,2009,7,12,Monday,false,false,false,false,false,false,false
2339679,What are the differences between .so and .dylib on macOS?,".dylib is the dynamic library extension on macOS, but it's never been clear to me when I can't / shouldn't use a traditional unix .so shared object.
Some of the questions I have:
- At a conceptual level, what are the main differences between .so and .dylib?
- When can/should I use one over the other?
- Compilation tricks & tips (For example, the replacement for gcc -shared -fPIC, since that doesn't work on osx)
",https://stackoverflow.com/questions/2339679/what-are-the-differences-between-so-and-dylib-on-macos,333,185320.0,4.0,,,2010-02-26 05:31:20,2023-05-29 04:03:34,2023-05-29 04:03:34,,,c++;c;macos;unix;dylib,Trent Davies,3688,77846,registered,true,2339910,,CC BY-SA 4.0,,465,415,0,0,0,5,true,false,false,true,true,true,57,10,true,0.022,0.0018,6112,2010,2,5,Friday,false,false,false,false,false,false,false
578202,"register" keyword in C?,"What does the register keyword do in C language? I have read that it is used for optimizing but is not clearly defined in any standard. Is it still relevant and if so, when would you use it?
",https://stackoverflow.com/questions/578202/register-keyword-in-c,332,157668.0,19.0,,,2009-02-23 16:12:43,2024-01-19 01:48:19,2014-08-08 06:36:30,,,c;memory;keyword,Nick Van Brunt,15582,30470,registered,true,578213,,CC BY-SA 3.0,2019-07-19 10:43:30,213,193,1,0,0,3,true,false,false,true,true,true,34,4,true,0.121,0.0021,6480,2009,2,16,Monday,false,false,false,false,false,false,false
14547087,Extracting bits with a single multiplication,"I saw an interesting technique used in an answer to another question, and would like to understand it a little better.
We're given an unsigned 64-bit integer, and we are interested in the following bits:
1.......2.......3.......4.......5.......6.......7.......8.......
Specifically, we'd like to move them to the top eight positions, like so:
12345678........................................................
We don't care about the value of the bits indicated by ., and they don't have to be preserved.
The solution was to mask out the unwanted bits, and multiply the result by 0x2040810204081. This, as it turns out, does the trick.
How general is this method? Can this technique be used to extract any subset of bits? If not, how does one figure out whether or not the method works for a particular set of bits?
Finally, how would one go about finding the (a?) correct multiplier to extract the given bits?
",https://stackoverflow.com/questions/14547087/extracting-bits-with-a-single-multiplication,332,26182.0,6.0,,,2013-01-27 11:58:23,2025-04-27 05:35:03,2017-05-23 12:34:12,,,c;multiplication;bit-manipulation,NPE,504110,367273,registered,true,14547307,,CC BY-SA 3.0,2019-07-18 16:17:39,1275,919,4,3,0,3,true,false,false,true,true,true,44,6,false,0.229,0.0127,5046,2013,1,11,Sunday,true,false,false,false,false,false,false
4384765,"What's the difference between __PRETTY_FUNCTION__, __FUNCTION__, __func__?","What's the difference between __PRETTY_FUNCTION__, __FUNCTION__, __func__, and where are they documented? How do I decide which one to use?
",https://stackoverflow.com/questions/4384765/whats-the-difference-between-pretty-function-function-func,331,258406.0,5.0,,,2010-12-08 06:28:27,2023-12-29 20:15:12,2023-12-29 20:15:12,,,c++;c;language-lawyer,Matt Joiner,120754,149482,registered,true,4384825,,CC BY-SA 4.0,,186,140,3,0,0,3,true,false,false,true,true,true,78,7,true,0.019,0.0013,5827,2010,12,6,Wednesday,false,false,false,false,false,false,false
4426280,What do pty and tty mean?,"I noticed many mentions of pty and tty in some open source projects, could someone tell me what do they mean and what is the difference between them?
",https://stackoverflow.com/questions/4426280/what-do-pty-and-tty-mean,330,174648.0,5.0,,,2010-12-13 06:19:39,2024-08-08 15:32:26,2020-12-21 09:50:10,,,c;unix;network-programming;tty;vocabulary,why,25137,335499,registered,true,4426291,,CC BY-SA 4.0,,183,150,2,0,0,5,true,false,false,true,true,true,25,6,true,0.029,0.0019,5822,2010,12,6,Monday,false,false,false,false,false,false,false
142508,How do I check OS with a preprocessor directive?,"I need my code to do different things based on the operating system on which it gets compiled. I'm looking for something like this:
#ifdef OSisWindows
// do Windows-specific stuff
#else
// do Unix-specific stuff
#endif
Is there a way to do this? Is there a better way to do the same thing?
",https://stackoverflow.com/questions/142508/how-do-i-check-os-with-a-preprocessor-directive,327,237295.0,20.0,,,2008-09-26 23:44:00,2025-05-02 23:49:29,2018-10-26 02:33:26,,,c;operating-system;c-preprocessor;conditional-compilation,perimosocordiae,17947,10601,registered,true,8249232,,CC BY-SA 4.0,,331,293,1,0,0,4,true,false,false,true,true,true,48,9,true,0.084,0.0014,6630,2008,9,23,Friday,false,false,false,false,false,false,false
36476178,"This C function should always return false, but it doesn’t","I stumbled over an interesting question in a forum a long time ago and I want to know the answer.
Consider the following C function:
f1.c
#include <stdbool.h>
bool f1()
{
int var1 = 1000;
int var2 = 2000;
int var3 = var1 + var2;
return (var3 == 0) ? true : false;
}
This should always return false since var3 == 3000. The main function looks like this:
main.c
#include <stdio.h>
#include <stdbool.h>
int main()
{
printf( f1() == true ? ""true\n"" : ""false\n"");
if( f1() )
{
printf(""executed\n"");
}
return 0;
}
Since f1() should always return false, one would expect the program to print only one false to the screen. But after compiling and running it, executed is also displayed:
$ gcc main.c f1.c -o test
$ ./test
false
executed
Why is that? Does this code have some sort of undefined behavior?
Note: I compiled it with gcc (Ubuntu 4.9.2-10ubuntu13) 4.9.2.
",https://stackoverflow.com/questions/36476178/this-c-function-should-always-return-false-but-it-doesn-t,327,22555.0,4.0,,,2016-04-07 12:27:08,2024-05-09 16:44:01,2016-04-10 12:38:00,,,c;gcc,Dimitri Podborski,3804,3734222,registered,true,36477209,,CC BY-SA 3.0,2016-04-21 18:44:01,1201,934,9,0,0,2,true,false,false,true,true,true,58,10,false,0.177,0.0145,3880,2016,4,12,Thursday,false,false,false,false,false,false,false
2284860,How does C compute sin() and other math functions?,"I've been poring through .NET disassemblies and the GCC source code, but can't seem to find anywhere the actual implementation of sin() and other math functions... they always seem to be referencing something else.
Can anyone help me find them? I feel like it's unlikely that ALL hardware that C will run on supports trig functions in hardware, so there must be a software algorithm somewhere, right?
I'm aware of several ways that functions can be calculated, and have written my own routines to compute functions using taylor series for fun. I'm curious about how real, production languages do it, since all of my implementations are always several orders of magnitude slower, even though I think my algorithms are pretty clever (obviously they're not).
",https://stackoverflow.com/questions/2284860/how-does-c-compute-sin-and-other-math-functions,327,238891.0,22.0,,,2010-02-17 22:22:49,2024-01-20 12:48:40,2017-03-17 21:21:02,,,c;math;trigonometry,Hank,8517,172387,registered,true,2285277,,CC BY-SA 3.0,,819,763,1,0,0,3,true,false,false,true,true,true,50,9,true,0.092,0.0014,6121,2010,2,22,Wednesday,false,false,false,false,false,false,false
101439,"The most efficient way to implement an integer based power function pow(int, int)","What is the most efficient way given to raise an integer to the power of another integer in C?
// 2^3
pow(2,3) == 8
// 5^5
pow(5,5) == 3125
",https://stackoverflow.com/questions/101439/the-most-efficient-way-to-implement-an-integer-based-power-function-powint-int,325,295114.0,20.0,,,2008-09-19 12:30:30,2025-09-29 06:58:29,2015-01-30 14:43:24,,,c;algorithm;math;exponentiation,Doug T.,66039,8123,registered,true,101613,,CC BY-SA 3.0,2015-06-20 15:45:27,174,143,1,0,0,4,true,false,false,true,true,true,81,13,false,0.068,0.0011,6637,2008,9,12,Friday,false,false,false,false,false,false,false
10493411,What is bit masking?,"I am fairly new to C programming, and I encountered bit masking. What is the general concept and function of bit masking?
Examples are much appreciated.
",https://stackoverflow.com/questions/10493411/what-is-bit-masking,324,623036.0,6.0,,,2012-05-08 06:07:28,2026-07-11 16:14:34,2022-08-29 12:20:51,,,c;bit-manipulation;bitwise-operators;terminology;bitmask,Mr.Z,3299,1377624,registered,true,,,CC BY-SA 4.0,2017-02-14 03:08:17,167,153,0,0,0,5,false,false,false,true,true,true,20,4,true,0.01,0.0005,5310,2012,5,6,Tuesday,false,false,false,false,false,false,false
252552,Why do we need C Unions?,"When should unions be used? Why do we need them?
",https://stackoverflow.com/questions/252552/why-do-we-need-c-unions,324,193484.0,21.0,,,2008-10-31 03:51:40,2024-11-07 10:41:12,2012-08-14 17:49:56,,,c;unions,ramu,,,does_not_exist,true,,,CC BY-SA 3.0,2013-03-23 12:27:30,56,49,0,0,0,2,false,false,false,true,false,true,24,6,true,0.109,0.0017,6595,2008,10,3,Friday,false,false,false,false,false,false,false
1942298,"Wrapping a C library in Python: C, Cython or ctypes?","I want to call a C library from a Python application. I don't want to wrap the whole API, only the functions and datatypes that are relevant to my case. As I see it, I have three choices:
- Create an actual extension module in C. Probably overkill, and I'd also like to avoid the overhead of learning extension writing.
- Use Cython to expose the relevant parts from the C library to Python.
- Do the whole thing in Python, using
ctypes to communicate with the external library.
I'm not sure whether 2) or 3) is the better choice. The advantage of 3) is that ctypes is part of the standard library, and the resulting code would be pure Python – although I'm not sure how big that advantage actually is.
Are there more advantages or disadvantages with either choice? Which approach do you recommend?
",https://stackoverflow.com/questions/1942298/wrapping-a-c-library-in-python-c-cython-or-ctypes,324,97748.0,12.0,,,2009-12-21 20:05:51,2026-09-26 18:32:29,2026-09-26 08:46:44,,,advice;python;c;cython;ctypes,balpha,51272,115866,registered,true,1942472,,CC BY-SA 4.0,,1024,795,2,2,0,5,true,false,false,true,true,true,52,10,true,0.123,0.0033,6179,2009,12,20,Monday,false,true,false,false,false,false,false
1289881,Using GCC to produce readable assembly?,"I was wondering how to use GCC on my C source file to dump a mnemonic version of the machine code so I could see what my code was being compiled into. You can do this with Java but I haven't been able to find a way with GCC.
I am trying to re-write a C method in assembly and seeing how GCC does it would be a big help.
",https://stackoverflow.com/questions/1289881/using-gcc-to-produce-readable-assembly,322,231670.0,11.0,,,2009-08-17 19:22:17,2023-01-22 14:31:18,2012-05-01 04:13:34,,,c;gcc;assembly,James,3772,112632,registered,true,1289907,,CC BY-SA 3.0,2019-07-19 10:53:51,419,321,0,1,0,3,true,false,false,true,true,true,39,6,true,0.047,0.0014,6305,2009,8,19,Monday,false,false,false,false,false,false,false
1608318,Is bool a native C type?,"I've noticed that the Linux kernel code uses bool, but I thought that bool was a C++ type. Is bool a standard C extension (e.g., ISO C90) or a GCC extension?
",https://stackoverflow.com/questions/1608318/is-bool-a-native-c-type,322,426255.0,12.0,,,2009-10-22 16:11:54,2022-12-22 16:52:55,2009-10-29 10:18:53,,,c;gcc;linux-kernel;boolean,asussex,3261,194718,registered,true,1608350,,CC BY-SA 2.5,2013-09-17 09:10:13,165,158,0,0,0,4,true,false,false,true,true,true,24,6,true,0.028,0.0008,6239,2009,10,16,Thursday,false,false,false,false,false,false,false
4568645,Printing 1 to 1000 without loop or conditionals,"Task: Print numbers from 1 to 1000 without using any loop or conditional statements. Don't just write the printf() or cout statement 1000 times.
How would you do that using C or C++?
",https://stackoverflow.com/questions/4568645/printing-1-to-1000-without-loop-or-conditionals,321,257844.0,106.0,,,2010-12-31 06:55:16,2013-06-26 20:00:57,2011-01-30 07:14:38,,,c++;c;printf,Saurabh Gokhale,311,559062,unregistered,true,4568650,,CC BY-SA 2.5,,241,184,2,0,0,3,true,false,false,true,true,true,47,8,false,0.411,0.0012,5804,2010,12,6,Friday,false,false,false,false,false,false,false
1694036,Why is the gets function so dangerous that it should not be used?,"When I try to compile C code that uses the gets() function with GCC, I get this warning:
(.text+0x34): warning: the `gets' function is dangerous and should not be used.
I remember this has something to do with stack protection and security, but I'm not sure exactly why.
How can I remove this warning and why is there such a warning about using gets()?
If gets() is so dangerous then why can't we remove it?
",https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used,319,255384.0,13.0,,,2009-11-07 18:55:07,2022-09-02 15:10:48,2019-06-09 00:11:53,,,c;fgets;buffer-overflow;gets,Vinit Dhatrak,7124,196629,registered,true,1694042,,CC BY-SA 4.0,2018-05-07 01:58:33,517,418,3,0,0,4,true,false,false,true,true,true,65,13,true,0.051,0.0012,6223,2009,11,18,Saturday,true,false,false,false,false,false,false
3318410,#pragma pack effect,"I was wondering if someone could explain to me what the #pragma pack preprocessor statement does, and more importantly, why one would want to use it.
I checked out the MSDN page, which offered some insight, but I was hoping to hear more from people with experience. I've seen it in code before, though I can't seem to find where anymore.
",https://stackoverflow.com/questions/3318410/pragma-pack-effect,317,366941.0,11.0,,,2010-07-23 13:12:58,2021-06-23 13:05:21,2018-08-22 10:05:04,,,c;c-preprocessor;pragma-pack,Cenoc,11810,330401,registered,true,3318475,,CC BY-SA 4.0,2019-05-19 17:59:35,453,339,1,1,0,3,true,false,false,true,true,true,19,3,false,0.03,0.0009,5965,2010,7,13,Friday,false,false,false,false,false,false,false
479207,How can I achieve function overloading in C?,"Is there a way to achieve function overloading in C?
I am looking at simple functions to be overloaded like
foo(int a)
foo(char b)
foo(float c, int d)
I think there isn't any straightforward way; I'm looking for workarounds if any exist.
",https://stackoverflow.com/questions/479207/how-can-i-achieve-function-overloading-in-c,316,296044.0,15.0,,,2009-01-26 09:20:35,2026-08-07 00:42:49,2026-08-07 00:37:35,,,c;overloading,FL4SOF,4359,34590,registered,true,479212,,CC BY-SA 4.0,2019-07-19 12:13:40,284,239,1,0,0,2,true,false,false,true,true,true,44,8,true,0.051,0.0011,6508,2009,1,9,Monday,false,false,false,false,false,false,false
22621241,What does the constant 0.0039215689 represent?,"I keep seeing this constant pop up in various graphics header files
0.0039215689
It seems to have something to do with color maybe?
Here is the first hit on Google:
void RDP_G_SETFOGCOLOR(void)
{
Gfx.FogColor.R = _SHIFTR(w1, 24, 8) * 0.0039215689f;
Gfx.FogColor.G = _SHIFTR(w1, 16, 8) * 0.0039215689f;
Gfx.FogColor.B = _SHIFTR(w1, 8, 8) * 0.0039215689f;
Gfx.FogColor.A = _SHIFTR(w1, 0, 8) * 0.0039215689f;
}
void RDP_G_SETBLENDCOLOR(void)
{
Gfx.BlendColor.R = _SHIFTR(w1, 24, 8) * 0.0039215689f;
Gfx.BlendColor.G = _SHIFTR(w1, 16, 8) * 0.0039215689f;
Gfx.BlendColor.B = _SHIFTR(w1, 8, 8) * 0.0039215689f;
Gfx.BlendColor.A = _SHIFTR(w1, 0, 8) * 0.0039215689f;
if(OpenGL.Ext_FragmentProgram && (System.Options & BRDP_COMBINER)) {
glProgramEnvParameter4fARB(GL_FRAGMENT_PROGRAM_ARB, 2, Gfx.BlendColor.R, Gfx.BlendColor.G, Gfx.BlendColor.B, Gfx.BlendColor.A);
}
}
//...more like this
What does this number represent? Why does no one seem to declare it as a const?
I couldn't find anything on Google that explained it.
",https://stackoverflow.com/questions/22621241/what-does-the-constant-0-0039215689-represent,315,22098.0,2.0,,,2014-03-24 21:45:42,2014-04-10 16:37:06,2014-04-10 16:37:06,,,c;floating-point;constants;magic-numbers,crush,17123,1195273,registered,true,22621361,,CC BY-SA 3.0,,1246,1085,2,1,0,4,true,false,false,true,true,true,46,6,true,0.091,0.0143,4625,2014,3,21,Monday,false,false,false,false,false,false,false
484635,What are the pros and cons in use of global variables?,"In C/C++, there is a widespread opinion that global variables are "bad" and should be avoided when possible.
Leaving aside the question whether this opinion is correct or not, what are the objective advantages and drawbacks that arise when using global variables?
",https://stackoverflow.com/questions/484635/what-are-the-pros-and-cons-in-use-of-global-variables,314,189386.0,28.0,,,2009-01-27 18:35:09,2023-05-24 18:20:37,2023-05-24 18:20:37,2017-04-04 16:30:32,Opinion-based,c++;c;global-variables,timp,,,does_not_exist,true,,,,2012-02-04 11:23:06,288,274,0,0,0,3,false,true,false,true,false,true,54,11,true,0.148,0.0017,6507,2009,1,18,Tuesday,false,false,false,false,false,false,false
108183,How to prevent SIGPIPEs (or handle them properly),"I have a small server program that accepts connections on a TCP or local UNIX socket, reads a simple command and (depending on the command) sends a reply.
The problem is that the client may have no interest in the answer and sometimes exits early. So writing to that socket will cause a SIGPIPE and make my server crash.
What's the best practice to prevent the crash here? Is there a way to check if the other side of the line is still reading? (select() doesn't seem to work here as it always says the socket is writable). Or should I just catch the SIGPIPE with a handler and ignore it?
",https://stackoverflow.com/questions/108183/how-to-prevent-sigpipes-or-handle-them-properly,314,265282.0,10.0,,,2008-09-20 13:43:21,2025-02-20 06:24:56,2020-10-09 18:44:31,,,c;io;signals;broken-pipe;sigpipe,user12523,,,does_not_exist,true,108192,,CC BY-SA 4.0,2019-07-19 10:49:51,650,590,3,0,0,5,true,false,false,true,false,true,49,8,false,0.038,0.0012,6636,2008,9,13,Saturday,true,false,false,false,false,false,false
4418708,What's the rationale for null terminated strings?,"As much as I love C and C++, I can't help but scratch my head at the choice of null terminated strings:
- Length prefixed (i.e. Pascal) strings existed before C
- Length prefixed strings make several algorithms faster by allowing constant time length lookup.
- Length prefixed strings make it more difficult to cause buffer overrun errors.
- Even on a 32 bit machine, if you allow the string to be the size of available memory, a length prefixed string is only three bytes wider than a null terminated string. On 16 bit machines this is a single byte. On 64 bit machines, 4GB is a reasonable string length limit, but even if you want to expand it to the size of the machine word, 64 bit machines usually have ample memory making the extra seven bytes sort of a null argument. I know the original C standard was written for insanely poor machines (in terms of memory), but the efficiency argument doesn't sell me here.
- Pretty much every other language (i.e. Perl, Pascal, Python, Java, C#, etc) use length prefixed strings. These languages usually beat C in string manipulation benchmarks because they are more efficient with strings.
- C++ rectified this a bit with the
std::basic_string template, but plain character arrays expecting null terminated strings are still pervasive. This is also imperfect because it requires heap allocation.
- Null terminated strings have to reserve a character (namely, null), which cannot exist in the string, while length prefixed strings can contain embedded nulls.
Several of these things have come to light more recently than C, so it would make sense for C to not have known of them. However, several were plain well before C came to be. Why would null terminated strings have been chosen instead of the obviously superior length prefixing?
EDIT: Since some asked for facts (and didn't like the ones I already provided) on my efficiency point above, they stem from a few things:
- Concat using null terminated strings requires O(n + m) time complexity. Length prefixing often require only O(m).
- Length using null terminated strings requires O(n) time complexity. Length prefixing is O(1).
- Length and concat are by far the most common string operations. There are several cases where null terminated strings can be more efficient, but these occur much less often.
From answers below, these are some cases where null terminated strings are more efficient:
- When you need to cut off the start of a string and need to pass it to some method. You can't really do this in constant time with length prefixing even if you are allowed to destroy the original string, because the length prefix probably needs to follow alignment rules.
- In some cases where you're just looping through the string character by character you might be able to save a CPU register. Note that this works only in the case that you haven't dynamically allocated the string (Because then you'd have to free it, necessitating using that CPU register you saved to hold the pointer you originally got from malloc and friends).
None of the above are nearly as common as length and concat.
There's one more asserted in the answers below:
- You need to cut off the end of the string
but this one is incorrect -- it's the same amount of time for null terminated and length prefixed strings. (Null terminated strings just stick a null where you want the new end to be, length prefixers just subtract from the prefix.)
",https://stackoverflow.com/questions/4418708/whats-the-rationale-for-null-terminated-strings,314,35371.0,20.0,,,2010-12-11 20:13:28,2026-05-28 10:43:52,2017-03-21 19:44:47,,,c++;c;string;null-terminated,Billy ONeal,107658,82320,registered,true,4418774,,CC BY-SA 3.0,,3655,3414,1,0,0,4,true,false,false,true,true,true,53,7,true,0.565,0.0089,5824,2010,12,20,Saturday,true,false,false,false,false,false,false
2355834,How can I autoformat/indent C code in vim?,"When I copy code from another file, the formatting is messed up, like this:
fun()
{
for(...)
{
for(...)
{
if(...)
{
}
}
}
}
How can I autoformat this code in vim?
",https://stackoverflow.com/questions/2355834/how-can-i-autoformat-indent-c-code-in-vim,313,260904.0,10.0,,,2010-03-01 12:50:42,2024-10-21 18:01:28,2015-05-07 19:06:47,,,c;vim;code-formatting,Yongwei Xing,13599,169477,registered,true,2355848,,CC BY-SA 3.0,2019-07-19 10:56:11,204,166,1,0,0,3,true,false,false,true,true,true,42,8,true,0.038,0.0012,6109,2010,3,12,Monday,false,false,false,false,false,false,false
466204,Rounding up to next power of 2,"I want to write a function that returns the nearest next power of 2 number. For example if my input is 789, the output should be 1024. Is there any way of achieving this without using any loops but just using some bitwise operators?
Related: Algorithm for finding the smallest power of two that's greater or equal to a given value is a C++ question. C++20 introduced std:bit_ceil which lets the compiler do whatever's optimal for the target system, but nothing equivalent is yet available in portable ISO C for bit-scan, popcount or other common bit operations that most CPUs have. Portable C code has to be less efficient and/or more complicated.
Given an integer, how do I find the next largest power of two using bit-twiddling? is a language-agnostic version of the question with some C++11 and 17 constexpr using GNU extensions.
Answers to this question don't need to be portable; fast versions for various platforms are useful.
",https://stackoverflow.com/questions/466204/rounding-up-to-next-power-of-2,313,344124.0,29.0,,,2009-01-21 17:26:18,2026-04-24 17:51:53,2023-02-28 04:50:20,,,c;optimization;bit-manipulation,Naveen,74071,39742,registered,true,466242,,CC BY-SA 4.0,2021-10-27 12:44:00,1285,941,2,2,0,3,true,false,false,true,true,true,30,7,false,0.084,0.0009,6513,2009,1,17,Wednesday,false,false,false,false,false,false,false
57650895,Why does glibc's strlen need to be so complicated to run quickly?,"I was looking through the strlen code here and I was wondering if the optimizations used in the code are really needed? For example, why wouldn't something like the following work equally good or better?
unsigned long strlen(char s[]) {
unsigned long i;
for (i = 0; s[i] != '\0'; i++)
continue;
return i;
}
Isn't simpler code better and/or easier for the compiler to optimize?
The code of strlen on the page behind the link looks like this:
/* Copyright (C) 1991, 1993, 1997, 2000, 2003 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Written by Torbjorn Granlund (tege@sics.se),
with help from Dan Sahlin (dan@sics.se);
commentary by Jim Blandy (jimb@ai.mit.edu).
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA. */
#include <string.h>
#include <stdlib.h>
#undef strlen
/* Return the length of the null-terminated string STR. Scan for
the null terminator quickly by testing four bytes at a time. */
size_t
strlen (str)
const char *str;
{
const char *char_ptr;
const unsigned long int *longword_ptr;
unsigned long int longword, magic_bits, himagic, lomagic;
/* Handle the first few characters by reading one character at a time.
Do this until CHAR_PTR is aligned on a longword boundary. */
for (char_ptr = str; ((unsigned long int) char_ptr
& (sizeof (longword) - 1)) != 0;
++char_ptr)
if (*char_ptr == '\0')
return char_ptr - str;
/* All these elucidatory comments refer to 4-byte longwords,
but the theory applies equally well to 8-byte longwords. */
longword_ptr = (unsigned long int *) char_ptr;
/* Bits 31, 24, 16, and 8 of this number are zero. Call these bits
the "holes." Note that there is a hole just to the left of
each byte, with an extra at the end:
bits: 01111110 11111110 11111110 11111111
bytes: AAAAAAAA BBBBBBBB CCCCCCCC DDDDDDDD
The 1-bits make sure that carries propagate to the next 0-bit.
The 0-bits provide holes for carries to fall into. */
magic_bits = 0x7efefeffL;
himagic = 0x80808080L;
lomagic = 0x01010101L;
if (sizeof (longword) > 4)
{
/* 64-bit version of the magic. */
/* Do the shift in two steps to avoid a warning if long has 32 bits. */
magic_bits = ((0x7efefefeL << 16) << 16) | 0xfefefeffL;
himagic = ((himagic << 16) << 16) | himagic;
lomagic = ((lomagic << 16) << 16) | lomagic;
}
if (sizeof (longword) > 8)
abort ();
/* Instead of the traditional loop which tests each character,
we will test a longword at a time. The tricky part is testing
if *any of the four* bytes in the longword in question are zero. */
for (;;)
{
/* We tentatively exit the loop if adding MAGIC_BITS to
LONGWORD fails to change any of the hole bits of LONGWORD.
1) Is this safe? Will it catch all the zero bytes?
Suppose there is a byte with all zeros. Any carry bits
propagating from its left will fall into the hole at its
least significant bit and stop. Since there will be no
carry from its most significant bit, the LSB of the
byte to the left will be unchanged, and the zero will be
detected.
2) Is this worthwhile? Will it ignore everything except
zero bytes? Suppose every byte of LONGWORD has a bit set
somewhere. There will be a carry into bit 8. If bit 8
is set, this will carry into bit 16. If bit 8 is clear,
one of bits 9-15 must be set, so there will be a carry
into bit 16. Similarly, there will be a carry into bit
24. If one of bits 24-30 is set, there will be a carry
into bit 31, so all of the hole bits will be changed.
The one misfire occurs when bits 24-30 are clear and bit
31 is set; in this case, the hole at bit 31 is not
changed. If we had access to the processor carry flag,
we could close this loophole by putting the fourth hole
at bit 32!
So it ignores everything except 128's, when they're aligned
properly. */
longword = *longword_ptr++;
if (
#if 0
/* Add MAGIC_BITS to LONGWORD. */
(((longword + magic_bits)
/* Set those bits that were unchanged by the addition. */
^ ~longword)
/* Look at only the hole bits. If any of the hole bits
are unchanged, most likely one of the bytes was a
zero. */
& ~magic_bits)
#else
((longword - lomagic) & himagic)
#endif
!= 0)
{
/* Which of the bytes was the zero? If none of them were, it was
a misfire; continue the search. */
const char *cp = (const char *) (longword_ptr - 1);
if (cp[0] == 0)
return cp - str;
if (cp[1] == 0)
return cp - str + 1;
if (cp[2] == 0)
return cp - str + 2;
if (cp[3] == 0)
return cp - str + 3;
if (sizeof (longword) > 4)
{
if (cp[4] == 0)
return cp - str + 4;
if (cp[5] == 0)
return cp - str + 5;
if (cp[6] == 0)
return cp - str + 6;
if (cp[7] == 0)
return cp - str + 7;
}
}
}
}
libc_hidden_builtin_def (strlen)
Why does this version run quickly?
Isn't it doing a lot of unnecessary work?
",https://stackoverflow.com/questions/57650895/why-does-glibcs-strlen-need-to-be-so-complicated-to-run-quickly,313,68516.0,8.0,,,2019-08-26 01:24:10,2023-09-01 06:47:05,2022-06-08 22:15:17,,,c;optimization;glibc;portability;strlen,user11954200,,,does_not_exist,true,57651888,,CC BY-SA 4.0,,6301,6046,4,1,0,5,true,false,false,true,false,true,69,12,true,0.117,0.0046,2644,2019,8,1,Monday,false,false,false,false,false,false,false
9682593,how to use #ifdef with an OR condition?,"I would like to set OR condition in #ifdef directive.?
I tried:
#ifdef LINUX | ANDROID
...
..
#endif
It did not work? What is the proper way?
",https://stackoverflow.com/questions/9682593/how-to-use-ifdef-with-an-or-condition,311,201905.0,2.0,,,2012-03-13 10:51:15,2025-01-26 18:32:11,2025-01-26 18:32:11,,,c;macros,Whoami,14518,916439,registered,true,9682617,,CC BY-SA 4.0,2019-07-19 12:14:41,189,144,1,0,0,2,true,false,false,true,true,true,39,8,true,0.01,0.0015,5366,2012,3,10,Tuesday,false,false,false,false,false,false,false
30821406,Why does rand() + rand() produce negative numbers?,"I observed that rand() library function when it is called just once within a loop, it almost always produces positive numbers.
for (i = 0; i < 100; i++) {
printf(""%d\n"", rand());
}
But when I add two rand() calls, the numbers generated now have more negative numbers.
for (i = 0; i < 100; i++) {
printf(""%d = %d\n"", rand(), (rand() + rand()));
}
Can someone explain why I am seeing negative numbers in the second case?
PS: I initialize the seed before the loop as srand(time(NULL)).
",https://stackoverflow.com/questions/30821406/why-does-rand-rand-produce-negative-numbers,309,49813.0,9.0,,,2015-06-13 17:15:39,2020-07-31 11:03:06,2015-06-17 08:25:16,,,c;random,badmad,2079,1580312,registered,true,30821428,,CC BY-SA 3.0,2018-02-16 23:10:49,619,504,5,0,0,2,true,false,false,true,true,true,50,8,true,0.181,0.0062,4179,2015,6,17,Saturday,true,false,false,false,false,false,false
503878,How to know what the 'errno' means?,"When calling execl(...), I get an errno=2. What does it mean? How can I know the meaning of this errno?
",https://stackoverflow.com/questions/503878/how-to-know-what-the-errno-means,308,529750.0,15.0,,,2009-02-02 16:49:13,2026-09-04 04:24:52,2015-02-18 00:01:35,,,c;linux;errno,Barth,15913,20986,registered,true,504039,,CC BY-SA 3.0,,150,104,3,0,0,3,true,false,false,true,true,true,43,7,true,0.028,0.0006,6501,2009,2,16,Monday,false,false,false,false,false,false,false
11720656,Modulo operation with negative numbers,"In a C program I was trying the below operations (Just to check the behavior)
x = 5 % (-3);
y = (-5) % (3);
z = (-5) % (-3);
printf("%d, %d, %d", x, y, z);
It gave me output as 2, -2 , -2 in gcc. I was expecting a positive result every time. Can a modulus be negative? Can anybody explain this behavior?
",https://stackoverflow.com/questions/11720656/modulo-operation-with-negative-numbers,308,400420.0,15.0,,,2012-07-30 11:31:22,2026-06-23 07:27:54,2025-09-30 17:17:32,,,c;gcc;modulo;negative-number,Alva,3092,1066676,registered,true,,,CC BY-SA 4.0,,372,321,2,0,0,4,false,false,false,true,true,true,38,5,false,0.037,0.0008,5227,2012,7,11,Monday,false,false,false,false,false,false,false
51667,Best Tips for documenting code using doxygen?,"My team is starting to document our C code using doxygen, paying particular attention to our public API headers. There appears to be a lot of flexibility and different special commands in doxygen, which is great, but it's not clear what's a good thing and what's a bad thing without trial and error.
What are your favourite ways to mark up your code, what are your MUST DOs and DO NOTs?
Please provide your top tips, one per answer to facilitate voting.
I am looking to define our whole approach to API documentation, including providing a template to get the rest of the team started. So far I have something like this:
/**
* @file example_action.h
* @Author Me (me@example.com)
* @date September, 2008
* @brief Brief description of file.
*
* Detailed description of file.
*/
/**
* @name Example API Actions
* @brief Example actions available.
* @ingroup example
*
* This API provides certain actions as an example.
*
* @param [in] repeat Number of times to do nothing.
*
* @retval TRUE Successfully did nothing.
* @retval FALSE Oops, did something.
*
* Example Usage:
* @code
* example_nada(3); // Do nothing 3 times.
* @endcode
*/
boolean example(int repeat);
",https://stackoverflow.com/questions/51667/best-tips-for-documenting-code-using-doxygen,308,154259.0,20.0,,,2008-09-09 11:41:38,2017-05-14 20:03:21,2014-06-06 22:02:23,2016-01-01 12:28:19,Opinion-based,c++;c;documentation;doxygen,Andrew Johnson,7289,5109,registered,true,,,,2013-03-09 11:23:26,1276,1210,1,0,0,4,false,true,false,true,true,true,45,7,true,0.13,0.002,6647,2008,9,11,Tuesday,false,false,false,false,false,false,false
1725855,What is the advantage of uint8_t over unsigned char?,"What is the advantage of using uint8_t over unsigned char in C?
I know that on almost every system uint8_t is just a typedef for unsigned char,
so why use it?
",https://stackoverflow.com/questions/1725855/what-is-the-advantage-of-uint8-t-over-unsigned-char,307,430552.0,8.0,,,2009-11-12 22:28:22,2024-11-01 18:56:51,2023-10-05 10:42:35,,,c;typedef;uint8t,Frames Catherine White,28560,179081,registered,true,1725867,,CC BY-SA 4.0,,226,160,4,0,0,3,true,false,false,true,true,true,52,9,true,0.019,0.0007,6218,2009,11,22,Thursday,false,false,false,false,false,false,false
8440816,Message "warning: implicit declaration of function","My compiler (GCC) is giving me the warning:
warning: implicit declaration of function
Why is it coming?
",https://stackoverflow.com/questions/8440816/message-warning-implicit-declaration-of-function,307,1312488.0,10.0,,,2011-12-09 03:49:01,2025-10-11 11:57:26,2022-10-23 19:29:40,,,c;compiler-warnings,Angus,12767,713179,registered,true,8440833,,CC BY-SA 4.0,2023-11-30 10:18:31,152,106,0,0,0,2,true,false,false,true,true,true,61,6,false,0.008,0.0002,5461,2011,12,3,Friday,false,false,false,false,false,false,false
32195949,Why does NaN - NaN == 0.0 with the Intel C++ Compiler?,"It is well-known that NaNs propagate in arithmetic, but I couldn't find any demonstrations, so I wrote a small test:
#include <limits>
#include <cstdio>
int main(int argc, char* argv[]) {
float qNaN = std::numeric_limits<float>::quiet_NaN();
float neg = -qNaN;
float sub1 = 6.0f - qNaN;
float sub2 = qNaN - 6.0f;
float sub3 = qNaN - qNaN;
float add1 = 6.0f + qNaN;
float add2 = qNaN + qNaN;
float div1 = 6.0f / qNaN;
float div2 = qNaN / 6.0f;
float div3 = qNaN / qNaN;
float mul1 = 6.0f * qNaN;
float mul2 = qNaN * qNaN;
printf(
""neg: %f\nsub: %f %f %f\nadd: %f %f\ndiv: %f %f %f\nmul: %f %f\n"",
neg, sub1,sub2,sub3, add1,add2, div1,div2,div3, mul1,mul2
);
return 0;
}
The example (running live here) produces basically what I would expect (the negative is a little weird, but it kind of makes sense):
neg: -nan
sub: nan nan nan
add: nan nan
div: nan nan nan
mul: nan nan
MSVC 2015 produces something similar. However, Intel C++ 15 produces:
neg: -nan(ind)
sub: nan nan 0.000000
add: nan nan
div: nan nan nan
mul: nan nan
Specifically, qNaN - qNaN == 0.0.
This... can't be right, right? What do the relevant standards (ISO C, ISO C++, IEEE 754) say about this, and why is there a difference in behavior between the compilers?
",https://stackoverflow.com/questions/32195949/why-does-nan-nan-0-0-with-the-intel-c-compiler,307,27724.0,3.0,,,2015-08-25 05:11:50,2015-09-01 11:08:39,2015-09-01 11:08:39,,,c++;c;floating-point;ieee-754;icc,geometrian,15627,688624,registered,true,,,CC BY-SA 3.0,,1514,1338,4,1,0,5,false,false,false,true,true,true,54,12,true,0.108,0.0111,4106,2015,8,5,Tuesday,false,false,false,false,false,false,false
2688466,Why malloc+memset is slower than calloc?,"It's known that calloc is different than malloc in that it initializes the memory allocated. With calloc, the memory is set to zero. With malloc, the memory is not cleared.
So in everyday work, I regard calloc as malloc+memset.
Incidentally, for fun, I wrote the following code for a benchmark.
The result is confusing.
Code 1:
#include<stdio.h>
#include<stdlib.h>
#define BLOCK_SIZE 1024*1024*256
int main()
{
int i=0;
char *buf[10];
while(i<10)
{
buf[i] = (char*)calloc(1,BLOCK_SIZE);
i++;
}
}
Output of Code 1:
time ./a.out
**real 0m0.287s**
user 0m0.095s
sys 0m0.192s
Code 2:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define BLOCK_SIZE 1024*1024*256
int main()
{
int i=0;
char *buf[10];
while(i<10)
{
buf[i] = (char*)malloc(BLOCK_SIZE);
memset(buf[i],'\0',BLOCK_SIZE);
i++;
}
}
Output of Code 2:
time ./a.out
**real 0m2.693s**
user 0m0.973s
sys 0m1.721s
Replacing memset with bzero(buf[i],BLOCK_SIZE) in Code 2 produces the same result.
My question is: Why is malloc+memset so much slower than calloc? How can calloc do that?
",https://stackoverflow.com/questions/2688466/why-mallocmemset-is-slower-than-calloc,306,72931.0,3.0,,,2010-04-22 05:40:25,2022-02-10 15:12:37,2013-07-20 19:03:03,,,c;malloc,kingkai,3779,316224,registered,true,2688522,,CC BY-SA 3.0,2013-07-29 04:31:07,1621,1276,17,0,0,2,true,false,false,true,true,true,40,6,true,0.041,0.0042,6057,2010,4,5,Thursday,false,false,false,false,false,false,false
34062595,Strange definitions of TRUE and FALSE macros,"I have seen the following macro definitions in a coding book.
#define TRUE '/'/'/'
#define FALSE '-'-'-'
There was no explanation there.
Please explain to me how these will work as TRUE and FALSE.
",https://stackoverflow.com/questions/34062595/strange-definitions-of-true-and-false-macros,306,24760.0,6.0,,,2015-12-03 09:46:32,2021-02-09 14:52:53,2017-04-08 04:53:54,,,c++;c;macros;boolean;obfuscation,Keshava GN,4295,2006333,registered,true,34062687,,CC BY-SA 3.0,2016-02-01 18:52:09,273,202,3,0,0,5,true,false,false,true,true,true,44,7,false,0.242,0.0124,4006,2015,12,9,Thursday,false,false,false,false,false,false,false
21476869,Constant pointer vs Pointer to constant,"I want to know the difference between
const int* ptr;
and
int * const ptr;
and how it works.
It is pretty difficult for me to understand or keep remember this.
Please help.
",https://stackoverflow.com/questions/21476869/constant-pointer-vs-pointer-to-constant,305,519605.0,8.0,,,2014-01-31 09:47:01,2024-04-30 01:53:51,2017-01-29 18:24:03,2014-01-31 10:46:18,Duplicate,c;pointers;constants,Venkatesh K,4784,2783882,registered,true,21476937,,,,259,183,2,0,0,3,true,true,false,true,true,true,39,6,false,0.015,0.0006,4677,2014,1,9,Friday,false,false,false,false,false,false,false
4627330,"Difference between fprintf, printf and sprintf?","Can anyone explain in simple English about the differences between printf, fprintf, and sprintf with examples?
What stream is it in?
I'm really confused between the three of these while reading about ""File Handling in C"".
",https://stackoverflow.com/questions/4627330/difference-between-fprintf-printf-and-sprintf,302,294818.0,9.0,,,2011-01-07 15:49:47,2022-08-05 10:02:03,2015-01-16 20:59:36,,,c;io;stream;printf,Vishwanath Dalvi,37054,435559,registered,true,4628144,,CC BY-SA 3.0,2019-07-19 12:21:33,285,225,3,0,0,4,true,false,false,true,true,true,47,6,true,0.031,0.001,5797,2011,1,15,Friday,false,false,false,false,false,false,false
1571340,What is the "assert" function?,"I've been studying OpenCV tutorials and came across the assert function; what does it do?
",https://stackoverflow.com/questions/1571340/what-is-the-assert-function,299,396049.0,9.0,,,2009-10-15 09:47:59,2020-03-09 12:53:27,2013-06-25 18:51:38,,,c++;c;assert,eomer,3694,189646,registered,true,1571360,,CC BY-SA 3.0,,110,90,1,0,0,3,true,false,false,true,true,true,40,5,true,0.023,0.0008,6246,2009,10,9,Thursday,false,false,false,false,false,false,false
5248915,Execution time of C program,"I have a C program that aims to be run in parallel on several processors. I need to be able to record the execution time (which could be anywhere from 1 second to several minutes). I have searched for answers, but they all seem to suggest using the clock() function, which then involves calculating the number of clocks the program took divided by the Clocks_per_second value.
I'm not sure how the Clocks_per_second value is calculated?
In Java, I just take the current time in milliseconds before and after execution.
Is there a similar thing in C? I've had a look, but I can't seem to find a way of getting anything better than a second resolution.
I'm also aware a profiler would be an option, but am looking to implement a timer myself.
Thanks
",https://stackoverflow.com/questions/5248915/execution-time-of-c-program,297,658027.0,18.0,,,2011-03-09 16:32:30,2024-07-23 12:17:19,2016-11-21 06:37:12,,,c;benchmarking,Roger,3611,502012,unregistered,true,5249150,,CC BY-SA 3.0,2019-07-19 12:27:31,837,756,3,0,0,2,true,false,false,true,true,true,27,5,false,0.027,0.0005,5736,2011,3,16,Wednesday,false,false,false,false,false,false,false
25495042,What is the >>>= operator in C?,"Given by a colleague as a puzzle, I cannot figure out how this C program actually compiles and runs. What is this >>>= operator and the strange 1P1 literal? I have tested in Clang and GCC. There are no warnings and the output is ""???""
#include <stdio.h>
int main()
{
int a[2]={ 10, 1 };
while( a[ 0xFULL?'\0':-1:>>>=a<:!!0X.1P1 ] )
printf(""?"");
return 0;
}
",https://stackoverflow.com/questions/25495042/what-is-the-operator-in-c,297,21976.0,3.0,,,2014-08-25 22:03:05,2014-12-23 21:34:25,2014-12-23 21:34:25,,,c;obfuscation;literals;bit-shift;digraphs,CustomCalc,2192,3976893,registered,true,25495211,,CC BY-SA 3.0,,466,409,3,0,0,5,true,false,false,true,true,true,40,7,true,0.137,0.0135,4471,2014,8,22,Monday,false,false,false,false,false,false,false
14733761,printf() formatting for hexadecimal,"Why, when printing a number in hexadecimal as an 8 digit number with leading zeros, does %#08X not display the same result as 0x%08X?
When I try to use the former, the 08 formatting flag is removed, and it doesn't work with just 8.
",https://stackoverflow.com/questions/14733761/printf-formatting-for-hexadecimal,297,1029177.0,5.0,,,2013-02-06 16:20:07,2021-04-27 15:06:23,2021-04-26 12:23:31,,,c;printf;hex,wsmccusker,2991,2015929,registered,true,,,CC BY-SA 4.0,,307,232,4,0,0,3,false,false,false,true,true,true,35,4,false,0.005,0.0003,5036,2013,2,16,Wednesday,false,false,false,false,false,false,false
3602827,What is the behavior of integer division?,"For example,
int result;
result = 125/100;
or
result = 43/100;
Will result always be the floor of the division? What is the defined behavior?
",https://stackoverflow.com/questions/3602827/what-is-the-behavior-of-integer-division,296,598997.0,6.0,,,2010-08-30 17:41:18,2024-03-28 16:31:27,2017-05-22 06:51:11,,,c;math;c99;c89;integer-division,T.T.T.,34947,52256,registered,true,3602857,,CC BY-SA 3.0,2017-10-12 09:13:27,219,150,2,0,0,5,true,false,false,true,true,true,41,7,true,0.01,0.0005,5927,2010,8,17,Monday,false,false,false,false,false,false,false
1002164,Write applications in C or C++ for Android?,"I'm trying to develop/port a game to Android, but it's in C, and Android supports Java, but I'm sure there must be a way to get a C app on there, anyone knows of a way to accomplish this?
",https://stackoverflow.com/questions/1002164/write-applications-in-c-or-c-for-android,295,332974.0,20.0,,,2009-06-16 15:14:50,2019-09-14 10:17:14,2019-09-14 10:17:14,2012-02-14 04:05:11,not constructive,c++;c;android,Robert Gould,70239,15124,registered,true,1571635,,,2015-04-28 09:28:44,195,188,0,0,0,3,true,true,false,true,true,true,43,8,true,0.06,0.0009,6367,2009,6,15,Tuesday,false,false,false,false,false,false,false
1591361,Understanding typedefs for function pointers in C,"I have always been a bit stumped when I read other peoples' code which had typedefs for pointers to functions with arguments. I recall that it took me a while to get around to such a definition while trying to understand a numerical algorithm written in C a while ago. So, could you share your tips and thoughts on how to write good typedefs for pointers to functions (Do's and Do not's), as to why are they useful and how to understand others' work? Thanks!
",https://stackoverflow.com/questions/1591361/understanding-typedefs-for-function-pointers-in-c,294,367002.0,8.0,,,2009-10-19 21:55:45,2024-08-14 14:12:32,2016-04-05 09:08:16,,,c;function-pointers;typedef,user192712,,,does_not_exist,true,,,CC BY-SA 3.0,,466,459,0,0,0,3,false,false,false,true,false,true,49,7,false,0.022,0.0008,6242,2009,10,21,Monday,false,false,false,false,false,false,false
1658476,C fopen vs open,"Is there any reason (other than syntactic ones) that you'd want to use
FILE *fdopen(int fd, const char *mode);
or
FILE *fopen(const char *path, const char *mode);
instead of
int open(const char *pathname, int flags, mode_t mode);
when using C in a Linux environment?
",https://stackoverflow.com/questions/1658476/c-fopen-vs-open,294,275404.0,12.0,,,2009-11-01 21:49:50,2026-06-15 22:36:45,2022-01-24 23:13:53,,,c;linux;file-io;fopen,LJM,6524,163103,registered,true,1658517,,CC BY-SA 4.0,,378,278,3,0,0,4,true,false,false,true,true,true,15,4,false,0.044,0.0011,6229,2009,11,21,Sunday,true,false,false,false,false,false,false
2595392,What does the question mark and the colon (?: ternary operator) mean in objective-c?,"What does this line of code mean?
label.frame = (inPseudoEditMode) ? kLabelIndentedRect : kLabelRect;
The ? and : confuse me.
",https://stackoverflow.com/questions/2595392/what-does-the-question-mark-and-the-colon-ternary-operator-mean-in-objectiv,293,391508.0,13.0,,,2010-04-07 19:44:04,2018-03-23 17:13:45,2017-01-07 08:45:44,,,objective-c;c;syntax;operators;conditional-operator,danielreiser,5360,227187,registered,true,2595403,,CC BY-SA 3.0,2014-07-09 01:05:18,193,129,3,0,0,5,true,false,false,true,true,true,84,14,true,0.033,0.0007,6072,2010,4,19,Wednesday,false,false,false,false,false,false,false
143174,How do I get the directory that a program is running from?,"Is there a platform-agnostic and filesystem-agnostic method to obtain the full path of the directory from where a program is running using C/C++? Not to be confused with the current working directory. (Please don't suggest libraries unless they're standard ones like clib or STL.)
(If there's no platform/filesystem-agnostic method, suggestions that work in Windows and Linux for specific filesystems are welcome too.)
",https://stackoverflow.com/questions/143174/how-do-i-get-the-directory-that-a-program-is-running-from,293,589892.0,24.0,,,2008-09-27 07:18:29,2023-10-28 05:59:03,2023-10-28 05:59:03,,,c++;c;executable-path,Ashwin Nanjappa,79244,1630,registered,true,198099,,CC BY-SA 4.0,2018-01-29 14:11:26,434,420,0,0,0,3,true,false,false,true,true,true,58,12,true,0.041,0.0005,6629,2008,9,7,Saturday,true,false,false,false,false,false,false
51032,Is there a difference between foo(void) and foo() in C++ or C?,"Consider these two function definitions:
void foo() { }
void foo(void) { }
Is there a difference between these two? If not, why is the void argument there? Is it for aesthetic reasons?
",https://stackoverflow.com/questions/51032/is-there-a-difference-between-foovoid-and-foo-in-c-or-c,293,82607.0,5.0,,,2008-09-09 00:48:23,2025-10-17 12:50:12,2025-10-17 12:50:12,,,c++;c;arguments;function-declaration,Landon,15856,1597,registered,true,51080,,CC BY-SA 4.0,,238,187,2,0,0,4,true,false,false,true,true,true,62,12,true,0.061,0.0035,6647,2008,9,0,Tuesday,false,false,false,false,false,false,false
20944784,Why is conversion from string literal to 'char*' valid in C but invalid in C++,"The C++11 Standard (ISO/IEC 14882:2011) says in § C.1.1:
char* p = ""abc""; // valid in C, invalid in C++
For the C++ it's OK as a pointer to a String Literal is harmful since any attempt to modify it leads to a crash. But why is it valid in C?
The C++11 says also:
char* p = (char*)""abc""; // OK: cast added
Which means that if a cast is added to the first statement it becomes valid.
Why does the casting makes the second statement valid in C++ and how is it different from the first one? Isn't it still harmful? If it's the case, why did the standard said that it's OK?
",https://stackoverflow.com/questions/20944784/why-is-conversion-from-string-literal-to-char-valid-in-c-but-invalid-in-c,293,297425.0,4.0,,,2014-01-06 07:06:42,2024-01-30 15:08:50,2024-01-30 15:08:50,,,c++;c;string;c++11;char,rullof,7512,2727656,registered,true,20944858,,CC BY-SA 4.0,,674,578,3,0,0,5,true,false,false,true,true,true,86,15,false,0.013,0.001,4702,2014,1,7,Monday,false,false,false,false,false,false,false
18195715,Why is unsigned integer overflow defined behavior but signed integer overflow isn't?,"Unsigned integer overflow is well defined by both the C and C++ standards. For example, the C99 standard (§6.2.5/9) states
A computation involving unsigned operands can never overflow,
because a result that cannot be represented by the resulting unsigned integer type is
reduced modulo the number that is one greater than the largest value that can be
represented by the resulting type.
However, both standards state that signed integer overflow is undefined behavior. Again, from the C99 standard (§3.4.3/1)
An example of undefined behavior is the behavior on integer overflow
Is there an historical or (even better!) a technical reason for this discrepancy?
",https://stackoverflow.com/questions/18195715/why-is-unsigned-integer-overflow-defined-behavior-but-signed-integer-overflow-is,293,84389.0,9.0,,,2013-08-12 20:04:18,2025-12-30 18:37:16,2017-05-22 06:48:19,,,c++;c;undefined-behavior;integer-overflow,anthonyvd,7720,600591,registered,true,18195756,,CC BY-SA 3.0,,878,678,2,1,0,4,true,false,false,true,true,true,88,12,true,0.107,0.0035,4849,2013,8,20,Monday,false,false,false,false,false,false,false
3501338,C read file line by line,"I wrote this function to read a line from a file:
const char *readLine(FILE *file) {
if (file == NULL) {
printf(""Error: file pointer is null."");
exit(1);
}
int maximumLineLength = 128;
char *lineBuffer = (char *)malloc(sizeof(char) * maximumLineLength);
if (lineBuffer == NULL) {
printf(""Error allocating memory for line buffer."");
exit(1);
}
char ch = getc(file);
int count = 0;
while ((ch != '\n') && (ch != EOF)) {
if (count == maximumLineLength) {
maximumLineLength += 128;
lineBuffer = realloc(lineBuffer, maximumLineLength);
if (lineBuffer == NULL) {
printf(""Error reallocating space for line buffer."");
exit(1);
}
}
lineBuffer[count] = ch;
count++;
ch = getc(file);
}
lineBuffer[count] = '\0';
char line[count + 1];
strncpy(line, lineBuffer, (count + 1));
free(lineBuffer);
const char *constLine = line;
return constLine;
}
The function reads the file correctly, and using printf I see that the constLine string did get read correctly as well.
However, if I use the function e.g. like this:
while (!feof(myFile)) {
const char *line = readLine(myFile);
printf(""%s\n"", line);
}
printf outputs gibberish. Why?
",https://stackoverflow.com/questions/3501338/c-read-file-line-by-line,291,1332695.0,18.0,,,2010-08-17 10:08:59,2024-09-10 04:29:27,2020-08-25 10:54:36,,,c;file-io;line;libc,lron,2897,422713,unregistered,true,,,CC BY-SA 4.0,,1436,1360,2,0,0,4,false,false,false,true,true,true,24,6,false,0.014,0.0002,5940,2010,8,10,Tuesday,false,false,false,false,false,false,false
1395591,What exactly is the base pointer and stack pointer? To what do they point?,"Using this example coming from Wikipedia, in which DrawSquare() calls DrawLine():
![]()
(Note that this diagram has high addresses at the bottom and low addresses at the top.)
Could anyone explain to me what ebp and esp are in this context?
From what I see, I'd say the stack pointer points always to the top of the stack, and the base pointer to the beginning of the current function? Right?
edit: I mean this in the context of Windows programs.
edit2: And how does eip work, too?
edit3: I have the following code from MSVC++:
var_C= dword ptr -0Ch
var_8= dword ptr -8
var_4= dword ptr -4
hInstance= dword ptr 8
hPrevInstance= dword ptr 0Ch
lpCmdLine= dword ptr 10h
nShowCmd= dword ptr 14h
All of them seem to be dwords, thus taking 4 bytes each. So I can see there is a gap from hInstance to var_4 of 4 bytes. What are they? I assume it is the return address, as can be seen in the diagram from Wikipedia.
(editor's note: removed a long quote from Michael's answer, which doesn't belong in the question, but a followup question was edited in):
This is because the flow of the function call is:
- Push parameters (hInstance, etc.)
- Call function, which pushes return address
- Push ebp
- Allocate space for locals
My question (last one, I hope!) now is, what exactly happens from the instant I pop the arguments of the function I want to call up to the end of the prolog? I want to know how the ebp, esp evolve during those moments (I already understood how the prolog works, I just want to know what is happening after I pushed the arguments on the stack and before the prolog).
",https://stackoverflow.com/questions/1395591/what-exactly-is-the-base-pointer-and-stack-pointer-to-what-do-they-point,291,286327.0,6.0,,,2009-09-08 18:37:01,2023-11-27 13:08:19,2023-11-27 13:08:19,,,c;assembly;x86;stack-frame;stack-pointer,devoured elysium,106194,130758,registered,true,1395646,,CC BY-SA 4.0,,2122,1578,8,1,1,5,true,false,false,true,true,true,74,14,true,0.021,0.001,6283,2009,9,18,Tuesday,false,false,false,false,false,false,false
1102542,How can I define an enumerated type (enum) in C?,"I'm not sure what the proper syntax for using C enums is. I have the following code:
enum {RANDOM, IMMEDIATE, SEARCH} strategy;
strategy = IMMEDIATE;
But this does not compile, with the following error:
error: conflicting types for ‘strategy’
error: previous declaration of ‘strategy’ was here
What am I doing wrong?
",https://stackoverflow.com/questions/1102542/how-can-i-define-an-enumerated-type-enum-in-c,289,554041.0,13.0,,,2009-07-09 08:29:02,2024-03-10 00:44:50,2024-03-09 23:51:35,,,c;enums,lindelof,35526,1428,registered,true,1102556,,CC BY-SA 4.0,2019-07-19 10:40:55,427,319,2,0,0,2,true,false,false,true,true,true,48,10,true,0.023,0.0005,6344,2009,7,8,Thursday,false,false,false,false,false,false,false
3599160,How can I suppress "unused parameter" warnings in C?,"For instance:
Bool NullFunc(const struct timespec *when, const char *who)
{
return TRUE;
}
In C++ I was able to put a /*...*/ comment around the parameters. But not in C, of course, where it gives me the error:
error: parameter name omitted
",https://stackoverflow.com/questions/3599160/how-can-i-suppress-unused-parameter-warnings-in-c,289,333591.0,16.0,,,2010-08-30 09:14:21,2026-11-09 11:03:54,2024-10-17 03:39:08,,,c;gcc;gcc-warning,day0ops,7652,429199,registered,true,3599170,,CC BY-SA 4.0,,366,247,2,0,0,3,true,false,false,true,true,true,62,9,true,0.048,0.0009,5927,2010,8,9,Monday,false,false,false,false,false,false,false
1195206,Is there a Java equivalent or methodology for the typedef keyword in C++?,"Coming from a C and C++ background, I found judicious use of typedef to be incredibly helpful. Do you know of a way to achieve similar functionality in Java, whether that be a Java mechanism, pattern, or some other effective way you have used?
",https://stackoverflow.com/questions/1195206/is-there-a-java-equivalent-or-methodology-for-the-typedef-keyword-in-c,289,150645.0,12.0,,,2009-07-28 16:23:22,2024-05-24 01:47:44,2012-11-09 02:40:54,,,java;c++;c;design-patterns;typedef,bn.,7979,89339,registered,true,1195221,,CC BY-SA 3.0,2012-02-27 17:30:32,282,245,1,0,0,5,true,false,false,true,true,true,73,13,true,0.08,0.0019,6325,2009,7,16,Tuesday,false,false,false,true,false,false,false
6805026,Is 'switch' faster than 'if'?,"Is a switch statement actually faster than an if statement?
I ran the code below on Visual Studio 2010's x64 C++ compiler with the /Ox flag:
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define MAX_COUNT (1 << 29)
size_t counter = 0;
size_t testSwitch()
{
clock_t start = clock();
size_t i;
for (i = 0; i < MAX_COUNT; i++)
{
switch (counter % 4 + 1)
{
case 1: counter += 4; break;
case 2: counter += 3; break;
case 3: counter += 2; break;
case 4: counter += 1; break;
}
}
return 1000 * (clock() - start) / CLOCKS_PER_SEC;
}
size_t testIf()
{
clock_t start = clock();
size_t i;
for (i = 0; i < MAX_COUNT; i++)
{
const size_t c = counter % 4 + 1;
if (c == 1) { counter += 4; }
else if (c == 2) { counter += 3; }
else if (c == 3) { counter += 2; }
else if (c == 4) { counter += 1; }
}
return 1000 * (clock() - start) / CLOCKS_PER_SEC;
}
int main()
{
printf("Starting...\n");
printf("Switch statement: %u ms\n", testSwitch());
printf("If statement: %u ms\n", testIf());
}
and got these results:
Switch statement: 5261 ms
If statement: 5196 ms
From what I've learned, switch statements apparently use jump tables to optimize the branching.
Questions:
What would a basic jump table look like, in x86 or x64?
Is this code using a jump table?
Why is there no performance difference in this example? Is there any situation in which there is a significant performance difference?
Disassembly of the code:
testIf:
13FE81B10 sub rsp,48h
13FE81B14 call qword ptr [__imp_clock (13FE81128h)]
13FE81B1A mov dword ptr [start],eax
13FE81B1E mov qword ptr [i],0
13FE81B27 jmp testIf+26h (13FE81B36h)
13FE81B29 mov rax,qword ptr [i]
13FE81B2E inc rax
13FE81B31 mov qword ptr [i],rax
13FE81B36 cmp qword ptr [i],20000000h
13FE81B3F jae testIf+0C3h (13FE81BD3h)
13FE81B45 xor edx,edx
13FE81B47 mov rax,qword ptr [counter (13FE835D0h)]
13FE81B4E mov ecx,4
13FE81B53 div rax,rcx
13FE81B56 mov rax,rdx
13FE81B59 inc rax
13FE81B5C mov qword ptr [c],rax
13FE81B61 cmp qword ptr [c],1
13FE81B67 jne testIf+6Dh (13FE81B7Dh)
13FE81B69 mov rax,qword ptr [counter (13FE835D0h)]
13FE81B70 add rax,4
13FE81B74 mov qword ptr [counter (13FE835D0h)],rax
13FE81B7B jmp testIf+0BEh (13FE81BCEh)
13FE81B7D cmp qword ptr [c],2
13FE81B83 jne testIf+89h (13FE81B99h)
13FE81B85 mov rax,qword ptr [counter (13FE835D0h)]
13FE81B8C add rax,3
13FE81B90 mov qword ptr [counter (13FE835D0h)],rax
13FE81B97 jmp testIf+0BEh (13FE81BCEh)
13FE81B99 cmp qword ptr [c],3
13FE81B9F jne testIf+0A5h (13FE81BB5h)
13FE81BA1 mov rax,qword ptr [counter (13FE835D0h)]
13FE81BA8 add rax,2
13FE81BAC mov qword ptr [counter (13FE835D0h)],rax
13FE81BB3 jmp testIf+0BEh (13FE81BCEh)
13FE81BB5 cmp qword ptr [c],4
13FE81BBB jne testIf+0BEh (13FE81BCEh)
13FE81BBD mov rax,qword ptr [counter (13FE835D0h)]
13FE81BC4 inc rax
13FE81BC7 mov qword ptr [counter (13FE835D0h)],rax
13FE81BCE jmp testIf+19h (13FE81B29h)
13FE81BD3 call qword ptr [__imp_clock (13FE81128h)]
13FE81BD9 sub eax,dword ptr [start]
13FE81BDD imul eax,eax,3E8h
13FE81BE3 cdq
13FE81BE4 mov ecx,3E8h
13FE81BE9 idiv eax,ecx
13FE81BEB cdqe
13FE81BED add rsp,48h
13FE81BF1 ret
testSwitch:
13FE81C00 sub rsp,48h
13FE81C04 call qword ptr [__imp_clock (13FE81128h)]
13FE81C0A mov dword ptr [start],eax
13FE81C0E mov qword ptr [i],0
13FE81C17 jmp testSwitch+26h (13FE81C26h)
13FE81C19 mov rax,qword ptr [i]
13FE81C1E inc rax
13FE81C21 mov qword ptr [i],rax
13FE81C26 cmp qword ptr [i],20000000h
13FE81C2F jae testSwitch+0C5h (13FE81CC5h)
13FE81C35 xor edx,edx
13FE81C37 mov rax,qword ptr [counter (13FE835D0h)]
13FE81C3E mov ecx,4
13FE81C43 div rax,rcx
13FE81C46 mov rax,rdx
13FE81C49 inc rax
13FE81C4C mov qword ptr [rsp+30h],rax
13FE81C51 cmp qword ptr [rsp+30h],1
13FE81C57 je testSwitch+73h (13FE81C73h)
13FE81C59 cmp qword ptr [rsp+30h],2
13FE81C5F je testSwitch+87h (13FE81C87h)
13FE81C61 cmp qword ptr [rsp+30h],3
13FE81C67 je testSwitch+9Bh (13FE81C9Bh)
13FE81C69 cmp qword ptr [rsp+30h],4
13FE81C6F je testSwitch+0AFh (13FE81CAFh)
13FE81C71 jmp testSwitch+0C0h (13FE81CC0h)
13FE81C73 mov rax,qword ptr [counter (13FE835D0h)]
13FE81C7A add rax,4
13FE81C7E mov qword ptr [counter (13FE835D0h)],rax
13FE81C85 jmp testSwitch+0C0h (13FE81CC0h)
13FE81C87 mov rax,qword ptr [counter (13FE835D0h)]
13FE81C8E add rax,3
13FE81C92 mov qword ptr [counter (13FE835D0h)],rax
13FE81C99 jmp testSwitch+0C0h (13FE81CC0h)
13FE81C9B mov rax,qword ptr [counter (13FE835D0h)]
13FE81CA2 add rax,2
13FE81CA6 mov qword ptr [counter (13FE835D0h)],rax
13FE81CAD jmp testSwitch+0C0h (13FE81CC0h)
13FE81CAF mov rax,qword ptr [counter (13FE835D0h)]
13FE81CB6 inc rax
13FE81CB9 mov qword ptr [counter (13FE835D0h)],rax
13FE81CC0 jmp testSwitch+19h (13FE81C19h)
13FE81CC5 call qword ptr [__imp_clock (13FE81128h)]
13FE81CCB sub eax,dword ptr [start]
13FE81CCF imul eax,eax,3E8h
13FE81CD5 cdq
13FE81CD6 mov ecx,3E8h
13FE81CDB idiv eax,ecx
13FE81CDD cdqe
13FE81CDF add rsp,48h
13FE81CE3 ret
Update:
Interesting results here. Not sure why one is faster and one is slower, though.
",https://stackoverflow.com/questions/6805026/is-switch-faster-than-if,287,77257.0,12.0,,,2011-07-24 05:00:19,2020-02-10 17:03:30,2020-06-20 09:12:55,,,c;performance;switch-statement;assembly;jump-table,user541686,213473,541686,registered,true,6805054,,CC BY-SA 4.0,2012-10-21 14:14:27,5822,5446,7,1,0,5,true,false,false,true,true,true,45,5,true,0.155,0.0037,5599,2011,7,5,Sunday,true,false,false,false,false,false,false
398395,"Why is the asterisk before the variable name, rather than after the type?","Why do most C programmers name variables like this:
int *myVariable;
rather than like this:
int* myVariable;
Both are valid. It seems to me that the asterisk is a part of the type, not a part of the variable name. Can anyone explain this logic?
",https://stackoverflow.com/questions/398395/why-is-the-asterisk-before-the-variable-name-rather-than-after-the-type,286,103421.0,13.0,,,2008-12-29 19:22:25,2024-11-22 23:15:52,2017-05-16 14:57:53,,,c;pointers;variables;naming-conventions,WBlasko,3143,26149,registered,true,398414,,CC BY-SA 3.0,,320,251,2,0,0,4,true,false,false,true,true,true,73,13,true,0.126,0.0028,6536,2008,12,19,Monday,false,false,false,false,false,false,false
10186765,What is the difference between char array and char pointer in C?,"I am trying to understand pointers in C but I am currently confused with the following:
char *p = ""hello""
This is a char pointer pointing at the character array, starting at h.
char p[] = ""hello""
This is an array that stores hello.
What is the difference when I pass both these variables into this function?
void printSomething(char *p)
{
printf(""p: %s"",p);
}
",https://stackoverflow.com/questions/10186765/what-is-the-difference-between-char-array-and-char-pointer-in-c,286,489687.0,10.0,,,2012-04-17 07:12:43,2024-11-12 13:31:12,2019-09-13 12:43:05,,,c;arrays;pointers,diesel,3435,700272,registered,true,10186799,,CC BY-SA 4.0,,519,374,3,0,0,3,true,false,false,true,true,true,64,12,true,0.02,0.0006,5331,2012,4,7,Tuesday,false,false,false,false,false,false,false
33495283,What does opening a file actually do?,"In all programming languages (that I use at least), you must open a file before you can read or write to it.
But what does this open operation actually do?
Manual pages for typical functions dont actually tell you anything other than it 'opens a file for reading/writing':
http://www.cplusplus.com/reference/cstdio/fopen/
https://docs.python.org/3/library/functions.html#open
Obviously, through usage of the function you can tell it involves creation of some kind of object which facilitates accessing a file.
Another way of putting this would be, if I were to implement an open function, what would it need to do on Linux?
",https://stackoverflow.com/questions/33495283/what-does-opening-a-file-actually-do,285,35025.0,8.0,,,2015-11-03 09:16:51,2018-08-30 03:00:28,2018-08-30 03:00:28,,,c;linux,jramm,6765,2768350,registered,true,,,CC BY-SA 4.0,2015-11-26 14:27:58,859,632,1,2,0,2,false,false,false,true,true,true,37,7,true,0.228,0.0081,4036,2015,11,9,Tuesday,false,false,false,false,false,false,false
7338858,"Once upon a time, when > was faster than < ... Wait, what?","I am reading an awesome OpenGL tutorial. It's really great, trust me. The topic I am currently at is Z-buffer. Aside from explaining what's it all about, the author mentions that we can perform custom depth tests, such as GL_LESS, GL_ALWAYS, etc. He also explains that the actual meaning of depth values (which is top and which isn't) can also be customized. I understand so far. And then the author says something unbelievable:
The range zNear can be greater than the range zFar; if it is, then the
window-space values will be reversed, in terms of what constitutes
closest or farthest from the viewer.
Earlier, it was said that the window-space Z value of 0 is closest and
1 is farthest. However, if our clip-space Z values were negated, the
depth of 1 would be closest to the view and the depth of 0 would be
farthest. Yet, if we flip the direction of the depth test (GL_LESS to
GL_GREATER, etc), we get the exact same result. So it's really just a
convention. Indeed, flipping the sign of Z and the depth test was once
a vital performance optimization for many games.
If I understand correctly, performance-wise, flipping the sign of Z and the depth test is nothing but changing a < comparison to a > comparison. So, if I understand correctly and the author isn't lying or making things up, then changing < to > used to be a vital optimization for many games.
Is the author making things up, am I misunderstanding something, or is it indeed the case that once < was slower (vitally, as the author says) than >?
Thanks for clarifying this quite curious matter!
Disclaimer: I am fully aware that algorithm complexity is the primary source for optimizations. Furthermore, I suspect that nowadays it definitely wouldn't make any difference and I am not asking this to optimize anything. I am just extremely, painfully, maybe prohibitively curious.
",https://stackoverflow.com/questions/7338858/once-upon-a-time-when-was-faster-than-wait-what,284,14784.0,3.0,,,2011-09-07 18:39:29,2021-09-22 15:00:36,2021-09-22 15:00:36,,,c;optimization;opengl;cpu;gpu,Armen Tsirunyan,134019,469935,registered,true,7340201,,CC BY-SA 4.0,,2221,1868,6,1,0,5,true,false,false,true,true,true,64,13,true,0.203,0.0192,5554,2011,9,18,Wednesday,false,false,false,false,false,false,false
9834067,Difference between char* and const char*?,"What's the difference between
char* name
which points to a constant string literal, and
const char* name
",https://stackoverflow.com/questions/9834067/difference-between-char-and-const-char,282,499083.0,9.0,,,2012-03-23 04:09:43,2024-07-23 19:17:53,2013-10-29 22:18:19,,,c;pointers;constants,Iceman,4382,1279782,registered,true,9834194,,CC BY-SA 3.0,,174,112,2,0,0,3,true,false,false,true,true,true,41,6,true,0.018,0.0006,5356,2012,3,4,Friday,false,false,false,false,false,false,false
9053658,Correct format specifier to print pointer or address?,"Which format specifier should I be using to print the address of a variable? I am confused between the below lot.
%u - unsigned integer
%x - hexadecimal value
%p - void pointer
Which would be the optimum format to print an address?
",https://stackoverflow.com/questions/9053658/correct-format-specifier-to-print-pointer-or-address,282,526767.0,6.0,,,2012-01-29 13:49:58,2023-04-30 13:27:36,2018-10-14 10:19:55,,,c;pointers;format;memory-address,San,4204,340236,registered,true,9053835,,CC BY-SA 4.0,,308,248,0,0,0,4,true,false,false,true,true,true,53,8,true,0.011,0.0005,5410,2012,1,13,Sunday,true,false,false,false,false,false,false
2589749,How to initialize array to 0 in C?,"I need a big null array in C as a global. Is there any way to do this besides typing out
char ZEROARRAY[1024] = {0, 0, 0, /* ... 1021 more times... */ };
?
",https://stackoverflow.com/questions/2589749/how-to-initialize-array-to-0-in-c,281,540745.0,2.0,,,2010-04-07 03:03:28,2021-11-02 08:31:31,2016-05-10 18:51:28,,,c;arrays;initialization,Claudiu,231311,15055,registered,true,2589751,,CC BY-SA 3.0,2013-07-05 06:46:10,197,159,1,0,0,3,true,false,false,true,true,true,34,8,true,0.004,0.0005,6072,2010,4,3,Wednesday,false,false,false,false,false,false,false
41183935,Why does GCC use multiplication by a strange number in implementing integer division?,"I've been reading about div and mul assembly operations, and I decided to see them in action by writing a simple program in C:
File division.c
#include <stdlib.h>
#include <stdio.h>
int main()
{
size_t i = 9;
size_t j = i / 5;
printf("%zu\n",j);
return 0;
}
And then generating assembly language code with:
gcc -S division.c -O0 -masm=intel
But looking at generated division.s file, it doesn't contain any div operations! Instead, it does some kind of black magic with bit shifting and magic numbers. Here's a code snippet that computes i/5:
mov rax, QWORD PTR [rbp-16] ; Move i (=9) to RAX
movabs rdx, -3689348814741910323 ; Move some magic number to RDX (?)
mul rdx ; Multiply 9 by magic number
mov rax, rdx ; Take only the upper 64 bits of the result
shr rax, 2 ; Shift these bits 2 places to the right (?)
mov QWORD PTR [rbp-8], rax ; Magically, RAX contains 9/5=1 now,
; so we can assign it to j
What's going on here? Why doesn't GCC use div at all? How does it generate this magic number and why does everything work?
",https://stackoverflow.com/questions/41183935/why-does-gcc-use-multiplication-by-a-strange-number-in-implementing-integer-divi,281,44712.0,5.0,,,2016-12-16 11:59:45,2022-03-08 04:10:06,2020-06-20 09:12:55,,,c;gcc;assembly;x86-64;integer-division,qiubit,4886,3552561,registered,true,,,CC BY-SA 4.0,2016-12-22 19:55:00,1346,1185,7,0,0,5,false,false,false,true,true,true,85,13,true,0.112,0.0063,3627,2016,12,11,Friday,false,false,false,false,false,false,false
3683602,Single quotes vs. double quotes in C or C++,"When should I use single quotes and double quotes in C or C++ programming?
",https://stackoverflow.com/questions/3683602/single-quotes-vs-double-quotes-in-c-or-c,279,234779.0,15.0,,,2010-09-10 09:43:39,2023-01-23 18:35:24,2016-08-15 14:45:41,,,c++;c;syntax;char;string-literals,Vishwanath Dalvi,37054,435559,registered,true,3683613,,CC BY-SA 3.0,,82,75,0,0,0,5,true,false,false,true,true,true,43,9,false,0.064,0.0012,5916,2010,9,9,Friday,false,false,false,false,false,false,false
24430504,How to avoid "if" chains?,"Assuming I have this pseudo-code:
bool conditionA = executeStepA();
if (conditionA){
bool conditionB = executeStepB();
if (conditionB){
bool conditionC = executeStepC();
if (conditionC){
...
}
}
}
executeThisFunctionInAnyCase();
Functions executeStepX should be executed if and only if the previous succeed.
In any case, the executeThisFunctionInAnyCase function should be called at the end.
I'm a newbie in programming, so sorry for the very basic question: is there a way (in C/C++ for example) to avoid that long if chain producing that sort of ""pyramid of code"", at the expense of the code legibility?
I know that if we could skip the executeThisFunctionInAnyCase function call, the code could be simplified as:
bool conditionA = executeStepA();
if (!conditionA) return;
bool conditionB = executeStepB();
if (!conditionB) return;
bool conditionC = executeStepC();
if (!conditionC) return;
But the constraint is the executeThisFunctionInAnyCase function call.
Could the break statement be used in some way?
",https://stackoverflow.com/questions/24430504/how-to-avoid-if-chains,277,51429.0,51.0,,,2014-06-26 12:25:25,2022-08-05 16:56:54,2014-06-27 23:15:37,,,c++;c;if-statement;control-flow,ABCplus,4041,3253359,registered,true,,,CC BY-SA 3.0,2014-06-30 16:49:11,1220,1066,8,0,0,4,false,false,false,true,true,true,35,5,true,0.992,0.0054,4531,2014,6,12,Thursday,false,false,false,false,false,false,false
1343890,How do I round a number to 2 decimal places in C?,"How can I round a floating-point value (such as 37.777779) to two decimal places (37.78) in C?
",https://stackoverflow.com/questions/1343890/how-do-i-round-a-number-to-2-decimal-places-in-c,277,1113725.0,18.0,,,2009-08-27 21:41:57,2025-04-11 18:42:55,2025-04-11 18:42:55,,,c;floating-point;decimal,Tyler,,,does_not_exist,true,,,CC BY-SA 4.0,2019-07-19 12:25:16,102,95,0,0,0,3,false,false,false,true,false,true,49,12,true,0.016,0.0002,6295,2009,8,21,Thursday,false,false,false,false,false,false,false
693788,Is it better to use C void arguments "void foo(void)" or not "void foo()"?,"What is better: void foo() or void foo(void)?
With void, it looks ugly and inconsistent, but I've been told that it is good. Is this true?
I know some old compilers do weird things, but if I'm using just GCC, is void foo() Ok? Will foo(bar); then be accepted?
",https://stackoverflow.com/questions/693788/is-it-better-to-use-c-void-arguments-void-foovoid-or-not-void-foo,277,183936.0,6.0,,,2009-03-28 23:44:29,2025-10-17 15:20:08,2025-10-17 15:20:08,2017-09-04 05:45:20,Duplicate,c;void,Zifre,27145,83871,registered,true,693794,,,,339,260,5,0,0,2,true,true,false,true,true,true,94,14,true,0.033,0.0015,6447,2009,3,23,Saturday,true,false,false,false,false,false,false
1464174,size_t vs. uintptr_t,"The C standard guarantees that size_t is a type that can hold any array index. This means that, logically, size_t should be able to hold any pointer type. I've read on some sites that I found on the Googles that this is legal and/or should always work:
void *v = malloc(10);
size_t s = (size_t) v;
So then in C99, the standard introduced the intptr_t and uintptr_t types, which are signed and unsigned types guaranteed to be able to hold pointers:
uintptr_t p = (size_t) v;
So what is the difference between using size_t and uintptr_t? Both are unsigned, and both should be able to hold any pointer type, so they seem functionally identical. Is there any real compelling reason to use uintptr_t (or better yet, a void *) rather than a size_t, other than clarity? In an opaque structure, where the field will be handled only by internal functions, is there any reason not to do this?
By the same token, ptrdiff_t has been a signed type capable of holding pointer differences, and therefore capable of holding most any pointer, so how is it distinct from intptr_t?
Aren't all of these types basically serving trivially different versions of the same function? If not, why? What can't I do with one of them that I can't do with another? If so, why did C99 add two essentially superfluous types to the language?
I'm willing to disregard function pointers, as they don't apply to the current problem, but feel free to mention them, as I have a sneaking suspicion they will be central to the ""correct"" answer.
",https://stackoverflow.com/questions/1464174/size-t-vs-uintptr-t,277,71962.0,8.0,,,2009-09-23 05:59:41,2023-05-31 20:54:38,2017-03-22 22:11:45,,,c;pointers;size-t,Chris Lutz,76143,60777,registered,true,1464194,,CC BY-SA 3.0,2019-07-19 10:46:31,1747,1514,13,0,0,3,true,false,false,true,true,true,20,3,false,0.111,0.0038,6268,2009,9,5,Wednesday,false,false,false,false,false,false,false
1637332,'static const' vs. '#define',"Is it better to use static const variables than #define preprocessor? Or does it maybe depend on the context?
What are advantages/disadvantages for each method?
",https://stackoverflow.com/questions/1637332/static-const-vs-define,275,211359.0,11.0,,,2009-10-28 13:44:28,2023-08-31 13:18:21,2023-08-31 13:18:21,,,c++;c;constants,Patrice Bernassola,14536,178488,registered,true,1637367,,CC BY-SA 4.0,,201,161,2,0,0,3,true,false,false,true,true,true,44,4,false,0.052,0.0013,6233,2009,10,13,Wednesday,false,false,false,false,false,false,false
1641957,Is an array name a pointer?,"Is an array's name a pointer in C?
If not, what is the difference between an array's name and a pointer variable?
",https://stackoverflow.com/questions/1641957/is-an-array-name-a-pointer,274,109805.0,10.0,,,2009-10-29 06:38:05,2025-04-14 23:31:52,2017-05-22 08:30:33,,,c;arrays;pointers,user188276,,,does_not_exist,true,1641963,,CC BY-SA 3.0,2015-11-24 07:59:03,121,114,0,0,0,3,true,false,false,true,false,true,27,6,true,0.091,0.0025,6232,2009,10,6,Thursday,false,false,false,false,false,false,false
2876357,Determine the line of code that causes a segmentation fault?,"How does one determine where the mistake is in the code that causes a segmentation fault?
Can my compiler (gcc) show the location of the fault in the program?
",https://stackoverflow.com/questions/2876357/determine-the-line-of-code-that-causes-a-segmentation-fault,272,450199.0,9.0,,,2010-05-20 17:39:29,2026-04-05 15:19:18,2020-01-26 22:43:16,,,c++;c;debugging;segmentation-fault,user319824,,,does_not_exist,true,2876374,,CC BY-SA 4.0,,274,160,1,1,0,4,true,false,false,true,false,true,60,10,true,0.02,0.0006,6029,2010,5,17,Thursday,false,false,false,false,false,false,false
4523497,typedef fixed length array,"I have to define a 24-bit data type.I am using char[3] to represent the type. Can I typedef char[3] to type24? I tried it in a code sample. I put typedef char[3] type24; in my header file. The compiler did not complain about it. But when I defined a function void foo(type24 val) {} in my C file, it did complain. I would like to be able to define functions like type24_to_int32(type24 val) instead of type24_to_int32(char value[3]).
",https://stackoverflow.com/questions/4523497/typedef-fixed-length-array,272,315310.0,8.0,,,2010-12-24 00:35:01,2024-06-05 18:16:18,2014-06-03 18:28:51,,,c;arrays;gcc;typedef,341008,10330,341008,registered,true,4523537,,CC BY-SA 3.0,,532,434,7,0,0,4,true,false,false,true,true,true,26,4,false,0.025,0.0009,5811,2010,12,0,Friday,false,false,false,false,false,false,false
6988487,What does the brk() system call do?,"According to Linux programmers manual:
brk() and sbrk() change the location of the program break, which
defines the end of the process's data segment.
What does the data segment mean over here? Is it just the data segment or data, BSS, and heap combined?
According to wiki Data segment:
Sometimes the data, BSS, and heap areas are collectively referred to as the "data segment".
I see no reason for changing the size of just the data segment. If it is data, BSS and heap collectively then it makes sense as heap will get more space.
Which brings me to my second question. In all the articles I read so far, author says that heap grows upward and stack grows downward. But what they do not explain is what happens when heap occupies all the space between heap and stack?
![]()
",https://stackoverflow.com/questions/6988487/what-does-the-brk-system-call-do,272,144127.0,8.0,,,2011-08-08 20:57:32,2023-10-05 07:33:45,2021-10-04 08:38:46,,,c;linux;unix;memory-management;brk,nik,8885,246095,registered,true,6990428,,CC BY-SA 4.0,,1144,785,0,2,1,5,true,false,false,true,true,true,35,7,true,0.056,0.0019,5584,2011,8,20,Monday,false,false,false,false,false,false,false
6729366,What is the difference between AF_INET and PF_INET in socket programming?,"What is the difference between AF_INET and PF_INET in socket programming?
I'm confused between using AF_INET and PF_INET in socket() and bind().
Also, how to give ip-address in sin_addr field?
",https://stackoverflow.com/questions/6729366/what-is-the-difference-between-af-inet-and-pf-inet-in-socket-programming,270,225742.0,8.0,,,2011-07-18 06:37:37,2026-04-29 17:27:43,2013-06-04 16:46:25,,,c;linux;sockets,SP Sandhu,2848,580939,registered,true,6737450,,CC BY-SA 3.0,,255,195,3,0,0,3,true,false,false,true,true,true,73,11,true,0.035,0.0012,5605,2011,7,6,Monday,false,false,false,false,false,false,false
1790750,"What is the Difference Between read() and recv() , and Between send() and write()?","What is the difference between read() and recv(), and between send() and write() in socket programming in terms of performances, speed and other behaviors?
",https://stackoverflow.com/questions/1790750/what-is-the-difference-between-read-and-recv-and-between-send-and-write,270,155481.0,9.0,,,2009-11-24 15:20:52,2022-04-22 13:39:33,2019-09-03 15:54:22,,,c;sockets;unix;network-programming;posix,Sajad Bahmani,17509,140934,registered,true,1790778,,CC BY-SA 4.0,,215,156,4,0,0,5,true,false,false,true,true,true,82,14,true,0.058,0.0017,6206,2009,11,15,Tuesday,false,false,false,false,false,false,false
746171,Efficient Algorithm for Bit Reversal (from MSB->LSB to LSB->MSB) in C,"What is the most efficient algorithm to achieve the following:
0010 0000 => 0000 0100
The conversion is from MSB->LSB to LSB->MSB. All bits must be reversed; that is, this is not endianness-swapping.
",https://stackoverflow.com/questions/746171/efficient-algorithm-for-bit-reversal-from-msb-lsb-to-lsb-msb-in-c,269,277182.0,28.0,,,2009-04-14 02:48:46,2023-09-09 04:17:06,2020-01-29 03:53:04,,,c;algorithm;bit-manipulation,green_t,3037,17329,registered,true,746203,,CC BY-SA 4.0,2018-07-13 13:03:13,249,206,1,0,0,3,true,false,false,true,true,true,75,11,false,0.101,0.001,6430,2009,4,2,Tuesday,false,false,false,false,false,false,false
141720,How do you compare structs for equality in C?,"How do you compare two instances of structs for equality in standard C?
",https://stackoverflow.com/questions/141720/how-do-you-compare-structs-for-equality-in-c,268,294311.0,14.0,,,2008-09-26 20:21:23,2024-10-06 18:30:26,,,,c;struct;equality,Hans Sjunnesson,22515,8683,registered,true,141724,,CC BY-SA 2.5,,79,72,0,0,0,3,true,false,false,true,true,false,45,9,true,0.048,0.0009,6630,2008,9,20,Friday,false,false,false,false,false,false,false
8004237,How do I properly compare strings in C?,"I am trying to get a program to let a user enter a word or character, store it, and then print it until the user types it again, exiting the program. My code looks like this:
#include <stdio.h>
int main()
{
char input[40];
char check[40];
int i = 0;
printf("Hello!\nPlease enter a word or character:\n");
gets(input); /* obsolete function: do not use!! */
printf("I will now repeat this until you type it back to me.\n");
while (check != input)
{
printf("%s\n", input);
gets(check); /* obsolete function: do not use!! */
}
printf("Good bye!");
return 0;
}
The problem is that I keep getting the printing of the input string, even when the input by the user (check) matches the original (input). Am I comparing the two incorrectly?
",https://stackoverflow.com/questions/8004237/how-do-i-properly-compare-strings-in-c,267,744211.0,11.0,,,2011-11-04 02:22:27,2023-08-10 20:52:50,2023-08-10 11:06:11,,,c;string;strcmp,nmagerko,6884,996249,registered,true,8004250,,CC BY-SA 4.0,2016-06-02 19:03:37,914,850,3,0,0,3,true,false,false,true,true,true,39,8,true,0.015,0.0004,5496,2011,11,2,Friday,false,false,false,false,false,false,false
1644868,#define macro for debug printing in C?,"Trying to create a macro which can be used for print debug messages when DEBUG is defined, like the following pseudo code:
#define DEBUG 1
#define debug_print(args ...) if (DEBUG) fprintf(stderr, args)
How is this accomplished with a macro?
",https://stackoverflow.com/questions/1644868/define-macro-for-debug-printing-in-c,265,281858.0,15.0,,,2009-10-29 16:17:32,2025-10-01 19:28:00,2019-02-25 05:17:57,,,c;c-preprocessor,jfarrell,4620,179279,registered,true,1644898,,CC BY-SA 4.0,,282,244,1,0,0,2,true,false,false,true,true,true,38,7,true,0.053,0.0009,6232,2009,10,16,Thursday,false,false,false,false,false,false,false
4160347,close vs shutdown socket?,"In C, I understood that if we close a socket, it means the socket will be destroyed and can be re-used later.
How about shutdown? The description said it closes half of a duplex connection to that socket. But will that socket be destroyed like close system call?
",https://stackoverflow.com/questions/4160347/close-vs-shutdown-socket,265,342138.0,9.0,,,2010-11-11 23:38:21,2020-09-12 08:09:47,2013-12-12 22:28:24,,,c;sockets;network-programming,user188276,,,does_not_exist,true,4160356,,CC BY-SA 3.0,,292,265,1,0,0,3,true,false,false,true,false,true,25,4,true,0.026,0.0008,5854,2010,11,23,Thursday,false,false,false,false,false,false,false
2229498,Passing by reference in C,"If C does not support passing a variable by reference, why does this work?
#include <stdio.h>
void f(int *j) {
(*j)++;
}
int main() {
int i = 20;
int *p = &i;
f(p);
printf(""i = %d\n"", i);
return 0;
}
Output:
$ gcc -std=c99 test.c
$ a.exe
i = 21
",https://stackoverflow.com/questions/2229498/passing-by-reference-in-c,263,550626.0,19.0,,,2010-02-09 13:52:33,2023-04-03 15:08:32,2019-09-05 21:57:32,,,c;pointers;pass-by-reference,aks,4825,311097,registered,true,2229521,,CC BY-SA 4.0,2019-07-19 12:24:30,340,276,2,0,0,3,true,false,false,true,true,true,25,5,false,0.035,0.0005,6129,2010,2,13,Tuesday,false,false,false,false,false,false,false
11761703,Overloading Macro on Number of Arguments,"I have two macros FOO2 and FOO3:
#define FOO2(x,y) ...
#define FOO3(x,y,z) ...
I want to define a new macro FOO as follows:
#define FOO(x,y) FOO2(x,y)
#define FOO(x,y,z) FOO3(x,y,z)
But this doesn't work because macros do not overload on number of arguments.
Without modifying FOO2 and FOO3, is there some way to define a macro FOO (using __VA_ARGS__ or otherwise) to get the same effect of dispatching FOO(x,y) to FOO2, and FOO(x,y,z) to FOO3?
",https://stackoverflow.com/questions/11761703/overloading-macro-on-number-of-arguments,263,114621.0,11.0,,,2012-08-01 14:42:42,2025-05-19 00:47:20,2014-11-02 18:56:50,,,c;macros;c-preprocessor,Andrew Tomazos,69658,1131467,registered,true,11763277,,CC BY-SA 3.0,2013-08-08 11:16:34,671,452,13,0,0,3,true,false,false,true,true,true,40,6,false,0.096,0.0023,5225,2012,8,14,Wednesday,false,false,false,false,false,false,false
88957,What does {0} mean when initializing an object?,"When {0} is used to initialize an object, what does it mean? I can't find any references to {0} anywhere, and because of the curly braces Google searches are not helpful.
Example code:
SHELLEXECUTEINFO sexi = {0}; // what does this do?
sexi.cbSize = sizeof(SHELLEXECUTEINFO);
sexi.hwnd = NULL;
sexi.fMask = SEE_MASK_NOCLOSEPROCESS;
sexi.lpFile = lpFile.c_str();
sexi.lpParameters = args;
sexi.nShow = nShow;
if(ShellExecuteEx(&sexi))
{
DWORD wait = WaitForSingleObject(sexi.hProcess, INFINITE);
if(wait == WAIT_OBJECT_0)
GetExitCodeProcess(sexi.hProcess, &returnCode);
}
Without it, the above code will crash on runtime.
",https://stackoverflow.com/questions/88957/what-does-0-mean-when-initializing-an-object,262,69258.0,10.0,,,2008-09-18 00:38:36,2020-06-22 13:45:06,2017-07-08 17:54:43,,,c++;c,Mahmoud Al-Qudsi,30014,17027,registered,true,88960,,CC BY-SA 3.0,,721,650,3,0,0,2,true,false,false,true,true,true,47,8,true,0.144,0.0038,6638,2008,9,0,Thursday,false,false,false,false,false,false,false
284325,How to make child process die after parent exits?,"Suppose I have a process which spawns exactly one child process. Now when the parent process exits for whatever reason (normally or abnormally, by kill, ^C, assert failure or anything else) I want the child process to die. How to do that correctly?
Some similar question on stackoverflow:
- (asked earlier) How can I cause a child process to exit when the parent does?
- (asked later) Are child processes created with fork() automatically killed when the parent is killed?
Some similar question on stackoverflow for Windows:
- How do I automatically destroy child processes in Windows?
- Kill child process when parent process is killed
",https://stackoverflow.com/questions/284325/how-to-make-child-process-die-after-parent-exits,260,233817.0,24.0,,,2008-11-12 15:37:51,2022-09-04 04:35:35,2017-05-23 12:03:02,,,c;linux;unix;process;fork,Paweł Hajdan,18662,9403,registered,true,284443,,CC BY-SA 3.0,,1221,645,0,4,0,5,true,false,false,true,true,true,49,9,true,0.103,0.0011,6583,2008,11,15,Wednesday,false,false,false,false,false,false,false
12784766,Check substring exists in a string in C,"I'm trying to check whether a string contains a substring in C like:
char *sent = ""this is my sample example"";
char *word = ""sample"";
if (/* sentence contains word */) {
/* .. */
}
What is something to use instead of string::find in C++?
",https://stackoverflow.com/questions/12784766/check-substring-exists-in-a-string-in-c,260,732103.0,12.0,,,2012-10-08 15:28:00,2024-04-23 14:41:06,2017-06-02 17:46:06,,,c;string,none,12257,1385119,registered,true,12784812,,CC BY-SA 3.0,2016-03-29 05:50:50,296,245,2,0,0,2,true,false,false,true,true,true,39,8,false,0.016,0.0004,5157,2012,10,15,Monday,false,false,false,false,false,false,false
399003,Is the sizeof(some pointer) always equal to four?,"For example:
sizeof(char*) returns 4. As does int*, long long*, everything that I've tried. Are there any exceptions to this?
",https://stackoverflow.com/questions/399003/is-the-sizeofsome-pointer-always-equal-to-four,259,162255.0,17.0,,,2008-12-29 23:03:23,2023-04-02 05:01:00,2014-03-08 09:07:54,,,c++;c;pointers;memory;sizeof,Joel,15666,25632,registered,true,399030,,CC BY-SA 3.0,,174,128,3,0,0,5,true,false,false,true,true,true,49,8,true,0.105,0.0016,6536,2008,12,23,Monday,false,false,false,false,false,false,false
34182672,Why is 0 < -0x80000000?,"I have below a simple program:
#include <stdio.h>
#define INT32_MIN (-0x80000000)
int main(void)
{
long long bal = 0;
if(bal < INT32_MIN )
{
printf(""Failed!!!"");
}
else
{
printf(""Success!!!"");
}
return 0;
}
The condition if(bal < INT32_MIN ) is always true. How is it possible?
It works fine if I change the macro to:
#define INT32_MIN (-2147483648L)
Can anyone point out the issue?
",https://stackoverflow.com/questions/34182672/why-is-0-0x80000000,258,19543.0,6.0,,,2015-12-09 15:31:05,2023-09-01 07:18:51,2023-09-01 07:18:51,,,c;constants;signed;numeric-limits;numeric-conversion,Jayesh Bhoi,26201,3150853,registered,true,34183176,,CC BY-SA 4.0,2015-12-20 05:52:34,557,468,3,0,0,5,true,false,false,true,true,true,26,5,true,0.307,0.0132,4000,2015,12,15,Wednesday,false,false,false,false,false,false,false
6893285,Why do function pointer definitions work with any number of ampersands '&' or asterisks '*'?,"Why do the following work?
void foo() {
cout << ""Foo to you too!\n"";
};
int main() {
void (*p1_foo)() = foo;
void (*p2_foo)() = *foo;
void (*p3_foo)() = &foo;
void (*p4_foo)() = *&foo;
void (*p5_foo)() = &*foo;
void (*p6_foo)() = **foo;
void (*p7_foo)() = **********************foo;
(*p1_foo)();
(*p2_foo)();
(*p3_foo)();
(*p4_foo)();
(*p5_foo)();
(*p6_foo)();
(*p7_foo)();
}
",https://stackoverflow.com/questions/6893285/why-do-function-pointer-definitions-work-with-any-number-of-ampersands-or-as,257,21388.0,5.0,,,2011-08-01 00:37:26,2022-05-06 02:44:24,2016-04-13 12:50:31,,,c++;c;function-pointers,Jimmy,4527,862620,registered,true,6893288,,CC BY-SA 3.0,,489,458,1,0,0,3,true,false,false,true,true,true,112,15,true,0.234,0.012,5591,2011,8,0,Monday,false,false,false,false,false,false,false
3523145,Pointer arithmetic for void pointer in C,"When a pointer to a particular type (say int, char, float, ..) is incremented, its value is increased by the size of that data type. If a void pointer which points to data of size x is incremented, how does it get to point x bytes ahead? How does the compiler know to add x to value of the pointer?
",https://stackoverflow.com/questions/3523145/pointer-arithmetic-for-void-pointer-in-c,255,194104.0,10.0,,,2010-08-19 15:05:28,2023-02-21 15:26:22,2021-04-26 18:21:39,,,c;void-pointers;pointer-arithmetic,Siva Sankaran,2577,424873,registered,true,,,CC BY-SA 4.0,,397,299,7,0,0,3,false,false,false,true,true,true,40,7,false,0.052,0.0013,5938,2010,8,15,Thursday,false,false,false,false,false,false,false
745870,Realistic usage of the C99 'restrict' keyword?,"I was browsing through some documentation and questions/answers and saw it mentioned. I read a brief description, stating that it would be basically a promise from the programmer that the pointer won't be used to point somewhere else.
Can anyone offer some realistic cases where its worth actually using this?
",https://stackoverflow.com/questions/745870/realistic-usage-of-the-c99-restrict-keyword,254,92542.0,3.0,,,2009-04-14 00:09:53,2024-07-15 12:42:08,2012-08-02 18:05:13,,,c;gcc;c99;restrict-qualifier,user90052,2754,90052,registered,true,745877,,CC BY-SA 3.0,,326,312,0,0,0,4,true,false,false,true,true,true,54,7,true,0.032,0.0027,6430,2009,4,0,Tuesday,false,false,false,false,false,false,false
150543,Forward an invocation of a variadic function in C,"In C, is it possible to forward the invocation of a variadic function? As in,
int my_printf(char *fmt, ...) {
fprintf(stderr, ""Calling printf with fmt %s"", fmt);
return SOMEHOW_INVOKE_LIBC_PRINTF;
}
Forwarding the invocation in the manner above obviously isn't strictly necessary in this case (since you could log invocations in other ways, or use vfprintf), but the codebase I'm working on requires the wrapper to do some actual work, and doesn't have (and can't have added) a helper function akin to vfprintf.
[Update: there seems to be some confusion based on the answers that have been supplied so far. To phrase the question another way: in general, can you wrap some arbitrary variadic function without modifying that function's definition.]
",https://stackoverflow.com/questions/150543/forward-an-invocation-of-a-variadic-function-in-c,254,103433.0,14.0,,,2008-09-29 20:41:15,2026-03-04 09:47:56,2016-03-15 14:34:58,,,c;variadic,Patrick,2643,23600,registered,true,150616,,CC BY-SA 3.0,,812,760,1,0,0,2,true,false,false,true,true,true,49,9,false,0.135,0.0025,6627,2008,9,20,Monday,false,false,false,false,false,false,false
2611764,Can I use a binary literal in C or C++?,"I need to work with a binary number.
I tried writing:
const char x = 00010000;
But it didn't work.
I know that I can use a hexadecimal number that has the same value as 00010000, but I want to know if there is a type in C++ for binary numbers, and if there isn't, is there another solution for my problem?
",https://stackoverflow.com/questions/2611764/can-i-use-a-binary-literal-in-c-or-c,253,522936.0,25.0,,,2010-04-10 00:35:10,2025-08-14 20:43:10,2022-09-19 13:27:14,,,c++;c;binary,hamza,2834,1815939,registered,true,2611883,,CC BY-SA 4.0,,372,307,2,0,0,3,true,false,false,true,true,true,39,10,true,0.048,0.0005,6069,2010,4,0,Saturday,true,false,false,false,false,false,false
4706199,Post-increment and pre-increment within a 'for' loop produce same output,"The following for loops produce identical results even though one uses post increment and the other pre-increment.
Here is the code:
for(i=0; i<5; i++) {
printf(""%d"", i);
}
for(i=0; i<5; ++i) {
printf(""%d"", i);
}
I get the same output for both 'for' loops. Am I missing something?
",https://stackoverflow.com/questions/4706199/post-increment-and-pre-increment-within-a-for-loop-produce-same-output,252,292134.0,12.0,,,2011-01-16 15:33:13,2026-03-23 17:01:50,2019-08-14 18:30:40,2014-12-21 01:00:00,Duplicate,c++;c;for-loop;operator-precedence,theReverseFlick,6112,441077,registered,true,4706225,,,,346,301,1,0,0,4,true,true,false,true,true,true,80,10,false,0.041,0.0009,5788,2011,1,15,Sunday,true,false,false,false,false,false,false
7109964,Creating your own header file in C,"Can anyone explain how to create a header file in C with a simple example from beginning to end.
",https://stackoverflow.com/questions/7109964/creating-your-own-header-file-in-c,252,515861.0,5.0,,,2011-08-18 15:25:21,2025-02-19 06:37:49,2019-03-13 09:00:13,,,c;header;include;include-guards;c-header,Anuragdeb3,2539,900900,registered,true,,,CC BY-SA 4.0,2016-11-25 21:47:06,104,97,0,0,0,5,false,false,false,true,true,true,34,7,false,0.01,0.0005,5574,2011,8,15,Thursday,false,false,false,false,false,false,false
502856,What's the difference between size_t and int in C++?,"In several C++ examples I see a use of the type size_t where I would have used a simple int. What's the difference, and why size_t should be better?
",https://stackoverflow.com/questions/502856/whats-the-difference-between-size-t-and-int-in-c,252,236920.0,5.0,,,2009-02-02 11:03:54,2024-08-20 19:29:25,2024-01-09 00:00:51,2024-01-09 00:02:03,Duplicate,c++;c;types;integer;size-t,tunnuz,24262,25418,registered,true,502862,,,,195,149,3,0,0,5,true,true,false,true,true,true,56,9,true,0.021,0.0011,6501,2009,2,11,Monday,false,false,false,false,false,false,false
1653340,Differences between fork and exec,"What are the differences between fork and exec?
",https://stackoverflow.com/questions/1653340/differences-between-fork-and-exec,250,166146.0,9.0,,,2009-10-31 03:47:33,2024-11-04 03:58:37,2017-10-03 06:19:56,,,c;unix;fork;exec,Sashi,3207,200031,registered,true,1653415,,CC BY-SA 3.0,,81,48,2,0,0,4,true,false,false,true,true,true,33,5,false,0.054,0.0015,6230,2009,10,3,Saturday,true,false,false,false,false,false,false
679979,How to make a variadic macro (variable number of arguments),"I want to write a macro in C that accepts any number of parameters, not a specific number
example:
#define macro( X ) something_complicated( whatever( X ) )
where X is any number of parameters
I need this because whatever is overloaded and can be called with 2 or 4 parameters.
I tried defining the macro twice, but the second definition overwrote the first one!
The compiler I'm working with is g++ (more specifically, mingw)
",https://stackoverflow.com/questions/679979/how-to-make-a-variadic-macro-variable-number-of-arguments,250,291174.0,6.0,,,2009-03-25 02:08:15,2023-06-27 12:28:19,2015-03-31 02:10:19,,,c;g++;c-preprocessor;variadic,hasen,167722,35364,registered,true,679993,,CC BY-SA 3.0,,527,435,3,0,0,4,true,false,false,true,true,true,59,10,false,0.021,0.0009,6450,2009,3,2,Wednesday,false,false,false,false,false,false,false
3025050,Error "initializer element is not constant" when trying to initialize variable with const,"I get an error on line 6 (initialize my_foo to foo_init) of the following program and I'm not sure I understand why.
typedef struct foo_t {
int a, b, c;
} foo_t;
const foo_t foo_init = { 1, 2, 3 };
foo_t my_foo = foo_init;
int main()
{
return 0;
}
Keep in mind this is a simplified version of a larger, multi-file project I'm working on. The goal was to have a single constant in the object file, that multiple files could use to initialize a state structure. Since it's an embedded target with limited resources and the struct isn't that small, I don't want multiple copies of the source. I'd prefer not to use:
#define foo_init { 1, 2, 3 }
I'm also trying to write portable code, so I need a solution that's valid C89 or C99.
Does this have to do with the ORGs in an object file? That initialized variables go into one ORG and are initialized by copying the contents of a second ORG?
Maybe I'll just need to change my tactic, and have an initializing function do all of the copies at startup. Unless there are other ideas out there?
",https://stackoverflow.com/questions/3025050/error-initializer-element-is-not-constant-when-trying-to-initialize-variable-w,248,443797.0,8.0,,,2010-06-11 17:55:27,2023-01-15 14:41:45,2015-08-03 14:14:49,,,c;initialization,tomlogic,11754,266392,registered,true,3025106,,CC BY-SA 3.0,2021-09-19 10:03:28,1141,1058,2,0,0,2,true,false,false,true,true,true,99,13,false,0.018,0.0006,6007,2010,6,17,Friday,false,false,false,false,false,false,false
15646973,How dangerous is it to access an array out of bounds?,"How dangerous is accessing an array outside of its bounds (in C)? It can sometimes happen that I read from outside the array (I now understand I then access memory used by some other parts of my program or even beyond that) or I am trying to set a value to an index outside of the array. The program sometimes crashes, but sometimes just runs, only giving unexpected results.
Now what I would like to know is, how dangerous is this really? If it damages my program, it is not so bad. If on the other hand it breaks something outside my program, because I somehow managed to access some totally unrelated memory, then it is very bad, I imagine.
I read a lot of 'anything can happen', 'segmentation might be the least bad problem', 'your hard disk might turn pink and unicorns might be singing under your window', which is all nice, but what is really the danger?
My questions:
- Can reading values from way outside the array damage anything
apart from my program? I would imagine just looking at things does
not change anything, or would it for instance change the 'last time
opened' attribute of a file I happened to reach?
- Can setting values way out outside of the array damage anything apart from my
program? From this
Stack Overflow question I gather that it is possible to access
any memory location, that there is no safety guarantee.
- I now run my small programs from within XCode. Does that
provide some extra protection around my program where it cannot
reach outside its own memory? Can it harm XCode?
- Any recommendations on how to run my inherently buggy code safely?
I use OSX 10.7, Xcode 4.6.
",https://stackoverflow.com/questions/15646973/how-dangerous-is-it-to-access-an-array-out-of-bounds,247,63191.0,12.0,,,2013-03-26 20:41:30,2022-12-23 00:52:36,2018-06-03 19:50:34,,,c;arrays;memory,ChrisD,2477,2213209,registered,true,,,CC BY-SA 4.0,2018-06-15 10:11:59,1887,1617,0,2,0,3,false,false,false,true,true,true,53,11,true,0.19,0.0039,4988,2013,3,20,Tuesday,false,false,false,false,false,false,false
2998864,How to add a 'or' condition in #ifdef,"How can I add a 'or' condition in #ifdef ?
I have tried:
#ifdef CONDITION1 || CONDITION2
#endif
This does not work.
",https://stackoverflow.com/questions/2998864/how-to-add-a-or-condition-in-ifdef,246,214789.0,4.0,,,2010-06-08 15:38:34,2022-08-30 07:41:10,2021-10-26 15:49:27,,,c++;c;c-preprocessor,michael,111692,286802,registered,true,2998876,,CC BY-SA 4.0,,202,121,1,0,0,3,true,false,false,true,true,true,45,8,false,0.019,0.0011,6010,2010,6,15,Tuesday,false,false,false,false,false,false,false
1023306,Finding current executable's path without /proc/self/exe,"It seems to me that Linux has it easy with /proc/self/exe. But I'd like to know if there is a convenient way to find the current application's directory in C/C++ with cross-platform interfaces. I've seen some projects mucking around with argv[0], but it doesn't seem entirely reliable.
If you ever had to support, say, Mac OS X, which doesn't have /proc/, what would you have done? Use #ifdefs to isolate the platform-specific code (NSBundle, for example)? Or try to deduce the executable's path from argv[0], $PATH and whatnot, risking finding bugs in edge cases?
",https://stackoverflow.com/questions/1023306/finding-current-executables-path-without-proc-self-exe,245,154752.0,16.0,,,2009-06-21 06:12:48,2026-09-19 21:13:35,2011-03-02 23:32:21,,,c++;c;linux;macos;executable,Uros Dimitrijevic,2661,41896,registered,true,,,CC BY-SA 2.5,,581,567,0,0,0,5,false,false,false,true,true,true,60,6,false,0.103,0.0016,6362,2009,6,6,Sunday,true,false,false,false,false,false,false
1067226,C multi-line macro: do/while(0) vs scope block,"
Possible Duplicates:
What’s the use of do while(0) when we define a macro?
Why are there sometimes meaningless do/while and if/else statements in C/C++ macros?
do { … } while (0) what is it good for?
I've seen some multi-line C macros that are wrapped inside a do/while(0) loop like:
#define FOO \
do { \
do_stuff_here \
do_more_stuff \
} while (0)
What are the benefits (if any) of writing the code that way as opposed to using a basic block:
#define FOO \
{ \
do_stuff_here \
do_more_stuff \
}
",https://stackoverflow.com/questions/1067226/c-multi-line-macro-do-while0-vs-scope-block,245,158831.0,1.0,,,2009-07-01 04:06:35,2020-12-03 23:15:34,2017-05-23 12:18:24,2009-07-01 07:10:15,exact duplicate,c;macros;multiline,krasnaya,3195,87240,registered,true,1067238,,,,984,555,0,3,0,3,true,true,false,true,true,true,46,7,false,0.006,0.0015,6352,2009,7,4,Wednesday,false,false,false,false,false,false,false
421860,Capture characters from standard input without waiting for enter to be pressed,"I can never remember how I do this because it comes up so infrequently for me. But in C or C++, what is the best way to read a character from standard input without waiting for a newline (press enter).
Also ideally it wouldn't echo the input character to the screen. I just want to capture keystrokes with out effecting the console screen.
",https://stackoverflow.com/questions/421860/capture-characters-from-standard-input-without-waiting-for-enter-to-be-pressed,244,315355.0,24.0,,,2009-01-07 20:04:16,2025-11-25 11:58:14,2014-09-20 07:44:41,,,c++;c;inputstream,Wavesonics,26635,1366,registered,true,421871,,CC BY-SA 3.0,,355,341,0,0,0,3,true,false,false,true,true,true,78,12,false,0.076,0.0008,6527,2009,1,20,Wednesday,false,false,false,false,false,false,false
31016660,Why does this for loop exit on some platforms and not on others?,"I have recently started to learn C and I am taking a class with C as the subject. I'm currently playing around with loops and I'm running into some odd behaviour which I don't know how to explain.
#include <stdio.h>
int main()
{
int array[10],i;
for (i = 0; i <=10 ; i++)
{
array[i]=0; /*code should never terminate*/
printf(""test \n"");
}
printf(""%d \n"", sizeof(array)/sizeof(int));
return 0;
}
On my laptop running Ubuntu 14.04, this code does not break. It runs to completion. On my school's computer running CentOS 6.6, it also runs fine. On Windows 8.1, the loop never terminates.
What's even more strange is that when I edit the condition of the for loop to: i <= 11, the code only terminates on my laptop running Ubuntu. It never terminates in CentOS and Windows.
Can anyone explain what's happening in the memory and why the different OSes running the same code give different outcomes?
EDIT: I know the for loop goes out of bounds. I'm doing it intentionally. I just can't figure out how the behaviour can be different across different OSes and computers.
",https://stackoverflow.com/questions/31016660/why-does-this-for-loop-exit-on-some-platforms-and-not-on-others,243,23871.0,14.0,,,2015-06-24 02:34:05,2015-10-11 10:27:57,2015-10-11 09:57:49,,,c;debugging;undefined-behavior;buffer-overflow,JonCav,1667,5005388,registered,true,31016813,,CC BY-SA 3.0,2019-07-19 10:47:02,1195,1110,3,0,0,4,true,false,false,true,true,true,64,13,true,0.586,0.0102,4168,2015,6,2,Wednesday,false,false,false,false,false,false,false
1893490,What is the difference between conversion specifiers %i and %d in formatted IO functions (*printf / *scanf),"What is the difference between %d and %i when used as format specifiers in printf and scanf?
",https://stackoverflow.com/questions/1893490/what-is-the-difference-between-conversion-specifiers-i-and-d-in-formatted-io-f,242,157495.0,4.0,,,2009-12-12 13:49:34,2021-01-13 17:59:04,2020-10-14 14:54:58,,,c++;c;printf;scanf;format-specifiers,Ayoub M.,4858,153383,registered,true,1893518,,CC BY-SA 4.0,2012-06-20 11:58:30,152,93,4,0,0,5,true,false,false,true,true,true,107,17,false,0.025,0.0015,6188,2009,12,13,Saturday,true,false,false,false,false,false,false
39002052,How can I print to standard error in C with 'printf'?,"In C, printing to standard output (stdout) is easy, with printf from stdio.h.
However, how can I print to standard error (stderr)? We can use fprintf to achieve it apparently, but its syntax seems strange. Maybe we can use printf to print to standard error?
",https://stackoverflow.com/questions/39002052/how-can-i-print-to-standard-error-in-c-with-printf,241,514234.0,9.0,,,2016-08-17 16:40:20,2025-04-11 20:57:14,2023-06-22 15:04:00,,,c;printf;stderr,wad,2975,6706176,registered,true,39002243,,CC BY-SA 4.0,,533,258,4,2,0,3,true,false,false,true,true,true,61,11,true,0.018,0.0005,3748,2016,8,16,Wednesday,false,false,false,false,false,false,false
11656532,Returning an array using C,"I am relatively new to C and I need some help with methods dealing with arrays. Coming from Java programming, I am used to being able to say int [] method() in order to return an array. However, I have found out that with C you have to use pointers for arrays when you return them. Being a new programmer, I really do not understand this at all, even with the many forums I have looked through.
Basically, I am trying to write a method that returns a char array in C. I will provide the method (let’s call it returnArray) with an array. It will create a new array from the previous array and return a pointer to it. I just need some help on how to get this started and how to read the pointer once it is sent out of the array.
Proposed Code Format for Array Returning Function
char *returnArray(char array []){
char returned [10];
// Methods to pull values from the array, interpret
// them, and then create a new array
return &(returned[0]); // Is this correct?
}
Caller of the Function
int main(){
int i = 0;
char array [] = {1, 0, 0, 0, 0, 1, 1};
char arrayCount = 0;
char* returnedArray = returnArray(&arrayCount); // Is this correct?
for (i=0; i<10; i++)
printf(%d, ",", returnedArray[i]); // Is this correctly formatted?
}
I have not tested this yet as my C compiler is not working at the moment, but I would like to figure this out.
",https://stackoverflow.com/questions/11656532/returning-an-array-using-c,241,664478.0,9.0,,,2012-07-25 18:47:05,2026-02-14 16:16:56,2022-11-03 19:35:04,,,c;arrays;pointers;char,user1506919,2657,1506919,registered,true,11656585,,CC BY-SA 4.0,2016-05-02 15:15:38,1515,1385,3,0,0,4,true,false,false,true,true,true,26,5,false,0.014,0.0004,5232,2012,7,18,Wednesday,false,false,false,false,false,false,false
418914,"Why is C so fast, and why aren't other languages as fast or faster?","In listening to the Stack Overflow podcast, the jab keeps coming up that "real programmers" write in C, and that C is so much faster because it's "close to the machine." Leaving out the former assertion, what is special about C that allows it to be faster than other languages?
Or put another way: What stops other languages from being able to compile down to binary that runs every bit as fast as C?
",https://stackoverflow.com/questions/418914/why-is-c-so-fast-and-why-arent-other-languages-as-fast-or-faster,240,164179.0,33.0,,,2009-01-07 01:59:06,2025-02-22 00:46:46,2025-02-22 00:46:46,2020-03-09 21:53:48,Opinion-based,c;performance,Mike C.,4997,3799,registered,true,418956,,,2018-03-31 07:58:46,435,421,0,0,0,2,true,true,false,true,true,true,71,14,true,0.201,0.0015,6527,2009,1,1,Wednesday,false,false,false,false,false,false,false
298510,How to get the current directory in a C program?,"I'm making a C program where I need to get the directory that the program is started from. This program is written for UNIX computers. I've been looking at opendir() and telldir(), but telldir() returns a off_t (long int), so it really doesn't help me.
How can I get the current path in a string (char array)?
",https://stackoverflow.com/questions/298510/how-to-get-the-current-directory-in-a-c-program,240,463238.0,7.0,,,2008-11-18 11:36:29,2024-06-26 15:47:21,2013-11-28 13:28:47,,,c;unix;working-directory,Stian,,,does_not_exist,true,298518,,CC BY-SA 3.0,,379,313,4,0,0,3,true,false,false,true,false,true,48,10,true,0.015,0.0005,6577,2008,11,11,Tuesday,false,false,false,false,false,false,false
9653072,Return a `struct` from a function in C,"Today I was teaching a couple of friends how to use C structs. One of them asked if you could return a struct from a function, to which I replied: "No! You'd return pointers to dynamically malloced structs instead."
Coming from someone who primarily does C++, I was expecting not be able to return structs by values. In C++ you can overload the operator = for your objects and makes complete sense to have a function to return your object by value. In C, however, you do not have that option and so it got me thinking what the compiler is actually doing. Consider the following:
struct MyObj{
double x, y;
};
struct MyObj foo(){
struct MyObj a;
a.x = 10;
a.y = 10;
return a;
}
int main () {
struct MyObj a;
a = foo(); // This DOES work
struct b = a; // This does not work
return 0;
}
I understand why struct b = a; should not work -- you cannot overload operator = for your data type. How is it that a = foo(); compiles fine? Does it mean something other than struct b = a;? Maybe the question to ask is: What exactly does the return statement in conjunction to = sign do?
",https://stackoverflow.com/questions/9653072/return-a-struct-from-a-function-in-c,240,517137.0,11.0,,,2012-03-11 06:59:31,2023-06-12 15:33:28,2020-12-31 13:49:15,,,c,mmirzadeh,7209,928594,registered,true,9653083,,CC BY-SA 4.0,,1361,1160,13,0,0,1,true,false,false,true,true,true,38,8,false,0.021,0.0005,5368,2012,3,6,Sunday,true,false,false,false,false,false,false
273209,Are memory leaks ever OK?,"Is it ever acceptable to have a memory leak in your C or C++ application?
What if you allocate some memory and use it until the very last line of code in your application (for example, a global object's destructor)? As long as the memory consumption doesn't grow over time, is it OK to trust the OS to free your memory for you when your application terminates (on Windows, Mac, and Linux)? Would this even consider this a real memory leak if the memory was being used continuously until it was freed by the OS?
What if a third party library forced this situation on users? Should one refuse to use that third party library no matter how great it otherwise might be?
I only see one practical disadvantage, and that is that these benign leaks will show up with memory leak detection tools as false positives.
",https://stackoverflow.com/questions/273209/are-memory-leaks-ever-ok,238,40454.0,49.0,,,2008-11-07 19:01:52,2023-03-30 17:24:12,2023-03-30 17:24:12,2018-11-27 00:19:07,Opinion-based,c++;c;memory-leaks,Imbue,3895,3175,registered,true,273287,,,,916,807,0,1,0,3,true,true,false,true,true,true,25,5,true,1.211,0.0059,6588,2008,11,19,Friday,false,false,false,false,false,false,false
277258,How do I see a C/C++ source file after preprocessing in Visual Studio?,"Let's say I have a source file with many preprocessor directives. Is it possible to see how it looks after the preprocessor is done with it?
",https://stackoverflow.com/questions/277258/how-do-i-see-a-c-c-source-file-after-preprocessing-in-visual-studio,238,113939.0,10.0,,,2008-11-10 07:11:08,2017-02-16 14:33:56,2016-02-04 20:21:45,,,c++;c;debugging;visual-studio-2005;c-preprocessor,Geo,97857,31610,registered,true,277362,,CC BY-SA 3.0,,148,141,0,0,0,5,true,false,false,true,true,true,70,13,true,0.088,0.0021,6585,2008,11,7,Monday,false,false,false,false,false,false,false
2528318,How come an array's address is equal to its value in C?,"In the following bit of code, pointer values and pointer addresses differ as expected.
But array values and addresses don't!
How can this be?
Output
my_array = 0022FF00
&my_array = 0022FF00
pointer_to_array = 0022FF00
&pointer_to_array = 0022FEFC
#include <stdio.h>
int main()
{
char my_array[100] = ""some cool string"";
printf(""my_array = %p\n"", my_array);
printf(""&my_array = %p\n"", &my_array);
char *pointer_to_array = my_array;
printf(""pointer_to_array = %p\n"", pointer_to_array);
printf(""&pointer_to_array = %p\n"", &pointer_to_array);
printf(""Press ENTER to continue...\n"");
getchar();
return 0;
}
",https://stackoverflow.com/questions/2528318/how-come-an-arrays-address-is-equal-to-its-value-in-c,238,115362.0,6.0,,,2010-03-27 05:59:56,2019-08-01 21:06:00,2013-01-07 14:25:17,,,c;pointers;arrays,Alexandre,5185,67550,registered,true,2528328,,CC BY-SA 3.0,,738,662,2,0,0,3,true,false,false,true,true,true,59,12,true,0.052,0.0021,6083,2010,3,5,Saturday,true,false,false,false,false,false,false
14884126,Build .so file from .c file using gcc command line,"I'm trying to create a hello world project for Linux dynamic libraries (.so files). So I have a file hello.c:
#include <stdio.h>
void hello()
{
printf(""Hello world!\n"");
}
How do I create a .so file that exports hello(), using gcc from the command line?
",https://stackoverflow.com/questions/14884126/build-so-file-from-c-file-using-gcc-command-line,237,272471.0,1.0,,,2013-02-14 21:11:53,2020-09-27 19:56:22,2018-07-03 11:05:10,,,c;linux;gcc;shared-libraries,sashoalm,81158,492336,registered,true,14884166,,CC BY-SA 4.0,2020-12-24 17:19:15,318,267,2,0,0,4,true,false,false,true,true,true,50,10,false,0.004,0.0009,5028,2013,2,21,Thursday,false,false,false,false,false,false,false
461449,return statement vs exit() in main(),"Is there a difference between using exit() or just return statements in main()?
Personally I favor the return statements because I feel it's like reading any other function and the flow control when I'm reading the code is smooth (in my opinion). And even if I want to refactor the main() function, having return seems like a better choice than exit().
Does exit() do anything special that return doesn't?
",https://stackoverflow.com/questions/461449/return-statement-vs-exit-in-main,237,95902.0,8.0,,,2009-01-20 14:15:10,2023-10-19 16:55:07,2023-10-19 16:55:07,,,c++;c;return;exit,Srikanth,12240,7205,registered,true,461528,,CC BY-SA 4.0,,544,406,9,0,0,4,true,false,false,true,true,true,36,6,false,0.083,0.0025,6514,2009,1,14,Tuesday,false,false,false,false,false,false,false
1855459,maximum value of int,"Is there any code to find the maximum value of integer (accordingly to the compiler) in C/C++ like Integer.MaxValue function in java?
",https://stackoverflow.com/questions/1855459/maximum-value-of-int,236,392843.0,7.0,,,2009-12-06 13:59:15,2019-04-25 06:11:28,2015-11-26 15:13:40,,,c++;c;stl;limits;numeric-limits,d3vdpro,3087,81773,registered,true,1855465,,CC BY-SA 3.0,,154,134,1,0,0,5,true,false,false,true,true,true,20,4,false,0.018,0.0006,6194,2009,12,13,Sunday,true,false,false,false,false,false,false
2553522,Interview question: Check if one string is a rotation of other string,"A friend of mine was asked the following question today at interview for the position of software developer:
Given two string s1 and s2 how will you check if s1 is a rotated version of s2 ?
Example:
If s1 = ""stackoverflow"" then the following are some of its rotated versions:
""tackoverflows""
""ackoverflowst""
""overflowstack""
where as ""stackoverflwo"" is not a rotated version.
The answer he gave was:
Take s2 and find the longest prefix that is a sub string of s1, that will give you the point of rotation. Once you find that point, break s2 at that point to get s2a and s2b, then just check if concatenate(s2a,s2b) == s1
It looks like a good solution to me and my friend. But the interviewer thought otherwise. He asked for a simpler solution. Please help me by telling how would you do this in Java/C/C++ ?
Thanks in advance.
",https://stackoverflow.com/questions/2553522/interview-question-check-if-one-string-is-a-rotation-of-other-string,235,128171.0,26.0,,,2010-03-31 13:58:25,2015-06-07 19:45:39,2011-11-22 08:11:36,2011-04-26 14:24:32,not constructive,java;c++;c,Webdev,2317,248865,registered,true,2553533,,,,1195,841,14,0,0,3,true,true,false,true,true,true,69,12,false,0.203,0.0018,6079,2010,3,13,Wednesday,false,false,false,true,false,false,false
9191388,It is more efficient to use if-return-return or if-else-return?,"Suppose I have an if statement with a return. From the efficiency perspective, should I use
if(A > B):
return A+1
return A-1
or
if(A > B):
return A+1
else:
return A-1
Should I prefer one or another when using a compiled language (C) or a scripted one (Python)?
",https://stackoverflow.com/questions/9191388/it-is-more-efficient-to-use-if-return-return-or-if-else-return,234,478554.0,9.0,,,2012-02-08 10:20:53,2024-12-15 11:32:50,2024-12-15 11:32:50,,,python;c;performance,Jorge Leitao,20360,931303,registered,true,9191474,,CC BY-SA 4.0,2020-02-13 23:58:44,380,285,4,0,0,3,true,false,false,true,true,true,63,9,true,0.019,0.0005,5400,2012,2,10,Wednesday,false,true,false,false,false,false,false
6481668,Protecting executable from reverse engineering?,"I've been contemplating how to protect my C/C++ code from disassembly and reverse engineering. Normally I would never condone this behavior myself in my code; however the current protocol I've been working on must not ever be inspected or understandable, for the security of various people.
Now this is a new subject to me, and the internet is not really resourceful for prevention against reverse engineering but rather depicts tons of information on how to reverse engineer
Some of the things I've thought of so far are:
- Code injection (calling dummy functions before and after actual function calls)
- Code obfustication (mangles the disassembly of the binary)
Write my own startup routines (harder for debuggers to bind to)
void startup();
int _start()
{
startup( );
exit (0)
}
void startup()
{
/* code here */
}
Runtime check for debuggers (and force exit if detected)
Function trampolines
void trampoline(void (*fnptr)(), bool ping = false)
{
if(ping)
fnptr();
else
trampoline(fnptr, true);
}
Pointless allocations and deallocations (stack changes a lot)
- Pointless dummy calls and trampolines (tons of jumping in disassembly output)
- Tons of casting (for obfuscated disassembly)
I mean these are some of the things I've thought of but they can all be worked around and or figured out by code analysts given the right time frame. Is there anything else alternative I have?
",https://stackoverflow.com/questions/6481668/protecting-executable-from-reverse-engineering,233,93233.0,25.0,,,2011-06-26 01:49:24,2022-09-05 06:12:13,2012-05-01 04:04:31,,,c++;c;obfuscation;assembly,graphitemaster,3793,658162,registered,true,6481695,,CC BY-SA 3.0,2016-10-03 18:12:45,1675,1458,2,0,0,4,true,false,false,true,true,true,47,5,true,0.268,0.0025,5627,2011,6,1,Sunday,true,false,false,false,false,false,false
11438794,Is the size of C "int" 2 bytes or 4 bytes?,"Does an Integer variable in C occupy 2 bytes or 4 bytes? What are the factors that it depends on?
Most of the textbooks say integer variables occupy 2 bytes.
But when I run a program printing the successive addresses of an array of integers it shows the difference of 4.
",https://stackoverflow.com/questions/11438794/is-the-size-of-c-int-2-bytes-or-4-bytes,233,788306.0,13.0,,,2012-07-11 18:11:57,2019-02-25 20:44:15,2014-02-13 16:09:10,,,c;int;byte,Rajiv Prathap,2349,1119482,registered,true,,,CC BY-SA 3.0,2018-11-09 08:03:46,286,272,0,0,0,3,false,false,false,true,true,true,52,11,true,0.016,0.0003,5246,2012,7,18,Wednesday,false,false,false,false,false,false,false
344317,Where does gcc look for C and C++ header files?,"On a Unix system, where does gcc look for header files?
I spent a little time this morning looking for some system header files, so I thought this would be good information to have here.
",https://stackoverflow.com/questions/344317/where-does-gcc-look-for-c-and-c-header-files,233,186795.0,11.0,,,2008-12-05 16:02:35,2025-08-19 23:17:38,2022-11-12 23:09:28,,,c++;c;gcc;header,Bill the Lizard,408082,1288,registered,true,344525,,CC BY-SA 4.0,2018-04-17 12:25:37,202,188,0,0,0,4,true,false,false,true,true,true,47,10,true,0.059,0.0012,6560,2008,12,16,Friday,false,false,false,false,false,false,false
471248,What is time_t ultimately a typedef to?,"I searched my Linux box and saw this typedef:
typedef __time_t time_t;
But I could not find the __time_t definition.
",https://stackoverflow.com/questions/471248/what-is-time-t-ultimately-a-typedef-to,233,380822.0,11.0,,,2009-01-22 23:12:55,2021-10-09 07:18:17,2019-04-06 19:49:02,,,c;linux;types,kal,29741,43756,registered,true,471287,,CC BY-SA 4.0,2018-09-15 17:34:10,172,121,2,0,0,3,true,false,false,true,true,true,39,7,true,0.029,0.0006,6512,2009,1,23,Thursday,false,false,false,false,false,false,false
93039,Where are static variables stored in C and C++?,"In what segment (.BSS, .DATA, other) of an executable file are static variables stored so that they don't have name collision?
For example:
foo.c: bar.c:
static int foo = 1; static int foo = 10;
void fooTest() { void barTest() {
static int bar = 2; static int bar = 20;
foo++; foo++;
bar++; bar++;
printf(""%d,%d"", foo, bar); printf(""%d, %d"", foo, bar);
} }
If I compile both files and link it to a main that calls fooTest() and barTest repeatedly, the printf statements increment independently. Makes sense since the foo and bar variables are local to the translation unit.
But where is the storage allocated?
To be clear, the assumption is that you have a toolchain that would output a file in ELF format. Thus, I believe that there has to be some space reserved in the executable file for those static variables.
For discussion purposes, lets assume we use the GCC toolchain.
",https://stackoverflow.com/questions/93039/where-are-static-variables-stored-in-c-and-c,232,252304.0,17.0,,,2008-09-18 14:29:05,2023-12-27 14:37:55,2018-09-08 22:30:20,,,c++;c;compiler-construction,Benoit,39630,10703,registered,true,93411,,CC BY-SA 4.0,2018-09-08 23:07:40,1117,1035,1,0,0,3,true,false,false,true,true,true,47,9,true,0.067,0.0009,6638,2008,9,14,Thursday,false,false,false,false,false,false,false
38296756,What is the idiomatic way in CMAKE to add the -fPIC compiler option?,"I've come across at least 3 ways to do this and I'm wondering which is the idiomatic way. This needs to be done almost universally to any static library. I'm surprised that the Makefile generator in CMake doesn't automatically add this to static libraries. (unless I'm missing something?)
target_compile_options(myLib PRIVATE -fPIC)
add_compile_options(-fPIC)
set(CMAKE_C_FLAGS ""${CMAKE_C_FLAGS} -fpic"")
set(CMAKE_CXX_FLAGS ""${CMAKE_CXX_FLAGS} -fpic"")
I believe there might also be other variations. (please edit my question if you find one)
If you happen to know the answer to this question, do you also know if there is a way to cause a 3rd party CMake project to be compiled with this flag without modifying its CMakeLists.txt file? I have run across static libraries missing that flag. It causes problems when compiling a static library into a dynamic library.
You get:
relocation R_X86_64_32 against `.rodata' can not be used when making a shared object; recompile with -fPIC
",https://stackoverflow.com/questions/38296756/what-is-the-idiomatic-way-in-cmake-to-add-the-fpic-compiler-option,232,150307.0,2.0,,,2016-07-10 21:50:25,2022-09-18 21:41:20,,,,c++;c;cmake,101010,16026,451007,registered,true,38297422,,CC BY-SA 3.0,,1072,996,2,0,0,3,true,false,false,true,true,false,68,13,true,0.013,0.0015,3786,2016,7,21,Sunday,true,false,false,false,false,false,false
1722112,What are the most common naming conventions in C?,"What are the naming conventions commonly use in C? I know there are at least two:
- GNU / linux / K&R with lower_case_functions
- ? name ? with UpperCaseFoo functions
I am talking about C only here. Most of our projects are small embedded systems in which we use C.
Here is the one I am planning on using for my next project:
C Naming Convention
Struct TitleCase
Struct Members lower_case or lowerCase
Enum ETitleCase
Enum Members ALL_CAPS or lowerCase
Public functions pfx_TitleCase (pfx = two or three letter module prefix)
Private functions TitleCase
Trivial variables i,x,n,f etc...
Local variables lower_case or lowerCase
Global variables g_lowerCase or g_lower_case (searchable by g_ prefix)
",https://stackoverflow.com/questions/1722112/what-are-the-most-common-naming-conventions-in-c,231,345148.0,13.0,,,2009-11-12 13:16:49,2024-04-22 12:33:33,2019-03-17 15:47:19,2024-10-14 19:22:55,Needs more focus,c;naming-conventions,JeffV,54929,445087,registered,true,,,,,886,764,1,0,0,2,false,true,false,true,true,true,49,9,true,0.038,0.0007,6218,2009,11,13,Thursday,false,false,false,false,false,false,false
1694164,Is errno thread-safe?,"In errno.h, this variable is declared as extern int errno; so my question is, is it safe to check errno value after some calls or use perror() in multi-threaded code. Is this a thread safe variable? If not, then whats the alternative ?
I am using linux with gcc on x86 architecture.
",https://stackoverflow.com/questions/1694164/is-errno-thread-safe,231,65645.0,8.0,,,2009-11-07 19:39:54,2019-02-11 20:14:45,2014-03-07 10:28:52,,,c;linux;multithreading;gcc,Vinit Dhatrak,7124,196629,registered,true,1694170,,CC BY-SA 3.0,,339,286,3,0,0,4,true,false,false,true,true,true,21,3,true,0.122,0.0035,6223,2009,11,19,Saturday,true,false,false,false,false,false,false
856636,Effects of the extern keyword on C functions,"In C, I did not notice any effect of the extern keyword used before function declaration.
At first, I thought that when defining extern int f(); in a single file forces you to implement it outside of the file's scope. However I found out that both:
extern int f();
int f() {return 0;}
and
extern int f() {return 0;}
compile just fine, with no warnings from gcc. I used gcc -Wall -ansi; it wouldn't even accept // comments.
Are there any effects for using extern before function definitions? Or is it just an optional keyword with no side effects for functions.
In the latter case I don't understand why did the standard designers chose to litter the grammar with superfluous keywords.
EDIT: To clarify, I know there's usage for extern in variables, but I'm only asking about extern in functions.
",https://stackoverflow.com/questions/856636/effects-of-the-extern-keyword-on-c-functions,230,267398.0,10.0,,,2009-05-13 07:51:53,2024-01-22 21:38:29,2015-07-14 08:09:04,,,c;syntax;standards,Elazar Leibovich,33993,55094,registered,true,856736,,CC BY-SA 3.0,,1055,806,9,0,0,3,true,false,false,true,true,true,44,8,false,0.037,0.0009,6401,2009,5,7,Wednesday,false,false,false,false,false,false,false
8487986,__FILE__ macro shows full path,"The standard predefined macro __FILE__ available in C shows the full path to the file. Is there any way to shorten the path and get just the filename? I mean instead of
/full/path/to/file.c
I see
to/file.c
or
file.c
",https://stackoverflow.com/questions/8487986/file-macro-shows-full-path,229,256372.0,32.0,,,2011-12-13 10:57:27,2026-03-06 07:26:19,2023-07-10 20:25:15,,,c;file;path;macros;preprocessor,mahmood,25423,859227,registered,true,8488201,,CC BY-SA 4.0,2022-06-09 07:56:44,325,219,4,0,0,5,true,false,false,true,true,true,30,5,false,0.125,0.0009,5457,2011,12,10,Tuesday,false,false,false,false,false,false,false
341817,Is there a replacement for unistd.h for Windows (Visual C)?,"I'm porting a relatively simple console program written for Unix to the Windows platform (Visual C++ 8.0). All the source files include "unistd.h", which doesn't exist. Removing it, I get complaints about missing prototypes for 'srandom', 'random', and 'getopt'.
I know I can replace the random functions, and I'm pretty sure I can find/hack-up a getopt implementation.
But I'm sure others have run into the same challenge.
My question is: is there a port of "unistd.h" to Windows? At least one containing those functions which do have a native Windows implementation - I don't need pipes or forking.
EDIT:
I know I can create my very own "unistd.h" which contains replacements for the things I need - especially in this case, since it is a limited set. But since it seems like a common problem, I was wondering if someone had done the work already for a bigger subset of the functionality.
Switching to a different compiler or environment isn't possible at work - I'm stuck with Visual Studio.
",https://stackoverflow.com/questions/341817/is-there-a-replacement-for-unistd-h-for-windows-visual-c,229,456689.0,10.0,,,2008-12-04 19:51:08,2024-03-12 05:50:18,2024-03-12 05:50:18,,,c++;c;windows;portability;unistd.h,AShelly,35925,10396,registered,true,826027,,CC BY-SA 4.0,,1165,1026,0,1,0,5,true,false,false,true,true,true,59,10,true,0.022,0.0005,6561,2008,12,19,Thursday,false,false,false,false,false,false,false
13683563,What's the difference between “mod” and “remainder”?,"My friend said that there are differences between ""mod"" and ""remainder"".
If so, what are those differences in C and C++? Does '%' mean either ""mod"" or ""rem"" in C?
",https://stackoverflow.com/questions/13683563/whats-the-difference-between-mod-and-remainder,229,196941.0,7.0,,,2012-12-03 12:45:42,2025-04-10 16:13:18,2017-07-01 11:54:29,,,c;math;operators,songhir,3633,1498303,registered,true,,,CC BY-SA 3.0,,178,164,0,0,0,3,false,false,false,true,true,true,56,7,true,0.036,0.0012,5101,2012,12,12,Monday,false,false,false,false,false,false,false
4989451,Mutex example / tutorial?,"I was trying to understand how mutexes work. Did a lot of Googling but it still left some doubts of how it works because I created my own program in which locking didn't work.
One absolutely non-intuitive syntax of the mutex is pthread_mutex_lock( &mutex1 );, where it looks like the mutex is being locked, when what I really want to lock is some other variable. Does this syntax mean that locking a mutex locks a region of code until the mutex is unlocked? Then how do threads know that the region is locked? [UPDATE: Threads know that the region is locked, by Memory Fencing ]. And isn't such a phenomenon supposed to be called critical section? [UPDATE: Critical section objects are available in Windows only, where the objects are faster than mutexes and are visible only to the thread which implements it. Otherwise, critical section just refers to the area of code protected by a mutex]
What's the simplest possible mutex example program and the simplest possible explanation on the logic of how it works?
",https://stackoverflow.com/questions/4989451/mutex-example-tutorial,228,374977.0,7.0,,,2011-02-14 06:33:46,2026-03-10 00:53:57,2022-12-29 01:22:59,2020-03-05 20:57:48,Not suitable for this site,c++;c;multithreading;synchronization;mutex,Nav,20872,453673,registered,true,5154174,,,,1191,1016,1,1,0,5,true,true,false,true,true,true,25,4,true,0.019,0.0006,5759,2011,2,6,Monday,false,false,false,false,false,false,false
52550,"What does the comma operator , do?","What does the , operator do in C?
",https://stackoverflow.com/questions/52550/what-does-the-comma-operator-do,227,65936.0,9.0,,,2008-09-09 18:34:09,2024-02-14 11:05:14,2017-05-22 07:00:53,,,c;operators;comma-operator,lillq,15503,2064,registered,true,52558,,CC BY-SA 3.0,2016-01-03 10:29:26,54,34,1,0,0,3,true,false,false,true,true,true,34,7,true,0.136,0.0034,6647,2008,9,18,Tuesday,false,false,false,false,false,false,false
4650243,Convert Python program to C/C++ code?,"is it possible to convert a Python program to C/C++?
I need to implement a couple of algorithms, and I'm not sure if the performance gap is big enough to justify all the pain I'd go through when doing it in C/C++ (which I'm not good at). I thought about writing one simple algorithm and benchmark it against such a converted solution. If that alone is significantly faster than the Python version, then I'll have no other choice than doing it in C/C++.
",https://stackoverflow.com/questions/4650243/convert-python-program-to-c-c-code,227,581841.0,8.0,,,2011-01-10 18:46:12,2022-10-26 15:14:22,2015-08-05 17:45:13,2022-10-27 14:07:26,Needs more focus,c++;python;c;code-generation,CrazyFlyingCloseline,2289,570252,unregistered,true,4650280,,,2022-09-03 13:50:40,468,454,0,0,0,4,true,true,false,true,true,true,37,6,true,0.014,0.0004,5794,2011,1,18,Monday,false,true,false,false,false,false,false
15151377,What exactly is a C pointer if not a memory address?,"In a reputable source about C, the following information is given after discussing the & operator:
... It's a bit unfortunate that the terminology [address of] remains, because it confuses those who don't know what addresses are about, and misleads those who do: thinking about pointers as if they were addresses usually leads to grief...
Other materials I have read (from equally reputable sources, I would say) have always unabashedly referred to pointers and the & operator as giving memory addresses. I would love to keep searching for the actuality of the matter, but it is kind of difficult when reputable sources KIND OF disagree.
Now I am slightly confused--what exactly is a pointer, then, if not a memory address?
P.S.
The author later says: ...I will continue to use the term 'address of' though, because to invent a different one [term] would be even worse.
",https://stackoverflow.com/questions/15151377/what-exactly-is-a-c-pointer-if-not-a-memory-address,227,43906.0,24.0,,,2013-03-01 05:48:39,2020-10-18 09:28:58,2013-07-14 20:09:26,,,c;pointers;memory-address,d0rmLife,4330,1760339,registered,true,,,CC BY-SA 3.0,2019-07-19 12:18:23,1051,888,2,0,0,3,false,false,false,true,true,true,52,11,true,0.547,0.0052,5013,2013,3,5,Friday,false,false,false,false,false,false,false
14588767,Where in memory are my variables stored in C?,"By considering that the memory is divided into four segments: data, heap, stack, and code, where do global variables, static variables, constant data types, local variables (defined and declared in functions), variables (in main function), pointers, and dynamically allocated space (using malloc and calloc) get stored in memory?
I think they would be allocated as follows:
- Global variables -------> data
- Static variables -------> data
- Constant data types -----> code
- Local variables (declared and defined in functions) --------> stack
- Variables declared and defined in main function -----> heap
- Pointers (for example,
char *arr, int *arr) -------> heap
- Dynamically allocated space (using malloc and calloc) --------> stack
I am referring to these variables only from the C perspective.
Please correct me if I am wrong as I am new to C.
",https://stackoverflow.com/questions/14588767/where-in-memory-are-my-variables-stored-in-c,226,338498.0,9.0,,,2013-01-29 17:32:22,2020-05-03 12:45:40,2018-06-05 11:35:33,,,c;memory;memory-management;types,starkk92,5974,1632141,registered,true,14588866,,CC BY-SA 4.0,2017-04-02 09:51:30,979,853,2,0,0,4,true,false,false,true,true,true,45,9,true,0.027,0.0007,5044,2013,1,17,Tuesday,false,false,false,false,false,false,false
2565039,How are multi-dimensional arrays formatted in memory?,"In C, I know I can dynamically allocate a two-dimensional array on the heap using the following code:
int** someNumbers = malloc(arrayRows*sizeof(int*));
for (i = 0; i < arrayRows; i++) {
someNumbers[i] = malloc(arrayColumns*sizeof(int));
}
Clearly, this actually creates a one-dimensional array of pointers to a bunch of separate one-dimensional arrays of integers, and ""The System"" can figure out what I mean when I ask for:
someNumbers[4][2];
But when I statically declare a 2D array, as in the following line...:
int someNumbers[ARRAY_ROWS][ARRAY_COLUMNS];
...does a similar structure get created on the stack, or is it of another form completely? (i.e. is it a 1D array of pointers? If not, what is it, and how do references to it get figured out?)
Also, when I said, ""The System,"" what is actually responsible for figuring that out? The kernel? Or does the C compiler sort it out while compiling?
",https://stackoverflow.com/questions/2565039/how-are-multi-dimensional-arrays-formatted-in-memory,226,107260.0,6.0,,,2010-04-02 04:46:42,2020-01-13 21:37:32,2013-05-06 00:03:00,,,c;arrays;memory;data-structures;stack-memory,Chris Cooper,17684,300807,registered,true,2565048,,CC BY-SA 3.0,2013-06-10 00:27:09,1028,921,3,0,0,5,true,false,false,true,true,true,53,7,true,0.056,0.0021,6077,2010,4,4,Friday,false,false,false,false,false,false,false
3737139,Reference Guide: What does this symbol mean in PHP? (PHP Syntax),"What is this?
This is a collection of questions that come up now and then about syntax in PHP. This is also a Community Wiki, so everyone is invited to participate in maintaining this list.
This question shouldn't be used as a dupe target for closing questions. Use actual questions linked here as dupe targets instead.
Why is this?
It used to be hard to find questions about operators and other syntax tokens.¹
The main idea is to have links to existing questions on Stack Overflow, so it's easier for us to reference them, and not to copy over content from the PHP Manual.
Note: Since January 2013, Stack Overflow does support special characters. Just surround the search terms by quotes, e.g. [php] "==" vs "==="
What should I do here?
If you have been pointed here by someone because you have asked such a question, please find the particular syntax below. The linked pages to the PHP manual along with the linked questions will likely answer your question then. If so, you are encouraged to upvote the answer. This list is not meant as a substitute for the help others provide.
The List
If your particular token is not listed below, you might find it in the List of Parser Tokens.
& Bitwise Operators or References
- What does it mean to start a PHP function with an ampersand?
- Understanding PHP & (ampersand, bitwise and) operator
- PHP "&" operator
- Difference between & and && in PHP
- What does "&" mean here in PHP?
- What does "&" mean in this case?
- What does the "&" sign mean in PHP?
- What does this signature mean (&) in PHP?
- How does the "&" operator work in a PHP function?
- What does & in &2 mean in PHP?
- When should I use a bitwise operator?
- Is there ever a need to use ampersand in front of an object? (&$)
=& References
- Reference assignment operator in PHP, =&
- What do the "=&" and "&=" operators in PHP mean?
- What do the '&=' and '=&' operators do?
- What does =& mean in PHP?
- 'AND' vs '&&' as operator
- Difference between & and && in PHP
- Is there any difference between "and" and "&&" operators in PHP?
- PHP - and / or keywords
- What does the percent sign mean in PHP?
- What is the PHP operator % and how do I use it in real-world examples?
- What is the use of the @ symbol in PHP?
- 'At' symbol before variable name in PHP: @$_POST
- PHP functions and @functions
- Should I use @ in my PHP code?
- What does @ mean in PHP?
- What are the PHP operators "?" and ":" called and what do they do?
- ?: operator (the 'Elvis operator') in PHP
- Where can I read about conditionals done with "?" and ":" (colon)?
- Using PHP 5.3 ?: operator
Double question mark
?? Null Coalesce Operator (since PHP 7)
A question mark followed by a type declaration
?string
?int
?array
?bool
?float Nullable type declaration (since PHP 7.1)
- How to use a nullable type
- Nullable return typ",https://stackoverflow.com/questions/3737139/reference-guide-what-does-this-symbol-mean-in-php-php-syntax,5140,861021.0,25.0,,,2010-09-17 16:24:07,2026-09-17 13:45:43,2026-09-17 13:45:43,,,php;arguments;operators;symbols;semantics,gooh,318163,208809,registered,true,3737177,,CC BY-SA 4.0,2013-05-19 07:17:06,23902,8375,56,173,0,5,true,false,false,true,true,true,64,11,false,0.029,0.006,5909,2010,9,16,Friday,false,false,false,false,false,false,true
369602,Deleting an element from an array in PHP,"
Is there an easy way to delete an element from an array using PHP, such that foreach ($array) no longer includes that element?
I thought that setting it to null would do it, but apparently it does not work.
",https://stackoverflow.com/questions/369602/deleting-an-element-from-an-array-in-php,3113,3872511.0,26.0,,,2008-12-15 20:28:55,2025-03-25 12:00:11,2019-10-17 10:22:33,,,php;arrays;unset,Ben,69024,11522,registered,true,369608,,CC BY-SA 4.0,2012-02-02 15:46:29,248,208,2,0,0,3,true,false,false,true,true,true,40,8,false,0.007,0.0008,6550,2008,12,20,Monday,false,false,false,false,false,false,true
2068344,How do I get a YouTube video thumbnail from the YouTube API?,"If I have a YouTube video URL, is there any way to use PHP and cURL to get the associated thumbnail from the YouTube API?
",https://stackoverflow.com/questions/2068344/how-do-i-get-a-youtube-video-thumbnail-from-the-youtube-api,2858,2128882.0,31.0,,,2010-01-14 23:34:24,2025-02-25 08:48:19,2020-12-31 01:19:03,,,php;curl;youtube;youtube-api;youtube-data-api,CodeOverload,48921,241654,registered,true,2068371,,CC BY-SA 4.0,2013-07-21 17:12:58,129,122,0,0,0,5,true,false,false,true,true,true,60,12,true,0.015,0.0013,6155,2010,1,23,Thursday,false,false,false,false,false,false,true
60174,How can I prevent SQL injection in PHP?,"If user input is inserted without modification into an SQL query, then the application becomes vulnerable to SQL injection, like in the following example:
$unsafe_variable = $_POST['user_input'];
mysql_query(""INSERT INTO `table` (`column`) VALUES ('$unsafe_variable')"");
That's because the user can input something like value'); DROP TABLE table;--, and the query becomes:
INSERT INTO `table` (`column`) VALUES('value'); DROP TABLE table;--')
What can be done to prevent this from happening?
",https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php,2769,2239084.0,27.0,,,2008-09-12 23:55:00,2025-09-28 15:36:27,2016-10-01 08:08:27,,,php;mysql;sql;security;sql-injection,Andrew G. Johnson,27133,428190,registered,true,60496,,CC BY-SA 3.0,2012-06-06 09:59:00,670,500,3,1,0,5,true,false,false,true,true,true,39,8,true,0.012,0.0012,6644,2008,9,23,Friday,false,false,false,false,false,true,true
12859942,Why shouldn't I use mysql_* functions in PHP?,"What are the technical reasons for why one shouldn't use mysql_* functions? (e.g. mysql_query(), mysql_connect() or mysql_real_escape_string())?
Why should I use something else even if they work on my site?
If they don't work on my site, why do I get errors like
Warning: mysql_connect(): No such file or directory
",https://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php,2738,270671.0,14.0,,,2012-10-12 13:18:39,2025-08-13 21:27:07,2020-02-29 23:30:12,,,php;mysql,Madara's Ghost,175799,871050,registered,true,12860046,,CC BY-SA 4.0,2012-10-14 21:32:28,428,323,4,0,0,2,true,false,false,true,true,true,49,8,true,0.052,0.0101,5153,2012,10,13,Friday,false,false,false,false,false,false,true
4366730,How do I check if a string contains a specific word?,"Consider:
$a = 'How are you?';
if ($a contains 'are')
echo 'true';
Suppose I have the code above, what is the correct way to write the statement if ($a contains 'are')?
",https://stackoverflow.com/questions/4366730/how-do-i-check-if-a-string-contains-a-specific-word,2649,6859953.0,36.0,,,2010-12-06 13:14:05,2024-06-06 19:35:37,2018-05-01 10:30:52,,,php;string;substring;contains;string-matching,Charles Yeung,38875,495452,registered,true,4366748,,CC BY-SA 3.0,2013-04-28 21:46:56,228,177,2,0,0,5,true,false,false,true,true,true,52,11,true,0.005,0.0004,5829,2010,12,13,Monday,false,false,false,false,false,false,true
3577641,How do you parse and process HTML/XML in PHP?,"How can one parse HTML/XML and extract information from it?
",https://stackoverflow.com/questions/3577641/how-do-you-parse-and-process-html-xml-in-php,2327,491803.0,32.0,,,2010-08-26 17:17:19,2024-09-14 16:44:52,2021-12-24 15:45:37,,,php;html;xml;xml-parsing;html-parsing,RobertPitt,57265,353790,registered,true,3577662,,CC BY-SA 4.0,2013-06-10 05:13:44,67,60,0,0,0,5,true,false,false,true,true,true,45,9,true,0.065,0.0047,5931,2010,8,17,Thursday,false,false,false,false,false,false,true
10057671,How does PHP 'foreach' actually work?,"Let me prefix this by saying that I know what foreach is, does and how to use it. This question concerns how it works under the bonnet, and I don't want any answers along the lines of ""this is how you loop an array with foreach"".
For a long time I assumed that foreach worked with the array itself. Then I found many references to the fact that it works with a copy of the array, and I have since assumed this to be the end of the story. But I recently got into a discussion on the matter, and after a little experimentation found that this was not in fact 100% true.
Let me show what I mean. For the following test cases, we will be working with the following array:
$array = array(1, 2, 3, 4, 5);
foreach ($array as $item) {
echo ""$item\n"";
$array[] = $item;
}
print_r($array);
/* Output in loop: 1 2 3 4 5
$array after loop: 1 2 3 4 5 1 2 3 4 5 */
This clearly shows that we are not working directly with the source array - otherwise the loop would continue forever, since we are constantly pushing items onto the array during the loop. But just to be sure this is the case:
foreach ($array as $key => $item) {
$array[$key + 1] = $item + 2;
echo ""$item\n"";
}
print_r($array);
/* Output in loop: 1 2 3 4 5
$array after loop: 1 3 4 5 6 7 */
This backs up our initial conclusion, we are working with a copy of the source array during the loop, otherwise we would see the modified values during the loop. But...
If we look in the manual, we find this statement:
When foreach first starts executing, the internal array pointer is automatically reset to the first element of the array.
Right... this seems to suggest that foreach relies on the array pointer of the source array. But we've just proved that we're not working with the source array, right? Well, not entirely.
// Move the array pointer on one to make sure it doesn't affect the loop
var_dump(each($array));
foreach ($array as $item) {
echo ""$item\n"";
}
var_dump(each($array));
/* Output
array(4) {
[1]=>
int(1)
[""value""]=>
int(1)
[0]=>
int(0)
[""key""]=>
int(0)
}
1
2
3
4
5
bool(false)
*/
So, despite the fact that we are not working directly with the source array, we are working directly with the source array pointer - the fact that the pointer is at the end of the array at the end of the loop shows this. Except this can't be true - if it was, then test case 1 would loop forever.
The PHP manual also states:
As foreach relies on the internal array pointer changing it within the loop may lead to unexpected behavior.
Well, let's find out what that ""unexpected behavior"" is (technically, any behavior is unexpected since I no longer know what to expect).
foreach ($array as $key => $item) {
echo ""$item\n"";
each($array);
}
/* Output: 1 2 3 4 5 */
foreach ($array as $key => $item) {
echo ""$item\n"";
reset($array);
}
/* Output: 1 2 3 4 5 */
...nothing that unexpected there, in fact it seems to support the ""copy of source"" theory.
The Question
What is going on here? My C-fu is not good enough for me to able to extract a proper conclusion simply by looking at the PHP source code, I would appreciate it if someone could translate it into English for me.
It seems to me that foreach works with a copy of the array, but sets the array pointer of the source array to the end of the array after the loop.
- Is this correct and the whole story?
- If not, what is it really doing?
- Is there any situation where using functions that adjust the array pointer (
each(), reset() et al.) during a foreach could affect the outcome of the loop?
",https://stackoverflow.com/questions/10057671/how-does-php-foreach-actually-work,2287,471180.0,7.0,,,2012-04-07 19:33:57,2025-11-13 22:54:36,2016-12-27 02:52:11,,,php;loops;foreach;iteration;php-internals,DaveRandom,88819,889949,registered,true,14854568,,CC BY-SA 3.0,2013-02-28 09:10:54,4693,3710,14,7,0,5,true,false,false,true,true,true,45,6,true,0.015,0.0049,5341,2012,4,19,Saturday,true,false,false,false,false,false,true
151969,When should I use 'self' over '$this'?,"In PHP 5, what is the difference between using self and $this?
When is each appropriate?
",https://stackoverflow.com/questions/151969/when-should-i-use-self-over-this,2241,861370.0,24.0,,,2008-09-30 06:23:06,2023-06-10 23:15:38,2021-09-02 23:14:19,,,php;class;oop;scope,Casey Watson,53082,4682,registered,true,151976,,CC BY-SA 4.0,2013-07-24 15:06:58,130,90,2,0,0,4,true,false,false,true,true,true,54,7,true,0.028,0.0026,6626,2008,9,6,Tuesday,false,false,false,false,false,false,true
1053424,How do I get PHP errors to display?,"I have checked my PHP ini file (php.ini) and display_errors is set and also error reporting is E_ALL. I have restarted my Apache webserver.
I have even put these lines at the top of my script, and it doesn't even catch simple parse errors. For example, I declare variables with a ""$"" and I don't close statements"";"". But all my scripts show a blank page on these errors, but I want to actually see the errors in my browser output.
error_reporting(E_ALL);
ini_set('display_errors', 1);
What is left to do?
",https://stackoverflow.com/questions/1053424/how-do-i-get-php-errors-to-display,2056,3976994.0,27.0,,,2009-06-27 19:09:59,2023-09-20 09:07:01,2020-01-16 08:18:28,,,php;error-handling;syntax-error;error-reporting,Abs,58356,51649,registered,true,21429652,,CC BY-SA 4.0,2016-06-08 18:22:38,637,510,6,0,0,4,true,false,false,true,true,true,35,8,true,0.007,0.0005,6356,2009,6,19,Saturday,true,false,false,false,false,false,true
391005,How Can I add HTML And CSS Into PDF,"I have an HTML (not XHTML) document that renders fine in Firefox 3 and IE 7. It uses fairly basic CSS to style it and renders fine in HTML.
I'm now after a way of converting it to PDF. I have tried:
- DOMPDF: it had huge problems with tables. I factored out my large nested tables and it helped (before it was just consuming up to 128M of memory then dying--thats my limit on memory in php.ini) but it makes a complete mess of tables and doesn't seem to get images. The tables were just basic stuff with some border styles to add some lines at various points;
- HTML2PDF and HTML2PS: I actually had better luck with this. It rendered some of the images (all the images are Google Chart URLs) and the table formatting was much better but it seemed to have some complexity problem I haven't figured out yet and kept dying with unknown node_type() errors. Not sure where to go from here; and
- Htmldoc: this seems to work fine on basic HTML but has almost no support for CSS whatsoever so you have to do everything in HTML (I didn't realize it was still 2001 in Htmldoc-land...) so it's useless to me.
I tried a Windows app called Html2Pdf Pilot that actually did a pretty decent job but I need something that at a minimum runs on Linux and ideally runs on-demand via PHP on the Webserver.
What am I missing, or how can I resolve this issue?
",https://stackoverflow.com/questions/391005/how-can-i-add-html-and-css-into-pdf,1724,962822.0,30.0,,,2008-12-24 08:14:20,2023-05-03 21:53:51,2021-04-05 13:06:47,2016-10-19 18:25:12,Not suitable for this site,php;html;css;pdf;pdf-generation,cletus,627700,18393,registered,true,434827,,,2011-05-22 01:59:09,1607,1345,0,3,0,5,true,true,false,true,true,true,35,9,false,0.031,0.0018,6541,2008,12,8,Wednesday,false,false,false,false,false,false,true
834303,str_starts_with and str_ends_with functions in PHP,"How can I write two functions that would take a string and return if it starts with the specified character/string or ends with it?
For example:
$str = '|apples}';
echo startsWith($str, '|'); //Returns true
echo endsWith($str, '}'); //Returns true
",https://stackoverflow.com/questions/834303/str-starts-with-and-str-ends-with-functions-in-php,1704,1011620.0,37.0,,,2009-05-07 12:14:27,2025-03-27 01:58:27,2025-03-27 01:58:27,,,php;string,Ali,268320,49153,registered,true,834355,,CC BY-SA 4.0,2013-02-28 12:17:25,290,252,1,0,0,2,true,false,false,true,true,true,50,6,false,0.037,0.0017,6407,2009,5,12,Thursday,false,false,false,false,false,false,true
768431,How do I make a redirect in PHP?,"Is it possible to redirect a user to a different page through the use of PHP?
Say the user goes to www.example.com/page.php and I want to redirect them to www.example.com/index.php, how would I do so without the use of a meta refresh? Is it possible?
This could even protect my pages from unauthorized users.
",https://stackoverflow.com/questions/768431/how-do-i-make-a-redirect-in-php,1611,4032423.0,35.0,,,2009-04-20 14:13:22,2025-03-14 20:09:54,2020-12-29 05:39:07,,,php;http-redirect;http-status-code-301,Sam,19227,93181,registered,true,,,CC BY-SA 4.0,2011-03-15 07:40:42,358,311,2,0,0,3,false,false,false,true,true,true,32,8,true,0.009,0.0004,6424,2009,4,14,Monday,false,false,false,false,false,false,true
3003145,How to get the client IP address in PHP,"How can I get the client IP address using PHP?
I want to keep record of the user who logged into my website through his/her IP address.
",https://stackoverflow.com/questions/3003145/how-to-get-the-client-ip-address-in-php,1453,2295008.0,39.0,,,2010-06-09 04:50:16,2024-12-17 22:15:24,2019-02-13 15:56:54,,,php;environment-variables;ip-address,Anup Prakash,14792,356170,registered,true,,,CC BY-SA 4.0,2014-03-29 17:36:19,151,137,0,0,0,3,false,false,false,true,true,true,39,9,false,0.017,0.0006,6009,2010,6,4,Wednesday,false,false,false,false,false,false,true
2418473,"Difference between require, include, require_once and include_once?","In PHP:
- When should I use
require vs. include?
- When should I use
require_once vs. include_once?
",https://stackoverflow.com/questions/2418473/difference-between-require-include-require-once-and-include-once,1453,734538.0,30.0,,,2010-03-10 16:13:25,2025-04-19 04:13:56,2018-03-27 11:39:41,,,php;include;require;require-once,Scott B,40635,209102,registered,true,2418514,,CC BY-SA 3.0,2017-12-28 18:43:55,185,99,4,0,0,4,true,false,false,true,true,true,67,7,true,0.041,0.002,6100,2010,3,16,Wednesday,false,false,false,false,false,false,true
2699086,Sort a 2d array by a column value,"How can I sort this array by the value of the "order" key?
Even though the values are currently sequential, they will not always be.
Array
(
[0] => Array
(
[hashtag] => a7e87329b5eab8578f4f1098a152d6f4
[title] => Flower
[order] => 3
)
[1] => Array
(
[hashtag] => b24ce0cd392a5b0b8dedc66c25213594
[title] => Free
[order] => 2
)
[2] => Array
(
[hashtag] => e7d31fc0602fb2ede144d18cdffd816b
[title] => Ready
[order] => 1
)
)
",https://stackoverflow.com/questions/2699086/sort-a-2d-array-by-a-column-value,1422,1195475.0,18.0,,,2010-04-23 13:54:26,2024-11-02 15:25:35,2024-11-02 15:25:35,,,php;arrays;sorting;multidimensional-array,stef,28006,149664,registered,true,2699159,,CC BY-SA 4.0,2018-03-13 09:29:35,677,639,1,0,0,4,true,false,false,true,true,true,33,8,false,0.015,0.0012,6056,2010,4,13,Friday,false,false,false,false,false,false,true
4261133,""Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP","I'm running a PHP script and continue to receive errors like:
Notice: Undefined variable: my_variable_name in C:\wamp\www\mypath\index.php on line 10
Notice: Undefined index: my_index C:\wamp\www\mypath\index.php on line 11
Warning: Undefined array key "my_index" in C:\wamp\www\mypath\index.php on line 11
Line 10 and 11 looks like this:
echo "My variable value is: " . $my_variable_name;
echo "My index value is: " . $my_array["my_index"];
What is the meaning of these error messages?
Why do they appear all of a sudden? I used to use this script for years and I've never had any problem.
How do I fix them?
This is a General Reference question for people to link to as duplicate, instead of having to explain the issue over and over again. I feel this is necessary because most real-world answers on this issue are very specific.
Related Meta discussion:
",https://stackoverflow.com/questions/4261133/notice-undefined-variable-notice-undefined-index-warning-undefined-arr,1375,2222711.0,29.0,,,2010-11-23 21:26:54,2025-11-02 07:07:55,2022-02-24 13:01:00,,,php;arrays;variables;warnings;undefined-index,Pekka,451481,187606,registered,true,4261200,,CC BY-SA 4.0,2012-12-09 12:00:51,1426,989,1,2,0,5,true,false,false,true,true,true,169,16,false,0.013,0.0006,5842,2010,11,21,Tuesday,false,false,false,false,false,false,true
279170,UTF-8 all the way through,"
I'm setting up a new server and want to support UTF-8 fully in my web application. I have tried this in the past on existing servers and always seem to end up having to fall back to ISO-8859-1.
Where exactly do I need to set the encoding/charsets? I'm aware that I need to configure Apache, MySQL, and PHP to do this — is there some standard checklist I can follow, or perhaps troubleshoot where the mismatches occur?
This is for a new Linux server, running MySQL 5, PHP, 5 and Apache 2.
",https://stackoverflow.com/questions/279170/utf-8-all-the-way-through,1371,226176.0,13.0,,,2008-11-10 21:04:56,2025-01-25 17:53:50,2024-01-03 16:17:57,,,php;mysql;apache;utf-8,mercutio,22688,1951,registered,true,279279,,CC BY-SA 4.0,2014-01-06 12:57:30,512,491,0,0,0,4,true,false,false,true,true,true,25,5,false,0.057,0.0061,6585,2008,11,21,Monday,false,false,false,false,false,false,true
1921421,Get the first element of an array,"I have an array:
array( 4 => 'apple', 7 => 'orange', 13 => 'plum' )
I would like to get the first element of this array. Expected result: string apple
One requirement: it cannot be done with passing by reference, so array_shift is not a good solution.
How can I do this?
",https://stackoverflow.com/questions/1921421/get-the-first-element-of-an-array,1364,2244023.0,27.0,,,2009-12-17 12:26:44,2026-05-26 13:33:36,2023-02-03 04:09:57,,,php;arrays,hsz,152932,223386,registered,true,3771228,,CC BY-SA 4.0,2012-08-09 12:32:53,378,288,3,0,0,2,true,false,false,true,true,true,33,7,false,0.012,0.0006,6183,2009,12,12,Thursday,false,false,false,false,false,false,true
4795385,How do you use bcrypt for hashing passwords in PHP?,"Every now and then I hear the advice ""Use bcrypt for storing passwords in PHP, bcrypt rules"".
But what is bcrypt? PHP doesn't offer any such functions, Wikipedia babbles about a file-encryption utility and Web searches just reveal a few implementations of Blowfish in different languages. Now Blowfish is also available in PHP via mcrypt, but how does that help with storing passwords? Blowfish is a general purpose cipher, it works two ways. If it could be encrypted, it can be decrypted. Passwords need a one-way hashing function.
What is the explanation?
",https://stackoverflow.com/questions/4795385/how-do-you-use-bcrypt-for-hashing-passwords-in-php,1341,497411.0,11.0,,,2011-01-25 15:34:04,2022-06-10 03:01:43,2014-04-13 17:01:50,2022-06-10 05:04:05,Duplicate,php;passwords;cryptography;password-protection;bcrypt,Vilx-,107664,41360,registered,true,6337021,,,2012-05-03 16:46:23,689,560,2,1,0,5,true,true,false,true,true,true,51,10,true,0.022,0.0027,5779,2011,1,15,Tuesday,false,false,false,false,false,false,true
254514,Enumerations on PHP,"I know that PHP doesn't yet have native Enumerations. But I have become accustomed to them from the Java world. I would love to use enums as a way to give predefined values which IDEs' auto-completion features could understand.
Constants do the trick, but there's the namespace collision problem and (or actually because) they're global. Arrays don't have the namespace problem, but they're too vague, they can be overwritten at runtime and IDEs rarely know how to autofill their keys without additional static analysis annotations or attributes.
Are there any solutions/workarounds you commonly use? Does anyone recall whether the PHP guys have had any thoughts or decisions around enumerations?
",https://stackoverflow.com/questions/254514/enumerations-on-php,1324,688903.0,40.0,,,2008-10-31 18:51:14,2023-11-07 23:20:56,2021-02-16 07:17:57,,,php;enumeration,Henrik Paul,67991,2238,registered,true,254543,,CC BY-SA 4.0,2013-08-23 04:12:20,727,697,0,0,0,2,true,false,false,true,true,true,19,3,false,0.058,0.0019,6595,2008,10,18,Friday,false,false,false,false,false,false,true
12769982,Reference - What does this error mean in PHP?,"What is this?
This is a number of answers about warnings, errors, and notices you might encounter while programming PHP and have no clue how to fix them. This is also a Community Wiki, so everyone is invited to participate adding to and maintaining this list.
Why is this?
Questions like "Headers already sent" or "Calling a member of a non-object" pop up frequently on Stack Overflow. The root cause of those questions is always the same. So the answers to those questions typically repeat them and then show the OP which line to change in their particular case. These answers do not add any value to the site because they only apply to the OP's particular code. Other users having the same error cannot easily read the solution out of it because they are too localized. That is sad because once you understood the root cause, fixing the error is trivial. Hence, this list tries to explain the solution in a general way to apply.
What should I do here?
If your question has been marked as a duplicate of this one, please find your error message below and apply the fix to your code. The answers usually contain further links to investigate in case it shouldn't be clear from the general answer alone.
If you want to contribute, please add your "favorite" error message, warning or notice, one per answer, a short description what it means (even if it is only highlighting terms to their manual page), a possible solution or debugging approach and a listing of existing Q&A that are of value. Also, feel free to improve any existing answers.
The List
- Nothing is seen. The page is empty and white. (also known as White Page/Screen Of Death)
- Code doesn't run/what looks like parts of my PHP code are output
- Warning: Cannot modify header information - headers already sent
- Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given a.k.a.
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource
- Warning: [function] expects parameter 1 to be resource, boolean given
- Warning: [function]: failed to open stream: [reason]
- Warning: open_basedir restriction in effect
- Warning: Division by zero
- Warning: Illegal string offset 'XXX'
- Warning: count(): Parameter must be an array or an object that implements Countable
- Parse error: syntax error, unexpected '['
- Parse error: syntax error, unexpected T_XXX
- Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE
- Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM
- Parse error: syntax error, unexpected 'require_once' (T_REQUIRE_ONCE), expecting function (T_FUNCTION)
- Parse error: syntax error, unexpected T_VARIABLE
- Fatal error: Allowed memory size of XXX bytes exhausted (tried to allocate XXX bytes)
- Fatal error: Maximum execution time of XX seconds exceeded
- Fatal error: Call to a member function ... on a non-object or null
- Fatal Error: Call to Undefined function XXX
- Fatal Error: Cannot redeclare XXX
- Fatal error: Can't use function return value in write context
- Fatal error: Declaration of AAA::BBB() must be compatible with that of CCC::BBB()'
- Return type of AAA::BBB() should either be compatible with CCC::BBB(), or the #[\ReturnTypeWillChange] attribute should be used
- Fatal error: Using $this when not in object context
- Fatal error: Object of class Closure could not be converted to string
- Fatal error: Undefined class constant
- Fatal error: Uncaught TypeError: Argument #n must be of type x, y given
- Notice: Array to string conversion (< PHP 8.0) or Warning: Array to string conversion (>= PHP 8.0)
- Notice: Trying to get property of non-object error
- Notice: Undefined variable or property
- "Notice: Undefined Index", or "Warning: Undefined array key"
- Notice: Undefined offset XXX [Reference]
- Notice: Uninitialized string offset: XXX
- Notice: Use of undefined constant XXX - assumed 'XXX' / Error: Undefined constant XXX
- MySQL: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ... at line ...
- Strict Standards: Non-static method [<class>::<method>] should not be called statically
- Warning: function expects parameter X to be boolean/string/integer
- HTTP Error 500 - Internal server error
- Deprecated: Arrays and strings offset access syntax with curly braces is deprecated
- Warning: foreach() argument must be of type array|object, <type> given
Also, see:
",https://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php,1293,289456.0,39.0,,,2012-10-07 15:11:00,2024-02-04 05:02:23,2024-02-04 05:02:23,,,php;arrays;debugging;error-handling;warnings,hakre,200070,367456,registered,true,,,CC BY-SA 4.0,2015-10-05 08:59:08,7356,4478,0,46,0,5,false,false,false,true,true,true,45,9,true,0.135,0.0045,5158,2012,10,15,Sunday,true,false,false,false,false,false,true
129677,How can I sanitize user input with PHP?,"Is there a catchall function somewhere that works well for sanitizing user input for SQL injection and XSS attacks, while still allowing certain types of HTML tags?
",https://stackoverflow.com/questions/129677/how-can-i-sanitize-user-input-with-php,1288,711511.0,17.0,,,2008-09-24 20:20:39,2025-01-02 11:55:03,2019-06-26 18:34:03,,,php;security;xss;sql-injection;user-input,Brent,23764,10680,registered,true,130323,,CC BY-SA 4.0,2014-01-15 04:28:00,172,165,0,0,0,5,true,false,false,true,true,true,39,8,true,0.024,0.0018,6632,2008,9,20,Wednesday,false,false,false,false,false,false,true
401656,Secure hash and salt for PHP passwords,"It is currently said that MD5 is partially unsafe. Taking this into consideration, I'd like to know which mechanism to use for password protection.
This question, Is “double hashing” a password less secure than just hashing it once?
suggests that hashing multiple times may be a good idea, whereas How to implement password protection for individual files? suggests using salt.
I'm using PHP. I want a safe and fast password encryption system. Hashing a password a million times may be safer, but also slower. How to achieve a good balance between speed and safety? Also, I'd prefer the result to have a constant number of characters.
- The hashing mechanism must be available in PHP
- It must be safe
- It can use salt (in this case, are all salts equally good? Is there any way to generate good salts?)
Also, should I store two fields in the database (one using MD5 and another one using SHA, for example)? Would it make it safer or unsafer?
In case I wasn't clear enough, I want to know which hashing function(s) to use and how to pick a good salt in order to have a safe and fast password protection mechanism.
Related questions that don't quite cover my question:
What's the difference between SHA and MD5 in PHP
Simple Password Encryption
Secure methods of storing keys, passwords for asp.net
How would you implement salted passwords in Tomcat 5.5
",https://stackoverflow.com/questions/401656/secure-hash-and-salt-for-php-passwords,1256,263196.0,14.0,,,2008-12-30 22:02:45,2024-06-07 09:18:56,2022-05-24 15:16:11,,,php;security;hash;passwords,luiscubal,25221,32775,registered,true,401684,,CC BY-SA 4.0,2012-06-25 23:16:36,2118,1358,0,6,0,4,true,false,false,true,true,true,38,7,false,0.053,0.0048,6535,2008,12,22,Tuesday,false,false,false,false,false,false,true
11077857,"What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet?","I have tried reading some articles, but I am not very clear on the concepts yet.
Would someone like to take a shot at explaining to me what these technologies are:
- Long Polling
- Server-Sent Events
- Websockets
- Comet
One thing that I came across every time was, the server keeps a connection open and pushes data to the client. How is the connection kept open, and how does the client get the pushed data? (How does the client use the data, maybe some code might help?)
Now, which one of them should I use for a real-time app. I have been hearing a lot about websockets (with socket.io [a node.js library]) but why not PHP?
",https://stackoverflow.com/questions/11077857/what-are-long-polling-websockets-server-sent-events-sse-and-comet,1212,227406.0,4.0,,,2012-06-18 06:28:08,2021-05-30 06:27:00,2016-11-12 21:27:09,,,php;websocket;comet;long-polling;server-sent-events,user1437328,15906,1437328,registered,true,12855533,,CC BY-SA 3.0,2014-07-09 08:11:47,699,626,0,0,0,5,true,false,false,true,true,true,70,9,true,0.018,0.0053,5269,2012,6,6,Monday,false,false,false,false,false,false,true
7225070,PHP array delete by value (not key),"I have a PHP array like so:
$messages = [312, 401, 1599, 3, ...];
Given that the values in the array are unique, how can I delete the element with a given value (without knowing its key)?
",https://stackoverflow.com/questions/7225070/php-array-delete-by-value-not-key,1193,1352031.0,22.0,,,2011-08-29 00:44:04,2025-12-26 11:01:44,2023-12-23 07:25:40,,,php;arrays,Adam Strudwick,13229,774018,registered,true,7225113,,CC BY-SA 4.0,2018-11-14 03:47:52,244,189,1,0,0,2,true,false,false,true,true,true,35,7,false,0.016,0.0009,5563,2011,8,0,Monday,false,false,false,false,false,false,true
520237,How do I expire a PHP session after 30 minutes?,"I need to keep a session alive for 30 minutes and then destroy it.
",https://stackoverflow.com/questions/520237/how-do-i-expire-a-php-session-after-30-minutes,1183,1246617.0,18.0,,,2009-02-06 13:14:14,2024-03-12 18:37:57,2011-10-13 07:38:45,,,php;session;cookies,Tom,34504,45350,registered,true,1270960,,CC BY-SA 3.0,2018-01-12 18:27:27,75,68,0,0,0,3,true,false,false,true,true,true,47,10,true,0.014,0.0009,6497,2009,2,13,Friday,false,false,false,false,false,false,true
931407,What is stdClass in PHP?,"Please define what stdClass is.
",https://stackoverflow.com/questions/931407/what-is-stdclass-in-php,1170,683873.0,18.0,,,2009-05-31 05:49:01,2025-03-27 11:36:44,2015-02-14 02:42:53,,,php;stdclass,Keira Nighly,15504,95663,registered,true,931419,,CC BY-SA 3.0,2013-12-01 04:57:58,52,32,1,0,0,2,true,false,false,true,true,true,24,5,true,0.026,0.0017,6383,2009,5,5,Sunday,true,false,false,false,false,false,true
64003,How do I use PHP to get the current year?,"I want to put a copyright notice in the footer of a web site, but I think it's incredibly tacky for the year to be outdated.
How would I make the year update automatically with PHP?
",https://stackoverflow.com/questions/64003/how-do-i-use-php-to-get-the-current-year,1165,1598419.0,18.0,,,2008-09-15 15:34:54,2025-11-04 01:40:20,2025-11-04 01:40:20,,,php;date,JD Graffam,11745,1661459,registered,true,64097,,CC BY-SA 4.0,2015-03-01 02:02:09,196,182,0,0,0,2,true,false,false,true,true,true,41,10,true,0.011,0.0007,6641,2008,9,15,Monday,false,false,false,false,false,false,true
4064444,Returning JSON from a PHP Script,"I want to return JSON from a PHP script.
Do I just echo the result? Do I have to set the Content-Type header?
",https://stackoverflow.com/questions/4064444/returning-json-from-a-php-script,1163,1660036.0,20.0,,,2010-10-31 18:23:54,2023-10-04 05:53:53,2016-06-11 16:06:34,,,php;json;header,Scott Nicol,11878,492914,registered,true,4064468,,CC BY-SA 3.0,2018-12-11 13:14:54,138,111,1,0,0,3,true,false,false,true,true,true,32,6,false,0.012,0.0007,5865,2010,10,18,Sunday,true,false,false,false,false,false,true
4361553,"What is the difference between public, private, and protected?","When and why should I use public, private, and protected functions and variables inside a class? What is the difference between them?
Examples:
// Public
public $variable;
public function doSomething() {
// ...
}
// Private
private $variable;
private function doSomething() {
// ...
}
// Protected
protected $variable;
protected function doSomething() {
// ...
}
",https://stackoverflow.com/questions/4361553/what-is-the-difference-between-public-private-and-protected,1144,647381.0,16.0,,,2010-12-05 22:13:14,2020-07-22 05:52:41,2017-01-02 00:16:40,,,php;oop;private;public;protected,Adam Halasz,58539,380562,registered,true,4361582,,CC BY-SA 3.0,2012-09-21 00:41:22,451,374,4,0,0,5,true,false,false,true,true,true,62,9,true,0.025,0.0018,5830,2010,12,22,Sunday,true,false,false,false,false,false,true
359047,"Detecting request type in PHP (GET, POST, PUT or DELETE)","How can I detect which request type was used (GET, POST, PUT or DELETE) in PHP?
",https://stackoverflow.com/questions/359047/detecting-request-type-in-php-get-post-put-or-delete,1106,606018.0,15.0,,,2008-12-11 11:31:27,2024-10-19 15:57:31,2019-06-24 19:00:52,,,php;http;request,UnkwnTech,91724,115,registered,true,359050,,CC BY-SA 4.0,,87,80,0,0,0,3,true,false,false,true,true,true,56,10,false,0.025,0.0018,6554,2008,12,11,Thursday,false,false,false,false,false,false,true
8684609,Where can I find php.ini?,"Today I needed to install the IBM DB2 library. I went through all the steps up to make install, and I found ibm_db2.so in $PHP_HOME/lib/extensions/somecomplicatedname/ibm_db2.so.
The great catch is the last step is to configure file php.ini, but there aren't any php.ini files on my system. PHP works fine, except of course for this newfangled ibm_db2 thingamajig. (I tried a small PHP script which fails and indicates that the ibm_db2 functions are not available.)
How would I go about finding or setting up the php.ini file so that I can enable the library I need?
",https://stackoverflow.com/questions/8684609/where-can-i-find-php-ini,1104,1365576.0,15.0,,,2011-12-30 22:20:06,2024-07-30 05:42:23,2024-03-01 14:15:57,,,php;linux;php-ini,necromancer,24781,621338,registered,true,72046017,,CC BY-SA 4.0,2015-04-27 02:18:45,659,568,2,0,0,3,true,false,false,true,true,true,25,5,true,0.011,0.0008,5440,2011,12,22,Friday,false,false,false,false,false,false,true
470617,How do I get the current date and time in PHP?,"Which PHP function can return the current date/time?
",https://stackoverflow.com/questions/470617/how-do-i-get-the-current-date-and-time-in-php,1097,3328388.0,47.0,,,2009-01-22 20:09:18,2024-12-16 19:30:50,2019-02-22 23:36:31,,,php;datetime,Mike,,,does_not_exist,true,,,CC BY-SA 4.0,2014-01-20 07:50:08,60,53,0,0,0,2,false,false,false,true,false,true,46,11,true,0.014,0.0003,6512,2009,1,20,Thursday,false,false,false,false,false,false,true
3654295,Remove empty array elements,"Some elements in my array are empty strings from users. $linksArray still has empty elements after the following:
foreach($linksArray as $link)
{
if($link == '')
{
unset($link);
}
}
print_r($linksArray);
The empty() function doesn't work either.
",https://stackoverflow.com/questions/3654295/remove-empty-array-elements,1079,1450088.0,27.0,,,2010-09-06 21:06:57,2023-07-07 13:43:17,2023-03-17 08:06:45,,,php;arrays;string,Will,11311,434269,unregistered,true,3654309,,CC BY-SA 4.0,2014-04-29 11:07:32,331,267,3,0,0,3,true,false,false,true,true,true,27,4,false,0.019,0.0007,5920,2010,9,21,Monday,false,false,false,false,false,false,true
4356289,PHP random string generator,"I'm trying to create a randomized string in PHP, and I get absolutely no output with this:
<?php
function RandomString()
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randstring = '';
for ($i = 0; $i < 10; $i++) {
$randstring = $characters[rand(0, strlen($characters))];
}
return $randstring;
}
RandomString();
echo $randstring;
What am I doing wrong?
",https://stackoverflow.com/questions/4356289/php-random-string-generator,1031,1890609.0,62.0,,,2010-12-04 22:56:21,2025-03-20 04:25:39,2019-07-18 13:38:11,,,php;string;random,Captain Lightning,10803,519455,registered,true,4356295,,CC BY-SA 4.0,2013-07-17 22:51:30,509,471,1,0,0,3,true,false,false,true,true,true,27,4,false,0.033,0.0005,5831,2010,12,22,Saturday,true,false,false,false,false,false,true
4345554,Convert a PHP object to an associative array,"I'm integrating an API to my website which works with data stored in objects while my code is written using arrays.
I'd like a quick-and-dirty function to convert an object to an array.
",https://stackoverflow.com/questions/4345554/convert-a-php-object-to-an-associative-array,1024,1967798.0,32.0,,,2010-12-03 12:34:16,2024-02-22 11:34:23,2019-08-31 20:26:56,,,php;arrays,Haroldo,37567,289666,registered,true,4345609,,CC BY-SA 4.0,2018-03-28 04:23:47,201,187,0,0,0,2,true,false,false,true,true,true,44,8,false,0.016,0.0005,5832,2010,12,12,Friday,false,false,false,false,false,false,true
2973202,mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource,"I am trying to select data from a MySQL table, but I get one of the following error messages:
mysql_fetch_array() expects parameter 1 to be resource, boolean given
This is my code:
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query('SELECT * FROM Users WHERE UserName LIKE $username');
while($row = mysql_fetch_array($result)) {
echo $row['FirstName'];
}
",https://stackoverflow.com/questions/2973202/mysql-fetch-array-mysql-fetch-assoc-mysql-fetch-row-mysql-num-rows-etc,1007,778795.0,31.0,,,2010-06-04 10:18:08,2026-10-14 14:07:46,2020-04-08 13:20:15,,,php;mysql,iamjonesy,25156,299871,registered,true,2973209,,CC BY-SA 4.0,2014-03-22 21:57:18,474,404,1,0,0,2,true,false,false,true,true,true,114,8,false,0.04,0.0013,6014,2010,6,10,Friday,false,false,false,false,false,false,true
1623914,What is thread safe or non-thread safe in PHP?,"I saw different binaries for PHP, like non-thread or thread safe?
What does this mean?
What is the difference between these packages?
",https://stackoverflow.com/questions/1623914/what-is-thread-safe-or-non-thread-safe-in-php,977,496876.0,5.0,,,2009-10-26 09:41:33,2022-07-22 22:47:34,2020-04-19 17:35:06,,,php;multithreading;package;thread-safety;threadcontext,O..,11455,190494,unregistered,true,,,CC BY-SA 4.0,2020-06-20 17:21:38,158,137,0,0,0,5,false,false,false,true,true,true,46,9,true,0.01,0.002,6235,2009,10,9,Monday,false,false,false,false,false,false,true
6768793,Get the full URL in PHP,"I use this code to get the full URL:
$actual_link = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
The problem is that I use some masks in my .htaccess, so what we see in the URL is not always the real path of the file.
What I need is to get the URL, what is written in the URL, nothing more and nothing less—the full URL.
I need to get how it appears in the Navigation Bar in the web browser, and not the real path of the file on the server.
",https://stackoverflow.com/questions/6768793/get-the-full-url-in-php,974,4120706.0,27.0,,,2011-07-20 21:29:51,2025-06-13 17:38:56,2014-02-02 09:48:25,,,php;url,DiegoP.,45865,735997,registered,true,6768831,,CC BY-SA 3.0,2015-11-06 06:35:33,520,455,2,0,0,2,true,false,false,true,true,true,23,6,false,0.007,0.0002,5603,2011,7,21,Wednesday,false,false,false,false,false,false,true
8529656,How do I convert a string to a number in PHP?,"I want to convert these types of values, '3', '2.34', '0.234343', etc. to a number. In JavaScript we can use Number(), but is there any similar method available in PHP?
Input Output
'2' 2
'2.34' 2.34
'0.3454545' 0.3454545
",https://stackoverflow.com/questions/8529656/how-do-i-convert-a-string-to-a-number-in-php,970,3136376.0,26.0,,,2011-12-16 04:08:14,2025-08-14 07:18:51,2019-06-24 19:42:29,,,php;casting;type-conversion,Sara,14708,2421575,registered,true,8529687,,CC BY-SA 4.0,2016-01-11 22:28:49,350,267,5,0,0,3,true,false,false,true,true,true,45,11,true,0.008,0.0003,5454,2011,12,4,Friday,false,false,false,false,false,false,true
3446216,What is the difference between single-quoted and double-quoted strings in PHP?,"I'm a little confused why I see some code in PHP with string placed in single quotes and sometimes in double quotes.
I just know in .NET, or the C language, if it is in a single quote, that means it is a character, not a string.
",https://stackoverflow.com/questions/3446216/what-is-the-difference-between-single-quoted-and-double-quoted-strings-in-php,945,495585.0,7.0,,,2010-08-10 05:12:56,2026-03-18 11:45:42,2019-09-02 13:57:58,,,php;string;syntax,rob waminal,18489,379800,registered,true,3446286,,CC BY-SA 4.0,2014-02-06 09:38:08,244,230,0,0,0,3,true,false,false,true,true,true,78,11,true,0.014,0.0019,5947,2010,8,5,Tuesday,false,false,false,false,false,false,true
173400,How to check if PHP array is associative or sequential?,"PHP treats all arrays as associative, so there aren't any built in functions. Can anyone recommend a fairly efficient way to check if an array "is a list" (contains only numeric keys starting from 0)?
Basically, I want to be able to differentiate between this:
$sequentialArray = [
'apple', 'orange', 'tomato', 'carrot'
];
and this:
$assocArray = [
'fruit1' => 'apple',
'fruit2' => 'orange',
'veg1' => 'tomato',
'veg2' => 'carrot'
];
",https://stackoverflow.com/questions/173400/how-to-check-if-php-array-is-associative-or-sequential,943,361289.0,47.0,,,2008-10-06 07:01:13,2025-08-08 15:58:26,2022-04-03 06:49:42,,,php;arrays,Wilco,33482,5291,registered,true,173479,,CC BY-SA 4.0,2013-06-21 09:22:31,556,478,2,0,0,2,true,false,false,true,true,true,55,10,true,0.13,0.0026,6620,2008,10,7,Monday,false,false,false,false,false,false,true
173868,How can I get a file's extension in PHP?,"This is a question you can read everywhere on the web with various answers:
$ext = end(explode('.', $filename));
$ext = substr(strrchr($filename, '.'), 1);
$ext = substr($filename, strrpos($filename, '.') + 1);
$ext = preg_replace('/^.*\.([^.]+)$/D', '$1', $filename);
$exts = split("[/\\.]", $filename);
$n = count($exts)-1;
$ext = $exts[$n];
etc.
However, there is always "the best way".
",https://stackoverflow.com/questions/173868/how-can-i-get-a-files-extension-in-php,883,887547.0,33.0,,,2008-10-06 11:00:02,2025-02-22 22:31:32,2024-01-26 01:14:23,,,php;file-extension,Bite code,602069,9951,registered,true,173876,,CC BY-SA 4.0,2013-07-06 21:04:06,461,416,1,0,0,2,true,false,false,true,true,true,44,9,true,0.037,0.001,6620,2008,10,11,Monday,false,false,false,false,false,false,true
18236294,How do I get the query builder to output its raw SQL query as a string?,"Given the following code:
DB::table('users')->get();
I want to get the raw SQL query string that the database query builder above will generate. In this example, it would be SELECT * FROM users.
How do I do this?
",https://stackoverflow.com/questions/18236294/how-do-i-get-the-query-builder-to-output-its-raw-sql-query-as-a-string,879,1457885.0,41.0,,,2013-08-14 15:43:54,2025-05-02 10:04:11,2021-12-26 00:23:09,,,php;sql;laravel;eloquent;laravel-query-builder,meiryo,11817,665518,registered,true,18236656,,CC BY-SA 4.0,2014-11-06 05:38:55,316,220,2,0,0,5,true,false,false,true,true,true,71,16,true,0.028,0.0006,4847,2013,8,15,Wednesday,false,false,false,false,false,true,true
5592994,Remove trailing delimiting character from a delimited string,"What is fastest way to remove the last character from a string?
I have a string like
a,b,c,d,e,
I would like to remove the last ',' and get the remaining string back:
OUTPUT: a,b,c,d,e
What is the fastest way to do this?
",https://stackoverflow.com/questions/5592994/remove-trailing-delimiting-character-from-a-delimited-string,840,1204497.0,8.0,,,2011-04-08 09:15:10,2024-06-15 12:43:10,2022-08-18 09:23:45,,,php;csv;delimiter;truncate;trailing,I-M-JM,16000,515659,registered,true,5593009,,CC BY-SA 4.0,2023-01-12 17:05:35,304,228,2,0,0,5,true,false,false,true,true,true,60,8,false,0.007,0.0007,5706,2011,4,9,Friday,false,false,false,false,false,false,true
676824,How can I calculate the difference between two dates using PHP?,"I have two dates of the form:
Start Date: 2007-03-24
End Date: 2009-06-26
Now I need to find the difference between these two in the following form:
2 years, 3 months and 2 days
How can I do this in PHP?
",https://stackoverflow.com/questions/676824/how-can-i-calculate-the-difference-between-two-dates-using-php,832,1151925.0,33.0,,,2009-03-24 10:33:07,2026-06-28 20:07:10,2025-12-31 20:36:20,,,php;datetime;datediff,gnanesh,,,does_not_exist,true,676828,,CC BY-SA 4.0,2011-08-05 13:28:13,353,206,2,0,0,3,true,false,false,true,false,true,63,11,true,0.029,0.0007,6451,2009,3,10,Tuesday,false,false,false,false,false,false,true
8028957,How to fix "Headers already sent" error in PHP,"When running my script, I am getting several errors like this:
Warning: Cannot modify header information - headers already sent by (output started at /some/file.php:12) in /some/file.php on line 23
The lines mentioned in the error messages contain header() and setcookie() calls.
What could be the reason for this? And how to fix it?
",https://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php,829,2076764.0,16.0,,,2011-11-06 17:41:22,2023-10-08 11:55:57,2023-10-08 11:42:37,,,php;http-headers,Moses89,4363,1031807,registered,true,8028987,,CC BY-SA 4.0,2012-08-02 22:03:35,580,341,2,2,0,2,true,false,false,true,true,true,56,9,false,0.008,0.0004,5494,2011,11,17,Sunday,true,false,false,false,false,false,true
561066,Fatal Error: Allowed Memory Size of 134217728 Bytes Exhausted,"I have a bunch of client point of sale (POS) systems that periodically send new sales data to one centralized database, which stores the data into one big database for report generation.
The client POS is based on PHPPOS, and I have implemented a module that uses the standard XML-RPC library to send sales data to the service. The server system is built on CodeIgniter, and uses the XML-RPC and XML-RPCS libraries for the webservice component. Whenever I send a lot of sales data (as little as 50 rows from the sales table, and individual rows from sales_items pertaining to each item within the sale) I get the following error:
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 54 bytes)
128M is the default value in php.ini, but I assume that is a huge number to break. In fact, I have even tried setting this value to 1024M, and all it does is take a longer time to error out.
As for steps I've taken, I've tried disabling all processing on the server-side, and have rigged it to return a canned response regardless of the input. However, I believe the problem lies in the actual sending of the data. I've even tried disabling the maximum script execution time for PHP, and it still errors out.
",https://stackoverflow.com/questions/561066/fatal-error-allowed-memory-size-of-134217728-bytes-exhausted,827,2353531.0,39.0,,,2009-02-18 13:33:44,2025-08-01 21:00:08,2024-03-18 18:26:11,,,php;memory;memory-limit,ArcticZero,8301,410280,registered,true,,,CC BY-SA 4.0,2015-07-19 08:42:17,1305,1232,1,0,0,3,false,false,false,true,true,true,61,9,false,0.017,0.0004,6485,2009,2,13,Wednesday,false,false,false,false,false,false,true
1028668,Get first key in a (possibly) associative array?,"What's the best way to determine the first key in a possibly associative array? My first thought it to just foreach the array and then immediately breaking it, like this:
foreach ($an_array as $key => $val) break;
Thus having $key contain the first key, but this seems inefficient. Does anyone have a better solution?
",https://stackoverflow.com/questions/1028668/get-first-key-in-a-possibly-associative-array,827,664045.0,25.0,,,2009-06-22 18:13:59,2026-11-14 21:57:45,2013-07-15 03:02:33,,,php;arrays,Alex S,26289,94077,registered,true,1028677,,CC BY-SA 3.0,,362,324,1,0,0,2,true,false,false,true,true,true,48,8,true,0.038,0.0012,6361,2009,6,18,Monday,false,false,false,false,false,false,true
5647461,How do I send a POST request with PHP?,"Actually I want to read the contents that come after the search query, when it is done. The problem is that the URL only accepts POST methods, and it does not take any action with GET method...
I have to read all contents with the help of domdocument or file_get_contents(). Is there any method that will let me send parameters with POST method and then read the contents via PHP?
",https://stackoverflow.com/questions/5647461/how-do-i-send-a-post-request-with-php,824,1526831.0,18.0,,,2011-04-13 10:06:00,2025-11-28 11:38:24,2015-09-22 17:53:09,,,php;http;post;request,Fred Tanrikut,10301,705004,unregistered,true,,,CC BY-SA 3.0,2015-02-18 21:17:23,474,382,6,0,0,4,false,false,false,true,true,true,38,9,true,0.012,0.0005,5701,2011,4,10,Wednesday,false,false,false,false,false,false,true
2040560,Finding the number of days between two dates,"How to find number of days between two dates using PHP?
",https://stackoverflow.com/questions/2040560/finding-the-number-of-days-between-two-dates,814,1214637.0,36.0,,,2010-01-11 08:06:57,2024-09-02 11:03:36,2019-06-24 20:26:06,,,php;datetime,PHP Ferrari,15744,233679,registered,true,2040589,,CC BY-SA 4.0,2019-12-31 10:50:03,63,56,0,0,0,2,true,false,false,true,true,true,44,8,false,0.03,0.0007,6158,2010,1,8,Monday,false,false,false,false,false,false,true
6054033,Pretty-Printing JSON with PHP,"I'm building a PHP script that feeds JSON data to another script. My script builds data into a large associative array, and then outputs the data using json_encode. Here is an example script:
$data = array('a' => 'apple', 'b' => 'banana', 'c' => 'catnip');
header('Content-type: text/javascript');
echo json_encode($data);
The above code yields the following output:
{""a"":""apple"",""b"":""banana"",""c"":""catnip""}
This is great if you have a small amount of data, but I'd prefer something along these lines:
{
""a"": ""apple"",
""b"": ""banana"",
""c"": ""catnip""
}
Is there a way to do this in PHP without an ugly hack? It seems like someone at Facebook figured it out.
",https://stackoverflow.com/questions/6054033/pretty-printing-json-with-php,813,910281.0,27.0,,,2011-05-19 05:08:29,2023-04-04 08:02:14,2016-06-29 04:04:13,,,php;json;pretty-print,Zach Rattner,21487,371408,registered,true,9120871,,CC BY-SA 3.0,2017-07-18 12:25:26,867,684,4,1,0,3,true,false,false,true,true,true,29,4,false,0.03,0.0009,5665,2011,5,5,Thursday,false,false,false,false,false,false,true
49432735,Converting a Postman request to curl,"I am calling my Java webservice (POST request) via Postman in the following manner which works perfectly fine (i.e. I can see my records getting inserted into the database):
And, here's how the contents inside the Headers(1) tab look like:
Instead of calling it via Postman, I have to call the same request in PHP using cURL. I am wondering if there's a way to export this command to a curl command so that I could use it in my PHP code? I have found the opposite approach at many places online where someone is asking to convert a curl based request to Postman but couldn't figure out how to do the opposite.
I found this question for curl to Postman: Simulate a specific CURL in PostMan
",https://stackoverflow.com/questions/49432735/converting-a-postman-request-to-curl,812,845852.0,10.0,,,2018-03-22 15:36:35,2024-09-02 11:41:42,2023-05-12 22:09:38,,,php;curl;postman,Coder,8221,9520405,registered,true,49433083,,CC BY-SA 4.0,2022-10-27 17:12:06,1140,691,2,3,2,3,true,false,false,true,true,true,36,6,false,0.012,0.001,3166,2018,3,15,Thursday,false,false,false,false,false,false,true
4483540,Show a number to two decimal places,"What's the correct way to round a PHP string to two decimal places?
$number = ""520""; // It's a string from a database
$formatted_number = round_to_2dp($number);
echo $formatted_number;
The output should be 520.00;
How should the round_to_2dp() function definition be?
",https://stackoverflow.com/questions/4483540/show-a-number-to-two-decimal-places,807,1947639.0,24.0,,,2010-12-19 15:10:30,2023-08-27 23:34:19,2019-09-07 20:16:08,,,php;formatting;numbers;rounding;number-formatting,Rich Bradshaw,73401,16511,registered,true,4483561,,CC BY-SA 4.0,2017-04-03 09:41:56,345,274,3,0,0,5,true,false,false,true,true,true,35,7,false,0.012,0.0004,5816,2010,12,15,Sunday,true,false,false,false,false,false,true
11321491,"When to use single quotes, double quotes, and backticks in MySQL","I am trying to learn the best way to write queries. I also understand the importance of being consistent. Until now, I have randomly used single quotes, double quotes, and backticks without any real thought.
Example:
$query = 'INSERT INTO table (id, col1, col2) VALUES (NULL, val1, val2)';
Also, in the above example, consider that table, col1, val1, etc. may be variables.
What is the standard for this? What do you do?
",https://stackoverflow.com/questions/11321491/when-to-use-single-quotes-double-quotes-and-backticks-in-mysql,806,345084.0,13.0,,,2012-07-04 01:53:36,2025-12-01 17:22:07,2025-12-01 17:00:06,,,php;sql;mysql;quotes,Nate,29542,1101095,registered,true,11321508,,CC BY-SA 4.0,2015-10-05 08:58:33,551,422,4,0,0,4,true,false,false,true,true,true,64,11,false,0.038,0.0023,5253,2012,7,1,Wednesday,false,false,false,false,false,true,true
5741187,SQL injection that gets around mysql_real_escape_string(),"Is there an SQL injection possibility even when using mysql_real_escape_string() function?
Consider this sample situation. SQL is constructed in PHP like this:
$login = mysql_real_escape_string(GetFromPost('login'));
$password = mysql_real_escape_string(GetFromPost('password'));
$sql = ""SELECT * FROM table WHERE login='$login' AND password='$password'"";
I have heard numerous people say to me that code like that is still dangerous and possible to hack even with mysql_real_escape_string() function used. But I cannot think of any possible exploit?
Classic injections like this:
aaa' OR 1=1 --
do not work.
Do you know of any possible injection that would get through the PHP code above?
",https://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string,799,328877.0,4.0,,,2011-04-21 07:56:11,2020-09-30 07:55:26,2019-06-04 09:43:12,,,php;mysql;sql;security;sql-injection,Richard Knop,84401,95944,registered,true,5741264,,CC BY-SA 4.0,2015-10-05 09:21:43,816,700,4,0,0,5,true,false,false,true,true,true,57,6,false,0.012,0.0024,5693,2011,4,7,Thursday,false,false,false,false,false,true,true
367711,What is the best collation to use for MySQL with PHP?,"Is there a collation type which is officially recommended by MySQL, for a general website where you aren't 100% sure of what will be entered? I understand that all the encodings should be the same, such as MySQL, Apache, the HTML and anything inside PHP.
In the past I have set PHP to output in "UTF-8", but which collation does this match in MySQL? I'm thinking it's one of the UTF-8 ones, but I have used utf8_unicode_ci, utf8_general_ci, and utf8_bin before, and I do not know which of these "utf8" maps to, or if that is the best to use.
",https://stackoverflow.com/questions/367711/what-is-the-best-collation-to-use-for-mysql-with-php,798,500326.0,11.0,,,2008-12-15 07:48:36,2023-03-12 17:59:26,2023-03-12 17:59:26,2015-10-12 19:47:03,Opinion-based,php;mysql;encoding;collation,Darryl Hein,145615,5441,registered,true,367725,,,2017-08-04 18:33:14,615,562,3,0,0,4,true,true,false,true,true,true,53,11,true,0.022,0.0016,6550,2008,12,7,Monday,false,false,false,false,false,false,true
23740548,How do I pass variables and data from PHP to JavaScript?,"I have a variable in PHP, and I need its value in my JavaScript code. How can I get my variable from PHP to JavaScript?
I have code that looks like this:
<?php
// Makes an API and database call
$val = $myService->getValue();
On the same page, I have JavaScript code that needs the value of the $val variable to be passed as a parameter:
<script>
// I tried this, but it didn't work
myPlugin.start($val);
// This didn't work either
<?php myPlugin.start($val); ?>
// This works sometimes, but sometimes it fails
myPlugin.start(<?=$val?>);
</script>
",https://stackoverflow.com/questions/23740548/how-do-i-pass-variables-and-data-from-php-to-javascript,796,1056097.0,21.0,,,2014-05-19 14:37:56,2026-01-20 21:59:29,2026-01-20 21:45:47,,,javascript;php,Madara's Ghost,175799,871050,registered,true,23740549,,CC BY-SA 4.0,2014-05-21 13:32:33,760,603,3,0,0,2,true,false,false,true,true,true,56,11,true,0.02,0.0008,4569,2014,5,14,Monday,false,false,true,false,false,false,true
2109325,How do I strip all spaces out of a string in PHP?,"How can I strip / remove all spaces of a string in PHP?
I have a string like $string = ""this is my string"";
The output should be ""thisismystring""
How can I do that?
",https://stackoverflow.com/questions/2109325/how-do-i-strip-all-spaces-out-of-a-string-in-php,793,1603920.0,4.0,,,2010-01-21 13:02:35,2020-01-31 06:44:05,2019-07-03 23:55:25,2020-01-31 06:44:05,Duplicate,php;string;spaces,streetparade,33099,179235,registered,true,2109339,,,,308,169,2,0,0,3,true,true,false,true,true,true,49,12,true,0.002,0.0005,6148,2010,1,13,Thursday,false,false,false,false,false,false,true
2447791,PHP | define() vs. const,"In PHP, you can declare constants in two ways:
With define keyword
define('FOO', 1);
Using const keyword
const FOO = 1;
- What are the main differences between those two?
- When and why should you use one and when use the other?
",https://stackoverflow.com/questions/2447791/php-define-vs-const,786,275835.0,9.0,,,2010-03-15 14:23:57,2022-10-06 11:23:27,2022-10-06 11:23:27,,,php;constants;psr-1;psr-12,danjarvis,10260,191201,registered,true,3193704,,CC BY-SA 4.0,2013-12-09 19:33:15,389,234,4,0,0,4,true,false,false,true,true,true,24,5,false,0.033,0.0028,6095,2010,3,14,Monday,false,false,false,false,false,false,true
1795025,What are the differences in die() and exit() in PHP?,"What are the differences between die() and exit() functions in PHP?
I think both have the same functionality, but I doubt there is something different in both... what is it?
",https://stackoverflow.com/questions/1795025/what-are-the-differences-in-die-and-exit-in-php,783,328809.0,15.0,,,2009-11-25 06:28:07,2025-09-02 05:56:53,2019-01-12 09:57:34,,,php;exit;die,coderex,28141,110976,registered,true,,,CC BY-SA 4.0,2012-12-21 15:03:07,215,175,2,0,0,3,false,false,false,true,true,true,52,10,true,0.046,0.0024,6205,2009,11,6,Wednesday,false,false,false,false,false,false,true
18050071,PHP parse/syntax errors; and how to solve them,"Everyone runs into syntax errors. Even experienced programmers make typos. For newcomers, it's just part of the learning process. However, it's often easy to interpret error messages such as:
PHP Parse error: syntax error, unexpected '{' in index.php on line 20
The unexpected symbol isn't always the real culprit. But the line number gives a rough idea of where to start looking.
Always look at the code context. The syntax mistake often hides in the mentioned or in previous code lines. Compare your code against syntax examples from the manual.
While not every case matches the other. Yet there are some general steps to solve syntax mistakes.
This references summarized the common pitfalls:
-
-
Unexpected T_CONSTANT_ENCAPSED_STRING
Unexpected T_ENCAPSED_AND_WHITESPACE
-
-
-
-
-
-
-
Unexpected continue (T_CONTINUE)
Unexpected continue (T_BREAK)
Unexpected continue (T_RETURN)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Unexpected , (comma)
Unpexected . (period)
Unexpected ; (semicolon)
Unexpected * (asterisk)
Unexpected : (colon)
-
Unexpected & (call-time pass-by-reference)
-
Closely related references:
- What does this error mean in PHP? (runtime errors)
- What does this symbol mean in PHP? (language tokens)
- Those
“” smart ‘’ quotes mean nothing to PHP
And:
- The PHP manual on php.net and its various language tokens
- Or Wikipedia's syntax introduction on PHP.
- And lastly our php tag-wiki of course.
While Stack Overflow is also welcom",https://stackoverflow.com/questions/18050071/php-parse-syntax-errors-and-how-to-solve-them,783,909957.0,21.0,,,2013-08-05 03:11:15,2026-04-30 15:25:18,2021-01-02 13:57:55,,,php;parsing;debugging;syntax-error,mario,145851,345031,registered,true,18050072,,CC BY-SA 4.0,2015-02-10 11:15:24,9306,3558,18,50,0,4,true,false,false,true,true,true,46,8,false,0.023,0.0009,4856,2013,8,3,Monday,false,false,false,false,false,false,true
2303372,Create a folder if it doesn't already exist,"
I've run into a few cases with WordPress installs with Bluehost where I've encountered errors with my WordPress theme because the uploads folder wp-content/uploads was not present.
Apparently the Bluehost cPanel WordPress installer does not create this folder, though HostGator does.
So I need to add code to my theme that checks for the folder and creates it otherwise.
",https://stackoverflow.com/questions/2303372/create-a-folder-if-it-doesnt-already-exist,781,910431.0,22.0,,,2010-02-20 19:26:09,2025-12-11 01:43:41,2019-11-24 00:45:42,,,php;wordpress;directory,Scott B,40635,209102,registered,true,2303377,,CC BY-SA 4.0,2015-06-05 13:59:50,616,373,1,3,0,3,true,false,false,true,true,true,47,8,false,0.024,0.0009,6118,2010,2,19,Saturday,true,false,false,false,false,false,true
1699958,Formatting a number with leading zeros in PHP,"I have a variable which contains the value 1234567.
I would like it to contain exactly 8 digits, i.e. 01234567.
Is there a PHP function for that?
",https://stackoverflow.com/questions/1699958/formatting-a-number-with-leading-zeros-in-php,752,801119.0,11.0,,,2009-11-09 09:25:01,2019-10-11 08:40:30,2017-08-10 04:00:44,2020-06-19 03:48:26,Duplicate,php;numbers;format,Andromeda,12927,120330,registered,true,1699980,,,2020-08-19 12:02:35,195,148,2,0,0,3,true,true,false,true,true,true,45,8,false,0.014,0.0009,6221,2009,11,9,Monday,false,false,false,false,false,false,true
134099,Are PDO prepared statements sufficient to prevent SQL injection?,"Let's say I have code like this:
$dbh = new PDO(""blahblah"");
$stmt = $dbh->prepare('SELECT * FROM users where username = :username');
$stmt->execute( array(':username' => $_REQUEST['username']) );
The PDO documentation says:
The parameters to prepared statements don't need to be quoted; the driver handles it for you.
Is that truly all I need to do to avoid SQL injections? Is it really that easy?
You can assume MySQL if it makes a difference. Also, I'm really only curious about the use of prepared statements against SQL injection. In this context, I don't care about XSS or other possible vulnerabilities.
",https://stackoverflow.com/questions/134099/are-pdo-prepared-statements-sufficient-to-prevent-sql-injection,747,269642.0,7.0,,,2008-09-25 15:43:35,2024-12-04 15:16:09,2014-06-22 17:15:47,,,php;security;pdo;sql-injection,Mark Biek,152519,305,registered,true,12202218,,CC BY-SA 3.0,2014-02-21 04:36:21,735,634,1,0,0,4,true,false,false,true,true,true,64,9,true,0.026,0.0028,6631,2008,9,15,Thursday,false,false,false,false,false,false,true
6815520,Error "Cannot use object of type stdClass as array","I get a strange error using json_decode(). It decodes the data correctly (I saw it using print_r), but when I try to access to information inside the array I get:
Fatal error: Cannot use object of type stdClass as array in
C:\Users\Dail\software\abs.php on line 108
I only tried to do: $result['context'] where $result has the data returned by json_decode()
How can I read values inside this array?
",https://stackoverflow.com/questions/6815520/error-cannot-use-object-of-type-stdclass-as-array,738,1091496.0,17.0,,,2011-07-25 11:40:14,2023-04-20 21:38:13,2023-04-20 20:45:33,,,php;json,Dail,7389,861417,unregistered,true,,,CC BY-SA 4.0,2018-10-03 15:05:42,549,400,6,0,0,2,false,false,false,true,true,true,61,9,false,0.016,0.0007,5598,2011,7,11,Monday,false,false,false,false,false,false,true
53828891,dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac,"I installed node using homebrew (Mojave), afterwards php stoped working and if I try to run php -v I get this error:
php -v
dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib
Referenced from: /usr/local/bin/php
Reason: image not found
I tried to uninstall both node and icu4c but the problem persists
",https://stackoverflow.com/questions/53828891/dyld-library-not-loaded-usr-local-opt-icu4c-lib-libicui18n-62-dylib-error-run,728,546435.0,48.0,,,2018-12-18 08:20:21,2025-11-05 19:12:44,2019-07-14 12:33:37,,,php;node.js;macos;homebrew,petekaner,9011,2882899,registered,true,54873233,,CC BY-SA 4.0,2023-12-20 11:39:27,379,328,2,0,0,4,true,false,false,true,true,true,127,15,false,0.088,0.0013,2895,2018,12,8,Tuesday,false,false,false,false,false,false,true
2790899,How to check if a string starts with a specified string?,"I'm trying to check if a string starts with http. How can I do this check?
$string1 = 'google.com';
$string2 = 'http://www.google.com';
",https://stackoverflow.com/questions/2790899/how-to-check-if-a-string-starts-with-a-specified-string,721,964320.0,5.0,,,2010-05-07 18:43:37,2020-11-27 10:23:24,2016-10-25 10:48:26,2014-11-20 13:08:32,Duplicate,php,Andrew,241827,48523,registered,true,2790919,,,,182,138,2,0,0,1,true,true,false,true,true,true,56,11,true,0.005,0.0007,6042,2010,5,18,Friday,false,false,false,false,false,false,true
40914114,How to install a specific version of package using Composer?,"I am trying to install a specific version of a package using Composer. I tried composer install and composer require but they are installing the latest version of the package. What if I want an older version?
",https://stackoverflow.com/questions/40914114/how-to-install-a-specific-version-of-package-using-composer,714,873446.0,7.0,,,2016-12-01 15:12:54,2022-11-26 09:03:13,2018-06-11 16:43:13,,,php;composer-php;dependency-management,gdaras,10304,6082275,registered,true,41703068,,CC BY-SA 4.0,,242,209,2,0,0,3,true,false,false,true,true,true,60,10,true,0.008,0.0008,3642,2016,12,15,Thursday,false,false,false,false,false,false,true
23126562,How can I remove a package from Laravel using PHP Composer?,"What is the correct way to remove a package from Laravel using PHP Composer?
So far I've tried:
- Remove declaration from file composer.json (in the "require" section)
- Remove any class aliases from file app.php
- Remove any references to the package from my code :-)
- Run
composer update
- Run
composer dump-autoload
None of these options are working! What am I missing?
",https://stackoverflow.com/questions/23126562/how-can-i-remove-a-package-from-laravel-using-php-composer,702,1268179.0,20.0,,,2014-04-17 06:59:26,2025-04-07 14:00:12,2023-10-23 15:12:08,,,php;laravel;composer-php;uninstallation;package-managers,igaster,13753,1680535,registered,true,27440198,,CC BY-SA 4.0,2022-05-06 19:30:33,504,376,2,0,0,5,true,false,false,true,true,true,59,11,true,0.016,0.0006,4601,2014,4,6,Thursday,false,false,false,false,false,false,true
4282413,Sort array of objects by one property,"How can I sort this array of objects by one of its fields, like name or count?
Array
(
[0] => stdClass Object
(
[ID] => 1
[name] => Mary Jane
[count] => 420
)
[1] => stdClass Object
(
[ID] => 2
[name] => Johnny
[count] => 234
)
[2] => stdClass Object
(
[ID] => 3
[name] => Kathy
[count] => 4354
)
....
",https://stackoverflow.com/questions/4282413/sort-array-of-objects-by-one-property,696,575422.0,23.0,,,2010-11-26 03:50:56,2024-08-18 06:33:07,2022-07-02 00:18:51,,,php;arrays;sorting;object;multidimensional-array,Alex,66826,376947,registered,true,4282423,,CC BY-SA 4.0,2013-12-17 17:25:12,570,513,3,0,0,5,true,false,false,true,true,true,37,7,false,0.04,0.0012,5839,2010,11,3,Friday,false,false,false,false,false,false,true
139474,How can I capture the result of var_dump to a string?,"I'd like to capture the output of var_dump to a string.
The PHP documentation says;
As with anything that outputs its result directly to the browser, the output-control functions can be used to capture the output of this function, and save it in a string (for example).
What would be an example of how that might work?
print_r() isn't a valid possibility, because it's not going to give me the information that I need.
",https://stackoverflow.com/questions/139474/how-can-i-capture-the-result-of-var-dump-to-a-string,695,456066.0,15.0,,,2008-09-26 13:23:02,2024-10-06 15:48:43,2023-11-17 20:42:18,,,php;string;var-dump,Mark Biek,152519,305,registered,true,139491,,CC BY-SA 4.0,,670,421,2,2,0,3,true,false,false,true,true,true,53,11,true,0.033,0.0015,6630,2008,9,13,Friday,false,false,false,false,false,false,true
141108,How can I find the foreach index?,"Is it possible to find the foreach index in a for loop as follows?
for ($i = 0; $i < 10; ++$i) {
echo $i . ' ';
}
$i will give you the index.
Do I have to use the for loop or is there some way to get the index in the foreach loop?
",https://stackoverflow.com/questions/141108/how-can-i-find-the-foreach-index,672,1084601.0,14.0,,,2008-09-26 18:23:15,2026-08-01 20:35:40,2026-08-01 19:41:30,,,php;loops;foreach,user18334,6813,18334,registered,true,141114,,CC BY-SA 4.0,2017-03-03 20:07:04,336,238,3,0,0,3,true,false,false,true,true,true,33,7,true,0.013,0.0006,6630,2008,9,18,Friday,false,false,false,false,false,false,true
804045,Preferred method to store PHP arrays (json_encode vs serialize),"I need to store a multi-dimensional associative array of data in a flat file for caching purposes. I might occasionally come across the need to convert it to JSON for use in my web app but the vast majority of the time I will be using the array directly in PHP.
Would it be more efficient to store the array as JSON or as a PHP serialized array in this text file? I've looked around and it seems that in the newest versions of PHP (5.3), json_decode is actually faster than unserialize.
I'm currently leaning towards storing the array as JSON as I feel its easier to read by a human if necessary, it can be used in both PHP and JavaScript with very little effort, and from what I've read, it might even be faster to decode (not sure about encoding, though).
Does anyone know of any pitfalls? Anyone have good benchmarks to show the performance benefits of either method?
",https://stackoverflow.com/questions/804045/preferred-method-to-store-php-arrays-json-encode-vs-serialize,672,241844.0,21.0,,,2009-04-29 20:09:43,2024-04-28 18:20:56,2015-03-06 22:58:23,,,php;performance;arrays;json;serialization,KyleFarris,17618,83304,registered,true,804089,,CC BY-SA 3.0,2013-06-23 10:19:36,928,874,2,0,0,5,true,false,false,true,true,true,63,9,false,0.087,0.0028,6415,2009,4,20,Wednesday,false,false,false,false,false,false,true
676677,How can I add elements to an array in PHP?,"If I define an array in PHP such as:
$cart = array();
Do I simply add elements to it using the following?
$cart[] = 13;
$cart[] = "foo";
$cart[] = obj;
Don't arrays in PHP have an add method, for example, cart.add(13)?
",https://stackoverflow.com/questions/676677/how-can-i-add-elements-to-an-array-in-php,671,1544519.0,9.0,,,2009-03-24 09:35:00,2026-09-08 19:57:59,2026-09-08 19:57:59,,,php;arrays,AquinasTub,8625,78026,unregistered,true,676703,,CC BY-SA 4.0,,389,231,3,0,0,2,true,false,false,true,true,true,42,10,true,0.006,0.0004,6451,2009,3,9,Tuesday,false,false,false,false,false,false,true
1532618,Is there a function to make a copy of a PHP array to another?,"Is there a function to make a copy of a PHP array to another?
I have been burned a few times trying to copy PHP arrays. I want to copy an array defined inside an object to a global outside it.
",https://stackoverflow.com/questions/1532618/is-there-a-function-to-make-a-copy-of-a-php-array-to-another,669,608220.0,19.0,,,2009-10-07 16:11:50,2023-01-11 23:11:56,2013-07-21 01:23:13,,,php;arrays;copy,vfclists,20621,172406,registered,true,1533214,,CC BY-SA 3.0,2022-02-24 05:41:13,208,194,0,0,0,3,true,false,false,true,true,true,61,14,true,0.031,0.0011,6254,2009,10,16,Wednesday,false,false,false,false,false,false,true
592322,PHP expects T_PAAMAYIM_NEKUDOTAYIM?,"Does anyone have a T_PAAMAYIM_NEKUDOTAYIM?
",https://stackoverflow.com/questions/592322/php-expects-t-paamayim-nekudotayim,659,203518.0,11.0,,,2009-02-26 20:34:52,2024-10-15 10:23:41,2022-04-11 23:17:38,,,php;runtime-error;syntax-error;error-code,Peter Turner,11445,1765,registered,true,592326,,CC BY-SA 4.0,2022-04-12 00:49:18,63,43,1,0,0,4,true,false,false,true,true,true,35,3,true,0.054,0.0032,6477,2009,2,20,Thursday,false,false,false,false,false,false,true
845021,How can I get useful error messages in PHP?,"Quite often I will try and run a PHP script and just get a blank screen back. No error message; just an empty screen. The cause might have been a simple syntax error (wrong bracket, missing semicolon), or a failed function call, or something else entirely.
It is very difficult to figure out what went wrong. I end up commenting out code, entering ""echo"" statements everywhere, etc. trying to narrow down the problem. But there surely must be a better way, right?
Is there a way to get PHP to produce a useful error message, like Java does?
",https://stackoverflow.com/questions/845021/how-can-i-get-useful-error-messages-in-php,658,753945.0,41.0,,,2009-05-10 09:48:12,2023-08-16 07:17:34,2019-11-19 18:58:45,,,php;debugging;error-handling,Candidasa,8740,5010,registered,true,845025,,CC BY-SA 4.0,2015-10-05 09:00:00,564,543,0,0,0,3,true,false,false,true,true,true,43,9,true,0.054,0.0009,6404,2009,5,9,Sunday,true,false,false,false,false,false,true
1035634,Converting an integer to a string in PHP,"Is there a way to convert an integer to a string in PHP?
",https://stackoverflow.com/questions/1035634/converting-an-integer-to-a-string-in-php,653,1753047.0,15.0,,,2009-06-23 22:37:45,2022-06-03 18:34:58,2019-06-24 21:41:28,,,php;string;casting;type-conversion;integer,kman99,7705,127896,registered,true,1035658,,CC BY-SA 4.0,,64,57,0,0,0,5,true,false,false,true,true,true,40,8,false,0.009,0.0004,6360,2009,6,22,Tuesday,false,false,false,false,false,false,true
2216052,How to check whether an array is empty using PHP?,"players will either be empty or a comma separated list (or a single value). What is the easiest way to check if it's empty? I'm assuming I can do so as soon as I fetch the $gameresult array into $gamerow? In this case it would probably be more efficient to skip exploding the $playerlist if it's empty, but for the sake of argument, how would I check if an array is empty as well?
$gamerow = mysql_fetch_array($gameresult);
$playerlist = explode(",", $gamerow['players']);
",https://stackoverflow.com/questions/2216052/how-to-check-whether-an-array-is-empty-using-php,645,1345741.0,18.0,,,2010-02-07 05:30:02,2024-08-02 07:09:06,2024-08-02 07:09:06,,,php;arrays;is-empty,aslum,12364,248547,registered,true,2216063,,CC BY-SA 4.0,2016-05-30 10:41:12,568,485,5,0,0,3,true,false,false,true,true,true,49,10,true,0.013,0.0005,6131,2010,2,5,Sunday,true,false,false,false,false,false,true
1032161,What is the use of the @ symbol in PHP?,"I have seen uses of @ in front of certain functions, like the following:
$fileHandle = @fopen($fileName, $writeAttributes);
What is the use of this symbol?
",https://stackoverflow.com/questions/1032161/what-is-the-use-of-the-symbol-in-php,644,273929.0,11.0,,,2009-06-23 12:08:32,2023-12-27 09:49:59,2015-12-06 11:32:06,,,php;operators;error-suppression,sv_in,14047,22550,registered,true,14520316,,CC BY-SA 3.0,2016-10-06 05:41:25,210,159,2,0,0,3,true,false,false,true,true,true,39,10,true,0.04,0.0024,6360,2009,6,12,Tuesday,false,false,false,false,false,false,true
920353,Can I bind an array to an IN() condition in a PDO query?,"I'm curious to know if it's possible to bind an array of values to a placeholder using PDO. The use case here is attempting to pass an array of values for use with an IN() condition.
I'd like to be able to do something like this:
<?php
$ids=array(1,2,3,7,8,9);
$db = new PDO(...);
$stmt = $db->prepare(
'SELECT *
FROM table
WHERE id IN(:an_array)'
);
$stmt->bindParam('an_array',$ids);
$stmt->execute();
?>
And have PDO bind and quote all the values in the array.
At the moment I'm doing:
<?php
$ids = array(1,2,3,7,8,9);
$db = new PDO(...);
foreach($ids as &$val)
$val=$db->quote($val); //iterate through array and quote
$in = implode(',',$ids); //create comma separated list
$stmt = $db->prepare(
'SELECT *
FROM table
WHERE id IN('.$in.')'
);
$stmt->execute();
?>
Which certainly does the job, but just wondering if there's a built in solution I'm missing?
",https://stackoverflow.com/questions/920353/can-i-bind-an-array-to-an-in-condition-in-a-pdo-query,644,259098.0,24.0,,,2009-05-28 11:17:57,2024-07-30 14:07:18,2022-04-02 14:06:54,,,php;arrays;pdo;prepared-statement;where-in,Andru,7171,113659,registered,true,,,CC BY-SA 4.0,2015-06-17 08:44:03,1032,936,3,0,0,5,false,false,false,true,true,true,56,13,true,0.093,0.0025,6386,2009,5,11,Thursday,false,false,false,false,false,false,true
2138527,"PHP, cURL, and HTTP POST example?","Can anyone show me how to do a PHP cURL with an HTTP POST?
I want to send data like this:
username=user1, password=passuser1, gender=1
To www.example.com
I expect the cURL to return a response like result=OK. Are there any examples?
",https://stackoverflow.com/questions/2138527/php-curl-and-http-post-example,643,1723280.0,16.0,,,2010-01-26 09:39:35,2025-04-12 09:03:48,2022-01-16 22:38:19,,,php;http;curl;http-post,mysqllearner,13983,213568,unregistered,true,2138534,,CC BY-SA 4.0,2016-05-06 20:50:42,313,235,3,0,0,4,true,false,false,true,true,true,33,6,true,0.009,0.0004,6143,2010,1,9,Tuesday,false,false,false,false,false,false,true
6243051,How to pass an array within a query string?,"Is there a standard way of passing an array through a query string?
To be clear, I have a query string with multiple values, one of which would be an array value. I want that query string value to be treated as an array- I don't want the array to be exploded so that it is indistinguishable from the other query string variables.
Also, according to this post answer, the author suggests that query string support for arrays is not defined. Is this accurate?
EDIT:
Based on @Alex's answer, there is no standard way of doing this, so my follow-up is then what is an easy way to recognize that the parameter I'm reading is an array in both PHP and Javascript?
Would it be acceptable to name multiple params the same name, and that way I would know that they belong to an array? Example:
?myarray=value1&myarray=value2&myarray=value3...
Or would this be a bad practice?
",https://stackoverflow.com/questions/6243051/how-to-pass-an-array-within-a-query-string,642,1259900.0,11.0,,,2011-06-05 13:03:27,2025-08-19 14:41:48,2021-04-30 15:30:19,,,php;arrays;query-string;querystringparameter,Yarin,186649,165673,registered,true,9547490,,CC BY-SA 4.0,2025-08-19 15:56:59,1121,877,1,1,0,4,true,false,false,true,true,true,43,9,true,0.009,0.0005,5648,2011,6,13,Sunday,true,false,false,false,false,false,true
3797239,Insert new item in array on any position in PHP,"How can I insert a new item into an array on any position, for example in the middle of array?
",https://stackoverflow.com/questions/3797239/insert-new-item-in-array-on-any-position-in-php,639,591958.0,23.0,,,2010-09-26 09:39:22,2023-07-19 09:45:38,2013-02-19 12:27:13,,,php;arrays;insert,kusanagi,14634,276640,registered,true,3797526,,CC BY-SA 3.0,2017-03-03 20:03:53,102,95,0,0,0,3,true,false,false,true,true,true,47,10,false,0.039,0.0011,5900,2010,9,9,Sunday,true,false,false,false,false,false,true
1070244,PHP How to determine the first and last iteration in a foreach loop?,"The question is simple. I have a foreach loop in my code:
foreach($array as $element) {
//code
}
In this loop, I want to react differently when we are in first or last iteration.
How to do this?
",https://stackoverflow.com/questions/1070244/php-how-to-determine-the-first-and-last-iteration-in-a-foreach-loop,630,798477.0,22.0,,,2009-07-01 16:57:59,2025-06-10 17:19:41,2022-04-16 05:35:30,,,php;loops;foreach,mehdi,9552,111279,registered,true,1070256,,CC BY-SA 4.0,2015-06-23 16:43:31,261,203,2,0,0,3,true,false,false,true,true,true,68,13,true,0.028,0.0008,6352,2009,7,16,Wednesday,false,false,false,false,false,false,true
28290332,How to create custom helper functions in Laravel,"I would like to create helper functions to avoid repeating code between views in Laravel. For example:
view.blade.php
<p>Foo Formated text: {{ fooFormatText($text) }}</p>
They're basically text formatting functions. How should I define globally available helper functions like fooFormatText()?
",https://stackoverflow.com/questions/28290332/how-to-create-custom-helper-functions-in-laravel,622,434936.0,24.0,,,2015-02-03 02:25:12,2025-01-30 08:02:34,2023-03-28 16:47:39,,,php;laravel;laravel-8;laravel-blade;laravel-helper,Calebe Oliveira,6331,1604223,registered,true,28290359,,CC BY-SA 4.0,2021-12-26 22:22:55,374,307,2,0,0,5,true,false,false,true,true,true,48,8,false,0.055,0.0014,4309,2015,2,2,Tuesday,false,false,false,false,false,false,true
1597736,Sort an array of associative arrays by column value,"Given this array:
$inventory = array(
array(""type""=>""fruit"", ""price""=>3.50),
array(""type""=>""milk"", ""price""=>2.90),
array(""type""=>""pork"", ""price""=>5.43),
);
I would like to sort $inventory's elements by price to get:
$inventory = array(
array(""type""=>""pork"", ""price""=>5.43),
array(""type""=>""fruit"", ""price""=>3.50),
array(""type""=>""milk"", ""price""=>2.90),
);
How can I do this?
",https://stackoverflow.com/questions/1597736/sort-an-array-of-associative-arrays-by-column-value,620,779033.0,23.0,,,2009-10-20 22:47:26,2024-09-28 21:54:01,2023-02-08 22:43:11,,,php;arrays;sorting;multidimensional-array,Matt,23181,145435,registered,true,1598385,,CC BY-SA 4.0,,519,437,3,0,0,4,true,false,false,true,true,true,51,9,false,0.03,0.0008,6241,2009,10,22,Tuesday,false,false,false,false,false,false,true
46483,htmlentities() vs. htmlspecialchars(),"What are the differences between htmlspecialchars() and htmlentities(). When should I use one or the other?
",https://stackoverflow.com/questions/46483/htmlentities-vs-htmlspecialchars,616,377144.0,11.0,,,2008-09-05 18:29:12,2019-04-28 07:26:09,2013-09-08 11:02:18,,,php,Eric Hogue,8980,4137,registered,true,46491,,CC BY-SA 3.0,2012-03-03 20:50:53,141,108,2,0,0,1,true,false,false,true,true,true,37,3,false,0.029,0.0016,6651,2008,9,18,Friday,false,false,false,false,false,false,true
13246597,How to read a large file line by line?,"I want to read a file line by line, but without completely loading it in memory.
My file is too large to open in memory, and if try to do so I always get out of memory errors.
The file size is 1 GB.
",https://stackoverflow.com/questions/13246597/how-to-read-a-large-file-line-by-line,615,879360.0,14.0,,,2012-11-06 07:49:10,2026-03-01 22:22:52,2019-01-16 13:32:28,,,php,adnan masood,6275,1799853,registered,true,,,CC BY-SA 4.0,,222,201,0,0,0,1,false,false,false,true,true,true,38,9,true,0.016,0.0007,5128,2012,11,7,Tuesday,false,false,false,false,false,false,true
2184513,Change the maximum upload file size,"I have a website hosted on a PC I have no access to. I have an upload form allowing people to upload mp3 files up to 30MB big. My server side script is done in PHP.
Every time I try and upload a file, I receive an error claiming that the file exceeds the maximum size allowed, so I need to increase the size. My research on the web suggested changing the .htaccess file which I do not have access to, so that won't work. Others suggested that I should add a custom php.ini file to my root which did not work. Any other suggestions?
",https://stackoverflow.com/questions/2184513/change-the-maximum-upload-file-size,612,1436208.0,24.0,,,2010-02-02 14:00:46,2022-12-13 10:11:11,2017-10-13 12:58:24,,,php,Yo Momma,8817,220007,registered,true,2184541,,CC BY-SA 3.0,2013-09-27 15:20:01,573,533,2,0,0,1,true,false,false,true,true,true,35,6,false,0.017,0.0004,6136,2010,2,14,Tuesday,false,false,false,false,false,false,true
277224,How do I catch a PHP fatal (`E_ERROR`) error?,"I can use set_error_handler() to catch most PHP errors, but it doesn't work for fatal (E_ERROR) errors, such as calling a function that doesn't exist. Is there another way to catch these errors?
I am trying to call mail() for all errors and am running PHP 5.2.3.
",https://stackoverflow.com/questions/277224/how-do-i-catch-a-php-fatal-e-error-error,606,440459.0,18.0,,,2008-11-10 06:42:27,2021-06-26 20:56:58,2020-04-21 01:22:54,,,php;fatal-error,too much php,91760,28835,registered,true,,,CC BY-SA 4.0,2014-01-15 06:40:15,317,264,3,0,0,2,false,false,false,true,true,true,45,9,true,0.041,0.0014,6585,2008,11,6,Monday,false,false,false,false,false,false,true
5197300,New self vs. new static,"I am converting a PHP 5.3 library to work on PHP 5.2. The main thing standing in my way is the use of late static binding like return new static($options); , if I convert this to return new self($options) will I get the same results?
What is the difference between new self and new static?
",https://stackoverflow.com/questions/5197300/new-self-vs-new-static,604,270238.0,3.0,,,2011-03-04 17:41:46,2019-12-08 00:28:13,2015-10-10 00:44:49,,,php;static;late-static-binding,Mike,12925,429909,registered,true,5197655,,CC BY-SA 3.0,2014-11-14 08:05:59,357,291,4,0,0,3,true,false,false,true,true,true,23,5,false,0.011,0.0022,5741,2011,3,17,Friday,false,false,false,false,false,false,true
19325312,How to Create Multiple Where Clause Query Using Laravel Eloquent?,"I'm using the Laravel Eloquent query builder and I have a query where I want a WHERE clause on multiple conditions. It works, but it's not elegant.
Example:
$results = User::where('this', '=', 1)
->where('that', '=', 1)
->where('this_too', '=', 1)
->where('that_too', '=', 1)
->where('this_as_well', '=', 1)
->where('that_as_well', '=', 1)
->where('this_one_too', '=', 1)
->where('that_one_too', '=', 1)
->where('this_one_as_well', '=', 1)
->where('that_one_as_well', '=', 1)
->get();
Is there a better way to do this, or should I stick with this method?
",https://stackoverflow.com/questions/19325312/how-to-create-multiple-where-clause-query-using-laravel-eloquent,597,1165930.0,26.0,,,2013-10-11 18:56:44,2025-03-10 05:40:29,2021-12-26 22:29:50,,,php;laravel;eloquent;laravel-query-builder,veksen,6993,1732521,registered,true,27522556,,CC BY-SA 4.0,2021-12-26 22:17:37,726,630,2,0,0,4,true,false,false,true,true,true,65,10,true,0.022,0.0005,4789,2013,10,18,Friday,false,false,false,false,false,false,true
34571330,PHP short-ternary ("Elvis") operator vs null coalescing operator,"Can someone explain the differences between ternary operator shorthand (?:) and null coalescing operator (??) in PHP?
When do they behave differently and when in the same way (if that even happens)?
$a ?: $b
VS.
$a ?? $b
",https://stackoverflow.com/questions/34571330/php-short-ternary-elvis-operator-vs-null-coalescing-operator,595,292591.0,14.0,,,2016-01-02 22:23:40,2024-10-12 23:14:41,2023-02-03 18:11:46,,,php;conditional-operator;null-coalescing-operator;elvis-operator,balping,8088,898783,registered,true,34571460,,CC BY-SA 4.0,,585,223,4,2,0,4,true,false,false,true,true,true,74,8,false,0.048,0.002,3976,2016,1,22,Saturday,true,false,false,false,false,false,true
80646,How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?,"What is the difference between == and ===?
- How exactly does the loosely
== comparison work?
- How exactly does the strict
=== comparison work?
What would be some useful examples?
",https://stackoverflow.com/questions/80646/how-do-the-php-equality-double-equals-and-identity-triple-equals-comp,587,398187.0,12.0,,,2008-09-17 06:56:45,2025-11-22 11:37:26,2023-08-07 07:46:02,,,php;operators,nickf,548426,9021,registered,true,80649,,CC BY-SA 4.0,2014-02-22 09:24:45,272,179,4,0,0,2,true,false,false,true,true,true,104,16,true,0.03,0.0015,6639,2008,9,6,Wednesday,false,false,false,false,false,false,true
2297403,What is the difference between HTTP_HOST and SERVER_NAME in PHP?,"What is the difference between $_SERVER['HTTP_HOST'] and $_SERVER['SERVER_NAME'] in PHP?
When would you consider using one over the other and why?
",https://stackoverflow.com/questions/2297403/what-is-the-difference-between-http-host-and-server-name-in-php,587,486488.0,11.0,,,2010-02-19 15:29:54,2022-10-05 09:17:35,2020-12-14 12:03:20,,,php;apache;server-variables,Emanuil Rusev,35625,200145,registered,true,2297421,,CC BY-SA 4.0,,187,147,2,0,0,3,true,false,false,true,true,true,64,10,true,0.023,0.0012,6119,2010,2,15,Friday,false,false,false,false,false,false,true
2681786,How to get the last char of a string in PHP?,"I need to get the last character of a string.
Say I have ""testers"" as input string and I want the result to be ""s"". how can I do that in PHP?
",https://stackoverflow.com/questions/2681786/how-to-get-the-last-char-of-a-string-in-php,585,639055.0,12.0,,,2010-04-21 09:44:57,2022-06-13 16:57:09,2019-11-30 02:43:58,,,php;string,streetparade,33099,179235,registered,true,2681810,,CC BY-SA 4.0,,149,142,0,0,0,2,true,false,false,true,true,true,44,11,true,0.019,0.0009,6058,2010,4,9,Wednesday,false,false,false,false,false,false,true
1995562,NOW() function in PHP,"Is there a PHP function that returns the date and time in the same format as the MySQL function NOW()?
I know how to do it using date(), but I am asking if there is a function only for this.
For example, to return:
2009-12-01 00:00:00
",https://stackoverflow.com/questions/1995562/now-function-in-php,581,2139283.0,20.0,,,2010-01-03 17:07:18,2022-06-13 07:44:10,2019-07-13 18:03:45,,,php;datetime;time;timestamp,MoeAmine,6106,180685,registered,true,1995565,,CC BY-SA 4.0,2015-12-20 05:57:24,312,241,3,0,0,4,true,false,false,true,true,true,21,4,false,0.009,0.0003,6166,2010,1,17,Sunday,true,false,false,false,false,false,true
3687358,How to get the last element of an array without deleting it?,"Ok,
I know all about array_pop(), but that deletes the last element. How to get the last element of an array without deleting it?
Here's a bonus:
$array = array('a' => 'a', 'b' => 'b', 'c' => 'c');
or even
$array = array('a', 'b', 'c', 'd');
unset($array[2]);
echo $array[sizeof($array) - 1]; // Output: PHP Notice: Undefined offset: 2 in - on line 4
",https://stackoverflow.com/questions/3687358/how-to-get-the-last-element-of-an-array-without-deleting-it,579,580147.0,34.0,,,2010-09-10 18:39:24,2025-07-01 04:12:38,2022-09-16 21:35:59,,,php;arrays,Theodore R. Smith,23635,430062,registered,true,41795859,,CC BY-SA 4.0,2016-05-28 22:32:32,514,365,3,1,0,2,true,false,false,true,true,true,60,12,true,0.059,0.001,5916,2010,9,18,Friday,false,false,false,false,false,false,true
5863870,How should a model be structured in MVC?,"I am just getting a grasp on the MVC framework and I often wonder how much code should go in the model. I tend to have a data access class that has methods like this:
public function CheckUsername($connection, $username)
{
try
{
$data = array();
$data['Username'] = $username;
//// SQL
$sql = ""SELECT Username FROM"" . $this->usersTableName . "" WHERE Username = :Username"";
//// Execute statement
return $this->ExecuteObject($connection, $sql, $data);
}
catch(Exception $e)
{
throw $e;
}
}
My models tend to be an entity class that is mapped to the database table.
Should the model object have all the database mapped properties as well as the code above or is it OK to separate that code out that actually does the database work?
Will I end up having four layers?
",https://stackoverflow.com/questions/5863870/how-should-a-model-be-structured-in-mvc,579,205614.0,5.0,,,2011-05-03 00:28:42,2018-11-21 14:54:48,2014-08-23 18:08:40,2018-11-22 00:32:07,Opinion-based,php;oop;model-view-controller;architecture;model,Dietpixel,10193,734587,registered,true,5864000,,,2013-09-17 23:49:02,909,857,1,0,0,5,true,true,false,true,true,true,40,8,true,0.024,0.0028,5681,2011,5,0,Tuesday,false,false,false,false,false,false,true
24644436,PHP mail function doesn't complete sending of e-mail,"<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: yoursite.com';
$to = 'contact@yoursite.com';
$subject = 'Customer Inquiry';
$body = ""From: $name\n E-Mail: $email\n Message:\n $message"";
if ($_POST['submit']) {
if (mail ($to, $subject, $body, $from)) {
echo '<p>Your message has been sent!</p>';
} else {
echo '<p>Something went wrong, go back and try again!</p>';
}
}
?>
I've tried creating a simple mail form. The form itself is on my index.html page, but it submits to a separate ""thank you for your submission"" page, thankyou.php, where the above PHP code is embedded.
The code submits perfectly, but never sends an email. How can I fix this?
",https://stackoverflow.com/questions/24644436/php-mail-function-doesnt-complete-sending-of-e-mail,575,560602.0,31.0,,,2014-07-09 02:18:55,2025-09-05 14:57:00,2022-04-12 01:04:27,,,php;html;function;email,user3818620,5793,3818620,registered,true,,,CC BY-SA 4.0,2015-10-05 08:58:57,873,816,3,0,0,4,false,false,false,true,true,true,56,8,false,0.055,0.001,4518,2014,7,2,Wednesday,false,false,false,false,false,false,true
13840429,How do client-side and server-side programming interact with each other?,"I have this code:
<script type=""text/javascript"">
var foo = 'bar';
<?php
file_put_contents('foo.txt', ' + foo + ');
?>
var baz = <?php echo 42; ?>;
alert(baz);
</script>
Why does this not write ""bar"" into my text file, but alerts ""42""?
NB: Earlier revisions of this question were explicitly about PHP on the server and JavaScript on the client. The essential nature of the problem and solutions is the same for any pair of languages when one is running on the client and the other on the server (even if they are the same language). Please take this in to account when you see answers talking about specific languages.
",https://stackoverflow.com/questions/13840429/how-do-client-side-and-server-side-programming-interact-with-each-other,575,62137.0,3.0,,,2012-12-12 13:03:00,2026-08-27 19:50:58,2026-08-27 19:09:31,,,javascript;php;client-side;server-side,deceze,525902,476,moderator,true,13840431,,CC BY-SA 4.0,2014-08-11 09:41:56,736,678,1,0,0,4,true,false,false,true,true,true,72,10,true,0.048,0.0093,5092,2012,12,13,Wednesday,false,false,true,false,false,false,true
2487921,Convert a date format in PHP,"I am trying to convert a date from yyyy-mm-dd to dd-mm-yyyy (but not in SQL); however I don't know how the date function requires a timestamp, and I can't get a timestamp from this string.
How is this possible?
",https://stackoverflow.com/questions/2487921/convert-a-date-format-in-php,572,2135117.0,18.0,,,2010-03-21 17:11:12,2023-12-20 18:36:57,2019-09-25 17:43:07,2021-04-22 12:15:34,Duplicate,php;date;formatting,matthy,8350,146773,registered,true,2487938,,,2012-09-06 19:08:22,252,212,2,0,0,3,true,true,false,true,true,true,28,6,false,0.008,0.0003,6089,2010,3,17,Sunday,true,false,false,false,false,false,true
15445285,How can I connect to a Tor hidden service using cURL in PHP?,"I'm trying to connect to a Tor hidden service using the following PHP code:
$url = 'http://jhiwjjlqpyawmpjx.onion/'
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_PROXY, "http://127.0.0.1:9050/");
curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
$output = curl_exec($ch);
$curl_error = curl_error($ch);
curl_close($ch);
print_r($output);
print_r($curl_error);
When I run it, I get the following error:
Couldn't resolve host name
However, when I run the following command from my command line in Ubuntu:
curl -v --socks5-hostname localhost:9050 http://jhiwjjlqpyawmpjx.onion
I get a response as expected.
The PHP cURL documentation says this:
--socks5-hostname
Use the specified SOCKS5 proxy (and let the proxy resolve the host name).
I believe the reason it works from the command line is because Tor (the proxy) is resolving the .onion hostname, which it recognizes. When running the PHP code above, my guess is that cURL or PHP is trying to resolve the .onion hostname and doesn't recognize it. I've searched for a way to tell cURL/PHP to let the proxy resolve the hostname, but I can't find a way.
There is a very similar Stack Overflow question, cURL request using socks5 proxy fails when using PHP, but it works through the command line.
",https://stackoverflow.com/questions/15445285/how-can-i-connect-to-a-tor-hidden-service-using-curl-in-php,570,320098.0,6.0,,,2013-03-16 03:39:25,2025-08-07 03:49:28,2025-01-30 20:05:20,,,php;curl;proxy;tor,frosty,5705,1249338,registered,true,,,CC BY-SA 4.0,2013-10-02 16:57:23,1636,1350,3,2,0,4,false,false,false,true,true,true,60,13,true,0.019,0.0018,4998,2013,3,3,Saturday,true,false,false,false,false,false,true
28098,PHP equivalent of .NET/Java's toString(),"How do I convert the value of a PHP variable to string?
I was looking for something better than concatenating with an empty string:
$myText = $myVar . '';
Like the ToString() method in Java or .NET.
",https://stackoverflow.com/questions/28098/php-equivalent-of-net-javas-tostring,567,1519445.0,26.0,,,2008-08-26 13:56:49,2025-07-08 09:32:36,2018-12-12 16:08:22,,,php;string,Antoine Aubry,12567,2680,registered,true,28111,,CC BY-SA 4.0,2020-01-01 18:11:06,261,203,2,0,0,2,true,false,false,true,true,true,44,5,false,0.017,0.0004,6661,2008,8,13,Tuesday,false,false,false,false,false,false,true
6041741,Fastest way to check if a string is JSON in PHP?,"I need a really, really fast method of checking if a string is JSON or not. I feel like this is not the best way:
function isJson($string) {
return ((is_string($string) &&
(is_object(json_decode($string)) ||
is_array(json_decode($string))))) ? true : false;
}
Any performance enthusiasts out there want to improve this method?
",https://stackoverflow.com/questions/6041741/fastest-way-to-check-if-a-string-is-json-in-php,557,604935.0,28.0,,,2011-05-18 08:18:03,2024-12-20 23:48:01,2023-12-03 20:50:22,,,php;json,Kirk Ouimet,28610,102635,registered,true,,,CC BY-SA 4.0,2017-10-13 10:02:13,404,366,1,0,0,2,false,false,false,true,true,true,48,11,true,0.046,0.0009,5666,2011,5,8,Wednesday,false,false,false,false,false,false,true
53610622,What does double question mark (??) operator mean in PHP,"I was diving into Symfony framework (version 4) code and found this piece of code:
$env = $_SERVER['APP_ENV'] ?? 'dev';
I'm not sure what this actually does but I imagine that it expands to something like:
$env = $_SERVER['APP_ENV'] != null ? $_SERVER['APP_ENV'] : 'dev';
Or maybe:
$env = isset($_SERVER['APP_ENV']) ? $_SERVER['APP_ENV'] : 'dev';
Does someone have any precision about the subject?
Note: the main difference between my question and this question is that most of people (like me before) ignore that the double question mark is called null coalescing operator. Thus, this question is more relevant and accessible to beginners.
",https://stackoverflow.com/questions/53610622/what-does-double-question-mark-operator-mean-in-php,556,389584.0,3.0,,,2018-12-04 10:18:12,2023-09-27 13:15:09,2023-09-27 13:15:09,2018-12-04 10:57:45,Duplicate,php;operator-keyword,elkolotfi,6450,5766339,registered,true,53610732,,,,947,644,3,1,0,2,true,true,false,true,true,true,56,10,false,0.008,0.0014,2909,2018,12,10,Tuesday,false,false,false,false,false,false,true
200640,Are PHP short tags acceptable to use?,"Here's the information according to the official documentation:
There are four different pairs of
opening and closing tags which can be
used in PHP. Two of those, <?php ?>
and <script language=""php""> </script>,
are always available. The other two
are short tags and ASP style tags, and
can be turned on and off from the
php.ini configuration file. As such,
while some people find short tags and
ASP style tags convenient, they are
less portable, and generally not
recommended.
In my experience most servers do have short tags enabled. Typing
<?=
is far more convenient than typing
<?php echo
The programmers convenience is an important factor, so why are they not recommended?
",https://stackoverflow.com/questions/200640/are-php-short-tags-acceptable-to-use,545,123542.0,28.0,,,2008-10-14 10:21:04,2023-05-15 17:35:19,2023-05-15 17:35:19,,,php;php-shorttags,MDCore,18255,1896,registered,true,200666,,CC BY-SA 4.0,2012-12-18 17:56:32,999,736,4,1,0,2,true,false,false,true,true,true,37,7,true,0.227,0.0044,6612,2008,10,10,Tuesday,false,false,false,false,false,false,true
6249707,Check if PHP session has already started,"I have a PHP file that is sometimes called from a page that has started a session and sometimes from a page that doesn't have session started. Therefore when I have session_start() on this script I sometimes get the error message for ""session already started"". For that I've put these lines:
if(!isset($_COOKIE[""PHPSESSID""]))
{
session_start();
}
but this time I got this warning message:
Notice: Undefined variable: _SESSION
Is there a better way to check if session has already started?
If I use @session_start will it make things work properly and just shut up the warnings?
",https://stackoverflow.com/questions/6249707/check-if-php-session-has-already-started,526,576542.0,28.0,,,2011-06-06 09:00:51,2024-08-26 13:16:15,2012-07-18 21:25:05,,,php;session;session-variables,Arda,10989,751969,registered,true,18542272,,CC BY-SA 3.0,2020-03-01 18:10:54,701,591,3,0,0,3,true,false,false,true,true,true,40,7,false,0.049,0.0009,5647,2011,6,9,Monday,false,false,false,false,false,false,true
1869091,How to convert an array to object in PHP?,"How can I convert an array like this to an object?
[128] => Array
(
[status] => "Figure A.
Facebook's horizontal scrollbars showing up on a 1024x768 screen resolution."
)
[129] => Array
(
[status] => "The other day at work, I had some spare time"
)
",https://stackoverflow.com/questions/1869091/how-to-convert-an-array-to-object-in-php,512,1185996.0,35.0,,,2009-12-08 18:56:06,2023-07-04 06:47:10,2020-10-29 20:41:45,,,php;arrays;object;casting,streetparade,33099,179235,registered,true,1869569,,CC BY-SA 4.0,2018-10-24 23:39:09,347,316,1,0,0,4,true,false,false,true,true,true,41,9,true,0.03,0.0004,6192,2009,12,18,Tuesday,false,false,false,false,false,false,true
16791613,Laravel Add a new column to existing table in a migration,"I can't figure out how to add a new column to my existing database table using the Laravel framework.
I tried to edit the migration file using...
<?php
public function up()
{
Schema::create('users', function ($table) {
$table->integer(""paid"");
});
}
In terminal, I execute php artisan migrate:install and migrate.
How do I add new columns?
",https://stackoverflow.com/questions/16791613/laravel-add-a-new-column-to-existing-table-in-a-migration,512,1250459.0,22.0,,,2013-05-28 12:03:43,2024-11-22 11:54:20,2021-12-23 06:11:23,,,php;laravel;laravel-migrations,kim larsen,5471,2079016,registered,true,16791988,,CC BY-SA 4.0,2021-12-21 17:00:49,484,368,3,0,0,3,true,false,false,true,true,true,57,11,false,0.018,0.0004,4925,2013,5,12,Tuesday,false,false,false,false,false,false,true
10368217,How to get the file extension in PHP?,"I wish to get the file extension of an image I am uploading, but I just get an array back.
$userfile_name = $_FILES['image']['name'];
$userfile_extn = explode(""."", strtolower($_FILES['image']['name']));
Is there a way to just get the extension itself?
",https://stackoverflow.com/questions/10368217/how-to-get-the-file-extension-in-php,511,744176.0,5.0,,,2012-04-28 22:46:11,2020-01-31 06:45:21,2017-05-23 12:34:47,2020-01-31 06:45:22,Duplicate,php;file-extension,Keith Power,14211,652541,registered,true,10368236,,,,294,256,1,0,0,2,true,true,false,true,true,true,37,8,true,0.007,0.0007,5320,2012,4,22,Saturday,true,false,false,false,false,false,true
1434368,How to define an empty object in PHP,"with a new array I do this:
$aVal = array();
$aVal[key1][var1] = ""something"";
$aVal[key1][var2] = ""something else"";
Is there a similar syntax for an object
(object)$oVal = """";
$oVal->key1->var1 = ""something"";
$oVal->key1->var2 = ""something else"";
",https://stackoverflow.com/questions/1434368/how-to-define-an-empty-object-in-php,510,606294.0,17.0,,,2009-09-16 17:24:29,2022-08-04 17:04:06,2017-05-29 13:01:47,,,php;object,ed209,11303,31399,registered,true,1434375,,CC BY-SA 3.0,,328,266,2,0,0,2,true,false,false,true,true,true,36,8,false,0.028,0.0008,6275,2009,9,17,Wednesday,false,false,false,false,false,false,true
26095051,How to run single test method with phpunit?,"I am struggling to run a single test method named testSaveAndDrop in the file escalation/EscalationGroupTest.php with phpunit. I tried the following combinations:
phpunit EscalationGroupTest escalation/EscalationGroupTest.php --filter=escalation/EscalationGroupTest.php::testSaveAndDrop
phpunit EscalationGroupTest escalation/EscalationGroupTest.php --filter=EscalationGroupTest.php::testSaveAndDrop
phpunit EscalationGroupTest escalation/EscalationGroupTest.php --filter=EscalationGroupTest::testSaveAndDrop
phpunit EscalationGroupTest escalation/EscalationGroupTest.php --filter=testSaveAndDrop
In each case all test methode in the file escalation/EscalationGroupTest.php are executed. How to select just ONE method instead?
The name of the class is EscalationGroupTest and the version of phpunit is 3.2.8.
",https://stackoverflow.com/questions/26095051/how-to-run-single-test-method-with-phpunit,510,373189.0,16.0,,,2014-09-29 07:56:30,2025-05-06 15:40:52,2014-09-29 08:13:44,,,php;phpunit,Alex,45087,1581090,registered,true,26095567,,CC BY-SA 3.0,,946,814,7,0,0,2,true,false,false,true,true,true,43,8,true,0.043,0.0014,4436,2014,9,7,Monday,false,false,false,false,false,false,true
70855,How can one use multi threading in PHP applications,"Is there a realistic way of implementing a multi-threaded model in PHP whether truly, or just simulating it. Some time back it was suggested that you could force the operating system to load another instance of the PHP executable and handle other simultaneous processes.
The problem with this is that when the PHP code finished executing the PHP instance remains in memory because there is no way to kill it from within PHP. So if you are simulating several threads you can imagine whats going to happen. So I am still looking for a way multi-threading can be done or simulated effectively from within PHP. Any ideas?
",https://stackoverflow.com/questions/70855/how-can-one-use-multi-threading-in-php-applications,510,659251.0,18.0,,,2008-09-16 09:56:31,2024-07-27 12:13:40,2011-10-22 00:47:38,,,php;multithreading,Steve Obbayi,6105,11190,registered,true,,,CC BY-SA 3.0,2012-10-21 12:00:01,635,621,0,0,0,2,false,false,false,true,true,true,51,9,false,0.027,0.0008,6640,2008,9,9,Tuesday,false,false,false,false,false,false,true
1686724,How to find the last day of the month from date?,"How can I get the last day of the month in PHP?
Given:
$a_date = ""2009-11-23""
I want 2009-11-30; and given
$a_date = ""2009-12-23""
I want 2009-12-31.
",https://stackoverflow.com/questions/1686724/how-to-find-the-last-day-of-the-month-from-date,509,727567.0,29.0,,,2009-11-06 10:27:50,2025-10-09 17:49:01,2014-11-25 06:42:15,,,php;date,Mithun Sreedharan,51668,174261,registered,true,1686742,,CC BY-SA 3.0,2022-06-20 08:07:59,232,156,2,0,0,2,true,false,false,true,true,true,48,11,true,0.04,0.0007,6224,2009,11,10,Friday,false,false,false,false,false,false,true
383944,What is a Python equivalent of PHP's var_dump()?,"When debugging in PHP, I frequently find it useful to simply stick a var_dump() in my code to show me what a variable is, what its value is, and the same for anything that it contains.
What is a good Python equivalent for this?
",https://stackoverflow.com/questions/383944/what-is-a-python-equivalent-of-phps-var-dump,506,398841.0,10.0,,,2008-12-21 00:43:36,2022-05-09 09:06:28,2014-05-14 19:00:08,2014-08-05 15:28:06,Duplicate,php;python;debugging,Zoredache,40120,20267,registered,true,383953,,,2019-07-15 09:21:57,298,229,0,1,0,3,true,true,false,true,true,true,52,8,true,0.025,0.0013,6544,2008,12,0,Sunday,true,true,false,false,false,false,true
4238433,How to create a newline character?,"In PHP I am trying to create a newline character:
echo $clientid;
echo ' ';
echo $lastname;
echo ' ';
echo '\r\n';
Afterwards I open the created file in Notepad and it writes the newline literally:
1 John Doe\r\n 1 John Doe\r\n 1 John Doe\r\n
I have tried many variations of the \r\n, but none work. Why isn't the newline turning into a newline?
",https://stackoverflow.com/questions/4238433/how-to-create-a-newline-character,504,1286391.0,12.0,,,2010-11-21 14:47:16,2024-06-23 13:54:16,2024-06-23 13:54:16,,,php;string-interpolation,davidjhp,8134,1267363,registered,true,4238438,,CC BY-SA 4.0,2014-01-06 17:12:46,446,356,2,0,0,2,true,false,false,true,true,true,34,6,true,0.009,0.0004,5844,2010,11,14,Sunday,true,false,false,false,false,false,true
1846202,"How to generate a random, unique, alphanumeric string?","How would it be possible to generate a random, unique string using numbers and letters for use in a verify link? Like when you create an account on a website, and it sends you an email with a link, and you have to click that link in order to verify your account
How can I generate one of those using PHP?
",https://stackoverflow.com/questions/1846202/how-to-generate-a-random-unique-alphanumeric-string,502,829588.0,32.0,,,2009-12-04 10:49:00,2025-01-07 08:54:52,2021-04-28 19:23:58,,,php;string;random;uniqueidentifier,Andrew,241827,48523,registered,true,1846229,,CC BY-SA 4.0,2013-06-27 00:32:33,319,305,0,0,0,4,true,false,false,true,true,true,54,8,true,0.039,0.0006,6196,2009,12,10,Friday,false,false,false,false,false,false,true
2750580,How can I find the php.ini file used by the command line?,"I need to enable pdo_mysql in my EasyPHP environment, so I went to the php.ini file and uncommented the following line:
extension=php_pdo_mysql.dll
Unfortunately I still have the same problem.
I'm using the CLI so I suppose I need to locate the php.ini file used by the CLI. How can I find it?
",https://stackoverflow.com/questions/2750580/how-can-i-find-the-php-ini-file-used-by-the-command-line,501,614782.0,15.0,,,2010-05-01 15:53:00,2024-06-13 12:14:58,2021-08-08 11:39:07,,,php;easyphp,Amokrane Chentir,30575,55093,registered,true,3744845,,CC BY-SA 4.0,,429,295,1,1,0,2,true,false,false,true,true,true,57,12,true,0.024,0.0008,6048,2010,5,15,Saturday,true,false,false,false,false,false,true
5164404,Use json_decode() to create array insead of an object,"I am trying to decode a JSON string into an array but i get the following error.
Fatal error: Cannot use object of type stdClass as array
Here is the code:
$json_string = 'http://www.example.com/jsondata.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata);
print_r($obj['Result']);
",https://stackoverflow.com/questions/5164404/use-json-decode-to-create-array-insead-of-an-object,498,867828.0,12.0,,,2011-03-02 07:03:41,2023-04-12 22:41:56,2023-04-12 22:41:56,,,php;arrays;json,Harsha M V,55177,155196,registered,true,5164417,,CC BY-SA 4.0,2019-07-31 16:31:50,386,316,1,0,0,3,true,false,false,true,true,true,53,9,false,0.014,0.0006,5743,2011,3,7,Wednesday,false,false,false,false,false,false,true
1065188,"In PHP, what is a closure and why does it use the "use" identifier?","I'm checking out some PHP 5.3.0 features and ran across some code on the site that looks quite funny:
public function getTotal($tax)
{
$total = 0.00;
$callback =
/* This line here: */
function ($quantity, $product) use ($tax, &$total)
{
$pricePerItem = constant(__CLASS__ . ""::PRICE_"" .
strtoupper($product));
$total += ($pricePerItem * $quantity) * ($tax + 1.0);
};
array_walk($this->products, $callback);
return round($total, 2);
}
as one of the examples on anonymous functions.
Does anybody know about this? Any documentation? And it looks evil, should it ever be used?
",https://stackoverflow.com/questions/1065188/in-php-what-is-a-closure-and-why-does-it-use-the-use-identifier,491,251128.0,6.0,,,2009-06-30 18:21:44,2024-07-05 20:54:54,2018-09-21 03:54:14,,,php;closures,SeanDowney,17808,5261,registered,true,1065197,,CC BY-SA 4.0,2024-07-05 20:52:09,816,674,2,1,0,2,true,false,false,true,true,true,77,14,true,0.024,0.002,6353,2009,6,18,Tuesday,false,false,false,false,false,false,true
5127838,"Where does PHP store the error log? (PHP 5, Apache, FastCGI, and cPanel)","I am on shared hosting and have cPanel, Apache, and PHP is run by FastCGI. Where does PHP store the error log?
Is there another way I can find the error log on a shared hosting environment instead of having to go through entire site structure to look for error_log files?
I have access to the php.ini file (I am using PHP version 5.2.16).
",https://stackoverflow.com/questions/5127838/where-does-php-store-the-error-log-php-5-apache-fastcgi-and-cpanel,491,1373545.0,28.0,,,2011-02-26 15:43:45,2023-09-30 06:39:53,2021-09-26 13:40:02,,,error-handling;php,PHPLOVER,7295,439232,registered,true,5127884,,CC BY-SA 4.0,2026-02-12 11:14:51,516,340,0,2,0,2,true,false,false,true,true,true,72,13,false,0.02,0.0004,5747,2011,2,15,Saturday,true,false,false,false,false,false,true
4343596,How to loop through PHP object with dynamic keys,"I tried to parse a JSON file using PHP. But I am stuck now.
This is the content of my JSON file:
{
"John": {
"status":"Wait"
},
"Jennifer": {
"status":"Active"
},
"James": {
"status":"Active",
"age":56,
"count":10,
"progress":0.0029857,
"bad":0
}
}
And this is what I have tried so far:
<?php
$string = file_get_contents("/home/michael/test.json");
$json_a = json_decode($string, true);
echo $json_a['John'][status];
echo $json_a['Jennifer'][status];
But because I don't know the names (like 'John', 'Jennifer') and all available keys and values (like 'age', 'count') beforehand, I think I need to create some foreach loop.
I would appreciate an example for this.
",https://stackoverflow.com/questions/4343596/how-to-loop-through-php-object-with-dynamic-keys,491,998349.0,16.0,,,2010-12-03 08:11:32,2022-12-28 13:18:07,2022-12-28 13:18:07,2022-05-26 13:55:23,Duplicate,php;json,John Doe,10301,439621,registered,true,4343691,,,2018-01-16 03:58:53,1103,891,6,0,0,2,true,true,false,true,true,true,48,9,false,0.016,0.0005,5832,2010,12,8,Friday,false,false,false,false,false,false,true
378959,How can I perform static code analysis in PHP?,"Is there a static analysis tool for PHP source files?
The binary itself can check for syntax errors, but I'm looking for something that does more, like:
- unused variable assignments
- arrays that are assigned into without being initialized first
- and possibly code style warnings
- ...
",https://stackoverflow.com/questions/378959/how-can-i-perform-static-code-analysis-in-php,487,159934.0,12.0,,,2008-12-18 19:39:58,2021-02-19 18:11:23,2021-02-07 16:36:11,2013-12-25 17:47:27,Not suitable for this site,php;code-analysis;static-analysis,eswald,8414,21229,registered,true,379471,,,,341,282,0,0,0,3,true,true,false,true,true,true,46,9,true,0.075,0.003,6547,2008,12,19,Thursday,false,false,false,false,false,false,true
8115683,PHP cURL custom headers,"I'm wondering if/how you can add custom headers to a cURL HTTP request in PHP. I'm trying to emulate how iTunes grabs artwork and it uses these non-standard headers:
X-Apple-Tz: 0
X-Apple-Store-Front: 143444,12
How could I add these headers to a request?
",https://stackoverflow.com/questions/8115683/php-curl-custom-headers,486,837776.0,4.0,,,2011-11-13 23:35:07,2024-01-26 06:06:07,,,,php;curl,123,5864,783236,registered,true,8115709,,CC BY-SA 3.0,2014-12-18 02:50:48,296,258,1,0,0,2,true,false,false,true,true,false,23,4,false,0.005,0.0006,5487,2011,11,23,Sunday,true,false,false,false,false,false,true
11939166,How to override trait function and call it from the overridden function?,"Scenario:
trait A {
function calc($v) {
return $v+1;
}
}
class MyClass {
use A;
function calc($v) {
$v++;
return A::calc($v);
}
}
print (new MyClass())->calc(2); // should print 4
This code doesn't work, and I cannot find a way to call a trait function like it was inherited. I tried calling self::calc($v), static::calc($v), parent::calc($v), A::calc($v) and the following:
trait A {
function calc($v) {
return $v+1;
}
}
class MyClass {
use A {
calc as traitcalc;
}
function calc($v) {
$v++;
return traitcalc($v);
}
}
Nothing works.
Is there a way to make it work or must I override completely the trait function which is much more complex than this :)
",https://stackoverflow.com/questions/11939166/how-to-override-trait-function-and-call-it-from-the-overridden-function,486,170909.0,6.0,,,2012-08-13 17:19:28,2022-08-20 14:40:57,2022-08-10 17:59:24,,,php;traits,Shu,5129,635786,registered,true,11939306,,CC BY-SA 4.0,,899,771,6,0,0,2,true,false,false,true,true,true,72,12,true,0.035,0.0028,5213,2012,8,17,Monday,false,false,false,false,false,false,true
5683592,PHPUnit assert that an exception was thrown?,"Does anyone know whether there is an assert or something like that which can test whether an exception was thrown in the code being tested?
",https://stackoverflow.com/questions/5683592/phpunit-assert-that-an-exception-was-thrown,484,378316.0,14.0,,,2011-04-16 00:23:39,2025-10-15 15:04:53,2013-11-08 15:41:51,,,php;exception;phpunit;assert,Felipe,11937,436721,registered,true,5683605,,CC BY-SA 3.0,,160,140,1,0,0,4,true,false,false,true,true,true,44,7,true,0.037,0.0013,5698,2011,4,0,Saturday,true,false,false,false,false,false,true
5164930,Fatal error: Maximum execution time of 30 seconds exceeded,"I am downloading a JSON file from an online source and and when it runs through the loop I am getting this error:
Fatal error: Maximum execution time of 30 seconds exceeded in C:\wamp\www\temp\fetch.php on line 24
",https://stackoverflow.com/questions/5164930/fatal-error-maximum-execution-time-of-30-seconds-exceeded,482,1136792.0,18.0,,,2011-03-02 08:11:45,2025-12-09 10:00:39,2015-05-05 16:16:32,,,php;json,Harsha M V,55177,155196,registered,true,5164954,,CC BY-SA 3.0,2014-07-17 12:00:33,258,219,0,0,0,2,true,false,false,true,true,true,58,9,false,0.016,0.0004,5743,2011,3,8,Wednesday,false,false,false,false,false,false,true
136782,Convert from MySQL datetime to another format with PHP,"I have a datetime column in MySQL.
How can I convert it to the display as mm/dd/yy H:M (AM/PM) using PHP?
",https://stackoverflow.com/questions/136782/convert-from-mysql-datetime-to-another-format-with-php,481,824090.0,15.0,,,2008-09-25 23:10:30,2026-10-22 21:31:18,2016-01-05 12:53:33,,,php;mysql;datetime,Tim Boland,10155,70,registered,true,5367048,,CC BY-SA 3.0,2012-03-09 22:28:40,152,108,1,0,0,3,true,false,false,true,true,true,54,9,false,0.018,0.0006,6631,2008,9,23,Thursday,false,false,false,false,false,false,true
7336861,How to convert string to boolean php,"How can I convert string to boolean?
$string = 'false';
$test_mode_mail = settype($string, 'boolean');
var_dump($test_mode_mail);
if($test_mode_mail) echo 'test mode is on.';
it returns,
boolean true
but it should be boolean false.
",https://stackoverflow.com/questions/7336861/how-to-convert-string-to-boolean-php,479,512898.0,20.0,,,2011-09-07 15:54:26,2023-10-23 09:03:06,2019-01-20 15:27:09,,,php;string;casting;boolean,Run,57755,413225,registered,true,7336873,,CC BY-SA 4.0,,347,244,3,0,0,4,true,false,false,true,true,true,36,7,false,0.039,0.0009,5554,2011,9,15,Wednesday,false,false,false,false,false,false,true
20723803,PDOException SQLSTATE[HY000] [2002] No such file or directory,"I believe that I've successfully deployed my (very basic) site to fortrabbit, but as soon as I connect to SSH to run some commands (such as php artisan migrate or php artisan db:seed) I get an error message:
[PDOException]
SQLSTATE[HY000] [2002] No such file or directory
At some point the migration must have worked, because my tables are there - but this doesn't explain why it isn't working for me now.
",https://stackoverflow.com/questions/20723803/pdoexception-sqlstatehy000-2002-no-such-file-or-directory,479,865113.0,39.0,,,2013-12-21 21:34:24,2024-11-29 17:14:14,2021-12-26 16:12:39,,,php;mysql;laravel;database;pdo,Daniel Hollands,6801,1049688,registered,true,20733001,,CC BY-SA 4.0,2015-11-08 20:19:46,473,409,3,0,0,5,true,false,false,true,true,true,61,8,false,0.045,0.0006,4718,2013,12,21,Saturday,true,false,false,false,false,false,true
6661530,Get the first level key of the first row containing a specified column value in a 2d array,"I have an array where I want to search the uid and get the key of the array.
Examples
Assume we have the following 2-dimensional array:
$userdb = array(
array(
'uid' => '100',
'name' => 'Sandra Shush',
'pic_square' => 'urlof100'
),
array(
'uid' => '5465',
'name' => 'Stefanie Mcmohn',
'pic_square' => 'urlof100'
),
array(
'uid' => '40489',
'name' => 'Michael',
'pic_square' => 'urlof40489'
)
);
The function call search_by_uid(100) (uid of first user) should return 0.
The function call search_by_uid(40489) should return 2.
I tried making loops, but I want a faster executing code.
",https://stackoverflow.com/questions/6661530/get-the-first-level-key-of-the-first-row-containing-a-specified-column-value-in,478,857306.0,24.0,,,2011-07-12 08:41:14,2024-11-20 23:14:04,2024-11-19 23:00:21,,,php;arrays;multidimensional-array;filter,Rachit,4819,836624,unregistered,true,6661561,,CC BY-SA 4.0,2018-02-05 11:42:09,846,713,6,0,0,4,true,false,false,true,true,true,90,18,false,0.028,0.0006,5611,2011,7,8,Tuesday,false,false,false,false,false,false,true
5438060,Showing all errors and warnings,"UPDATE 2:
I have now removed the following from the .php file:
<?php error_reporting( E_ALL ); ?>
I have set display_erros in php.ini as follows:
display_errors = On
Error reporting is set to the following in php.ini:
error_reporting = E_ALL | E_STRICT
After restarting Apache, I still get no errors/warnings.
UPDATE 1:
I have changed error_reporting in php.ini from:
error_reporting = E_ALL &
~E_DEPRECATED
to
error_reporting = E_ALL | E_STRICT
After which I restarted Apache, e.g.
/etc/init.d/apache2 restart
But the page will still not display errors/warnings of any kind.
ORIGINAL QUESTION:
The following script is generating a warning because the $err being inside the if statement. Why is this warning not being displayed on the PHP page in a web browser?
I have to look at the Apache logs to see the warning. Also, if I deliberately change the ""insert into"" to ""delete into"", it does not display an error on the PHP page. Why are the errors not displaying on the actual PHP page?
<?php
error_reporting(E_ALL);
?>
<html>
<head>
<title></title>
<link rel=""icon"" type=""image/png"" href=""favicon.ico"">
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$err = array();
if (empty( $_POST['display_name']))
$err[] = ""display name field is required"";
if (empty( $_POST['email']))
$err[] = ""email field is required"";
if (empty( $_POST['password']))
$err[] = ""password field is required"";
if (!$err) {
try {
$DBH = new PDO(""mysql:host=localhost;dbname=database1"", ""user"", ""pass"");
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$STH = $DBH->prepare(""delete into table1 (display_name, email, password) values ( :display_name, :email, :password )"");
$STH->bindParam(':display_name', $_POST['display_name'], PDO::PARAM_STR, 100);
$STH->bindParam(':email', $_POST['email'], PDO::PARAM_STR, 100);
$STH->bindParam(':password', $_POST['password'], PDO::PARAM_STR, 100);
$STH->execute();
$STH = $DBH->prepare(""delete into table2 ( username, status, users_id ) values ( :username, :status, :users_id )"");
$strStatus = 1;
$STH->bindParam(':username', $_POST['display_name'], PDO::PARAM_STR, 100);
$STH->bindParam(':status', $strStatus, PDO::PARAM_INT, 1);
$STH->bindParam(':users_id', $_POST['referer'], PDO::PARAM_INT, 1);
$STH->execute();
$DBH = null;
}
catch (PDOException $e) {
echo $e->getMessage();
}
header(""Location: "" . $_SERVER['PHP_SELF']);
exit;
}
else {
foreach ($_POST as $key => $val) {
$form[$key] = htmlspecialchars($val);
}
}
}
else {
$form['display_name'] = $form['email'] = $form['password'] = '';
}
?>
</head>
<body>
<?php foreach($err as $line) { ?>
<div style=""error""><?php echo $line; ?></div>
<?php } ?>
<h1>Register</h1>
<form method=""post"">
Referers id:<br/>
<input type=""text"" name=""referer"" /><br/><br/>
Name:<br/>
<input type=""text"" name=""display_name"" value=""<?php echo $form['display_name']; ?>"" /><br/><br/>
Email:<br/>
<input type=""text"" name=""email"" value=""<?php echo $form['email']; ?>"" /><br/><br/>
Password:<br/>
<input type=""text"" name=""password"" value=""<?php echo $form['password']; ?>"" /><br/><br/>
<input type=""submit"" value=""register"" />
</form>
</body>
</html>
",https://stackoverflow.com/questions/5438060/showing-all-errors-and-warnings,477,1481720.0,6.0,,,2011-03-25 20:55:39,2022-09-16 17:06:08,2019-07-31 20:04:59,2019-07-14 00:39:36,Duplicate,php;debugging;warnings,oshirowanen,16081,364312,registered,true,5438125,,,,4840,4464,4,0,0,3,true,true,false,true,true,true,31,5,false,0.004,0.0003,5720,2011,3,20,Friday,false,false,false,false,false,false,true
1075534,Can't use method return value in write context,"I would think the following piece of code should work, but it doesn't (Edited: Now works in PHP 5.5+):
if (!empty($r->getError()))
Where getError() is simply:
public function getError()
{
return $this->error;
}
Yet I end up with this error:
can't use method return value in write context
What does this mean? Isn't this just a read?
",https://stackoverflow.com/questions/1075534/cant-use-method-return-value-in-write-context,475,282421.0,8.0,,,2009-07-02 16:58:37,2020-06-25 22:18:36,2016-06-14 19:01:50,,,php,Extrakun,19343,128585,registered,true,4328049,,CC BY-SA 3.0,2013-09-17 06:24:19,493,355,3,0,0,1,true,false,false,true,true,true,50,8,false,0.028,0.0017,6351,2009,7,16,Thursday,false,false,false,false,false,false,true
778564,PHPDoc type hinting for array of objects?,"So, in PHPDoc one can specify @var above the member variable declaration to hint at its type. Then an IDE, for ex. PHPEd, will know what type of object it's working with and will be able to provide a code insight for that variable.
<?php
class Test
{
/** @var SomeObj */
private $someObjInstance;
}
?>
This works great until I need to do the same to an array of objects to be able to get a proper hint when I iterate through those objects later on.
So, is there a way to declare a PHPDoc tag to specify that the member variable is an array of SomeObjs? @var array is not enough, and @var array(SomeObj) doesn't seem to be valid, for example.
",https://stackoverflow.com/questions/778564/phpdoc-type-hinting-for-array-of-objects,471,290013.0,15.0,,,2009-04-22 18:29:13,2025-08-31 10:56:21,2011-09-18 17:42:27,,,php;ide;phpdoc;var;hint,Artem Russakovskii,22120,47680,registered,true,778787,,CC BY-SA 3.0,,763,666,5,0,0,5,true,false,false,true,true,true,41,7,true,0.052,0.0016,6422,2009,4,18,Wednesday,false,false,false,false,false,false,true
4260086,How to filter an associative array comparing keys with values in an indexed array?,"The callback function in array_filter() only passes in the array's values, not the keys.
If I have:
$my_array = array("foo" => 1, "hello" => "world");
$allowed = array("foo", "bar");
What's the best way to delete all keys in $my_array that are not in the $allowed array?
Desired output:
$my_array = array("foo" => 1);
",https://stackoverflow.com/questions/4260086/how-to-filter-an-associative-array-comparing-keys-with-values-in-an-indexed-arra,467,451643.0,12.0,,,2010-11-23 19:41:05,2022-10-21 19:14:30,2022-10-21 19:14:30,,,php;arrays;key;filtering;whitelist,maček,78044,184600,registered,true,26524231,,CC BY-SA 4.0,,587,390,5,1,0,5,true,false,false,true,true,true,82,14,true,0.027,0.001,5842,2010,11,19,Tuesday,false,false,false,false,false,false,true
6382539,Call to undefined function curl_init()?,"When i am going to implement Authorize.net payment gateway. However, I got this error:
Call to undefined function curl_init()
Please let me know what is wrong in it.
",https://stackoverflow.com/questions/6382539/call-to-undefined-function-curl-init,467,902037.0,2.0,,,2011-06-17 07:15:54,2025-02-17 09:32:48,2023-01-23 15:32:49,,,php;curl,Pramod Kumar Sharma,8072,712818,registered,true,6382581,,CC BY-SA 4.0,,219,173,0,0,0,2,true,false,false,true,true,true,39,5,true,0.002,0.0005,5636,2011,6,7,Friday,false,false,false,false,false,false,true
2121548,How to push both value and key into PHP array,"Take a look at this code:
$GET = array();
$key = 'one=1';
$rule = explode('=', $key);
/* array_push($GET, $rule[0] => $rule[1]); */
I'm looking for something like this so that:
print_r($GET);
/* output: $GET[one => 1, two => 2, ...] */
Is there a function to do this? (because array_push won't work this way)
",https://stackoverflow.com/questions/2121548/how-to-push-both-value-and-key-into-php-array,465,1223604.0,21.0,,,2010-01-23 00:44:22,2024-06-01 23:30:43,2019-12-19 06:06:36,2023-10-20 02:04:30,Duplicate,php;arrays,Gal,23742,202895,registered,true,2121551,,,2018-08-27 02:38:15,410,328,3,0,0,2,true,true,false,true,true,true,45,10,false,0.017,0.0004,6146,2010,1,0,Saturday,true,false,false,false,false,false,true
1290318,PHP Constants Containing Arrays?,"This failed:
define('DEFAULT_ROLES', array('guy', 'development team'));
Apparently, constants can't hold arrays. What is the best way to get around this?
define('DEFAULT_ROLES', 'guy|development team');
//...
$default = explode('|', DEFAULT_ROLES);
This seems like unnecessary effort.
",https://stackoverflow.com/questions/1290318/php-constants-containing-arrays,461,379833.0,18.0,,,2009-08-17 20:45:36,2024-11-28 08:38:44,2012-08-13 16:25:19,,,php;arrays;constants;scalar,Nick Heiner,123432,147601,registered,true,1290388,,CC BY-SA 3.0,2017-01-09 09:36:14,363,294,2,0,0,4,true,false,false,true,true,true,32,4,true,0.047,0.0012,6305,2009,8,20,Monday,false,false,false,false,false,false,true
3210935,What's the difference between isset() and array_key_exists()?,"How do the following two function calls compare:
isset($a['key'])
array_key_exists('key', $a)
",https://stackoverflow.com/questions/3210935/whats-the-difference-between-isset-and-array-key-exists,461,162299.0,8.0,,,2010-07-09 08:14:23,2023-04-26 18:31:11,2019-01-16 15:26:33,2019-05-10 12:14:16,Duplicate,php,Zacky112,8927,248901,registered,true,,,,,128,97,1,0,0,1,false,true,false,true,true,true,65,7,true,0.049,0.0028,5979,2010,7,8,Friday,false,false,false,false,false,false,true
16830405,Laravel requires the Mcrypt PHP extension,"I am trying to use the migrate function in Laravel 4 on OSX. However, I am getting the following error:
Laravel requires the Mcrypt PHP extension.
As far as I understand, it's already enabled (see the image below).
What is wrong, and how can I fix it?
![]()
",https://stackoverflow.com/questions/16830405/laravel-requires-the-mcrypt-php-extension,460,319268.0,22.0,,,2013-05-30 07:31:18,2023-07-24 18:19:19,2021-04-30 17:47:39,,,php;laravel;laravel-4;mcrypt,Patrick Reck,11372,1358522,registered,true,16832214,,CC BY-SA 4.0,2014-02-10 01:56:30,399,254,2,0,1,4,true,false,false,true,true,true,41,6,false,0.069,0.0014,4923,2013,5,7,Thursday,false,false,false,false,false,false,true
44839648,No Application Encryption Key Has Been Specified,"I'm trying to use the Artisan command like this:
php artisan serve
It displays:
Laravel development server started: http://127.0.0.1:8000
However, it won't automatically launch and when I manually enter http://127.0.0.1:8000 it shows this error:
RuntimeException No application encryption key has been specified.
What's the cause of this problem, and how can it be fixed?
I'm using Laravel framework 5.5-dev.
",https://stackoverflow.com/questions/44839648/no-application-encryption-key-has-been-specified,459,791055.0,26.0,,,2017-06-30 06:06:47,2024-09-12 06:22:29,2023-12-25 14:36:58,,,php;laravel;laravel-5;laravel-artisan,Carlos F,5111,5547502,registered,true,44839664,,CC BY-SA 4.0,2017-09-27 11:24:35,673,414,2,2,0,4,true,false,false,true,true,true,48,7,false,0.033,0.0006,3431,2017,6,6,Friday,false,false,false,false,false,false,true
97984,How to secure database passwords in PHP?,"When a PHP application makes a database connection it of course generally needs to pass a login and password. If I'm using a single, minimum-permission login for my application, then the PHP needs to know that login and password somewhere. What is the best way to secure that password? It seems like just writing it in the PHP code isn't a good idea.
",https://stackoverflow.com/questions/97984/how-to-secure-database-passwords-in-php,448,256964.0,18.0,,,2008-09-18 23:27:03,2023-10-28 08:31:10,2011-01-13 07:53:51,,,php;database;security,user18359,4743,18359,registered,true,98021,,CC BY-SA 2.5,2010-09-10 11:13:30,358,351,0,0,0,3,true,false,false,true,true,true,40,7,true,0.07,0.0017,6638,2008,9,23,Thursday,false,false,false,false,false,false,true
724391,Saving image from PHP URL,"I need to save an image from a PHP URL to my PC.
Let's say I have a page, http://example.com/image.php, holding a single ""flower"" image, nothing else. How can I save this image from the URL with a new name (using PHP)?
",https://stackoverflow.com/questions/724391/saving-image-from-php-url,441,896925.0,11.0,,,2009-04-07 06:50:46,2021-12-06 20:23:58,2014-08-12 06:30:33,,,php;image,riad,7194,87238,registered,true,724449,,CC BY-SA 3.0,2012-03-14 19:18:06,239,219,1,0,0,2,true,false,false,true,true,true,25,5,false,0.012,0.0005,6437,2009,4,6,Tuesday,false,false,false,false,false,false,true
128560,When do I use the PHP constant "PHP_EOL"?,"When is it a good idea to use PHP_EOL?
I sometimes see this in code samples of PHP. Does this handle DOS/Mac/Unix endline issues?
",https://stackoverflow.com/questions/128560/when-do-i-use-the-php-constant-php-eol,441,530650.0,19.0,,,2008-09-24 17:34:39,2022-04-09 16:54:52,2023-11-17 20:42:18,,,php;eol,Christian Oudard,50476,3757,registered,true,128564,,CC BY-SA 4.0,,241,130,1,1,0,2,true,false,false,true,true,true,51,8,true,0.036,0.0008,6632,2008,9,17,Wednesday,false,false,false,false,false,false,true
1179874,What is the difference between bindParam and bindValue?,"What is the difference between PDOStatement::bindParam() and PDOStatement::bindValue()?
",https://stackoverflow.com/questions/1179874/what-is-the-difference-between-bindparam-and-bindvalue,440,159223.0,7.0,,,2009-07-24 20:00:58,2019-07-29 08:22:10,2015-03-12 18:01:51,,,php;pdo;bindparam;bindvalue,koen,13849,141346,registered,true,1179927,,CC BY-SA 3.0,2014-01-02 21:51:59,295,88,2,2,0,4,true,false,false,true,true,true,55,8,true,0.044,0.0028,6329,2009,7,20,Friday,false,false,false,false,false,false,true
4098345,Why doesn't this code simply print letters A to Z?,"<?php
for ($i = 'a'; $i <= 'z'; $i++)
echo "$i ";
This snippet gives the following output:
a b c d e f g h i j k l m n o p q r s t u v w x y z aa ab ac ad ae af ag ah ai aj ak al am an ao ap aq ar as at au av aw ax ay az ba bb bc bd be bf bg bh bi bj bk bl bm bn bo bp bq br bs bt bu bv bw bx by bz ca cb cc cd ce cf cg ch ci cj ck cl cm cn co cp cq cr cs ct cu cv cw cx cy cz da db dc dd de df dg dh di dj dk dl dm dn do dp dq dr ds dt du dv dw dx dy dz ea eb ec ed ee ef eg eh ei ej ek el em en eo ep eq er es et eu ev ew ex... on to yz
I was expecting it to print the letters from A to Z; why didn't it?
",https://stackoverflow.com/questions/4098345/why-doesnt-this-code-simply-print-letters-a-to-z,439,31488.0,10.0,,,2010-11-04 15:36:31,2026-11-04 21:29:01,2026-11-04 21:29:01,,,php;type-conversion;character,Milan Babuškov,61903,14690,registered,true,4098397,,CC BY-SA 4.0,2017-04-04 17:07:51,700,630,1,0,0,3,true,false,false,true,true,true,54,10,true,0.318,0.0139,5861,2010,11,15,Thursday,false,false,false,false,false,false,true
29253979,Displaying HTML with Blade shows the HTML code,"I have a string returned to one of my views, like this:
$text = '<p><strong>Lorem</strong> ipsum dolor <img src="images/test.jpg"></p>'
I'm trying to display it with Blade:
{{$text}}
However, the output is a raw string instead of rendered HTML. How do I display HTML with Blade in Laravel?
PS. PHP echo() displays the HTML correctly.
",https://stackoverflow.com/questions/29253979/displaying-html-with-blade-shows-the-html-code,438,493908.0,21.0,,,2015-03-25 11:08:33,2024-01-19 23:46:32,2021-12-26 10:54:00,,,php;html;laravel;laravel-blade,lesssugar,16251,2890610,registered,true,29254016,,CC BY-SA 4.0,2019-10-11 10:43:56,465,376,3,0,0,4,true,false,false,true,true,true,46,8,false,0.043,0.0009,4259,2015,3,11,Wednesday,false,false,false,false,false,false,true
8900701,Creating default object from empty value in PHP?,"I see this error only after upgrading my PHP environment to PHP 5.4 and beyond. The error points to this line of code:
Error:
Creating default object from empty value
Code:
$res->success = false;
Do I first need to declare my $res object?
",https://stackoverflow.com/questions/8900701/creating-default-object-from-empty-value-in-php,438,701752.0,18.0,,,2012-01-17 19:43:09,2024-12-17 10:03:50,2015-12-14 19:44:05,,,php,Paul,11756,849065,registered,true,8900730,,CC BY-SA 3.0,,349,252,2,0,0,1,true,false,false,true,true,true,48,8,true,0.026,0.0006,5422,2012,1,19,Tuesday,false,false,false,false,false,false,true
30639174,How to set up file permissions for Laravel?,"I'm using Apache Web Server that has the owner set to _www:_www. I never know what is the best practice with file permissions, for example when I create new Laravel 5 project.
Laravel 5 requires /storage folder to be writable. I found plenty of different approaches to make it work and I usually end with making it 777 chmod recursively. I know it's not the best idea though.
The official doc says:
Laravel may require some permissions to be configured: folders within
storage and vendor require write access by the web server.
Does it mean that the web server needs access to the storage and vendor folders themselves too or just their current contents?
I assume that what is much better, is changing the owner instead of permissions. I changed all Laravel's files permissions recursively to _www:_www and that made the site work correctly, as if I changed chmod to 777. The problem is that now my text editor asks me for password each time I want to save any file and the same happens if I try to change anything in Finder, like for example copy a file.
What is the correct approach to solve these problems?
- Change
chmod
- Change the owner of the files to match those of the
web server and perhaps set the text editor (and Finder?) to skip
asking for password, or make them use
sudo
- Change the owner of the web server to match the os user (I don't
know the consequences)
- Something else
",https://stackoverflow.com/questions/30639174/how-to-set-up-file-permissions-for-laravel,437,881353.0,22.0,,,2015-06-04 08:49:08,2023-02-23 05:47:19,2019-08-29 21:52:04,,,php;apache;laravel;laravel-5;file-permissions,Robo Robok,23173,4403732,registered,true,37266353,,CC BY-SA 4.0,2024-09-20 19:36:40,1688,1409,11,0,0,5,true,false,false,true,true,true,43,8,true,0.025,0.0005,4188,2015,6,8,Thursday,false,false,false,false,false,false,true
18866571,Receive JSON POST with PHP,"I’m trying to receive a JSON POST on a payment interface website, but I can’t decode it.
When I print :
echo $_POST;
I get:
Array
The payment site log says everything is OK. What’s the problem?
",https://stackoverflow.com/questions/18866571/receive-json-post-with-php,436,698393.0,14.0,,,2013-09-18 07:47:44,2024-11-05 10:19:01,2024-11-05 10:19:01,2024-09-05 21:17:37,Duplicate,php;json;post,Pablo Ramirez,4405,2790389,registered,true,,,,2014-12-02 10:36:03,272,196,2,0,0,3,false,true,false,true,true,true,26,5,false,0.02,0.0006,4812,2013,9,7,Wednesday,false,false,false,false,false,false,true
1206105,What does PHP keyword 'var' do?,"This is probably a very trivial question, but I haven't been able to find the answer neither through web search engines, nor on php.net. Please just direct me to where I can read about this, if you haven't got time to explain.
- What does the 'var' keyword mean in PHP?
- Are there any differences between PHP4 and PHP5?
",https://stackoverflow.com/questions/1206105/what-does-php-keyword-var-do,436,143779.0,8.0,,,2009-07-30 11:52:03,2019-10-17 06:51:46,2009-07-30 12:06:34,,,php;keyword,joelpet,4879,133153,registered,true,1206120,,CC BY-SA 2.5,2017-07-26 13:43:57,354,320,0,0,0,2,true,false,false,true,true,true,39,6,true,0.056,0.003,6323,2009,7,11,Thursday,false,false,false,false,false,false,true
1241728,Can I try/catch a warning?,"I need to catch some warnings being thrown from some php native functions and then handle them.
Specifically:
array dns_get_record ( string $hostname [, int $type= DNS_ANY [, array &$authns [, array &$addtl ]]] )
It throws a warning when the DNS query fails.
try/catch doesn't work because a warning is not an exception.
I now have 2 options:
set_error_handler seems like overkill because I have to use it to filter every warning in the page (is this true?);
Adjust error reporting/display so these warnings don't get echoed to screen, then check the return value; if it's false, no records is found for hostname.
What's the best practice here?
",https://stackoverflow.com/questions/1241728/can-i-try-catch-a-warning,433,286961.0,13.0,,,2009-08-06 21:51:30,2024-05-25 14:24:09,2019-07-29 22:29:31,,,php;error-handling;try-catch,user121196,31290,121196,registered,true,1241751,,CC BY-SA 4.0,,827,668,5,0,0,3,true,false,false,true,true,true,26,5,true,0.045,0.0015,6316,2009,8,21,Thursday,false,false,false,false,false,false,true
1252693,Using str_replace so that it only acts on the first match?,"I want a version of str_replace() that only replaces the first occurrence of $search in the $subject. Is there an easy solution to this, or do I need a hacky solution?
",https://stackoverflow.com/questions/1252693/using-str-replace-so-that-it-only-acts-on-the-first-match,431,354515.0,22.0,,,2009-08-10 00:39:54,2026-06-23 10:16:49,2014-05-07 15:51:59,,,php;string,Nick Heiner,123432,147601,registered,true,1252705,,CC BY-SA 3.0,,214,168,3,0,0,2,true,false,false,true,true,true,58,11,true,0.062,0.0012,6312,2009,8,0,Monday,false,false,false,false,false,false,true
16995102,Laravel Eloquent Query: Using WHERE with OR AND OR?,"How do I say WHERE (a = 1 OR b =1 ) AND (c = 1 OR d = 1)
For more complicated queries am I supposed to use raw SQL?
",https://stackoverflow.com/questions/16995102/laravel-eloquent-query-using-where-with-or-and-or,431,742714.0,16.0,,,2013-06-08 01:29:42,2024-08-29 14:26:26,2023-02-06 13:49:37,,,php;laravel;eloquent;laravel-query-builder,Farzher,14651,845280,registered,true,16995151,,CC BY-SA 4.0,2023-08-01 17:28:12,144,117,1,0,0,4,true,false,false,true,true,true,51,9,true,0.022,0.0006,4914,2013,6,1,Saturday,true,false,false,false,false,false,true
996139,urlencode vs rawurlencode?,"If I want to create a URL using a variable I have two choices to encode the string. urlencode() and rawurlencode().
What exactly are the differences and which is preferred?
",https://stackoverflow.com/questions/996139/urlencode-vs-rawurlencode,431,223454.0,11.0,,,2009-06-15 13:33:35,2023-02-16 20:51:39,2016-11-30 14:26:06,,,php;urlencode;url-encoding,Gary Willoughby,53205,13227,registered,true,996161,,CC BY-SA 3.0,,214,174,2,0,0,3,true,false,false,true,true,true,26,3,true,0.049,0.0019,6368,2009,6,13,Monday,false,false,false,false,false,false,true
1526688,Get table column names in MySQL?,"Is there a way to grab the columns name of a table in MySQL using PHP?
",https://stackoverflow.com/questions/1526688/get-table-column-names-in-mysql,430,697780.0,19.0,,,2009-10-06 16:32:12,2021-10-27 21:26:00,2021-10-27 21:26:00,,,php;sql;mysql,An employee,6328,170841,registered,true,1526722,,CC BY-SA 4.0,2017-10-13 14:53:07,78,71,0,0,0,3,true,false,false,true,true,true,32,6,true,0.027,0.0006,6255,2009,10,16,Tuesday,false,false,false,false,false,true,true
5121495,"PHP code is not being executed, but the code shows in the browser source code","I'm trying to execute some PHP code on a project (using Dreamweaver) but the code isn't being run.
When I check the source code, the PHP code appears as HTML tags (I can see it in the source code). Apache is running properly (I'm working with XAMPP), the PHP pages are being opened properly but the PHP code isn't being executed.
Does someone have a suggestion about what is happening?
Note: The file is already named as filename.php
Edit:
The Code..:
<?
include_once(""/code/configs.php"");
?>
![]()
",https://stackoverflow.com/questions/5121495/php-code-is-not-being-executed-but-the-code-shows-in-the-browser-source-code,430,993798.0,37.0,,,2011-02-25 19:06:51,2024-08-06 13:47:51,2021-07-12 19:37:36,,,php;apache,Gui,9883,365383,registered,true,5121589,,CC BY-SA 4.0,2015-06-10 01:01:11,679,507,2,0,1,2,true,false,false,true,true,true,77,15,false,0.037,0.0004,5748,2011,2,19,Friday,false,false,false,false,false,false,true
659025,How to remove non-alphanumeric characters?,"I need to remove all characters from a string which aren't in a-z A-Z 0-9 set or are not spaces.
Does anyone have a function to do this?
",https://stackoverflow.com/questions/659025/how-to-remove-non-alphanumeric-characters,429,310173.0,7.0,,,2009-03-18 16:29:19,2024-01-15 09:37:26,2015-03-19 19:33:25,,,php;regex;string,zuk1,18489,26823,registered,true,659030,,CC BY-SA 3.0,2015-04-27 00:19:35,165,138,1,0,0,3,true,false,false,true,true,true,42,5,true,0.023,0.0014,6457,2009,3,16,Wednesday,false,false,false,false,false,false,true
3656713,How can I get the current time in milliseconds in PHP?,"time() is in seconds. Is there one in milliseconds?
",https://stackoverflow.com/questions/3656713/how-can-i-get-the-current-time-in-milliseconds-in-php,427,606065.0,17.0,,,2010-09-07 07:48:12,2026-01-04 06:44:50,2025-08-11 21:18:11,,,php;time,COMer,5281,431665,unregistered,true,,,CC BY-SA 4.0,2016-05-06 04:31:43,72,52,1,0,0,2,false,false,false,true,true,true,54,11,true,0.028,0.0007,5919,2010,9,7,Tuesday,false,false,false,false,false,false,true
4323411,How can I write to the console in PHP?,"Is it possible write a string or log into the console?
What I mean
Just like in JSP, if we print something like system.out.println(""some""), it will be there at the console, not at a page.
",https://stackoverflow.com/questions/4323411/how-can-i-write-to-the-console-in-php,426,1886699.0,30.0,,,2010-12-01 10:34:19,2024-03-05 06:42:30,2019-08-03 13:03:42,,,php;debugging;printing;console,Labeeb Panampullan,34863,477754,registered,true,4323450,,CC BY-SA 4.0,2024-01-10 08:05:44,226,190,1,0,0,4,true,false,false,true,true,true,38,9,true,0.016,0.0002,5834,2010,12,10,Wednesday,false,false,false,false,false,false,true
757675,Website screenshots,"Is there any way of taking a screenshot of a website in PHP, then saving it to a file?
",https://stackoverflow.com/questions/757675/website-screenshots,426,356186.0,18.0,,,2009-04-16 19:25:18,2022-07-12 04:53:57,2017-08-09 13:46:47,,,php;screenshot,Tom,,,does_not_exist,true,,,CC BY-SA 3.0,2015-09-22 23:18:25,94,87,0,0,0,2,false,false,false,true,false,true,19,2,false,0.051,0.0012,6428,2009,4,19,Thursday,false,false,false,false,false,false,true
240660,Replace keys in an array based on another lookup/mapping array,"I have an associative array in the form key => value where key is a numerical value, however it is not a sequential numerical value. The key is actually an ID number and the value is a count. This is fine for most instances, however I want a function that gets the human-readable name of the array and uses that for the key, without changing the value.
I didn't see a function that does this, but I'm assuming I need to provide the old key and new key (both of which I have) and transform the array. Is there an efficient way of doing this?
",https://stackoverflow.com/questions/240660/replace-keys-in-an-array-based-on-another-lookup-mapping-array,424,615940.0,25.0,,,2008-10-27 17:09:48,2023-12-17 08:38:09,2022-06-28 05:51:52,,,php;arrays;mapping;key;associative-array,Thomas Owens,116701,572,registered,true,240676,,CC BY-SA 4.0,2010-12-27 00:29:04,571,544,1,0,0,5,true,false,false,true,true,true,62,10,false,0.041,0.0007,6599,2008,10,17,Monday,false,false,false,false,false,false,true
3432257,"Difference between array_map, array_walk and array_filter","What exactly is the difference between array_map, array_walk and array_filter. What I could see from documentation is that you could pass a callback function to perform an action on the supplied array. But I don't seem to find any particular difference between them.
Do they perform the same thing?
Can they be used interchangeably?
I would appreciate your help with illustrative example if they are different at all.
",https://stackoverflow.com/questions/3432257/difference-between-array-map-array-walk-and-array-filter,423,215304.0,6.0,,,2010-08-07 22:19:35,2025-06-19 12:39:48,2020-08-14 19:21:03,,,php;arrays;callback,Web Logic,,,does_not_exist,true,3432266,,CC BY-SA 4.0,2014-02-02 11:14:10,484,418,3,0,0,3,true,false,false,true,false,true,57,6,false,0.028,0.002,5950,2010,8,22,Saturday,true,false,false,false,false,false,true
9183178,Can PHP cURL retrieve response headers AND body in a single request?,"Is there any way to get both headers and body for a cURL request using PHP? I found that this option:
curl_setopt($ch, CURLOPT_HEADER, true);
is going to return the body plus headers, but then I need to parse it to get the body. Is there any way to get both in a more usable (and secure) way?
Note that for ""single request"" I mean avoiding issuing a HEAD request prior of GET/POST.
",https://stackoverflow.com/questions/9183178/can-php-curl-retrieve-response-headers-and-body-in-a-single-request,422,664142.0,16.0,,,2012-02-07 20:13:03,2023-03-13 06:57:08,2017-03-14 17:58:41,,,php;http;curl,gremo,49047,220180,registered,true,9183272,,CC BY-SA 3.0,2016-08-01 12:04:51,448,386,1,0,0,3,true,false,false,true,true,true,68,12,true,0.024,0.0006,5401,2012,2,20,Tuesday,false,false,false,false,false,false,true
2852748,PDOException “could not find driver”,"I have just installed Debian Lenny with Apache, MySQL, and PHP and I am receiving a PDOException could not find driver.
This is the specific line of code it is referring to:
$dbh = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASS)
DB_HOST, DB_NAME, DB_USER, and DB_PASS are constants that I have defined. It works fine on the production server (and on my previous Ubuntu Server setup).
Is this something to do with my PHP installation?
Searching the internet has not helped, all I get is experts-exchange and examples, but no solutions.
",https://stackoverflow.com/questions/2852748/pdoexception-could-not-find-driver,418,1381098.0,44.0,,,2010-05-17 20:57:04,2025-01-03 18:56:51,2011-11-10 05:47:35,,,php;mysql;pdo;lamp,Mike Moore,7548,300575,registered,true,2852997,,CC BY-SA 3.0,2019-08-14 09:01:21,686,566,6,0,0,4,true,false,false,true,true,true,36,5,false,0.032,0.0003,6032,2010,5,20,Monday,false,false,false,false,false,false,true
4410704,Why would one omit the close tag?,"I keep reading it is poor practice to use the PHP close tag ?> at the end of the file. The header problem seems irrelevant in the following context (and this is the only good argument so far):
Modern versions of PHP set the output_buffering flag in php.ini
If output buffering is enabled, you can set HTTP headers and cookies after outputting HTML because the returned code is not sent to the browser immediately.
Every good practice book and wiki starts with this 'rule' but nobody offers good reasons.
Is there another good reason to skip the ending PHP tag?
",https://stackoverflow.com/questions/4410704/why-would-one-omit-the-close-tag,418,136278.0,13.0,,,2010-12-10 16:00:39,2019-07-25 15:36:00,2018-11-22 16:32:22,,,php;security;http-headers,johnlemon,21699,357314,registered,true,4499749,,CC BY-SA 4.0,2015-05-20 20:37:57,649,573,1,0,0,3,true,false,false,true,true,true,33,7,true,0.095,0.0031,5825,2010,12,16,Friday,false,false,false,false,false,false,true
5425891,"How do I check if a directory exists? "is_dir", "file_exists" or both?","I want to create a directory if it does not exist already.
Is using the is_dir function enough for that purpose?
if ( !is_dir( $dir ) ) {
mkdir( $dir );
}
Or should I combine is_dir with file_exists?
if ( !file_exists( $dir ) && !is_dir( $dir ) ) {
mkdir( $dir );
}
",https://stackoverflow.com/questions/5425891/how-do-i-check-if-a-directory-exists-is-dir-file-exists-or-both,417,517654.0,12.0,,,2011-03-24 21:38:12,2022-12-29 08:12:40,2021-01-14 23:46:58,,,php,Peter,6377,672125,unregistered,true,5425928,,CC BY-SA 4.0,,407,299,5,0,0,1,true,false,false,true,true,true,90,12,true,0.023,0.0008,5721,2011,3,21,Thursday,false,false,false,false,false,false,true
10542310,How can I get the last 7 characters of a PHP string?,"How would I go about grabbing the last 7 characters of the string below?
For example:
$dynamicstring = ""2490slkj409slk5409els"";
$newstring = some_function($dynamicstring);
echo ""The new string is: "" . $newstring;
Which would display:
The new string is: 5409els
",https://stackoverflow.com/questions/10542310/how-can-i-get-the-last-7-characters-of-a-php-string,416,557494.0,8.0,,,2012-05-10 21:19:45,2023-12-18 09:59:54,2016-12-16 08:35:54,,,php;string,Dave,9217,466290,registered,true,10542328,,CC BY-SA 3.0,,375,267,2,0,0,2,true,false,false,true,true,true,52,12,true,0.014,0.0007,5308,2012,5,21,Thursday,false,false,false,false,false,false,true
27095090,Laravel Checking If a Record Exists,"I am new to Laravel. How do I find if a record exists?
$user = User::where('email', '=', Input::get('email'));
What can I do here to see if $user has a record?
",https://stackoverflow.com/questions/27095090/laravel-checking-if-a-record-exists,414,966453.0,33.0,,,2014-11-23 22:24:42,2024-08-23 00:48:53,2022-02-11 17:24:56,,,php;laravel;laravel-5;eloquent;conditional-statements,Ben,5777,1577959,registered,true,27095159,,CC BY-SA 4.0,2022-04-06 08:06:07,250,161,2,0,0,5,true,false,false,true,true,true,35,6,false,0.034,0.0004,4381,2014,11,22,Sunday,true,false,false,false,false,false,true
9802788,Call a REST API in PHP,"Our client had given me a REST API to which I need to make a PHP call. But as a matter of fact, the documentation given with the API is very limited, so I don't really know how to call the service.
I've tried to Google it, but the only thing that came up was an already expired Yahoo! tutorial on how to call the service. Not mentioning the headers or anything in-depth information.
Is there any decent information around how to call a REST API or some documentation about it? Because even in W3schools, they only describe the SOAP method. What are different options for making the rest of API in PHP?
",https://stackoverflow.com/questions/9802788/call-a-rest-api-in-php,413,1080803.0,12.0,,,2012-03-21 10:33:38,2022-09-30 12:57:50,2022-02-25 00:14:44,,,php;rest;web-services,Michiel,8121,452421,registered,true,9802854,,CC BY-SA 4.0,2016-10-27 00:12:52,623,602,0,0,0,3,true,false,false,true,true,true,22,6,false,0.011,0.0004,5358,2012,3,10,Wednesday,false,false,false,false,false,false,true
2215354,PHP date() format when inserting into datetime in MySQL,"What is the correct format to pass to the date() function in PHP if I want to insert the result into a MySQL datetime type column?
I've been trying date('Y-M-D G:i:s') but that just inserts "0000-00-00 00:00:00" everytime.
",https://stackoverflow.com/questions/2215354/php-date-format-when-inserting-into-datetime-in-mysql,413,914436.0,15.0,,,2010-02-07 00:27:02,2026-04-24 17:12:50,2020-07-07 06:00:18,,,php;mysql,Alex,6685,263960,registered,true,2215359,,CC BY-SA 4.0,2014-11-11 10:05:30,286,233,3,0,0,2,true,false,false,true,true,true,55,9,false,0.016,0.0005,6131,2010,2,0,Sunday,true,false,false,false,false,false,true
3376881,Default value in Doctrine,"How do I set a default value in Doctrine 2?
",https://stackoverflow.com/questions/3376881/default-value-in-doctrine,412,436001.0,16.0,,,2010-07-31 04:59:15,2025-08-13 11:57:13,2016-01-08 22:42:19,,,php;orm;doctrine-orm,Jiew Meng,89473,292291,registered,true,3379560,,CC BY-SA 3.0,,51,44,0,0,0,3,true,false,false,true,true,true,25,4,false,0.037,0.0009,5957,2010,7,4,Saturday,true,false,false,false,false,false,true
21084833,Get the Last Inserted Id Using Laravel Eloquent,"I'm currently using the below code to insert data in a table:
<?php
public function saveDetailsCompany()
{
$post = Input::All();
$data = new Company;
$data->nombre = $post['name'];
$data->direccion = $post['address'];
$data->telefono = $post['phone'];
$data->email = $post['email'];
$data->giro = $post['type'];
$data->fecha_registro = date(""Y-m-d H:i:s"");
$data->fecha_modificacion = date(""Y-m-d H:i:s"");
if ($data->save()) {
return Response::json(array('success' => true), 200);
}
}
I want to return the last ID inserted but I don't know how to get it.
Kind regards!
",https://stackoverflow.com/questions/21084833/get-the-last-inserted-id-using-laravel-eloquent,412,852429.0,32.0,,,2014-01-13 06:02:24,2025-01-07 02:58:20,2018-11-20 07:08:52,,,php;database;laravel;eloquent,SoldierCorp,7660,1347435,registered,true,21084888,,CC BY-SA 4.0,2021-09-07 19:12:04,741,658,1,0,0,4,true,false,false,true,true,true,47,8,false,0.038,0.0005,4695,2014,1,6,Monday,false,false,false,false,false,false,true
8945879,How to get body of a JSON POST in PHP?,"I submit as POST to a PHP page the following data:
{a:1}
In my PHP code, what do I have to do to extract that value?
var_dump($_POST);
This does not work, and returns an empty array.
",https://stackoverflow.com/questions/8945879/how-to-get-body-of-a-json-post-in-php,411,499293.0,9.0,,,2012-01-20 18:05:41,2024-09-05 21:17:20,2024-09-05 21:17:20,,,php;json;post,Hakim Iben Isa AL Burage Al Mk,53846,67153,registered,true,8945912,,CC BY-SA 4.0,,332,186,2,0,0,3,true,false,false,true,true,true,38,10,true,0.018,0.0008,5419,2012,1,18,Friday,false,false,false,false,false,false,true
1699796,Best way to do multiple constructors in PHP,"You can't put two __construct functions with unique argument signatures in a PHP class. I'd like to do this:
class Student
{
protected $id;
protected $name;
// etc.
public function __construct($id){
$this->id = $id;
// other members are still uninitialized
}
public function __construct($row_from_database){
$this->id = $row_from_database->id;
$this->name = $row_from_database->name;
// etc.
}
}
What is the best way to do this in PHP?
",https://stackoverflow.com/questions/1699796/best-way-to-do-multiple-constructors-in-php,411,254076.0,25.0,,,2009-11-09 08:43:43,2021-11-16 18:08:58,,,,php;constructor;multiple-constructors,Jannie Theunissen,30336,96944,registered,true,1701337,,CC BY-SA 2.5,,550,512,1,0,0,3,true,false,false,true,true,false,43,8,false,0.098,0.0016,6221,2009,11,8,Monday,false,false,false,false,false,false,true
7093860,PHP shell_exec() vs exec(),"I'm struggling to understand the difference between shell_exec() and exec()...
I've always used exec() to execute server side commands, when would I use shell_exec()?
Is shell_exec() just a shorthand for exec()? It seems to be the same thing with fewer parameters.
",https://stackoverflow.com/questions/7093860/php-shell-exec-vs-exec,410,534359.0,4.0,,,2011-08-17 13:42:37,2019-04-29 06:13:41,2018-02-21 07:21:02,,,php;shell;command;exec,Ben,62782,197606,registered,true,7093892,,CC BY-SA 3.0,,367,268,6,0,0,4,true,false,false,true,true,true,26,4,false,0.007,0.0008,5575,2011,8,13,Wednesday,false,false,false,false,false,false,true
2630013,Invalid argument supplied for foreach(),"It often happens to me to handle data that can be either an array or a null variable and to feed some foreach with these data.
$values = get_values();
foreach ($values as $value){
...
}
When you feed a foreach with data that are not an array, you get a warning:
Warning: Invalid argument supplied for foreach() in [...]
Assuming it's not possible to refactor the get_values() function to always return an array (backward compatibility, not available source code, whatever other reason), I'm wondering which is the cleanest and most efficient way to avoid these warnings:
- Casting
$values to array
- Initializing
$values to array
- Wrapping the
foreach with an if
- Other (please suggest)
",https://stackoverflow.com/questions/2630013/invalid-argument-supplied-for-foreach,408,1279062.0,20.0,,,2010-04-13 13:48:46,2024-04-24 10:29:40,2016-09-21 16:52:09,,,php;foreach,Roberto Aloi,31095,169754,registered,true,2630032,,CC BY-SA 3.0,2015-09-01 13:49:00,896,696,7,0,0,2,true,false,false,true,true,true,39,5,false,0.016,0.0003,6066,2010,4,13,Tuesday,false,false,false,false,false,false,true
712392,Send email using the GMail SMTP server from a PHP page,"I am trying to send an email via GMail's SMTP server from a PHP page, but I get this error:
authentication failure [SMTP: SMTP server does no support authentication (code: 250, response: mx.google.com at your service, [98.117.99.235] SIZE 35651584 8BITMIME STARTTLS ENHANCEDSTATUSCODES PIPELINING)]
Can anyone help? Here is my code:
<?php
require_once ""Mail.php"";
$from = ""Sandra Sender <sender@example.com>"";
$to = ""Ramona Recipient <ramona@microsoft.com>"";
$subject = ""Hi!"";
$body = ""Hi,\n\nHow are you?"";
$host = ""smtp.gmail.com"";
$port = ""587"";
$username = ""testtest@gmail.com"";
$password = ""testtest"";
$headers = array ('From' => $from,
'To' => $to,
'Subject' => $subject);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'port' => $port,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($to, $headers, $body);
if (PEAR::isError($mail)) {
echo(""<p>"" . $mail->getMessage() . ""</p>"");
} else {
echo(""<p>Message successfully sent!</p>"");
}
?>
",https://stackoverflow.com/questions/712392/send-email-using-the-gmail-smtp-server-from-a-php-page,408,906376.0,16.0,,,2009-04-03 02:47:59,2022-05-19 17:35:51,2014-06-27 23:30:54,,,php;email;smtp;gmail,skb,31344,14101,registered,true,2748837,,CC BY-SA 3.0,2010-08-30 11:14:21,1174,1104,1,0,0,4,true,false,false,true,true,true,54,11,false,0.018,0.0005,6441,2009,4,2,Friday,false,false,false,false,false,false,true
6278296,Extract a single (unsigned) integer from a string,"I want to extract the digits from a string that contains numbers and letters like:
"In My Cart : 11 items"
I want to extract the number 11.
",https://stackoverflow.com/questions/6278296/extract-a-single-unsigned-integer-from-a-string,405,628783.0,23.0,,,2011-06-08 11:53:56,2024-08-08 11:25:00,2020-11-22 10:33:44,,,php;string;integer;text-extraction,Dali,7932,536116,registered,true,6278312,,CC BY-SA 4.0,,202,151,2,0,0,4,true,false,false,true,true,true,49,8,false,0.037,0.0006,5645,2011,6,11,Wednesday,false,false,false,false,false,false,true
168214,Pass a PHP variable to a JavaScript variable,"What is the easiest way to encode a PHP string for output to a JavaScript variable?
I have a PHP string which includes quotes and newlines. I need the contents of this string to be put into a JavaScript variable.
Normally, I would just construct my JavaScript in a PHP file, à la:
<script>
var myvar = ""<?php echo $myVarValue;?>"";
</script>
However, this doesn't work when $myVarValue contains quotes or newlines.
",https://stackoverflow.com/questions/168214/pass-a-php-variable-to-a-javascript-variable,405,348532.0,14.0,,,2008-10-03 18:27:03,2023-03-24 11:31:52,2023-03-24 11:18:00,2025-05-02 22:54:57,Duplicate,php;javascript;escaping;newline,David Laing,7705,13238,registered,true,169035,,,,505,440,2,0,0,4,true,true,false,true,true,true,44,8,false,0.04,0.0012,6623,2008,10,18,Friday,false,false,true,false,false,false,true
28468625,Laravel 5 Failed opening required bootstrap/../vendor/autoload.php,"I have recently installed Laravel 5 via Composer. I tried creating a new controller using Artisan and got the following error. Am I missing something?
bootstrap/../vendor/autoload.php. Failed to open stream: No such file or directory. The "vendor" folder does not exist.
",https://stackoverflow.com/questions/28468625/laravel-5-failed-opening-required-bootstrap-vendor-autoload-php,402,544770.0,30.0,,,2015-02-12 03:11:08,2023-05-23 18:30:02,2023-05-23 18:30:02,,,php;laravel-5;controller;composer-php;laravel-artisan,Scott,5094,2581673,registered,true,28491937,,CC BY-SA 4.0,2016-04-23 08:52:10,322,283,0,0,0,5,true,false,false,true,true,true,66,6,false,0.055,0.0007,4300,2015,2,3,Thursday,false,false,false,false,false,false,true
888,How do you debug PHP scripts?,"How do you debug PHP scripts?
I am aware of basic debugging such as using the Error Reporting. The breakpoint debugging in PHPEclipse is also quite useful.
What is the best (in terms of fast and easy) way to debug in phpStorm or any other IDE?
",https://stackoverflow.com/questions/888/how-do-you-debug-php-scripts,402,360162.0,30.0,,,2008-08-03 23:18:21,2016-08-04 08:15:23,2015-06-04 10:18:02,2016-08-04 09:22:00,Needs more focus,php;eclipse;debugging;phpstorm;xdebug,Marcel,6360,131,registered,true,890,,,2016-03-24 11:56:49,318,246,0,0,0,5,true,true,false,true,true,true,29,6,true,0.083,0.0011,6684,2008,8,23,Sunday,true,false,false,false,false,false,true
3172332,Convert seconds to Hour:Minute:Second,"I need to convert seconds to ""Hour:Minute:Second"".
For example: ""685"" converted to ""00:11:25""
How can I achieve this?
",https://stackoverflow.com/questions/3172332/convert-seconds-to-hourminutesecond,401,523686.0,28.0,,,2010-07-03 17:56:43,2025-05-06 08:36:18,2017-10-31 14:54:47,,,php;time,EzzDev,10250,232388,registered,true,3172358,,CC BY-SA 3.0,2016-03-17 19:08:14,141,120,0,0,0,2,true,false,false,true,true,true,37,4,false,0.053,0.0008,5985,2010,7,17,Saturday,true,false,false,false,false,false,true
9205083,Traits vs. interfaces,"I've been trying to study up on PHP lately, and I find myself getting hung up on traits. I understand the concept of horizontal code reuse and not wanting to necessarily inherit from an abstract class. What I don't understand is: What is the crucial difference between using traits versus interfaces?
I've tried searching for a decent blog post or article explaining when to use one or the other, but the examples I've found so far seem so similar as to be identical.
",https://stackoverflow.com/questions/9205083/traits-vs-interfaces,401,138476.0,13.0,,,2012-02-09 03:40:21,2020-10-13 19:30:19,2019-07-14 12:56:31,,,php;interface;traits,datguywhowanders,4411,361675,registered,true,9205132,,CC BY-SA 4.0,2018-11-13 16:25:48,483,469,0,0,0,3,true,false,false,true,true,true,21,3,false,0.094,0.0029,5399,2012,2,3,Thursday,false,false,false,false,false,false,true
1993409,?: operator (the 'Elvis operator') in PHP,"I saw this today in some PHP code:
$items = $items ?: $this->_handle->result('next', $this->_result, $this);
I'm not familiar with the ?: operator being used here. It looks like a ternary operator, but the expression to evaluate to if the predicate is true has been omitted. What does it mean?
",https://stackoverflow.com/questions/1993409/operator-the-elvis-operator-in-php,401,280037.0,7.0,,,2010-01-03 00:10:58,2023-09-01 13:30:03,2020-11-06 00:21:11,,,php;conditional-operator;language-construct,alpha_juno,4013,242494,registered,true,1993455,,CC BY-SA 4.0,,357,306,2,0,0,3,true,false,false,true,true,true,49,7,false,0.025,0.0014,6166,2010,1,0,Sunday,true,false,false,false,false,false,true
4268871,PHP append one array to another (not array_push or +),"How to append one array to another without comparing their keys?
$a = array( 'a', 'b' );
$b = array( 'c', 'd' );
At the end it should be: Array( [0]=>a [1]=>b [2]=>c [3]=>d )
If I use something like [] or array_push, it will cause one of these results:
Array( [0]=>a [1]=>b [2]=>Array( [0]=>c [1]=>d ) )
//or
Array( [0]=>c [1]=>d )
It just should be something, doing this, but in a more elegant way:
foreach ( $b AS $var )
$a[] = $var;
",https://stackoverflow.com/questions/4268871/php-append-one-array-to-another-not-array-push-or,401,651300.0,9.0,,,2010-11-24 16:09:56,2025-02-28 01:28:26,2015-11-18 03:48:28,,,php;arrays;function,Danil K,4057,515914,registered,true,4268954,,CC BY-SA 3.0,2022-05-11 23:03:29,613,481,6,0,0,3,true,false,false,true,true,true,53,10,false,0.014,0.0006,5841,2010,11,16,Wednesday,false,false,false,false,false,false,true
14395631,php create object without class,"In JavaScript, you can easiliy create an object without a class by:
myObj = {};
myObj.abc = "aaaa";
For PHP I've found this one, but it is nearly 4 years old:
http://www.subclosure.com/php-creating-anonymous-objects-on-the-fly.html
$obj = (object) array('foo' => 'bar', 'property' => 'value');
Now with PHP 5.4 in 2013, is there an alternative to this?
",https://stackoverflow.com/questions/14395631/php-create-object-without-class,400,457336.0,1.0,,,2013-01-18 09:13:03,2020-08-17 21:33:47,2020-08-17 21:33:47,2020-08-17 21:33:12,Duplicate,php,Wolfgang Adamec,8594,780522,registered,true,14395679,,,,546,373,2,1,0,1,true,true,false,true,true,true,31,5,false,0.002,0.0009,5055,2013,1,9,Friday,false,false,false,false,false,false,true
4915753,How can I remove three characters at the end of a string in PHP?,"How can I remove three characters at the end of a string in PHP?
"abcabcabc" would become "abcabc"!
",https://stackoverflow.com/questions/4915753/how-can-i-remove-three-characters-at-the-end-of-a-string-in-php,399,477206.0,3.0,,,2011-02-06 20:05:20,2021-10-13 18:23:04,2021-10-13 18:02:39,,,php;string,user502039,,,does_not_exist,true,4915787,,CC BY-SA 4.0,,134,120,0,0,0,2,true,false,false,true,false,true,64,14,true,0.006,0.0008,5767,2011,2,20,Sunday,true,false,false,false,false,false,true
26193314,Could not open input file: artisan,"When trying to create a new laravel project, The following error appears on the CLI:
Could not open input file: artisan
Script php artisan clear-compiled handling the post-install-cmd event returned with an error
I am using the latest version of XAMPP v3.2.1 with PHP 5.5.15 and with mcrypt enabled (made sure of that by issuing the command php -m). And I am running windows 8.1
",https://stackoverflow.com/questions/26193314/could-not-open-input-file-artisan,399,963573.0,25.0,,,2014-10-04 13:29:44,2023-05-11 06:14:23,2020-06-20 09:12:55,,,php;laravel;laravel-4;laravel-artisan,wessodesigner,4745,1799131,registered,true,,,CC BY-SA 4.0,2015-04-08 06:59:04,434,381,0,0,0,4,false,false,false,true,true,true,34,6,false,0.026,0.0004,4431,2014,10,13,Saturday,true,false,false,false,false,false,true
18352682,Correct file permissions for WordPress,"I've had a look over here but didn't find any details on the best file permissions. I also took a look at some of WordPress's form's questions over here too but anybody that suggests 777 obviously needs a little lesson in security.
In short my question is this. What permissions should I have for the following:
- root folder storing all the WordPress content
- wp-admin
- wp-content
- wp-includes
and then all the files in each of those folders?
",https://stackoverflow.com/questions/18352682/correct-file-permissions-for-wordpress,399,979354.0,15.0,,,2013-08-21 08:39:57,2020-01-24 23:38:56,2019-06-17 19:38:11,2019-06-17 19:59:34,Not suitable for this site,php;wordpress;chmod,John Crawford,10219,2266042,registered,true,23755604,,,,710,446,0,2,0,3,true,true,false,true,true,true,38,5,false,0.015,0.0004,4840,2013,8,8,Wednesday,false,false,false,false,false,false,true
3958615,Import file size limit in PHPMyAdmin,"I have changed all the php.ini parameters I know:
upload_max_filesize, and post_max_size.
Why am I still seeing 2MB?
I'm using Zend Server CE on a Ubuntu VirtualBox over a Windows 7 host.
",https://stackoverflow.com/questions/3958615/import-file-size-limit-in-phpmyadmin,398,1262731.0,31.0,,,2010-10-18 11:24:55,2025-04-17 12:53:40,2025-04-17 12:53:40,,,php;mysql;phpmyadmin,ronaldosantana,5282,234253,registered,true,3958659,,CC BY-SA 4.0,2014-10-27 14:13:29,235,188,2,0,0,3,true,false,false,true,true,true,36,6,false,0.025,0.0003,5878,2010,10,11,Monday,false,false,false,false,false,false,true
1372147,Check whether a request is GET or POST ,"
Possible Duplicate:
PHP detecting request type (GET, POST, PUT or DELETE)
This should be an easy one.
I have a script, and in the script I want to determine whether the request arrive via GET or POST method.
What is the correct way to do it?
I am thinking of using something like this
if (isset($_POST)) {
// do post
} else {
// do get
}
But deep in my heart I don't feel this is the right way. Any idea?
",https://stackoverflow.com/questions/1372147/check-whether-a-request-is-get-or-post,397,374657.0,2.0,,,2009-09-03 08:33:16,2024-08-21 15:39:33,2017-05-23 12:26:38,2012-11-05 20:38:55,exact duplicate,php,Graviton,83405,3834,registered,true,1372163,,,,677,432,3,1,0,1,true,true,false,true,true,true,39,8,false,0.005,0.0011,6288,2009,9,8,Thursday,false,false,false,false,false,false,true
346980,How should I choose an authentication library for CodeIgniter?,"I see there are a few. Which ones are maintained and easy to use? What are their pros and cons?
",https://stackoverflow.com/questions/346980/how-should-i-choose-an-authentication-library-for-codeigniter,397,155005.0,11.0,,,2008-12-06 23:31:03,2015-07-07 21:49:34,2012-05-24 03:37:07,2014-09-15 00:41:55,Not suitable for this site,php;codeigniter;authentication,GavinR,6264,2039,registered,true,476902,,,2011-02-26 18:57:57,199,97,0,1,0,3,true,true,false,true,true,true,62,9,true,0.071,0.0026,6559,2008,12,23,Saturday,true,false,false,false,false,false,true
113829,How to convert date to timestamp in PHP?,"How do I get timestamp from e.g. 22-09-2008?
",https://stackoverflow.com/questions/113829/how-to-convert-date-to-timestamp-in-php,395,1035083.0,16.0,,,2008-09-22 08:41:20,2024-08-06 09:09:55,2011-08-04 15:32:55,,,php;date;timestamp,Wizard4U,4127,205368,registered,true,,,CC BY-SA 3.0,2015-07-13 05:28:31,65,45,1,0,0,3,false,false,false,true,true,true,40,8,true,0.015,0.0004,6634,2008,9,8,Monday,false,false,false,false,false,false,true
5678959,PHP - Check if two arrays are equal,"I'd like to check if two arrays are equal. I mean: same size, same index, same values. How can I do that?
Using !== as suggested by a user, I expect that the following would print enter if at least one element in the array(s) are different, but in fact it does not.
if (($_POST['atlOriginal'] !== $oldAtlPosition)
or ($_POST['atl'] !== $aext)
or ($_POST['sidesOriginal'] !== $oldSidePosition)
or ($_POST['sidesOriginal'] !== $sideext)) {
echo ""enter"";
}
",https://stackoverflow.com/questions/5678959/php-check-if-two-arrays-are-equal,394,498402.0,21.0,,,2011-04-15 15:25:02,2026-09-26 14:48:40,2019-07-18 22:39:20,,,php;arrays,markzzz,48429,365251,registered,true,5678990,,CC BY-SA 4.0,2019-06-01 02:02:58,545,477,2,0,0,2,true,false,false,true,true,true,35,8,false,0.042,0.0008,5699,2011,4,15,Friday,false,false,false,false,false,false,true
16765158,"date(): It is not safe to rely on the system's timezone settings...","I got this error when I requested to update the PHP version from 5.2.17 to PHP 5.3.21 on the server.
<div style=""border:1px solid #990000;padding-left:20px;margin:0 0 10px 0;"">
<h4>A PHP Error was encountered</h4>
<p>Severity: Warning</p>
<p>Message: date(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'America/New_York' for 'EDT/-4.0/DST' instead</p>
<p>Filename: libraries/Log.php</p>
<p>Line Number: 86</p>
</div>
Warning: date(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'America/New_York' for 'EDT/-4.0/DST' instead in /filelocation right here/system/libraries/Log.php on line 86
Warning: date(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'America/New_York' for 'EDT/-4.0/DST' instead in /filelocation right here/system/libraries/Log.php on line 99
<div style=""border:1px solid #990000;padding-left:20px;margin:0 0 10px 0;"">
<h4>A PHP Error was encountered</h4>
<p>Severity: Warning</p>
<p>Message: date(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'America/New_York' for 'EDT/-4.0/DST' instead</p>
<p>Filename: libraries/Log.php</p>
<p>Line Number: 99</p>
</div>
",https://stackoverflow.com/questions/16765158/date-it-is-not-safe-to-rely-on-the-systems-timezone-settings,393,619332.0,25.0,,,2013-05-27 01:05:31,2021-07-10 10:52:09,2016-01-04 18:26:27,,,php;timezone,user1852837,4491,1852837,registered,true,16765214,,CC BY-SA 3.0,,2322,2244,1,1,0,2,true,false,false,true,true,true,83,12,false,0.04,0.0006,4926,2013,5,1,Monday,false,false,false,false,false,false,true
3161816,Truncate a string to first n characters of a string and add three dots if any characters are removed,"How can I get the first n characters of a string in PHP? What's the fastest way to trim a string to a specific number of characters, and append '...' if needed?
",https://stackoverflow.com/questions/3161816/truncate-a-string-to-first-n-characters-of-a-string-and-add-three-dots-if-any-ch,393,554300.0,21.0,,,2010-07-01 21:28:19,2025-04-29 12:01:48,2021-03-03 03:36:42,,,php;string;ellipsis;truncation,Alex,66826,376947,registered,true,3161830,,CC BY-SA 4.0,2013-12-17 17:25:20,168,161,0,0,0,4,true,false,false,true,true,true,100,19,false,0.038,0.0007,5987,2010,7,21,Thursday,false,false,false,false,false,false,true
4514323,Javascript Equivalent to PHP Explode(),"I have this string:
0000000020C90037:TEMP:data
I need this string:
TEMP:data.
With PHP I would do this:
$str = '0000000020C90037:TEMP:data';
$arr = explode(':', $str);
$var = $arr[1].':'.$arr[2];
How do I effectively explode a string in JavaScript the way it works in PHP?
",https://stackoverflow.com/questions/4514323/javascript-equivalent-to-php-explode,393,438571.0,17.0,,,2010-12-22 22:34:33,2021-01-26 14:59:26,2020-04-04 07:37:44,,,javascript;php;string,Doug Molineux,12458,242934,registered,true,4514357,,CC BY-SA 4.0,,417,288,2,0,0,3,true,false,false,true,true,true,38,5,false,0.039,0.0009,5813,2010,12,22,Wednesday,false,false,true,false,false,false,true
2473989,List of Big-O for PHP functions,"After using PHP for a while now, I've noticed that not all built-in PHP functions are as fast as expected. Consider these two possible implementations of a function that finds if a number is prime using a cached array of primes.
//very slow for large $prime_array
$prime_array = array( 2, 3, 5, 7, 11, 13, .... 104729, ... );
$result_array = array();
foreach( $prime_array => $number ) {
$result_array[$number] = in_array( $number, $large_prime_array );
}
//speed is much less dependent on size of $prime_array, and runs much faster.
$prime_array => array( 2 => NULL, 3 => NULL, 5 => NULL, 7 => NULL,
11 => NULL, 13 => NULL, .... 104729 => NULL, ... );
foreach( $prime_array => $number ) {
$result_array[$number] = array_key_exists( $number, $large_prime_array );
}
This is because in_array is implemented with a linear search O(n) which will linearly slow down as $prime_array grows. Where the array_key_exists function is implemented with a hash lookup O(1) which will not slow down unless the hash table gets extremely populated (in which case it's only O(n)).
So far I've had to discover the big-O's via trial and error, and occasionally looking at the source code. Now for the question...
Is there a list of the theoretical (or practical) big O times for all* the built-in PHP functions?
*or at least the interesting ones
For example, I find it very hard to predict the big O of functions listed because the possible implementation depends on unknown core data structures of PHP: array_merge, array_merge_recursive, array_reverse, array_intersect, array_combine, str_replace (with array inputs), etc.
",https://stackoverflow.com/questions/2473989/list-of-big-o-for-php-functions,393,103995.0,4.0,,,2010-03-18 23:12:32,2019-04-16 16:16:14,2019-04-16 16:16:14,,,php;performance;algorithm;arrays;big-o,Kendall Hopkins,44344,188044,registered,true,2484455,,CC BY-SA 4.0,,1981,1675,10,1,0,5,true,false,false,true,true,true,31,6,false,0.038,0.0038,6092,2010,3,23,Thursday,false,false,false,false,false,false,true
8469767,Get URL query string parameters,"What is the ""less code needed"" way to get parameters from a URL query string which is formatted like the following?
www.mysite.com/category/subcategory?myqueryhash
Output should be: myqueryhash
I am aware of this approach:
www.mysite.com/category/subcategory?q=myquery
<?php
echo $_GET['q']; //Output: myquery
?>
",https://stackoverflow.com/questions/8469767/get-url-query-string-parameters,392,1069449.0,12.0,,,2011-12-12 03:56:02,2025-11-22 12:09:43,2018-10-21 06:09:22,,,php;url;query-string,enloz,5904,901434,registered,true,8469777,,CC BY-SA 4.0,,423,333,2,0,0,3,true,false,false,true,true,true,31,5,false,0.011,0.0004,5458,2011,12,3,Monday,false,false,false,false,false,false,true
34199982,How can I query all the GraphQL type fields without writing a long query?,"Assume you have a GraphQL type and it includes many fields.
How can I query all the fields without writing down a long query that includes the names of all the fields?
For example, if I have these fields:
public function fields()
{
return [
'id' => [
'type' => Type::nonNull(Type::string()),
'description' => 'The id of the user'
],
'username' => [
'type' => Type::string(),
'description' => 'The email of user'
],
'count' => [
'type' => Type::int(),
'description' => 'login count for the user'
]
];
}
To query all the fields, usually the query is something like this:
FetchUsers{users(id:"2"){id,username,count}}
But I want a way to have the same results without writing all the fields. Something like this:
FetchUsers{users(id:"2"){*}}
// Or
FetchUsers{users(id:"2")}
Is there a way to do this in GraphQL?
I'm using the Folkloreatelier/laravel-graphql library.
",https://stackoverflow.com/questions/34199982/how-can-i-query-all-the-graphql-type-fields-without-writing-a-long-query,392,406863.0,8.0,,,2015-12-10 10:50:43,2026-05-12 17:16:04,2026-05-12 17:16:04,,,php;laravel;graphql;graphql-php,BlackSigma,4025,1334945,registered,true,34226484,,CC BY-SA 4.0,,1242,1119,3,0,0,4,true,false,false,true,true,true,73,14,true,0.02,0.001,3999,2015,12,10,Thursday,false,false,false,false,false,false,true
2167916,Convert one date format into another in PHP,"Is there a simple way to convert one date format into another date format in PHP?
I have this:
$old_date = date('y-m-d-h-i-s'); // works
$middle = strtotime($old_date); // returns bool(false)
$new_date = date('Y-m-d H:i:s', $middle); // returns 1970-01-01 00:00:00
But I'd of course like it to return a current date rather than the crack 'o dawn. What am I doing wrong?
",https://stackoverflow.com/questions/2167916/convert-one-date-format-into-another-in-php,390,730073.0,18.0,,,2010-01-30 12:58:56,2023-12-20 18:43:40,2019-06-05 19:07:33,,,php;date;datetime;format;date-conversion,Tom,30808,244932,registered,true,2167925,,CC BY-SA 4.0,2014-02-03 16:31:37,446,401,1,0,0,5,true,false,false,true,true,true,43,8,false,0.025,0.0005,6139,2010,1,12,Saturday,true,false,false,false,false,false,true
49212475,Composer require runs out of memory. PHP Fatal error: Allowed memory size of 1610612736 bytes exhausted,"I am trying to add HWIOAuthBundle to my project by running the below command.
composer require hwi/oauth-bundle php-http/guzzle6-adapter php-http/httplug-bundle
HWIOAuthBundle github: https://github.com/hwi/HWIOAuthBundle
When I try to run composer require I am getting the out of memory error.
Using version ^0.6.0@dev for hwi/oauth-bundle Using version ^1.2@dev
for php-http/guzzle6-adapter Using version ^1.10@dev for
php-http/httplug-bundle ./composer.json has been updated Loading
composer repositories with package information Updating dependencies
(including require-dev)
PHP Fatal error: Allowed memory size of 1610612736 bytes exhausted
(tried to allocate 67108864 bytes) in
phar:///usr/local/Cellar/composer/1.4.2/libexec/composer.phar/src/Composer/DependencyResolver/Solver.php on line 220
Fatal error: Allowed memory size of 1610612736 bytes exhausted (tried
to allocate 67108864 bytes) in
phar:///usr/local/Cellar/composer/1.4.2/libexec/composer.phar/src/Composer/DependencyResolver/Solver.php on line 220
I tried setting the memory_limit to 2G in my php.ini file but did not work. I found my php.ini by running php -i | grep php.ini
",https://stackoverflow.com/questions/49212475/composer-require-runs-out-of-memory-php-fatal-error-allowed-memory-size-of-161,387,612384.0,24.0,,,2018-03-10 18:19:13,2023-04-07 09:13:02,2018-03-10 22:14:13,,,php;symfony;composer-php,Brian Chen,4071,7416985,registered,true,49212550,,CC BY-SA 3.0,2020-12-03 20:31:10,1365,1185,2,1,0,3,true,false,false,true,true,true,103,16,false,0.039,0.0006,3178,2018,3,18,Saturday,true,false,false,false,false,false,true
1319903,How to Flatten a Multidimensional Array?,"Is it possible, in PHP, to flatten a (bi/multi)dimensional array without using recursion or references?
I'm only interested in the values so the keys can be ignored, I'm thinking in the lines of array_map() and array_values().
",https://stackoverflow.com/questions/1319903/how-to-flatten-a-multidimensional-array,387,472804.0,31.0,,,2009-08-23 23:47:25,2025-12-23 14:53:59,2012-01-08 19:41:06,,,php;arrays;multidimensional-array;flatten,Alix Axel,155512,89771,registered,true,1320259,,CC BY-SA 3.0,2014-05-08 20:36:19,268,228,2,0,0,4,true,false,false,true,true,true,40,6,true,0.066,0.0008,6299,2009,8,23,Sunday,true,false,false,false,false,false,true
2202999,Why is textarea filled with mysterious white spaces?,"I have a simple text area in a form like this:
<textarea style="width:350px; height:80px;" cols="42" rows="5" name="sitelink">
<?php if($siteLink_val) echo $siteLink_val;?>
</textarea>
I keep getting extra white space in this textarea. When I tab into it my cursor is like in the middle of the textarea and not in the beginning? What is the explanation?
",https://stackoverflow.com/questions/2202999/why-is-textarea-filled-with-mysterious-white-spaces,386,242615.0,23.0,,,2010-02-04 20:35:33,2025-10-11 03:11:03,2023-06-26 07:40:13,,,php;html;forms;textarea,Afamee,5360,79685,registered,true,2203009,,CC BY-SA 4.0,2013-07-29 06:26:23,588,446,3,1,0,4,true,false,false,true,true,true,52,8,true,0.095,0.0016,6134,2010,2,20,Thursday,false,false,false,false,false,false,true
3938534,Download File to server from URL,"Well, this one seems quite simple, and it is. All you have to do to download a file to your server is:
file_put_contents(""Tmpfile.zip"", file_get_contents(""http://someurl/file.zip""));
Only there is one problem. What if you have a large file, like 100mb. Then, you will run out of memory, and not be able to download the file.
What I want is a way to write the file to the disk as I am downloading it. That way, I can download bigger files, without running into memory problems.
",https://stackoverflow.com/questions/3938534/download-file-to-server-from-url,386,724602.0,12.0,,,2010-10-15 00:09:07,2022-01-06 15:09:08,2013-03-31 14:17:59,,,php;http;stream;download,xaav,7946,195644,registered,true,3938551,,CC BY-SA 3.0,,526,481,1,0,0,4,true,false,false,true,true,true,32,6,false,0.017,0.0005,5881,2010,10,0,Friday,false,false,false,false,false,false,true
35301,What is the difference between the | and || or operators?,"I have always used || (two pipes) in OR expressions, both in C# and PHP. Occasionally I see a single pipe used: |. What is the difference between those two usages? Are there any caveats when using one over the other or are they interchangeable?
",https://stackoverflow.com/questions/35301/what-is-the-difference-between-the-and-or-operators,386,240200.0,11.0,,,2008-08-29 21:11:17,2020-07-18 12:15:33,2013-07-23 08:05:47,,,c#;php;operators,GloryFish,13438,3238,registered,true,35314,,CC BY-SA 3.0,2020-05-15 20:30:03,278,245,2,0,0,3,true,false,false,true,true,true,57,11,true,0.046,0.0016,6658,2008,8,21,Friday,false,false,false,false,true,false,true
535020,Tracking the script execution time in PHP,"PHP must track the amount of CPU time a particular script has used in order to enforce the max_execution_time limit.
Is there a way to get access to this inside of the script? I'd like to include some logging with my tests about how much CPU was burnt in the actual PHP (the time is not incremented when the script is sitting and waiting for the database).
I am using a Linux box.
",https://stackoverflow.com/questions/535020/tracking-the-script-execution-time-in-php,385,596676.0,21.0,,,2009-02-11 00:58:31,2024-08-09 05:45:15,2014-08-07 21:21:03,,,php;performance,twk,17468,23524,registered,true,535040,,CC BY-SA 3.0,,409,388,0,0,0,2,true,false,false,true,true,true,41,7,false,0.035,0.0006,6492,2009,2,0,Wednesday,false,false,false,false,false,false,true
13917558,Laravel - Eloquent or Fluent random row,"How can I select a random row using Eloquent or Fluent in Laravel framework?
I know that by using SQL, you can do order by RAND(). However, I would like to get the random row without doing a count on the number of records prior to the initial query.
Any ideas?
",https://stackoverflow.com/questions/13917558/laravel-eloquent-or-fluent-random-row,385,446537.0,17.0,,,2012-12-17 15:59:25,2023-07-07 05:09:23,2020-06-16 04:38:09,,,php;laravel;random;eloquent;fluent,DigitalWM,4536,470017,registered,true,13931676,,CC BY-SA 4.0,2023-07-07 16:26:14,301,263,0,0,0,5,true,false,false,true,true,true,39,7,false,0.038,0.0009,5087,2012,12,15,Monday,false,false,false,false,false,false,true
5335273,How can I send an email using PHP?,"I am using PHP on a website and I want to add emailing functionality.
I have WampServer installed.
How do I send an email using PHP?
",https://stackoverflow.com/questions/5335273/how-can-i-send-an-email-using-php,385,1291877.0,20.0,,,2011-03-17 05:34:46,2025-10-22 18:49:28,2021-03-27 02:50:22,,,php;email;wamp;wampserver,user590849,11875,590849,registered,true,5335311,,CC BY-SA 4.0,2014-08-24 16:22:17,226,133,0,1,0,4,true,false,false,true,true,true,34,8,true,0.015,0.0003,5728,2011,3,5,Thursday,false,false,false,false,false,false,true
3967515,How to convert an image to Base64 encoding,"How can I convert an image from a URL to Base64 encoding?
",https://stackoverflow.com/questions/3967515/how-to-convert-an-image-to-base64-encoding,382,642527.0,9.0,,,2010-10-19 10:44:03,2025-02-20 16:04:24,2021-08-02 11:44:45,,,php;image;base64,Volatil3,15133,275002,registered,true,13758760,,CC BY-SA 4.0,2015-03-27 19:27:38,65,58,0,0,0,3,true,false,false,true,true,true,42,8,false,0.014,0.0006,5877,2010,10,10,Tuesday,false,false,false,false,false,false,true
1814821,Interface or an Abstract Class: which one to use?,"Please explain when I should use a PHP interface and when I should use an abstract class?
How I can change my abstract class in to an interface?
",https://stackoverflow.com/questions/1814821/interface-or-an-abstract-class-which-one-to-use,380,149912.0,11.0,,,2009-11-29 06:21:01,2024-08-28 17:12:09,2018-05-24 16:11:53,,,php;oop;interface;abstract-class,user220758,,,does_not_exist,true,,,CC BY-SA 4.0,,212,146,4,0,0,4,false,false,false,true,false,true,49,9,true,0.073,0.0025,6201,2009,11,6,Sunday,true,false,false,false,false,false,true
29822686,cURL error 60: SSL certificate: unable to get local issuer certificate,"I am trying to send an API request using Stripe but get the error message:
cURL error 60: SSL certificate problem: unable to get local issuer certificate
This is the code I am running:
public function chargeStripe()
{
$stripe = new Stripe;
$stripe = Stripe::make(env('STRIPE_PUBLIC_KEY'));
$charge = $stripe->charges()->create([
'amount' => 2900,
'customer' => Input::get('stripeEmail'),
'currency' => 'EUR',
]);
return Redirect::route('step1');
}
I searched a lot on Google and lots of people are suggesting that I download this file: cacert.pem, put it somewhere and reference it in my php.ini. This is the part in my php.ini:
curl.cainfo = "C:\Windows\cacert.pem"
Yet, even after restarting my server several times and changing the path, I get the same error message.
I have the ssl_module enabled in Apache, and I have php_curl enabled in my php.ini.
I have also tried another fix which suggests that I add these lines to my cURL options:
curl_setopt($process, CURLOPT_CAINFO, dirname(__FILE__) . '/cacert.pem');
curl_setopt($process, CURLOPT_SSL_VERIFYPEER, true);
Where do I add options to my cURL? Apparently not through the command line, since my CLI doesn't find the command "curl_setopt"
",https://stackoverflow.com/questions/29822686/curl-error-60-ssl-certificate-unable-to-get-local-issuer-certificate,378,694373.0,28.0,,,2015-04-23 11:54:20,2025-11-25 14:18:02,2023-02-16 21:21:43,,,php;ssl;curl;stripe-payments,LoveAndHappiness,10275,2807996,registered,true,34883260,,CC BY-SA 4.0,2018-04-04 14:00:51,1517,1286,4,1,0,4,true,false,false,true,true,true,70,11,false,0.04,0.0005,4230,2015,4,11,Thursday,false,false,false,false,false,false,true
6238992,Converting string to Date and DateTime,"If I have a PHP string in the format of mm-dd-YYYY (for example, 10-16-2003), how do I properly convert that to a Date and then a DateTime in the format of YYYY-mm-dd? The only reason I ask for both Date and DateTime is because I need one in one spot, and the other in a different spot.
",https://stackoverflow.com/questions/6238992/converting-string-to-date-and-datetime,377,1254547.0,13.0,,,2011-06-04 19:46:07,2024-03-24 23:38:19,2015-04-17 14:44:23,,,php;string;datetime;date,Chris Pinski,4683,591659,registered,true,6239010,,CC BY-SA 3.0,,372,287,6,0,0,4,true,false,false,true,true,true,38,6,false,0.01,0.0003,5649,2011,6,19,Saturday,true,false,false,false,false,false,true
3191664,List of All Locales and Their Short Codes?,"I'm looking for a list of all locales and their short codes for a PHP application I am writing. Is there much variation in this data between platforms?
Also, if I am developing an international application, can I just support one version of English or are there significant differences in English across the world?
",https://stackoverflow.com/questions/3191664/list-of-all-locales-and-their-short-codes,377,632980.0,11.0,,,2010-07-07 03:19:16,2025-11-13 18:58:01,2010-07-07 03:31:44,,,php;internationalization;locale,Kirk Ouimet,28610,102635,registered,true,3191729,,CC BY-SA 2.5,2021-06-26 20:09:43,330,316,0,0,0,3,true,false,false,true,true,true,42,8,true,0.017,0.0006,5981,2010,7,3,Wednesday,false,false,false,false,false,false,true
307674,How to remove duplicate values from a multi-dimensional array in PHP,"How can I remove duplicate values from a multi-dimensional array in PHP?
Example array:
Array
(
[0] => Array
(
[0] => abc
[1] => def
)
[1] => Array
(
[0] => ghi
[1] => jkl
)
[2] => Array
(
[0] => mno
[1] => pql
)
[3] => Array
(
[0] => abc
[1] => def
)
[4] => Array
(
[0] => ghi
[1] => jkl
)
[5] => Array
(
[0] => mno
[1] => pql
)
)
",https://stackoverflow.com/questions/307674/how-to-remove-duplicate-values-from-a-multi-dimensional-array-in-php,376,374345.0,17.0,,,2008-11-21 02:50:30,2022-11-18 23:57:16,,,,php;arrays;duplicate-data,Ian,12281,39539,registered,true,946300,,CC BY-SA 2.5,2012-10-02 15:15:47,601,563,1,0,0,3,true,false,false,true,true,false,68,11,false,0.045,0.001,6574,2008,11,2,Friday,false,false,false,false,false,false,true
4165195,MySQL query to get column names?,"I'd like to get all of a MySQL table's column names into an array in PHP.
Is there a query for this?
",https://stackoverflow.com/questions/4165195/mysql-query-to-get-column-names,376,767331.0,23.0,,,2010-11-12 13:42:23,2025-01-03 17:11:37,2024-12-30 23:30:55,,,php;mysql,Haroldo,37567,289666,registered,true,4165253,,CC BY-SA 4.0,2017-03-03 20:10:14,115,101,0,0,0,2,true,false,false,true,true,true,32,6,true,0.03,0.0005,5853,2010,11,13,Friday,false,false,false,false,false,false,true
2348205,How to get last key in an array?,"How can I get the last key of an array?
",https://stackoverflow.com/questions/2348205/how-to-get-last-key-in-an-array,376,517043.0,18.0,,,2010-02-27 17:09:50,2022-07-31 19:31:07,2015-04-02 12:42:09,,,php;arrays,ajsie,80288,206446,registered,true,2348213,,CC BY-SA 3.0,2019-05-05 19:33:47,47,40,0,0,0,2,true,false,false,true,true,true,32,8,true,0.035,0.0007,6111,2010,2,17,Saturday,true,false,false,false,false,false,true
272361,How can I handle the warning of file_get_contents() function in PHP?,"I wrote a PHP code like this
$site=""http://www.google.com"";
$content = file_get_content($site);
echo $content;
But when I remove ""http://"" from $site I get the following warning:
Warning:
file_get_contents(www.google.com)
[function.file-get-contents]: failed
to open stream:
I tried try and catch but it didn't work.
",https://stackoverflow.com/questions/272361/how-can-i-handle-the-warning-of-file-get-contents-function-in-php,375,446689.0,17.0,,,2008-11-07 15:10:52,2023-06-24 09:58:34,2021-10-04 13:18:50,2022-06-17 07:50:05,Duplicate,php;function;exception;warnings;file-get-contents,Waseem,11987,22634,registered,true,272377,,,,448,332,4,0,0,5,true,true,false,true,true,true,68,11,true,0.038,0.0008,6588,2008,11,15,Friday,false,false,false,false,false,false,true
4594180,Deleting all files from a folder using PHP?,"For example I had a folder called `Temp' and I wanted to delete or flush all files from this folder using PHP. Could I do this?
",https://stackoverflow.com/questions/4594180/deleting-all-files-from-a-folder-using-php,374,450831.0,18.0,,,2011-01-04 13:35:43,2023-03-29 19:51:09,2019-08-09 22:09:23,,,php;file;directory;glob,getaway,9034,428137,registered,true,4594262,,CC BY-SA 4.0,2019-10-01 09:39:59,135,128,0,0,0,4,true,false,false,true,true,true,43,8,true,0.04,0.0008,5800,2011,1,13,Tuesday,false,false,false,false,false,false,true
541430,How do I read any request header in PHP?,"How should I read any header in PHP?
For example the custom header: X-Requested-With.
",https://stackoverflow.com/questions/541430/how-do-i-read-any-request-header-in-php,373,638368.0,16.0,,,2009-02-12 14:21:25,2023-08-11 13:23:45,2023-08-11 13:23:45,,,php;http-headers,Sabya,12004,48625,registered,true,541463,,CC BY-SA 4.0,,114,87,1,0,0,2,true,false,false,true,true,true,40,9,true,0.025,0.0006,6491,2009,2,14,Thursday,false,false,false,false,false,false,true
31847054,How to use multiple databases in Laravel,"I want to combine multiple databases in my system. Most of the time the database is MySQL; but it may differ in future i.e. Admin can generate such a reports which is use source of heterogeneous database system.
So my question is does Laravel provide any Facade to deal with such situations? Or any other framework have more suitable capabilities for problem is?
",https://stackoverflow.com/questions/31847054/how-to-use-multiple-databases-in-laravel,372,401089.0,9.0,,,2015-08-06 04:47:55,2024-10-21 18:34:08,2021-12-26 22:31:56,,,php;mysql;laravel;database,Chintan7027,7649,1578380,registered,true,31847198,,CC BY-SA 4.0,2017-07-27 14:12:35,413,365,0,0,0,4,true,false,false,true,true,true,40,7,false,0.022,0.0009,4125,2015,8,4,Thursday,false,false,false,false,false,false,true
2185320,How to enable PHP short tags?,"I have a web application on a Linux server which starts with <?
I needed to copy this application to a windows environment and everything is working fine except that an SQL statement is being rendered differently. I don't know if this has to do with the script beginning with <?php instead of <? because I don't know from where to enable the <? from the PHP.ini so I changed it to <?php
I know that these 2 statements are supposed to mean the same but I need to test it with <? in order to ensure that the application is exactly the same. This way I can eliminate another possibility.
Thanks
",https://stackoverflow.com/questions/2185320/how-to-enable-php-short-tags,371,672807.0,21.0,,,2010-02-02 15:44:10,2021-05-22 20:20:48,2013-05-12 15:41:45,,,php;tags;php-shorttags,seedg,22015,213689,registered,true,2185331,,CC BY-SA 3.0,2014-08-24 16:22:39,732,613,7,0,0,3,true,false,false,true,true,true,29,6,true,0.031,0.0006,6136,2010,2,15,Tuesday,false,false,false,false,false,false,true
695289,Cannot simply use PostgreSQL table name ("relation does not exist"),"I'm trying to run the following PHP script to do a simple database query:
$db_host = ""localhost"";
$db_name = ""showfinder"";
$username = ""user"";
$password = ""password"";
$dbconn = pg_connect(""host=$db_host dbname=$db_name user=$username password=$password"")
or die('Could not connect: ' . pg_last_error());
$query = 'SELECT * FROM sf_bands LIMIT 10';
$result = pg_query($query) or die('Query failed: ' . pg_last_error());
This produces the following error:
Query failed: ERROR: relation ""sf_bands"" does not exist
In all the examples I can find where someone gets an error stating the relation does not exist, it's because they use uppercase letters in their table name. My table name does not have uppercase letters. Is there a way to query my table without including the database name, i.e. showfinder.sf_bands?
",https://stackoverflow.com/questions/695289/cannot-simply-use-postgresql-table-name-relation-does-not-exist,369,980006.0,19.0,,,2009-03-29 20:16:21,2024-06-12 07:02:36,2018-02-21 06:56:22,,,php;sql;postgresql;quoted-identifier,Keyslinger,5324,80857,registered,true,695312,,CC BY-SA 3.0,,914,824,2,0,0,4,true,false,false,true,true,true,77,10,false,0.019,0.0004,6446,2009,3,20,Sunday,true,false,false,false,false,true,true
3760816,Remove new lines from string and replace with one empty space,"$string = ""
put returns between paragraphs
for linebreak add 2 spaces at end
"";
Want to remove all new lines from string.
I've this regex, it can catch all of them, the problem is I don't know with which function should I use it.
/\r\n|\r|\n/
$string should become:
$string = ""put returns between paragraphs for linebreak add 2 spaces at end "";
",https://stackoverflow.com/questions/3760816/remove-new-lines-from-string-and-replace-with-one-empty-space,367,665492.0,20.0,,,2010-09-21 13:34:43,2024-03-12 07:22:31,2019-01-21 20:53:20,,,php;regex;string,James,43885,398431,registered,true,3760830,,CC BY-SA 4.0,,461,355,4,0,0,3,true,false,false,true,true,true,61,11,false,0.03,0.0006,5905,2010,9,13,Tuesday,false,false,false,false,false,false,true
15774669,List all files in one directory PHP,"What would be the best way to list all the files in one directory with PHP? Is there a $_SERVER function to do this? I would like to list all the files in the usernames/ directory and loop over that result with a link, so that I can just click the hyperlink of the filename to get there. Thanks!
",https://stackoverflow.com/questions/15774669/list-all-files-in-one-directory-php,367,799901.0,2.0,,,2013-04-02 21:23:29,2016-05-28 11:04:13,,2013-04-02 21:29:43,exact duplicate,php;list;directory,Shadowpat,3735,2213183,registered,true,15774700,,,,303,296,0,0,0,3,true,true,false,true,true,false,35,7,false,0.003,0.0005,4981,2013,4,21,Tuesday,false,false,false,false,false,false,true
9215588,break out of if and foreach,"I have a foreach loop and an if statement. If a match is found I need to ultimately break out of that foreach and if.
foreach($equipxml as $equip) {
$current_device = $equip->xpath("name");
if ($current_device[0] == $device) {
// found a match in the file
$nodeid = $equip->id;
// <break out of if and foreach here>
}
}
",https://stackoverflow.com/questions/9215588/break-out-of-if-and-foreach,367,609679.0,4.0,,,2012-02-09 17:19:36,2025-06-28 14:01:45,2024-11-06 01:45:39,,,php;if-statement;foreach;break,au_stan,4231,819600,registered,true,9215741,,CC BY-SA 4.0,,411,380,1,0,0,4,true,false,false,true,true,true,27,6,false,0.007,0.0006,5399,2012,2,17,Thursday,false,false,false,false,false,false,true
6245971,Accurate way to measure execution times of scripts,"I want to know how many milliseconds a PHP for loop takes to execute.
I know the structure of a generic algorithm:
Begin
init1 = timer(); // Where timer() is the amount of milliseconds from midnight
The loop begin
Some code
The loop end
total = timer() - init1;
End
But how can I implement it in PHP?
",https://stackoverflow.com/questions/6245971/accurate-way-to-measure-execution-times-of-scripts,366,409513.0,17.0,,,2011-06-05 21:25:41,2026-03-16 07:01:34,2025-10-29 16:55:04,,,php,DomingoSL,15590,310648,registered,true,6245978,,CC BY-SA 4.0,,395,302,1,0,0,1,true,false,false,true,true,true,50,8,false,0.042,0.0009,5648,2011,6,21,Sunday,true,false,false,false,false,false,true
23844761,upstream sent too big header while reading response header from upstream,"I am getting these kind of errors:
2014/05/24 11:49:06 [error] 8376#0: *54031 upstream sent too big header while reading response header from upstream, client: 107.21.193.210, server: aamjanata.com, request: ""GET /the-brainwash-chronicles-sponsored-by-gujarat-government/,%20https:/aamjanata.com/the-brainwash-chronicles-sponsored-by-gujarat-government/,%20https:/aamjanata.com/the-brainwash-chronicles-sponsored-by-gujarat-government/,%20https:/aamjanata.com/the-brainwash-chronicles-sponsored-by-gujarat-government/,%20https:/aamjanata.com/the-brainwash-chronicles-sponsored-by-gujarat-government/,%20https:/aamjanata.com/the-brainwash-chronicles-sponsored-by-gujarat-government/,%20https:/aamjanata.com/the-brainwash-chronicles-sponsored-by-gujarat-government/,%20https:/aamjanata.com/the-brainwash-chronicles-sponsored-by-gujarat-government/,%20https:/aamjanata.com/the-brainwash-chronicles-sponsored-by-gujarat-government/,%20https:/aamjanata.com/the-brainwash-chronicles-sponsored-by-gujarat-government/,%20https:/aamjanata.com/the-brainwash-chronicles-sponsored-by-gujarat-government/,%20https:/aamjanata.com/the-brainwash-chronicles-sponsored-by-gujarat-government/,%20https:/aamjanata.com/the-brainwash-chronicles-sponsored-by-gujarat-government/,%20https:/aamjanata.com/the-brainwash-chronicles-sponsored-by-gujarat-government/,%20https:/aamjanata.com/the-brainwash-chronicles-sponsored-by-gujarat-government/,%20https:/aamjanata.com/the-brainwash-chronicles-sponsored-by-gujarat-government/,%20https://aamjanata.com/the-brainwash-chronicles-sponsored-by-gujarat-government/,%20https:/aamjanata.com/the-brainwash-chronicles-sponsored-by-gujarat-government/,%20https:/aamjanata.com/the-brainwash-chronicles-sponsored-by-gujarat-government/,%20https:/aamjanata.com/the-brainwash-chronicles-sponsored-by-gujarat-government/,%20https:/aamjanata.com/the-brainwash-chronicles-sponsored-by-gujarat-government/,%20https:/aamjanata.com/the-brainwash-chronicles-sponsored-by-gujarat-government/,%20https:/aamjanata.com/the-brainwash-chronicles-sponsored-by-gujarat-government/,%20ht
Always it is the same. A url repeated over and over with comma separating. Can't figure out what is causing this. Anyone have an idea?
Update: Another error:
http request count is zero while sending response to client
Here is the config. There are other irrelevant things, but this part was added/edited
fastcgi_cache_path /var/nginx-cache levels=1:2 keys_zone=WORDPRESS:100m inactive=60m;
fastcgi_cache_key ""$scheme$request_method$host$request_uri"";
fastcgi_cache_use_stale error timeout invalid_header http_500;
fastcgi_ignore_headers Cache-Control Expires Set-Cookie;
proxy_buffer_size 128k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;
# Upstream to abstract backend connection(s) for PHP.
upstream php {
#this should match value of ""listen"" directive in php-fpm pool
server unix:/var/run/php5-fpm.sock;
}
And then in the server block:
set $skip_cache 0;
# POST requests and urls with a query string should always go to PHP
if ($request_method = POST) {
set $skip_cache 1;
}
if ($query_string != """") {
set $skip_cache 1;
}
# Don't cache uris containing the following segments
if ($request_uri ~* ""/wp-admin/|/xmlrpc.php|wp-.*.php|/feed/|index.php|sitemap(_index)?.xml"") {
set $skip_cache 1;
}
# Don't use the cache for logged in users or recent commenters
if ($http_cookie ~* ""comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_no_cache|wordpress_logged_in"") {
set $skip_cache 1;
}
location / {
# This is cool because no php is touched for static content.
# include the ""?$args"" part so non-default permalinks doesn't break when using query string
try_files $uri $uri/ /index.php?$args;
}
location ~ \.php$ {
try_files $uri /index.php;
include fastcgi_params;
fastcgi_pass php;
fastcgi_read_timeout 3000;
fastcgi_cache_bypass $skip_cache;
fastcgi_no_cache $skip_cache;
fastcgi_cache WORDPRESS;
fastcgi_cache_valid 60m;
}
location ~ /purge(/.*) {
fastcgi_cache_purge WORDPRESS ""$scheme$request_method$host$1"";
}`
",https://stackoverflow.com/questions/23844761/upstream-sent-too-big-header-while-reading-response-header-from-upstream,365,443083.0,19.0,,,2014-05-24 11:59:29,2024-01-23 18:57:25,2020-11-18 08:42:19,,,php;wordpress;nginx;fastcgi;nginx-reverse-proxy,Vidyut,3809,2600715,registered,true,23845727,,CC BY-SA 4.0,,4482,4343,3,0,0,5,true,false,false,true,true,true,72,11,false,0.043,0.0008,4564,2014,5,11,Saturday,true,false,false,false,false,false,true
37953019,WRONGTYPE Operation against a key holding the wrong kind of value php,"I am using Laravel with Redis .When I am trying to access a key by get method then get following error "WRONGTYPE Operation against a key holding the wrong kind of value"
I am using following code to access the key value -
I use this code for get data from redis
$values = "l_messages";
$value = $redis->HGETALL($values);
print($value);
",https://stackoverflow.com/questions/37953019/wrongtype-operation-against-a-key-holding-the-wrong-kind-of-value-php,364,379399.0,10.0,,,2016-06-21 19:28:14,2025-11-25 14:14:12,2025-11-25 14:14:12,,,php;redis,Trushar Narodia,3941,5620394,registered,true,44444966,,CC BY-SA 4.0,,406,361,1,0,0,2,true,false,false,true,true,true,69,12,false,0.026,0.001,3805,2016,6,19,Tuesday,false,false,false,false,false,false,true
7490488,Convert flat array to a delimited string to be saved in the database,"What is the best method for converting a PHP array into a string?
I have the variable $type which is an array of types.
$type = $_POST[type];
I want to store it as a single string in my database with each entry separated by | :
Sports|Festivals|Other
",https://stackoverflow.com/questions/7490488/convert-flat-array-to-a-delimited-string-to-be-saved-in-the-database,364,945095.0,13.0,,,2011-09-20 19:13:46,2022-07-03 09:04:15,2022-07-03 09:04:15,,,php;arrays;string;implode,Philip Kirkbride,23235,773263,registered,true,7490505,,CC BY-SA 4.0,2022-02-03 16:05:03,347,253,4,0,0,4,true,false,false,true,true,true,68,13,false,0.014,0.0004,5541,2011,9,19,Tuesday,false,false,false,false,false,false,true
3333353,String comparison using '==' or '===' vs. 'strcmp()',"It seems that PHP's === operator is case sensitive. So is there a reason to use strcmp()?
Is it safe to do something like the following?
if ($password === $password2) { ... }
",https://stackoverflow.com/questions/3333353/string-comparison-using-or-vs-strcmp,364,582377.0,15.0,,,2010-07-26 08:42:43,2024-05-07 19:25:47,2022-08-31 23:54:55,,,php,Jiew Meng,89473,292291,registered,true,3333369,,CC BY-SA 4.0,2019-04-08 20:53:53,242,178,3,0,0,1,true,false,false,true,true,true,76,8,false,0.026,0.0006,5962,2010,7,8,Monday,false,false,false,false,false,false,true
961074,How do I compare two DateTime objects in PHP 5.2.8?,"Having a look on the PHP documentation, the following two methods of the DateTime object would both seem to solve my problem:
- DateTime::diff : Get the difference and use that to determine which is more ancient.
- DateTime::getTimestamp : Get the UNIX timestampt and compare those.
Both these methods are marked in the doco as being available in version >= 5.3 (and, not surprisingly, if I try to call them I find they don't exist). I can't find any specific documentation for 5.2.8 so I am not sure if there are equivalent methods in my version. I have Googled the problem and found an eclectic range of solutions, none of which answer my very simple requirements:
- How do I compare two DateTime objects?
- Where can I find the doco for previous PHP versions? Specifically version 5.2.8?
For some context, I have the following code:
$st_dt = new DateTime(verifyParam ('start_date'));
$end_dt = new DateTime(verifyParam ('end_date'));
// is the end date more ancient than the start date?
if ($end_dt < $start_dt)
Apparently there is no comparison operator on this guy.
Edit
Apparently my assumptions were completely false (thanks Milen for illustrating this so effectively). There is a comparison operator and it works just fine thanks. Sometimes I really miss a compiler. The bug is in the code above, I am sure you will find it much faster than I did :).
",https://stackoverflow.com/questions/961074/how-do-i-compare-two-datetime-objects-in-php-5-2-8,363,452541.0,8.0,,,2009-06-07 02:33:23,2021-07-09 08:59:12,2019-05-27 14:18:36,,,php;datetime,RedBlueThing,42692,73488,registered,true,961116,,CC BY-SA 4.0,,1916,1375,2,4,0,2,true,false,false,true,true,true,51,10,true,0.018,0.0008,6376,2009,6,2,Sunday,true,false,false,false,false,false,true
4401949,What's the use of ob_start()?,"Is ob_start() used for output buffering so that the headers are buffered and not sent to the browser? Am I making sense here? If not then why should we use ob_start()?
",https://stackoverflow.com/questions/4401949/whats-the-use-of-ob-start,362,386155.0,10.0,,,2010-12-09 18:53:14,2025-10-21 12:12:12,2025-10-21 12:12:12,,,php;output-buffering,Aditya Shukla,14415,429888,registered,true,4401992,,CC BY-SA 4.0,2016-03-11 21:30:19,214,168,3,0,0,2,true,false,false,true,true,true,33,5,true,0.026,0.0009,5826,2010,12,18,Thursday,false,false,false,false,false,false,true
415801,Allowed memory size of 33554432 bytes exhausted (tried to allocate 43148176 bytes) in php,"This error message is being presented, any suggestions?
Allowed memory size of 33554432 bytes exhausted (tried to allocate
43148176 bytes) in php
",https://stackoverflow.com/questions/415801/allowed-memory-size-of-33554432-bytes-exhausted-tried-to-allocate-43148176-byte,362,902422.0,24.0,,,2009-01-06 08:18:28,2022-03-12 10:40:00,2016-07-06 09:36:47,2022-03-12 11:23:04,Duplicate,php;memory-management;memory-limit,panidarapu,9129,51950,registered,true,430516,,,2011-08-28 09:47:19,192,153,0,0,0,3,true,true,false,true,true,true,89,14,false,0.027,0.0004,6528,2009,1,8,Tuesday,false,false,false,false,false,false,true
249664,Best practices to test protected methods with PHPUnit,"I found the discussion on Do you test private method informative.
I have decided, that in some classes, I want to have protected methods, but test them.
Some of these methods are static and short. Because most of the public methods make use of them, I will probably be able to safely remove the tests later. But for starting with a TDD approach and avoid debugging, I really want to test them.
I thought of the following:
- Method Object as adviced in an answer seems to be overkill for this.
- Start with public methods and when code coverage is given by higher level tests, turn them protected and remove the tests.
- Inherit a class with a testable interface making protected methods public
Which is best practice? Is there anything else?
It seems, that JUnit automatically changes protected methods to be public, but I did not have a deeper look at it. PHP does not allow this via reflection.
",https://stackoverflow.com/questions/249664/best-practices-to-test-protected-methods-with-phpunit,361,197433.0,11.0,,,2008-10-30 09:32:41,2023-07-26 22:06:19,2017-05-23 12:10:41,,,php;unit-testing;phpunit,GrGr,4198,32679,registered,true,2798203,,CC BY-SA 3.0,,1316,898,0,4,0,3,true,false,false,true,true,true,53,8,false,0.056,0.0018,6596,2008,10,9,Thursday,false,false,false,false,false,false,true
1005857,How to call a function from a string stored in a variable?,"I need to be able to call a function, but the function name is stored in a variable, is this possible? e.g:
function foo ()
{
//code here
}
function bar ()
{
//code here
}
$functionName = "foo";
// I need to call the function based on what is $functionName
",https://stackoverflow.com/questions/1005857/how-to-call-a-function-from-a-string-stored-in-a-variable,360,372112.0,19.0,,,2009-06-17 08:44:22,2025-08-25 14:29:07,2021-01-01 16:23:46,,,php;dynamic-function,Lizard,45397,123140,registered,true,1005890,,CC BY-SA 4.0,,347,278,1,0,0,2,true,false,false,true,true,true,58,12,true,0.051,0.001,6366,2009,6,8,Wednesday,false,false,false,false,false,false,true
1125730,Split a comma-delimited string into an array?,"I need to split my string input into an array at the commas.
Is there a way to explode a comma-separated string into a flat, indexed array?
Input:
9,admin@example.com,8
Output:
['9', 'admin@example', '8']
",https://stackoverflow.com/questions/1125730/split-a-comma-delimited-string-into-an-array,359,619358.0,9.0,,,2009-07-14 14:21:52,2024-08-01 08:07:45,2021-04-19 22:12:58,,,php;arrays;string;csv;explode,Kevin,23694,98514,registered,true,1125740,,CC BY-SA 4.0,2021-03-10 14:22:31,285,209,2,0,0,5,true,false,false,true,true,true,45,7,true,0.015,0.0006,6339,2009,7,14,Tuesday,false,false,false,false,false,false,true
23411520,How to fix Error: laravel.log could not be opened?,"I'm pretty new at laravel, in fact and I'm trying to create my very first project. for some reason I keep getting this error (I haven't even started coding yet)
Error in exception handler: The stream or file ""/var/www/laravel/app/storage/logs/laravel.log"" could not be opened: failed to open stream: Permission denied in /var/www/laravel/bootstrap/compiled.php:8423
I've read this has something to do with permissions but chmod -R 775 storage didn't help at all.
![]()
",https://stackoverflow.com/questions/23411520/how-to-fix-error-laravel-log-could-not-be-opened,356,786675.0,21.0,,,2014-05-01 16:02:45,2024-07-15 23:33:10,2021-12-26 10:55:29,,,php;laravel;permission-denied,frankelot,14559,1949554,registered,true,23415081,,CC BY-SA 4.0,2019-02-04 20:28:53,588,469,2,0,1,3,true,false,false,true,true,true,50,9,true,0.027,0.0005,4587,2014,5,16,Thursday,false,false,false,false,false,false,true
4279282,How to set HTTP header to UTF-8 using PHP which is valid in W3C validator,"I have several PHP pages echoing out various things into HTML pages with the following code.
<meta http-equiv=""Content-type"" content=""text/html; charset=utf-8"" />
However, when I validate using the W3C validator it comes up with:
The character encoding specified in the HTTP header (iso-8859-1) is different from the value in the element (utf-8).
I am quite new to PHP, and I was wondering if I could and should change the header for the PHP files to match the HTML files.
",https://stackoverflow.com/questions/4279282/how-to-set-http-header-to-utf-8-using-php-which-is-valid-in-w3c-validator,356,1196193.0,7.0,,,2010-11-25 16:50:25,2021-08-26 21:30:21,2021-08-15 11:05:36,,,php;html;http-headers,manycheese,3673,457418,registered,true,4279294,,CC BY-SA 4.0,2016-12-19 11:12:56,786,489,1,3,0,3,true,false,false,true,true,true,73,15,false,0.006,0.0003,5840,2010,11,16,Thursday,false,false,false,false,false,false,true
686155,How to remove a cookie in PHP?,"When I want to remove a Cookie I try
unset($_COOKIE['hello']);
I see in my cookie browser from firefox that the cookie still exists. How can I really remove the cookie?
",https://stackoverflow.com/questions/686155/how-to-remove-a-cookie-in-php,355,813782.0,25.0,,,2009-03-26 14:59:15,2025-08-08 10:31:50,2024-12-26 18:16:35,,,php;cookies,sanders,10986,80040,registered,true,19972329,,CC BY-SA 4.0,2016-08-09 20:18:23,210,172,1,0,0,2,true,false,false,true,true,true,30,7,true,0.031,0.0004,6449,2009,3,14,Thursday,false,false,false,false,false,false,true
13002626,How to Set Variables in a Laravel Blade Template,"I'm reading the Laravel Blade documentation and I can't figure out how to assign variables inside a template for use later. I can't do {{ $old_section = ""whatever"" }} because that will echo ""whatever"" and I don't want that.
I understand that I can do <?php $old_section = ""whatever""; ?>, but that's not elegant.
Is there a better, elegant way to do that in a Blade template?
",https://stackoverflow.com/questions/13002626/how-to-set-variables-in-a-laravel-blade-template,354,567005.0,31.0,,,2012-10-21 22:02:08,2026-10-17 21:36:56,2022-02-23 11:39:48,,,php;laravel;laravel-blade,duality_,18916,291557,registered,true,13019365,,CC BY-SA 4.0,2022-01-31 10:11:38,499,383,2,1,0,3,true,false,false,true,true,true,48,9,false,0.055,0.0006,5144,2012,10,22,Sunday,true,false,false,false,false,false,true
732832,PHP exec() vs system() vs passthru(),"What are the differences?
Is there a specific situation or reason for each function? If yes, can you give some examples of those situations?
PHP.net says that they are used to execute external programs. see reference
From the examples I see, I don't see any obvious difference.
If I were to simply run a script (bash or python), which function do you recommend me to use?
",https://stackoverflow.com/questions/732832/php-exec-vs-system-vs-passthru,353,335256.0,5.0,,,2009-04-09 04:44:15,2019-08-21 12:42:22,2018-02-21 07:17:56,,,php;command;exec,codingbear,15173,191083,registered,true,,,CC BY-SA 3.0,2013-04-24 12:38:15,477,375,0,1,0,3,false,false,false,true,true,true,36,6,false,0.015,0.0011,6435,2009,4,4,Thursday,false,false,false,false,false,false,true
1423157,Print PHP Call Stack,"I'm looking for a way to print the call stack in PHP.
Bonus points if the function flushes the IO buffer.
",https://stackoverflow.com/questions/1423157/print-php-call-stack,351,237192.0,16.0,,,2009-09-14 18:22:17,2021-10-13 14:09:34,,,,php;stack-trace;error-logging,Justin,9949,149992,registered,true,1423167,,CC BY-SA 2.5,,122,108,0,0,0,3,true,false,false,true,true,false,20,4,false,0.067,0.0015,6277,2009,9,18,Monday,false,false,false,false,false,false,true
9998490,How to get xdebug var_dump to show full object/array,"I am using xdebug (php_xdebug-2.1.2-5.3-vc9.dll) on WAMP. When I use var_dump on a large object or variable it does not show the full variable.
array
'node' =>
array
'my_form' =>
array
'form' =>
array
...
Without xdebug it shows as should be expected. I looked at the documentation but did not see a solution. Does anyone know how I can fix this so xdebug var_dump shows the full object?
",https://stackoverflow.com/questions/9998490/how-to-get-xdebug-var-dump-to-show-full-object-array,350,264376.0,7.0,,,2012-04-03 17:38:57,2025-09-06 18:29:26,2015-04-28 02:28:38,,,php;xdebug,dm03514,56160,594589,registered,true,9998628,,CC BY-SA 3.0,2012-09-08 14:25:10,596,446,3,2,0,2,true,false,false,true,true,true,52,9,false,0.026,0.0013,5345,2012,4,17,Tuesday,false,false,false,false,false,false,true
2803321,'AND' vs '&&' as operator,"I have a codebase where developers decided to use AND and OR instead of && and ||.
I know that there is a difference in operators' precedence (&& goes before and), but with the given framework (PrestaShop to be precise) it is clearly not a reason.
Which version are you using? Is and more readable than &&? Or is there no difference?
",https://stackoverflow.com/questions/2803321/and-vs-as-operator,349,211956.0,10.0,,,2010-05-10 14:20:14,2020-05-28 23:38:08,2020-05-28 23:38:08,,,php;operators;operator-precedence,ts.,10729,129289,registered,true,2803576,,CC BY-SA 4.0,,557,360,8,1,0,3,true,false,false,true,true,true,49,5,false,0.047,0.0016,6039,2010,5,14,Monday,false,false,false,false,false,false,true
1374753,Passing base64 encoded strings in URL,"Is it safe to pass raw base64 encoded strings via GET parameters?
",https://stackoverflow.com/questions/1374753/passing-base64-encoded-strings-in-url,349,477248.0,13.0,,,2009-09-03 17:12:08,2025-12-21 10:25:06,2009-09-03 17:37:16,,,php;url;string;get;base64,Alix Axel,155512,89771,registered,true,1374794,,CC BY-SA 2.5,,73,66,0,0,0,5,true,false,false,true,true,true,37,6,false,0.027,0.0007,6288,2009,9,17,Thursday,false,false,false,false,false,false,true
559363,Matching a space in regex,"How can I match a space character in a PHP regular expression?
I mean like "gavin schulz", the space in between the two words. I am using a regular expression to make sure that I only allow letters, number and a space. But I'm not sure how to find the space. This is what I have right now:
$newtag = preg_replace("/[^a-zA-Z0-9s|]/", "", $tag);
",https://stackoverflow.com/questions/559363/matching-a-space-in-regex,349,1491088.0,9.0,,,2009-02-18 00:34:03,2022-10-04 14:55:28,2021-11-13 03:43:22,,,php;regex,Gavin Schulz,4776,64785,registered,true,559404,,CC BY-SA 4.0,,413,375,1,0,0,2,true,false,false,true,true,true,25,5,false,0.006,0.0002,6485,2009,2,0,Wednesday,false,false,false,false,false,false,true
2795177,How to Convert Boolean to String,"I have a Boolean variable which I want to convert to a string:
$res = true;
I need the converted value to be of the format: ""true"" ""false"", not ""0"" ""1""
$converted_res = ""true"";
$converted_res = ""false"";
I've tried:
$converted_res = string($res);
$converted_res = String($res);
But it tells me that string and String are not recognized functions.
How do I convert this Boolean to a string in the format of ""true"" or ""false"" in PHP?
",https://stackoverflow.com/questions/2795177/how-to-convert-boolean-to-string,348,344976.0,16.0,,,2010-05-08 18:28:37,2024-11-23 09:19:10,2020-03-01 19:54:20,,,php;string,tag,3545,330803,unregistered,true,2795180,,CC BY-SA 4.0,2016-05-22 16:45:55,622,440,9,0,0,2,true,false,false,true,true,true,32,6,false,0.046,0.001,6041,2010,5,18,Saturday,true,false,false,false,false,false,true
19852927,Get Specific Columns Using “With()” Function in Laravel Eloquent,"I have two tables, User and Post. One User can have many posts and one post belongs to only one user.
In my User model I have a hasMany relation...
public function post(){
return $this->hasmany('post');
}
And in my post model I have a belongsTo relation...
public function user(){
return $this->belongsTo('user');
}
Now I want to join these two tables using Eloquent with() but want specific columns from the second table. I know I can use the Query Builder but I don't want to.
When in the Post model I write...
public function getAllPosts() {
return Post::with('user')->get();
}
It runs the following queries...
select * from `posts`
select * from `users` where `users`.`id` in (<1>, <2>)
But what I want is...
select * from `posts`
select id,username from `users` where `users`.`id` in (<1>, <2>)
When I use...
Post::with('user')->get(array('columns'....));
It only returns the column from the first table. I want specific columns using with() from the second table. How can I do that?
",https://stackoverflow.com/questions/19852927/get-specific-columns-using-with-function-in-laravel-eloquent,347,613844.0,22.0,,,2013-11-08 06:30:34,2025-02-20 18:00:38,2023-04-05 16:18:44,,,php;laravel;eloquent;laravel-query-builder,Awais Qarni,18052,526367,registered,true,19921418,,CC BY-SA 4.0,2020-03-02 10:22:03,1473,1059,19,0,0,4,true,false,false,true,true,true,64,9,false,0.036,0.0006,4761,2013,11,6,Friday,false,false,false,false,false,false,true
3406171,What is the difference between var_dump() and print_r() in terms of spitting out an array as string?,"What is the difference between var_dump() and print_r() in terms of spitting out an array as string?
",https://stackoverflow.com/questions/3406171/what-is-the-difference-between-var-dump-and-print-r-in-terms-of-spitting-out,347,373627.0,13.0,,,2010-08-04 13:50:24,2025-11-22 11:38:15,2024-07-29 09:56:44,,,php;arrays,ina,19646,357189,registered,true,3406224,,CC BY-SA 4.0,,134,101,2,0,0,2,true,false,false,true,true,true,100,17,true,0.035,0.0009,5953,2010,8,13,Wednesday,false,false,false,false,false,false,true
365191,How to get time difference in minutes in PHP,"How to calculate minute difference between two date-times in PHP?
",https://stackoverflow.com/questions/365191/how-to-get-time-difference-in-minutes-in-php,346,788280.0,21.0,,,2008-12-13 13:05:25,2021-11-30 17:11:20,2012-07-21 07:58:41,,,php;date;time;minute,Tom Smykowski,26283,38940,registered,true,365214,,CC BY-SA 3.0,2011-08-06 10:02:47,73,66,0,0,0,4,true,false,false,true,true,true,44,9,false,0.027,0.0004,6552,2008,12,13,Saturday,true,false,false,false,false,false,true
959063,How to send a GET request from PHP?,"I'm planning to use PHP for a simple requirement. I need to download a XML content from a URL, for which I need to send HTTP GET request to that URL.
How do I do it in PHP?
",https://stackoverflow.com/questions/959063/how-to-send-a-get-request-from-php,346,763549.0,8.0,,,2009-06-06 05:30:58,2021-11-10 08:51:17,,,,php;http;get,Veera,33382,42372,registered,true,959069,,CC BY-SA 2.5,2020-08-12 02:24:56,189,175,0,0,0,3,true,false,false,true,true,false,35,8,true,0.01,0.0005,6377,2009,6,5,Saturday,true,false,false,false,false,false,true
63807930,Error “Target class controller does not exist” when using Laravel 8,"Here is my controller:
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class RegisterController extends Controller
{
public function register(Request $request)
{
dd('aa');
}
}
As seen in the screenshot, the class exists and is in the correct place:
My api.php route:
Route::get('register', 'Api\RegisterController@register');
When I hit my register route using Postman, it gave me the following error:
Target class [Api\RegisterController] does not exist.
How can I fix it?
Thanks to the answers, I was able to fix it. I decided to use the fully qualified class name for this route, but there are other options as described in the answers.
Route::get('register', 'App\Http\Controllers\Api\RegisterController@register');
",https://stackoverflow.com/questions/63807930/error-target-class-controller-does-not-exist-when-using-laravel-8,345,624928.0,33.0,,,2020-09-09 08:41:57,2026-11-16 17:39:54,2022-08-18 01:31:07,,,php;laravel;laravel-8;laravel-routing,Nguyễn Việt Dũng,3461,14246652,registered,true,63808132,,CC BY-SA 4.0,2020-11-18 17:34:59,1233,813,5,2,1,4,true,false,false,true,true,true,67,11,false,0.053,0.0006,2264,2020,9,8,Wednesday,false,false,false,false,false,false,true
23223292,What is 'YTowOnt9'?,"Our (PHP) framework sometimes renders hidden inputs with value YTowOnt9. I can't find that string anywhere in the (huge) codebase, and can't figure out where it came from. I decided to Google for that particular string, and the result surprised me. Over half a million - kind of random - hits. I haven't found any page describing the value itself. It has 0 hits on Stack Overflow.
Is YTowOnt9 some kind of magic string?
",https://stackoverflow.com/questions/23223292/what-is-ytowont9,345,16898.0,1.0,,,2014-04-22 15:04:24,2019-12-14 22:06:42,2019-12-14 22:06:42,,,php;html;output,Sherlock,7622,1329111,registered,true,23223602,,CC BY-SA 4.0,,539,427,2,1,0,3,true,false,false,true,true,true,27,3,true,0.059,0.0204,4596,2014,4,15,Tuesday,false,false,false,false,false,false,true
17808511,How to properly escape a double quote in CSV?,"I have a line like this in my CSV:
""Samsung U600 24"""",""10000003409"",""1"",""10000003427""
Quote next to 24 is used to express inches, while the quote just next to that quote closes the field. I'm reading the line with fgetcsv but the parser makes a mistake and reads the value as:
Samsung U600 24"",10000003409""
I tried putting a backslash before the inches quote, but then I just get a backslash in the name:
Samsung U600 24\""
Is there a way to properly escape this in the CSV, so that the value would be Samsung U600 24"" , or do I have to regex it in the processor?
",https://stackoverflow.com/questions/17808511/how-to-properly-escape-a-double-quote-in-csv,344,376210.0,7.0,,,2013-07-23 11:10:58,2026-06-05 19:07:38,2023-08-06 23:26:06,,,php;csv;escaping;fgetcsv,srgb,5343,785534,registered,true,17808731,,CC BY-SA 4.0,,696,569,6,0,0,4,true,false,false,true,true,true,45,9,true,0.019,0.0009,4869,2013,7,11,Tuesday,false,false,false,false,false,false,true
16176990,Proper Repository Pattern Design in PHP?,"Preface: I'm attempting to use the repository pattern in an MVC architecture with relational databases.
I've recently started learning TDD in PHP, and I'm realizing that my database is coupled much too closely with the rest of my application. I've read about repositories and using an IoC container to ""inject"" it into my controllers. Very cool stuff. But now have some practical questions about repository design. Consider the follow example.
<?php
class DbUserRepository implements UserRepositoryInterface
{
protected $db;
public function __construct($db)
{
$this->db = $db;
}
public function findAll()
{
}
public function findById($id)
{
}
public function findByName($name)
{
}
public function create($user)
{
}
public function remove($user)
{
}
public function update($user)
{
}
}
Issue #1: Too many fields
All of these find methods use a select all fields (SELECT *) approach. However, in my apps, I'm always trying to limit the number of fields I get, as this often adds overhead and slows things down. For those using this pattern, how do you deal with this?
Issue #2: Too many methods
While this class looks nice right now, I know that in a real-world app I need a lot more methods. For example:
- findAllByNameAndStatus
- findAllInCountry
- findAllWithEmailAddressSet
- findAllByAgeAndGender
- findAllByAgeAndGenderOrderByAge
- Etc.
As you can see, there could be a very, very long list of possible methods. And then if you add in the field selection issue above, the problem worsens. In the past I'd normally just put all this logic right in my controller:
<?php
class MyController
{
public function users()
{
$users = User::select('name, email, status')
->byCountry('Canada')->orderBy('name')->rows();
return View::make('users', array('users' => $users));
}
}
With my repository approach, I don't want to end up with this:
<?php
class MyController
{
public function users()
{
$users = $this->repo->get_first_name_last_name_email_username_status_by_country_order_by_name('Canada');
return View::make('users', array('users' => $users))
}
}
Issue #3: Impossible to match an interface
I see the benefit in using interfaces for repositories, so I can swap out my implementation (for testing purposes or other). My understanding of interfaces is that they define a contract that an implementation must follow. This is great until you start adding additional methods to your repositories like findAllInCountry(). Now I need to update my interface to also have this method, otherwise, other implementations may not have it, and that could break my application. By this feels insane...a case of the tail wagging the dog.
Specification Pattern?
This leads me to believe that repository should only have a fixed number of methods (like save(), remove(), find(), findAll(), etc). But then how do I run specific lookups? I've heard of the Specification Pattern, but it seems to me that this only reduces an entire set of records (via IsSatisfiedBy()), which clearly has major performance issues if you're pulling from a database.
Help?
Clearly, I need to rethink things a little when working with repositories. Can anyone enlighten on how this is best handled?
",https://stackoverflow.com/questions/16176990/proper-repository-pattern-design-in-php,344,94511.0,11.0,,,2013-04-23 18:50:05,2026-08-06 13:27:03,2026-08-06 13:27:03,,,best-practices;php;database;repository;repository-pattern,Jonathan,19269,297015,registered,true,16238079,,CC BY-SA 4.0,,3981,3379,10,2,0,5,true,false,false,true,true,true,40,6,true,0.116,0.0036,4960,2013,4,18,Tuesday,false,false,false,false,false,false,true
8439581,Catching multiple exception types in one catch block,"I'd like a cleaner way to obtain the following functionality, to catch AError and BError in one block:
try
{
/* something */
}
catch( AError, BError $e )
{
handler1( $e )
}
catch( Exception $e )
{
handler2( $e )
}
Is there any way to do this? Or do I have to catch them separately?
AError and Berror have a shared base class, but they also share it with other types that I'd like to fall through to handler2, so I can't just catch the base class.
",https://stackoverflow.com/questions/8439581/catching-multiple-exception-types-in-one-catch-block,343,289095.0,12.0,,,2011-12-09 00:22:37,2025-03-31 22:21:28,2011-12-09 00:45:51,,,php;exception,Dominic Gurto,4235,389135,registered,true,19325523,,CC BY-SA 3.0,,573,463,6,0,0,2,true,false,false,true,true,true,52,8,false,0.042,0.0012,5461,2011,12,0,Friday,false,false,false,false,false,false,true
907806,Passing an array to a query using a WHERE clause,"Given an array of ids $galleries = array(1,2,5) I want to have a SQL query that uses the values of the array in its WHERE clause like:
SELECT *
FROM galleries
WHERE id = /* values of array $galleries... eg. (1 || 2 || 5) */
How can I generate this query string to use with MySQL?
",https://stackoverflow.com/questions/907806/passing-an-array-to-a-query-using-a-where-clause,342,704949.0,17.0,,,2009-05-25 19:32:26,2022-04-08 14:35:39,2022-04-08 14:35:39,,,php;mysql,Quinn,,,does_not_exist,true,907821,,CC BY-SA 4.0,,372,283,2,0,0,2,true,false,false,true,false,true,48,10,false,0.024,0.0005,6389,2009,5,19,Monday,false,false,false,false,false,false,true
3258634,PHP: How to send HTTP response code?,"I have a PHP script that needs to make responses with HTTP response codes (status-codes), like HTTP 200 OK, or some 4XX or 5XX code.
How can I do this in PHP?
",https://stackoverflow.com/questions/3258634/php-how-to-send-http-response-code,342,598376.0,7.0,,,2010-07-15 18:23:56,2023-08-19 08:20:49,2013-12-25 12:53:19,,,php;http-response-codes,Paulo Coghi,15127,279712,registered,true,12018482,,CC BY-SA 3.0,2020-12-17 16:49:46,174,160,0,0,0,2,true,false,false,true,true,true,36,7,true,0.012,0.0006,5973,2010,7,18,Thursday,false,false,false,false,false,false,true
13569,mysqli or PDO - what are the pros and cons?,"In our place we're split between using mysqli and PDO for stuff like prepared statements and transaction support. Some projects use one, some the other. There is little realistic likelihood of us ever moving to another RDBMS.
I prefer PDO for the single reason that it allows named parameters for prepared statements, and as far as I am aware mysqli does not.
Are there any other pros and cons to choosing one over the other as a standard as we consolidate our projects to use just one approach?
",https://stackoverflow.com/questions/13569/mysqli-or-pdo-what-are-the-pros-and-cons,342,159221.0,13.0,,,2008-08-17 09:47:22,2013-03-04 12:41:59,2009-03-06 16:52:02,2013-02-08 08:26:28,not constructive,php;mysql;pdo;mysqli;database-abstraction,Polsonby,22877,137,registered,true,,,,,519,498,0,0,0,5,false,true,false,true,true,true,43,10,true,0.082,0.0021,6670,2008,8,9,Sunday,true,false,false,false,false,false,true
8251426,Insert string at specified position,"Is there a PHP function that can do that?
I'm using strpos to get the position of a substring and I want to insert a string after that position.
",https://stackoverflow.com/questions/8251426/insert-string-at-specified-position,341,395514.0,12.0,,,2011-11-24 02:01:38,2023-03-16 17:56:41,2016-09-26 12:31:54,,,php;string,Alex,66826,376947,registered,true,17880260,,CC BY-SA 3.0,,186,146,2,0,0,2,true,false,false,true,true,true,35,5,false,0.03,0.0009,5476,2011,11,2,Thursday,false,false,false,false,false,false,true
2445276,How to post data in PHP using file_get_contents?,"I'm using PHP's function file_get_contents() to fetch contents of a URL and then I process headers through the variable $http_response_header.
Now the problem is that some of the URLs need some data to be posted to the URL (for example, login pages).
How do I do that?
I realize using stream_context I may be able to do that but I am not entirely clear.
Thanks.
",https://stackoverflow.com/questions/2445276/how-to-post-data-in-php-using-file-get-contents,341,421650.0,4.0,,,2010-03-15 05:27:20,2024-09-24 15:07:09,2012-11-03 10:46:52,,,php;http;http-post;file-get-contents,Paras Chopra,4159,137006,registered,true,2445332,,CC BY-SA 3.0,2013-10-25 12:52:01,428,367,2,0,0,4,true,false,false,true,true,true,48,8,true,0.009,0.0008,6095,2010,3,5,Monday,false,false,false,false,false,false,true
43408604,PHP7 : install ext-dom issue,"I'm running laravel 5.4 on Ubuntu 16.04 server with PHP7. trying to install cviebrock/eloquent-sluggable package throw some error:
pish@let:/home/sherk/ftp/www$ sudo composer require cviebrock/eloquent-sluggable
Do not run Composer as root/super user! See https://getcomposer.org/root for details
Using version ^4.2 for cviebrock/eloquent-sluggable
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.
Problem 1
- phpunit/php-code-coverage 4.0.7 requires ext-dom * -> the requested PHP extension dom is missing from your system.
- phpunit/php-code-coverage 4.0.7 requires ext-dom * -> the requested PHP extension dom is missing from your system.
- Installation request for phpunit/php-code-coverage (installed at 4.0.7) -> satisfiable by phpunit/php-code-coverage[4.0.7].
To enable extensions, verify that they are enabled in those .ini files:
- /etc/php/7.0/cli/php.ini
- /etc/php/7.0/cli/conf.d/10-mysqlnd.ini
- /etc/php/7.0/cli/conf.d/10-opcache.ini
- /etc/php/7.0/cli/conf.d/10-pdo.ini
- /etc/php/7.0/cli/conf.d/20-calendar.ini
- /etc/php/7.0/cli/conf.d/20-ctype.ini
- /etc/php/7.0/cli/conf.d/20-exif.ini
- /etc/php/7.0/cli/conf.d/20-fileinfo.ini
- /etc/php/7.0/cli/conf.d/20-ftp.ini
- /etc/php/7.0/cli/conf.d/20-gd.ini
- /etc/php/7.0/cli/conf.d/20-gettext.ini
- /etc/php/7.0/cli/conf.d/20-iconv.ini
- /etc/php/7.0/cli/conf.d/20-json.ini
- /etc/php/7.0/cli/conf.d/20-mbstring.ini
- /etc/php/7.0/cli/conf.d/20-mcrypt.ini
- /etc/php/7.0/cli/conf.d/20-mysqli.ini
- /etc/php/7.0/cli/conf.d/20-pdo_mysql.ini
- /etc/php/7.0/cli/conf.d/20-phar.ini
- /etc/php/7.0/cli/conf.d/20-posix.ini
- /etc/php/7.0/cli/conf.d/20-readline.ini
- /etc/php/7.0/cli/conf.d/20-shmop.ini
- /etc/php/7.0/cli/conf.d/20-sockets.ini
- /etc/php/7.0/cli/conf.d/20-sysvmsg.ini
- /etc/php/7.0/cli/conf.d/20-sysvsem.ini
- /etc/php/7.0/cli/conf.d/20-sysvshm.ini
- /etc/php/7.0/cli/conf.d/20-tokenizer.ini
You can also run `php --ini` inside terminal to see which files are used by PHP in CLI mode.
Installation failed, reverting ./composer.json to its original content.
I have no problem installing this package on local version of the app .
",https://stackoverflow.com/questions/43408604/php7-install-ext-dom-issue,340,615450.0,4.0,,,2017-04-14 09:11:49,2025-02-22 18:35:34,2025-02-22 18:35:34,,,php;laravel;laravel-5;composer-php,alex,7951,4061644,registered,true,43408658,,CC BY-SA 4.0,2021-12-21 21:20:17,2453,2402,2,0,0,4,true,false,false,true,true,true,28,5,false,0.006,0.0006,3508,2017,4,9,Friday,false,false,false,false,false,false,true
5966746,Best way to initialize an (empty) array in PHP,"In certain other languages (ActionScript 3 for example), it has been noted that initializing a new array is faster if done like this var foo = [] rather than var foo = new Array() for reasons of object creation and instantiation. Are there are any equivalences in PHP?
class Foo {
private $arr = array(); // Is there another / better way?
}
",https://stackoverflow.com/questions/5966746/best-way-to-initialize-an-empty-array-in-php,339,651951.0,9.0,,,2011-05-11 15:28:05,2025-08-12 01:02:05,2025-08-12 00:55:54,,,php;arrays;initialization,Tom Auger,20266,467386,registered,true,5966855,,CC BY-SA 4.0,,486,346,3,1,0,3,true,false,false,true,true,true,46,9,false,0.014,0.0005,5673,2011,5,15,Wednesday,false,false,false,false,false,false,true
2040240,PHP function to generate v4 UUID,"So I've been doing some digging around and I've been trying to piece together a function that generates a valid v4 UUID in PHP. This is the closest I've been able to come. My knowledge in hex, decimal, binary, PHP's bitwise operators and the like is nearly nonexistent. This function generates a valid v4 UUID up until one area. A v4 UUID should be in the form of:
xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
Where y is 8, 9, A, or B. This is where the functions fails as it doesn't adhere to that.
I was hoping someone with more knowledge than me in this area could lend me a hand and help me fix this function so it does adhere to that rule.
The function is as follows:
<?php
function gen_uuid() {
$uuid = array(
'time_low' => 0,
'time_mid' => 0,
'time_hi' => 0,
'clock_seq_hi' => 0,
'clock_seq_low' => 0,
'node' => array()
);
$uuid['time_low'] = mt_rand(0, 0xffff) + (mt_rand(0, 0xffff) << 16);
$uuid['time_mid'] = mt_rand(0, 0xffff);
$uuid['time_hi'] = (4 << 12) | (mt_rand(0, 0x1000));
$uuid['clock_seq_hi'] = (1 << 7) | (mt_rand(0, 128));
$uuid['clock_seq_low'] = mt_rand(0, 255);
for ($i = 0; $i < 6; $i++) {
$uuid['node'][$i] = mt_rand(0, 255);
}
$uuid = sprintf('%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x',
$uuid['time_low'],
$uuid['time_mid'],
$uuid['time_hi'],
$uuid['clock_seq_hi'],
$uuid['clock_seq_low'],
$uuid['node'][0],
$uuid['node'][1],
$uuid['node'][2],
$uuid['node'][3],
$uuid['node'][4],
$uuid['node'][5]
);
return $uuid;
}
?>
",https://stackoverflow.com/questions/2040240/php-function-to-generate-v4-uuid,338,400217.0,19.0,,,2010-01-11 06:17:11,2025-10-06 20:37:55,2022-02-02 00:31:51,,,php;function;uuid,anomareh,5614,235002,registered,true,2040279,,CC BY-SA 4.0,,1695,1560,1,0,0,3,true,false,false,true,true,true,32,6,false,0.047,0.0008,6158,2010,1,6,Monday,false,false,false,false,false,false,true
3997336,Explode PHP string by new line,"Simple, right? Well, this isn't working :-\
$skuList = explode('\n\r', $_POST['skuList']);
",https://stackoverflow.com/questions/3997336/explode-php-string-by-new-line,338,444881.0,19.0,,,2010-10-22 13:39:11,2024-01-18 11:50:47,2010-10-22 13:46:24,2024-01-18 12:17:43,Duplicate,php,Ben,62782,197606,registered,true,29471912,,,,125,94,1,0,0,1,true,true,false,true,true,true,30,6,false,0.043,0.0008,5874,2010,10,13,Friday,false,false,false,false,false,false,true
8893574,PHP "php://input" vs $_POST,"I have been directed to use the method php://input instead of $_POST when interacting with Ajax requests from JQuery. What I do not understand is the benefits of using this vs the global method of $_POST or $_GET.
",https://stackoverflow.com/questions/8893574/php-php-input-vs-post,338,322357.0,6.0,,,2012-01-17 11:08:12,2025-10-25 12:02:24,2014-07-24 02:01:18,,,php;ajax;input,Lee,6044,401705,registered,true,8893792,,CC BY-SA 3.0,2023-07-18 17:19:01,274,215,4,0,0,3,true,false,false,true,true,true,37,4,false,0.019,0.001,5422,2012,1,11,Tuesday,false,false,false,false,false,false,true
30518899,Amazon S3 - How to fix 'The request signature we calculated does not match the signature' error?,"I have searched on the web for over two days now, and probably have looked through most of the online documented scenarios and workarounds, but nothing worked for me so far.
I am on AWS SDK for PHP V2.8.7 running on PHP 5.3.
I am trying to connect to my Amazon S3 bucket with the following code:
// Create a `Aws` object using a configuration file
$aws = Aws::factory('config.php');
// Get the client from the service locator by namespace
$s3Client = $aws->get('s3');
$bucket = "xxx";
$keyname = "xxx";
try {
$result = $s3Client->putObject(array(
'Bucket' => $bucket,
'Key' => $keyname,
'Body' => 'Hello World!'
));
$file_error = false;
} catch (Exception $e) {
$file_error = true;
echo $e->getMessage();
die();
}
My config.php file is as follows:
return [
// Bootstrap the configuration file with AWS specific features
'includes' => ['_aws'],
'services' => [
// All AWS clients extend from 'default_settings'. Here we are
// overriding 'default_settings' with our default credentials and
// providing a default region setting.
'default_settings' => [
'params' => [
'credentials' => [
'key' => 'key',
'secret' => 'secret'
]
]
]
]
];
It is producing the following error:
The request signature we calculated does not match the signature you provided. Check your key and signing method.
I've already checked my access key and secret at least 20 times, generated new ones, used different methods to pass in the information (i.e. profile and including credentials in code) but nothing is working at the moment.
",https://stackoverflow.com/questions/30518899/amazon-s3-how-to-fix-the-request-signature-we-calculated-does-not-match-the-s,338,737731.0,71.0,,,2015-05-28 23:47:55,2025-11-11 10:33:36,2021-09-09 15:32:38,,,php;amazon-web-services;amazon-s3;aws-php-sdk,Joseph Lam,6299,3289011,registered,true,30519762,,CC BY-SA 4.0,2024-09-06 16:31:08,1993,1778,2,0,0,4,true,false,false,true,true,true,104,17,true,0.096,0.0005,4195,2015,5,23,Thursday,false,false,false,false,false,false,true
17006309,How to order a Laravel query builder result by multiple columns?,"I want to sort multiple columns in Laravel 4 by using the method orderBy() in Laravel Eloquent. The query will be generated using Eloquent like this:
SELECT *
FROM mytable
ORDER BY
coloumn1 DESC, coloumn2 ASC
How can I do this?
",https://stackoverflow.com/questions/17006309/how-to-order-a-laravel-query-builder-result-by-multiple-columns,334,405840.0,5.0,,,2013-06-09 04:05:57,2025-01-19 11:22:26,2025-01-19 11:22:26,,,php;laravel;eloquent;laravel-query-builder,Sophy,9315,833394,registered,true,17006377,,CC BY-SA 4.0,,284,233,2,0,0,4,true,false,false,true,true,true,64,11,true,0.012,0.0008,4913,2013,6,4,Sunday,true,false,false,false,false,false,true
1442411,When should I use Memcache instead of Memcached?,"It seems that PHP has two memcached libraries named memcache and memcached. What is the difference and how do you know which one to use? Is one outdated? It seems that memcached offers more methods so I would assume that means it has had the most development - but it also seems to require external C/C++ libraries so I'm not sure if I can install it.
It seems that memcache has been around longer, does not require additional libraries, and has pre-compiled binaries for even windows! I would think that it would be the better choice for now. However, being new to memcached (server) I'm not sure if there is some super important features in memcached (php) that make it worth the extra trouble.
",https://stackoverflow.com/questions/1442411/when-should-i-use-memcache-instead-of-memcached,334,148506.0,4.0,,,2009-09-18 03:07:52,2015-08-11 09:15:51,2023-11-17 20:42:18,,,php;memcached,Xeoncross,57736,99923,registered,true,1442747,,CC BY-SA 4.0,2014-03-01 17:48:36,1042,697,0,4,0,2,true,false,false,true,true,true,48,8,true,0.027,0.0022,6273,2009,9,3,Friday,false,false,false,false,false,false,true
17483806,What does yield mean in PHP?,"I've recently stumbled over this code:
function xrange($min, $max)
{
for ($i = $min; $i <= $max; $i++) {
yield $i;
}
}
I've never seen this yield keyword before. Trying to run the code I get
Parse error: syntax error, unexpected T_VARIABLE on line x
So what is this yield keyword? Is it even valid PHP? And if it is, how do I use it?
",https://stackoverflow.com/questions/17483806/what-does-yield-mean-in-php,333,163821.0,9.0,,,2013-07-05 07:53:07,2023-06-20 12:58:05,2015-08-07 13:24:29,,,php;generator;php-5.5;yield-keyword,gooh,318163,208809,registered,true,17483807,,CC BY-SA 3.0,,467,364,3,0,0,4,true,false,false,true,true,true,28,6,true,0.055,0.002,4887,2013,7,7,Friday,false,false,false,false,false,false,true
1408,Make XAMPP / Apache serve file outside of htdocs folder,"Is it possible to configure xampp to serve up a file outside of the htdocs directory?
For instance, say I have a file located as follows:
C:\projects\transitCalculator\trunk\TransitCalculator.php
and my xampp files are normally served out from:
C:\xampp\htdocs\
(because that's the default configuration) Is there some way to make Apache recognize and serve up my TransitCalculator.php file without moving it under htdocs? Preferably I'd like Apache to serve up/have access to the entire contents of the projects directory, and I don't want to move the projects directory under htdocs.
edit: edited to add Apache to the question title to make Q/A more ""searchable""
",https://stackoverflow.com/questions/1408/make-xampp-apache-serve-file-outside-of-htdocs-folder,333,285077.0,6.0,,,2008-08-04 16:54:49,2020-10-23 07:15:33,2020-10-23 07:15:33,2013-07-18 15:23:17,Not suitable for this site,php;apache;xampp;server-configuration,cmcculloh,48821,58,registered,true,1421,,,2012-09-03 14:34:57,946,671,6,2,0,4,true,true,false,true,true,true,55,10,false,0.021,0.0012,6683,2008,8,16,Monday,false,false,false,false,false,false,true
910793,Detect encoding and make everything UTF-8,"I'm reading out lots of texts from various RSS feeds and inserting them into my database.
Of course, there are several different character encodings used in the feeds, e.g. UTF-8 and ISO 8859-1.
Unfortunately, there are sometimes problems with the encodings of the texts. Example:
The ""ß"" in ""Fußball"" should look like this in my database: ""Ÿ"". If it is a ""Ÿ"", it is displayed correctly.
Sometimes, the ""ß"" in ""Fußball"" looks like this in my database: ""ß"". Then it is displayed wrongly, of course.
In other cases, the ""ß"" is saved as a ""ß"" - so without any change. Then it is also displayed wrongly.
What can I do to avoid the cases 2 and 3?
How can I make everything the same encoding, preferably UTF-8? When must I use utf8_encode(), when must I use utf8_decode() (it's clear what the effect is but when must I use the functions?) and when must I do nothing with the input?
How do I make everything the same encoding? Perhaps with the function mb_detect_encoding()? Can I write a function for this? So my problems are:
- How do I find out what encoding the text uses?
- How do I convert it to UTF-8 - whatever the old encoding is?
Would a function like this work?
function correct_encoding($text) {
$current_encoding = mb_detect_encoding($text, 'auto');
$text = iconv($current_encoding, 'UTF-8', $text);
return $text;
}
I've tested it, but it doesn't work. What's wrong with it?
",https://stackoverflow.com/questions/910793/detect-encoding-and-make-everything-utf-8,333,452685.0,26.0,,,2009-05-26 13:50:34,2022-12-16 05:15:18,2019-07-08 16:28:53,,,php;encoding;utf-8;character-encoding,caw,31587,89818,registered,true,3479832,,CC BY-SA 4.0,2018-05-08 02:41:48,1617,1414,4,0,0,4,true,false,false,true,true,true,41,6,false,0.057,0.0007,6388,2009,5,13,Tuesday,false,false,false,false,false,false,true
4221333,"How can I get the current script file name, but without the extension ".php"?","If I have PHP script, how can I get the filename of the currently executed file without its extension?
Given the name of a script of the form "jquery.js.php", how can I extract just the "jquery.js" part?
",https://stackoverflow.com/questions/4221333/how-can-i-get-the-current-script-file-name-but-without-the-extension-php,332,509526.0,18.0,,,2010-11-19 01:24:11,2024-05-22 11:46:56,2023-03-28 10:03:48,,,php;file,Alex,66826,376947,registered,true,4221345,,CC BY-SA 4.0,2013-12-17 17:26:42,238,224,0,0,0,2,true,false,false,true,true,true,87,14,true,0.035,0.0007,5846,2010,11,1,Friday,false,false,false,false,false,false,true
14395239,Class 'DOMDocument' not found,"I've found an error on a page in my Magento application; it always show this message error when I visit it:
Fatal error: Class 'DOMDocument' not found in /home/.../lib/Zend/Feed/Abstract.php on line 95
Can you give me a solution? I'm using magento 1.4.1.1.
",https://stackoverflow.com/questions/14395239/class-domdocument-not-found,332,390954.0,20.0,,,2013-01-18 08:48:33,2024-07-23 05:45:23,2023-06-29 09:48:00,,,php;xml,ws_123,5761,1477136,registered,true,14395414,,CC BY-SA 4.0,2024-04-04 19:19:51,309,263,0,0,0,2,true,false,false,true,true,true,37,4,false,0.051,0.0008,5055,2013,1,8,Friday,false,false,false,false,false,false,true
23443398,nginx error connect to php5-fpm.sock failed (13: Permission denied),"I update nginx to 1.4.7 and php to 5.5.12, After that I got the 502 error. Before I update everything works fine.
nginx-error.log
2014/05/03 13:27:41 [crit] 4202#0: *1 connect() to unix:/var/run/php5-fpm.sock failed (13: Permission denied) while connecting to upstream, client: xx.xxx.xx.xx, server: localhost, request: ""GET / HTTP/1.1"", upstream: ""fastcgi://unix:/var/run/php5-fpm.sock:"", host: ""xx.xx.xx.xx""
nginx.conf
user www www;
worker_processes 1;
location / {
root /usr/home/user/public_html;
index index.php index.html index.htm;
}
location ~ [^/]\.php(/|$) {
fastcgi_split_path_info ^(.+?\.php)(/.*)$;
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /usr/home/user/public_html$fastcgi_script_name;
include fastcgi_params;
}
",https://stackoverflow.com/questions/23443398/nginx-error-connect-to-php5-fpm-sock-failed-13-permission-denied,330,389703.0,28.0,,,2014-05-03 10:47:54,2024-09-13 16:38:29,2014-06-02 08:25:59,,,unix;nginx;php,peter,3322,3450939,registered,true,23487409,,CC BY-SA 3.0,,1035,915,2,0,0,3,true,false,false,true,true,true,67,9,false,0.072,0.0008,4585,2014,5,10,Saturday,true,false,false,false,false,false,true
383631,JSON encode MySQL results,"How do I use the json_encode() function with MySQL query results? Do I need to iterate through the rows or can I just apply it to the entire results object?
",https://stackoverflow.com/questions/383631/json-encode-mysql-results,330,618374.0,15.0,,,2008-12-20 19:09:44,2023-07-16 19:23:31,2014-11-14 23:36:46,,,php;mysql;json,Trick Jarrett,3569,12073,registered,true,383664,,CC BY-SA 3.0,2017-10-07 07:51:25,177,157,1,0,0,3,true,false,false,true,true,true,25,4,false,0.024,0.0005,6545,2008,12,19,Saturday,true,false,false,false,false,false,true
9343151,Where is PHP.ini in Mac OS X Lion?,"I wanted to run some PHP right on my Mac, uncommented httpd.conf, activated web sharing, installed MySQL etc.
I can't seem to find my PHP files, most importantly, PHP.ini.
On my old machine it was located in /usr/local/php5/lib
But php5 directory doesn't exist in /usr/local..
Do I need to get a package or am I looking in the incorrect place?
Running OS X 10.7.3, PHP 5.3.8, Apache/2.2.21
",https://stackoverflow.com/questions/9343151/where-is-php-ini-in-mac-os-x-lion,329,574769.0,13.0,,,2012-02-18 16:58:12,2023-12-17 17:20:47,2021-03-21 01:38:15,,,macos;php,Orun,4644,808812,registered,true,9343210,,CC BY-SA 4.0,,421,393,0,0,0,2,true,false,false,true,true,true,34,8,true,0.023,0.0006,5390,2012,2,16,Saturday,true,false,false,false,false,false,true
21133,Simplest way to profile a PHP script,"What's the easiest way to profile a PHP script?
I'd love tacking something on that shows me a dump of all function calls and how long they took, but I'm also OK with putting something around specific functions.
I tried experimenting with the microtime function:
$then = microtime();
myFunc();
$now = microtime();
echo sprintf("Elapsed: %f", $now-$then);
But that sometimes gives me negative results. Plus it's a lot of trouble to sprinkle that all over my code.
",https://stackoverflow.com/questions/21133/simplest-way-to-profile-a-php-script,329,229445.0,14.0,,,2008-08-21 20:40:38,2025-10-29 01:59:32,2025-10-29 01:06:35,,,php;profiling,Mark Biek,152519,305,registered,true,21189,,CC BY-SA 4.0,2014-09-08 08:12:49,593,476,1,1,0,2,true,false,false,true,true,true,36,7,false,0.061,0.0014,6666,2008,8,20,Thursday,false,false,false,false,false,false,true
17364127,How can I sort arrays and data in PHP?,"
This question is intended as a reference for questions about sorting arrays in PHP. It is easy to think that your particular case is unique and worthy of a new question, but most are actually minor variations of one of the solutions on this page.
If your question is closed as a duplicate of this one, please ask for your question to be reopened only if you can explain why it differs markedly from all of the below.
How do I sort an array in PHP?
How do I sort a complex array in PHP?
How do I sort an array of objects in PHP?
-
-
-
For the practical answer using PHP's existing functions see 1., for the academic in-detail answer on sorting algorithms (which PHP's functions implement and which you may need for really, really complex cases), see 2.
",https://stackoverflow.com/questions/17364127/how-can-i-sort-arrays-and-data-in-php,328,99378.0,14.0,,,2013-06-28 11:53:56,2022-07-24 21:38:00,2020-06-20 09:12:55,,,php;arrays;sorting;object;spl,deceze,525902,476,moderator,true,17364128,,CC BY-SA 4.0,2014-10-28 06:11:14,1217,910,0,3,0,5,true,false,false,true,true,true,38,9,true,0.141,0.0033,4894,2013,6,11,Friday,false,false,false,false,false,false,true
30046691,Laravel: How to Get Current Route Name? (v5 ... v7),"In Laravel v4 I was able to get the current route name using...
Route::currentRouteName()
How can I do it in Laravel v5 and Laravel v6?
",https://stackoverflow.com/questions/30046691/laravel-how-to-get-current-route-name-v5-v7,327,711279.0,35.0,,,2015-05-05 07:27:49,2024-02-22 05:26:31,2020-05-14 14:59:32,,,php;laravel;laravel-5;laravel-routing;laravel-6,Md Rashedul Hoque Bhuiyan,10681,2775615,registered,true,30052319,,CC BY-SA 4.0,2024-01-15 23:09:23,249,139,1,0,0,5,true,false,false,true,true,true,51,10,false,0.049,0.0005,4218,2015,5,7,Tuesday,false,false,false,false,false,false,true
9593765,Convert a comma-delimited string into array of integers?,"The following code:
$string = "1,2,3"
$ids = explode(',', $string);
var_dump($ids);
Returns the array:
array(3) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(1) "3"
}
I need for the values to be of type int instead of type string. Is there a better way of doing this than looping through the array with foreach and converting each string to int?
",https://stackoverflow.com/questions/9593765/convert-a-comma-delimited-string-into-array-of-integers,325,366310.0,19.0,,,2012-03-06 23:52:22,2023-12-31 14:37:49,2022-06-02 18:51:57,,,php;arrays;string;integer;explode,cwal,3920,575594,registered,true,9593794,,CC BY-SA 4.0,,552,418,7,0,0,5,true,false,false,true,true,true,56,8,true,0.052,0.0009,5373,2012,3,23,Tuesday,false,false,false,false,false,false,true
1634782,What is the most accurate way to retrieve a user's correct IP address in PHP?,"I know there are a plethora of $_SERVER variables headers available for IP address retrieval. I was wondering if there is a general consensus as to how to most accurately retrieve a user's real IP address (well knowing no method is perfect) using said variables?
I spent some time trying to find an in depth solution and came up with the following code based on a number of sources. I would love it if somebody could please poke holes in the answer or shed some light on something perhaps more accurate.
edit includes optimizations from @Alix
/**
* Retrieves the best guess of the client's actual IP address.
* Takes into account numerous HTTP proxy headers due to variations
* in how different ISPs handle IP addresses in headers between hops.
*/
public function get_ip_address() {
// Check for shared internet/ISP IP
if (!empty($_SERVER['HTTP_CLIENT_IP']) && $this->validate_ip($_SERVER['HTTP_CLIENT_IP']))
return $_SERVER['HTTP_CLIENT_IP'];
// Check for IPs passing through proxies
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
// Check if multiple IP addresses exist in var
$iplist = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
foreach ($iplist as $ip) {
if ($this->validate_ip($ip))
return $ip;
}
}
}
if (!empty($_SERVER['HTTP_X_FORWARDED']) && $this->validate_ip($_SERVER['HTTP_X_FORWARDED']))
return $_SERVER['HTTP_X_FORWARDED'];
if (!empty($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']) && $this->validate_ip($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']))
return $_SERVER['HTTP_X_CLUSTER_CLIENT_IP'];
if (!empty($_SERVER['HTTP_FORWARDED_FOR']) && $this->validate_ip($_SERVER['HTTP_FORWARDED_FOR']))
return $_SERVER['HTTP_FORWARDED_FOR'];
if (!empty($_SERVER['HTTP_FORWARDED']) && $this->validate_ip($_SERVER['HTTP_FORWARDED']))
return $_SERVER['HTTP_FORWARDED'];
// Return unreliable IP address since all else failed
return $_SERVER['REMOTE_ADDR'];
}
/**
* Ensures an IP address is both a valid IP address and does not fall within
* a private network range.
*
* @access public
* @param string $ip
*/
public function validate_ip($ip) {
if (filter_var($ip, FILTER_VALIDATE_IP,
FILTER_FLAG_IPV4 |
FILTER_FLAG_IPV6 |
FILTER_FLAG_NO_PRIV_RANGE |
FILTER_FLAG_NO_RES_RANGE) === false)
return false;
self::$ip = $ip;
return true;
}
Words of Warning (update)
REMOTE_ADDR still represents the most reliable source of an IP address. The other $_SERVER variables mentioned here can be spoofed by a remote client very easily. The purpose of this solution is to attempt to determine the IP address of a client sitting behind a proxy. For your general purposes, you might consider using this in combination with the IP address returned directly from $_SERVER['REMOTE_ADDR'] and storing both.
For 99.9% of users this solution will suit your needs perfectly. It will not protect you from the 0.1% of malicious users looking to abuse your system by injecting their own request headers. If relying on IP addresses for something mission critical, resort to REMOTE_ADDR and don't bother catering to those behind a proxy.
",https://stackoverflow.com/questions/1634782/what-is-the-most-accurate-way-to-retrieve-a-users-correct-ip-address-in-php,325,120300.0,18.0,,,2009-10-28 02:03:26,2021-05-25 18:27:51,2014-04-16 07:53:03,,,php;ip-address,Corey Ballou,43815,185882,registered,true,2031935,,CC BY-SA 3.0,2011-03-15 07:34:07,3473,3284,5,0,0,2,true,false,false,true,true,true,81,15,true,0.15,0.0027,6233,2009,10,2,Wednesday,false,false,false,false,false,false,true
3349753,Delete directory with files in it?,"I wonder, what's the easiest way to delete a directory with all its files in it?
I'm using rmdir(PATH . '/' . $value); to delete a folder, however, if there are files inside of it, I simply can't delete it.
",https://stackoverflow.com/questions/3349753/delete-directory-with-files-in-it,324,495323.0,37.0,,,2010-07-28 03:41:48,2026-01-22 15:38:02,2012-11-21 21:17:26,,,php;rmdir,matt,44841,1444475,registered,true,3349792,,CC BY-SA 3.0,2017-06-06 14:05:49,235,208,1,0,0,2,true,false,false,true,true,true,34,6,true,0.075,0.0007,5960,2010,7,3,Wednesday,false,false,false,false,false,false,true
4636166,Only variables should be passed by reference,"// Other variables
$MAX_FILENAME_LENGTH = 260;
$file_name = $_FILES[$upload_name]['name'];
//echo ""testing-"".$file_name.""<br>"";
//$file_name = strtolower($file_name);
$file_extension = end(explode('.', $file_name)); //ERROR ON THIS LINE
$uploadErrors = array(
0=>'There is no error, the file uploaded with success',
1=>'The uploaded file exceeds the upload max filesize allowed.',
2=>'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
3=>'The uploaded file was only partially uploaded',
4=>'No file was uploaded',
6=>'Missing a temporary folder'
);
Any ideas? After 2 days still stuck.
",https://stackoverflow.com/questions/4636166/only-variables-should-be-passed-by-reference,324,420110.0,13.0,,,2011-01-08 21:10:39,2023-08-11 15:43:06,2018-06-14 08:55:43,,,php,Frank Nwoko,3914,512095,registered,true,4636183,,CC BY-SA 4.0,2021-09-08 21:48:59,709,678,1,0,0,1,true,false,false,true,true,true,44,7,false,0.031,0.0008,5796,2011,1,21,Saturday,true,false,false,false,false,false,true
4554758,How to read if a checkbox is checked in PHP?,"How to read if a checkbox is checked in PHP?
",https://stackoverflow.com/questions/4554758/how-to-read-if-a-checkbox-is-checked-in-php,322,1018607.0,21.0,,,2010-12-29 14:04:08,2022-06-08 15:02:19,2015-02-08 22:26:00,,,php;html;forms;post;checkbox,Thew,15999,528370,registered,true,4554784,,CC BY-SA 3.0,,52,45,0,0,0,5,true,false,false,true,true,true,44,10,true,0.021,0.0003,5806,2010,12,14,Wednesday,false,false,false,false,false,false,true
2030906,"Are arrays in PHP copied as value or as reference to new variables, and when passed to functions?","1) When an array is passed as an argument to a method or function, is it passed by reference, or by value?
2) When assigning an array to a variable, is the new variable a reference to the original array, or is it new copy?
What about doing this:
$a = array(1,2,3);
$b = $a;
Is $b a reference to $a?
",https://stackoverflow.com/questions/2030906/are-arrays-in-php-copied-as-value-or-as-reference-to-new-variables-and-when-pas,322,171477.0,8.0,,,2010-01-08 21:32:24,2020-04-06 18:49:40,2020-04-06 18:49:40,,,php;arrays;reference;pass-by-reference;pass-by-value,Frank,19542,209320,registered,true,2030924,,CC BY-SA 4.0,,378,303,3,0,0,5,true,false,false,true,true,true,97,18,true,0.047,0.0019,6161,2010,1,21,Friday,false,false,false,false,false,false,true
1996122,How can I prevent XSS with HTML/PHP?,"How do I prevent XSS (cross-site scripting) using just HTML and PHP?
I've seen numerous other posts on this topic, but I have not found an article that clear and concisely states how to actually prevent XSS.
",https://stackoverflow.com/questions/1996122/how-can-i-prevent-xss-with-html-php,322,367648.0,9.0,,,2010-01-03 20:09:09,2025-09-16 08:41:24,2023-08-03 13:25:59,,,php;xss,TimTim,3349,242812,unregistered,true,,,CC BY-SA 4.0,2016-11-24 05:20:35,304,208,0,1,0,2,false,false,false,true,true,true,36,7,true,0.024,0.0009,6166,2010,1,20,Sunday,true,false,false,false,false,false,true
3787540,How to get first 5 characters from string,"How to get first 5 characters from string using php
$myStr = ""HelloWordl"";
result should be like this
$result = ""Hello"";
",https://stackoverflow.com/questions/3787540/how-to-get-first-5-characters-from-string,320,710446.0,5.0,,,2010-09-24 13:25:17,2020-08-30 14:34:32,2015-09-30 04:47:29,2020-08-27 11:05:34,Duplicate,php;substring,faressoft,19769,423903,registered,true,3787576,,,2015-08-11 05:38:46,188,126,2,0,0,2,true,true,false,true,true,true,41,8,false,0.007,0.0005,5902,2010,9,13,Friday,false,false,false,false,false,false,true
11719495,PHP Warning: POST Content-Length of 8978294 bytes exceeds the limit of 8388608 bytes in Unknown on line 0,"I am getting this error when trying to upload an import on WordPress on my XAMPP local dev environment:
Warning: POST Content-Length of 8978294 bytes exceeds the limit of 8388608 bytes in Unknown on line 0
I changed the upload_max_filesize from 2M to 1000M, but that didn't seem to do anything.
Any ideas?
",https://stackoverflow.com/questions/11719495/php-warning-post-content-length-of-8978294-bytes-exceeds-the-limit-of-8388608-b,319,685602.0,24.0,,,2012-07-30 10:18:33,2024-04-13 06:04:31,,,,wordpress;xampp;php,novicePrgrmr,19525,474980,registered,true,11719522,,CC BY-SA 3.0,2024-04-15 13:47:04,377,310,3,0,0,3,true,false,false,true,true,false,105,18,false,0.035,0.0005,5227,2012,7,10,Monday,false,false,false,false,false,false,true
3264889,How to check for null in Twig?,"What construct should I use to check whether a value is NULL in a Twig template?
",https://stackoverflow.com/questions/3264889/how-to-check-for-null-in-twig,318,309208.0,8.0,,,2010-07-16 12:38:33,2024-02-01 00:18:29,2017-03-08 18:33:38,,,php;twig;short-circuiting,Fluffy,28660,123927,registered,true,4520470,,CC BY-SA 3.0,,88,81,0,0,0,3,true,false,false,true,true,true,30,7,true,0.026,0.001,5972,2010,7,12,Friday,false,false,false,false,false,false,true
4638569,How to remove the leading character from a string?,"I have a input string like:
$str = ':this is a applepie :) ';
How can I remove the first occurring : with PHP?
Desired output: this is a applepie :)
",https://stackoverflow.com/questions/4638569/how-to-remove-the-leading-character-from-a-string,317,511141.0,10.0,,,2011-01-09 09:48:40,2021-04-22 13:34:36,2021-04-22 13:34:36,,,php;string;trim,yuli chika,9261,499587,registered,true,4638589,,CC BY-SA 4.0,,222,151,3,0,0,3,true,false,false,true,true,true,50,9,true,0.02,0.0006,5795,2011,1,9,Sunday,true,false,false,false,false,false,true
5213528,Convert timestamp to readable date/time PHP,"I have a timestamp stored in a session (1299446702).
How can I convert that to a readable date/time in PHP? I have tried srttotime, etc. to no avail.
",https://stackoverflow.com/questions/5213528/convert-timestamp-to-readable-date-time-php,317,872569.0,17.0,,,2011-03-06 21:28:32,2024-11-28 07:43:42,2011-03-22 11:42:41,,,php,Adamski,6079,442794,registered,true,,,CC BY-SA 2.5,2019-05-08 21:48:43,165,151,0,0,0,1,false,false,false,true,true,true,43,6,false,0.019,0.0004,5739,2011,3,21,Sunday,true,false,false,false,false,false,true
1987579,Remove warning messages in PHP,"I have some PHP code. When I run it, a warning message appears.
How can I remove/suppress/ignore these warning messages?
",https://stackoverflow.com/questions/1987579/remove-warning-messages-in-php,316,925720.0,12.0,,,2010-01-01 00:32:50,2026-05-27 20:07:32,2018-02-05 16:03:32,,,php;warnings;error-reporting,Alireza,5701,238952,registered,true,1987588,,CC BY-SA 3.0,2012-03-08 03:24:26,136,122,0,0,0,3,true,false,false,true,true,true,30,5,false,0.013,0.0003,6168,2010,1,0,Friday,false,false,false,false,false,false,true
3292044,PHP: merge two arrays while keeping keys instead of reindexing?,"How can I merge two arrays (one with string => value pairs and another with int => value pairs) while keeping the string/int keys? None of them will ever overlap (because one has only strings and the other has only integers).
Here is my current code (which doesn't work, because array_merge is re-indexing the array with integer keys):
// get all id vars by combining the static and dynamic
$staticIdentifications = array(
Users::userID => ""USERID"",
Users::username => ""USERNAME""
);
// get the dynamic vars, formatted: varID => varName
$companyVarIdentifications = CompanyVars::getIdentificationVarsFriendly($_SESSION['companyID']);
// merge the static and dynamic vars (*** BUT KEEP THE INT INDICES ***)
$idVars = array_merge($staticIdentifications, $companyVarIdentifications);
",https://stackoverflow.com/questions/3292044/php-merge-two-arrays-while-keeping-keys-instead-of-reindexing,316,242952.0,6.0,,,2010-07-20 16:12:37,2023-06-21 06:38:22,2015-06-05 10:00:48,,,php;arrays;array-merge,Garrett,11793,365985,registered,true,3292071,,CC BY-SA 3.0,,832,794,1,0,0,3,true,false,false,true,true,true,63,10,true,0.025,0.0013,5968,2010,7,16,Tuesday,false,false,false,false,false,false,true
38549,What is the difference between INNER JOIN and OUTER JOIN?,"What is the difference between INNER JOIN and OUTER JOIN?
How do LEFT OUTER JOIN, RIGHT OUTER JOIN, and FULL OUTER JOIN fit in?
",https://stackoverflow.com/questions/38549/what-is-the-difference-between-inner-join-and-outer-join,5294,2733211.0,26.0,,,2008-09-01 22:36:06,2025-09-22 02:30:57,2025-04-05 22:33:55,,,sql;join;inner-join;outer-join,Chris de Vries,57861,3836,registered,true,38578,,CC BY-SA 4.0,2012-07-21 21:51:54,207,128,5,0,0,4,true,false,false,true,true,true,57,10,true,0.01,0.0019,6655,2008,9,22,Monday,false,false,false,false,false,true,false
2334712,UPDATE from a SELECT,"In SQL Server, it is possible to insert rows into a table with an INSERT.. SELECT statement:
INSERT INTO Table (col1, col2, col3)
SELECT col1, col2, col3
FROM other_table
WHERE sql = 'cool'
Is it also possible to update a table with SELECT? I have a temporary table containing the values and would like to update another table using those values. Perhaps something like this:
UPDATE Table SET col1, col2
SELECT col1, col2
FROM other_table
WHERE sql = 'cool'
WHERE Table.id = other_table.id
",https://stackoverflow.com/questions/2334712/update-from-a-select,4354,5681436.0,40.0,,,2010-02-25 14:36:53,2025-12-05 06:22:43,2025-12-05 06:22:43,,,sql;sql-server;t-sql;sql-update,jamesmhaley,45799,150939,registered,true,2334741,,CC BY-SA 4.0,2013-04-11 08:51:15,610,496,4,0,0,4,true,false,false,true,true,true,20,4,false,0.007,0.0008,6113,2010,2,14,Thursday,false,false,false,false,false,true,false
92082,How to add a column with a default value to an existing table in SQL Server?,"How can I add a column with a default value to an existing table in SQL Server 2000 / SQL Server 2005?
",https://stackoverflow.com/questions/92082/how-to-add-a-column-with-a-default-value-to-an-existing-table-in-sql-server,3330,3941553.0,45.0,,,2008-09-18 12:30:04,2024-12-03 16:25:05,2023-12-23 21:08:30,,,sql;sql-server;sql-server-2005;sql-server-2000,Mathias,34461,7241,registered,true,92123,,CC BY-SA 4.0,2013-08-23 07:44:51,296,103,0,2,0,4,true,false,false,true,true,true,76,16,true,0.011,0.0008,6638,2008,9,12,Thursday,false,false,false,false,false,true,false
1108,How does database indexing work in reality?,"Given that indexing is so important, as your data set increases in size, how does indexing work at a database-agnostic level?
For information on queries to index a field, check out How do I index a database column?.
",https://stackoverflow.com/questions/1108/how-does-database-indexing-work-in-reality,2909,1148427.0,7.0,,,2008-08-04 10:07:12,2026-03-04 20:49:08,2026-01-31 23:51:48,2022-03-09 03:42:38,Needs more focus,sql;database;performance;indexing;database-indexes,Xenph Yan,84211,264,registered,true,1130,,,2011-07-17 09:20:05,295,216,0,1,0,5,true,true,false,true,true,true,43,7,true,0.006,0.0025,6683,2008,8,10,Monday,false,false,false,false,false,true,false
2594829,Finding and deleting duplicate values in a SQL table,"It's easy to find duplicates with one field:
SELECT email, COUNT(email)
FROM users
GROUP BY email
HAVING COUNT(email) > 1
So if we have a table
ID NAME EMAIL
1 John asd@asd.com
2 Sam asd@asd.com
3 Tom asd@asd.com
4 Bob bob@asd.com
5 Tom asd@asd.com
This query will give us John, Sam, Tom, Tom because they all have the same email.
However, what I want is to get duplicates with the same email and name.
That is, I want to get "Tom", "Tom".
The reason I need this: I made a mistake, and allowed inserting duplicate name and email values. Now I need to remove/change the duplicates, so I need to find them first.
",https://stackoverflow.com/questions/2594829/finding-and-deleting-duplicate-values-in-a-sql-table,2549,4136986.0,37.0,,,2010-04-07 18:17:29,2025-08-15 15:31:21,2025-07-28 15:11:12,,,sql;duplicates,Alex,36559,279776,registered,true,2594855,,CC BY-SA 4.0,2015-07-22 08:55:29,890,670,7,0,0,2,true,false,false,true,true,true,52,9,false,0.009,0.0006,6072,2010,4,18,Wednesday,false,false,false,false,false,true,false
194852,Concatenate text from multiple rows into a single text string,"Consider a database table holding names, with three rows:
Peter
Paul
Mary
Is there an easy way to turn this into a single string of Peter, Paul, Mary?
",https://stackoverflow.com/questions/194852/concatenate-text-from-multiple-rows-into-a-single-text-string,2451,3462776.0,51.0,,,2008-10-11 23:49:59,2025-11-25 08:50:54,2025-11-25 08:50:54,,,sql;sql-server;concatenation;group-concat,JohnnyM,29656,27109,registered,true,545672,,CC BY-SA 4.0,2011-08-02 14:32:14,203,152,2,0,0,4,true,false,false,true,true,true,61,10,false,0.015,0.0007,6615,2008,10,23,Saturday,true,false,false,false,false,true,false
113045,How to return only the Date from a SQL Server DateTime datatype,"SELECT GETDATE()
Returns: 2008-09-22 15:24:13.790
I want that date part without the time part: 2008-09-22 00:00:00.000
How can I get that?
",https://stackoverflow.com/questions/113045/how-to-return-only-the-date-from-a-sql-server-datetime-datatype,2230,3980779.0,47.0,,,2008-09-22 03:31:33,2024-12-03 16:59:39,2022-05-24 03:26:54,,,sql;date;t-sql;datetime;sql-server-2008,Eddie Groves,35224,5769,registered,true,113055,,CC BY-SA 4.0,2014-11-19 21:46:35,214,143,3,0,0,5,true,false,false,true,true,true,63,12,false,0.012,0.0006,6634,2008,9,3,Monday,false,false,false,false,false,true,false
5706437,"What's the difference between INNER JOIN, LEFT JOIN, RIGHT JOIN and FULL JOIN?","What's the difference between INNER JOIN, LEFT JOIN, RIGHT JOIN and FULL JOIN
in MySQL?
",https://stackoverflow.com/questions/5706437/whats-the-difference-between-inner-join-left-join-right-join-and-full-join,2223,2284351.0,2.0,,,2011-04-18 17:15:24,2021-08-26 10:10:26,2018-03-26 06:18:06,2015-05-24 15:31:29,Duplicate,mysql;sql;join;inner-join;outer-join,Lion King,34152,459943,registered,true,,,,2018-05-17 13:46:03,174,89,4,0,0,5,false,true,false,true,true,true,82,13,true,0.001,0.001,5696,2011,4,17,Monday,false,false,false,false,false,true,false
406294,LEFT JOIN vs. LEFT OUTER JOIN,"What is the difference between LEFT JOIN and LEFT OUTER JOIN?
",https://stackoverflow.com/questions/406294/left-join-vs-left-outer-join,2120,2229764.0,12.0,,,2009-01-02 08:30:10,2026-09-03 07:42:27,2026-09-03 07:42:27,,,sql;sql-server;t-sql;left-join;outer-join,KG Sosa,22269,48581,registered,true,406333,,CC BY-SA 4.0,2015-10-08 02:28:58,95,62,2,0,0,5,true,false,false,true,true,true,29,6,false,0.005,0.001,6532,2009,1,8,Friday,false,false,false,false,false,true,false
452859,Inserting multiple rows in a single SQL query?,"I have multiple set of data to insert at once, say 4 rows. My table has three columns: Person, Id and Office.
INSERT INTO MyTable VALUES (""John"", 123, ""Lloyds Office"");
INSERT INTO MyTable VALUES (""Jane"", 124, ""Lloyds Office"");
INSERT INTO MyTable VALUES (""Billy"", 125, ""London Office"");
INSERT INTO MyTable VALUES (""Miranda"", 126, ""Bristol Office"");
Can I insert all 4 rows in a single SQL statement?
",https://stackoverflow.com/questions/452859/inserting-multiple-rows-in-a-single-sql-query,2110,3789658.0,4.0,,,2009-01-17 05:55:54,2025-01-08 09:11:23,2019-10-17 13:25:45,,,sql;sql-server;t-sql;insert,rits,,,does_not_exist,true,,,CC BY-SA 4.0,2017-10-25 16:03:46,482,405,4,0,0,4,false,false,false,true,false,true,46,8,true,0.001,0.0006,6517,2009,1,5,Saturday,true,false,false,false,false,true,false
3800551,Select first row in each GROUP BY group?,"
I'd like to select the first row of each set of rows grouped with a GROUP BY.
Specifically, if I've got a purchases table that looks like this:
SELECT * FROM purchases;
My Output:
id
customer
total
1
Joe
5
2
Sally
3
3
Joe
2
4
Sally
1
I'd like to query for the id of the largest purchase (total) made by each customer. Something like this:
SELECT FIRST(id), customer, FIRST(total)
FROM purchases
GROUP BY customer
ORDER BY total DESC;
Expected Output:
FIRST(id)
customer
FIRST(total)
1
Joe
5
2
Sally
3
",https://stackoverflow.com/questions/3800551/select-first-row-in-each-group-by-group,2076,1924959.0,21.0,,,2010-09-27 01:23:22,2025-12-22 16:53:06,2023-08-22 23:44:05,,,sql;postgresql;greatest-n-per-group,David Wolever,156308,71522,registered,true,3800572,,CC BY-SA 4.0,2016-10-20 09:43:15,1278,536,7,0,0,3,true,false,false,true,true,true,40,8,true,0.011,0.0011,5899,2010,9,1,Monday,false,false,false,false,false,true,false
3305561,How to query MongoDB with "like","I want to query something with SQL's like query:
SELECT * FROM users WHERE name LIKE '%m%'
How can I achieve the same in MongoDB? I can't find an operator for like in the documentation.
",https://stackoverflow.com/questions/3305561/how-to-query-mongodb-with-like,1993,1915536.0,47.0,,,2010-07-22 03:19:21,2026-02-07 03:42:50,2021-05-11 14:00:10,,,sql;mongodb;mongodb-query;sql-like,Freewind,199358,342235,registered,true,3305687,,CC BY-SA 4.0,2014-12-17 23:14:12,336,188,3,1,0,4,true,false,false,true,true,true,42,6,false,0.025,0.001,5966,2010,7,3,Thursday,false,false,false,false,false,true,false
338156,Table Naming Dilemma: Singular vs. Plural Names,"Academia has it that table names should be the singular of the entity that they store attributes of.
I dislike any T-SQL that requires square brackets around names, but I have renamed a Users table to the singular, forever sentencing those using the table to sometimes have to use brackets.
My gut feel is that it is more correct to stay with the singular, but my gut feel is also that brackets indicate undesirables like column names with spaces in them etc.
Should I stay, or should I go?
",https://stackoverflow.com/questions/338156/table-naming-dilemma-singular-vs-plural-names,1931,652672.0,41.0,,,2008-12-03 18:09:30,2023-05-29 15:20:47,2017-11-05 04:11:39,2013-10-09 20:24:16,Opinion-based,sql;sql-server;naming-conventions,ProfK,51536,8741,registered,true,338433,,,,539,498,1,0,0,3,true,true,false,true,true,true,47,7,false,0.063,0.003,6562,2008,12,18,Wednesday,false,false,false,false,false,true,false
25969,Insert into ... values ( SELECT ... FROM ... ),"I am trying to INSERT INTO a table using the input from another table. Although this is entirely feasible for many database engines, I always seem to struggle to remember the correct syntax for the SQL engine of the day (MySQL, Oracle, SQL Server, Informix, and DB2).
Is there a silver-bullet syntax coming from an SQL standard (for example, SQL-92) that would allow me to insert the values without worrying about the underlying database?
",https://stackoverflow.com/questions/25969/insert-into-values-select-from,1903,3661685.0,29.0,,,2008-08-25 12:45:56,2025-08-02 12:46:06,2018-05-29 15:45:13,,,sql;database;syntax;database-agnostic;ansi-sql-92,RandomDev1999,43316,244,registered,true,25971,,CC BY-SA 4.0,2014-07-17 23:00:12,911,440,2,6,0,5,true,false,false,true,true,true,46,10,false,0.008,0.0005,6662,2008,8,12,Monday,false,false,false,false,false,true,false
653714,Insert results of a stored procedure into a temporary table,"How do I do a SELECT * INTO [temp table] FROM [stored procedure]? Not FROM [Table] and without defining [temp table]?
Select all data from BusinessLine into tmpBusLine works fine.
select *
into tmpBusLine
from BusinessLine
I am trying the same, but using a stored procedure that returns data, is not quite the same.
select *
into tmpBusLine
from
exec getBusinessLineHistory '16 Mar 2009'
Output message:
Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword
'exec'.
I have read several examples of creating a temporary table with the same structure as the output stored procedure, which works fine, but it would be nice to not supply any columns.
",https://stackoverflow.com/questions/653714/insert-results-of-a-stored-procedure-into-a-temporary-table,1873,2708154.0,35.0,,,2009-03-17 10:45:26,2025-03-05 10:01:51,2018-03-26 06:07:06,,,sql;sql-server;sql-server-2005;t-sql;stored-procedures,Ferdeen,21922,42829,registered,true,,,CC BY-SA 3.0,2011-07-06 20:23:13,902,679,9,0,0,5,false,false,false,true,true,true,59,10,false,0.013,0.0007,6458,2009,3,10,Tuesday,false,false,false,false,false,true,false
4849652,Find all tables containing column with specified name,"Is it possible to query for table names which contain columns being
LIKE '%myName%'
",https://stackoverflow.com/questions/4849652/find-all-tables-containing-column-with-specified-name,1825,4567825.0,36.0,,,2011-01-31 10:12:26,2025-05-27 11:37:54,2024-02-01 18:28:06,,,sql;sql-server;t-sql;system-tables,gruber,30029,326821,registered,true,,,CC BY-SA 4.0,2017-04-24 15:24:32,116,85,1,0,0,4,false,false,false,true,true,true,53,8,false,0.008,0.0004,5773,2011,1,10,Monday,false,false,false,false,false,true,false
63447,How do I perform an IF...THEN in an SQL SELECT?,"How do I perform an IF...THEN in an SQL SELECT statement?
For example:
SELECT IF(Obsolete = 'N' OR InStock = 'Y' ? 1 : 0) AS Saleable, * FROM Product
",https://stackoverflow.com/questions/63447/how-do-i-perform-an-if-then-in-an-sql-select,1815,4798157.0,30.0,,,2008-09-15 14:34:09,2026-06-09 07:57:12,2018-03-26 06:09:19,,,sql;sql-server;t-sql;if-statement;case,Eric Labashosky,30118,6522,registered,true,63480,,CC BY-SA 3.0,2014-11-07 07:03:43,217,153,3,0,0,5,true,false,false,true,true,true,47,10,true,0.006,0.0004,6641,2008,9,14,Monday,false,false,false,false,false,true,false
16481379,How can I delete using INNER JOIN with SQL Server?,"I want to delete using INNER JOIN in SQL Server 2008.
But I get this error:
Msg 156, Level 15, State 1, Line 15
Incorrect syntax near the keyword 'INNER'.
My code:
DELETE
FROM WorkRecord2
INNER JOIN Employee
ON EmployeeRun=EmployeeNo
WHERE Company = '1'
AND Date = '2013-05-06'
",https://stackoverflow.com/questions/16481379/how-can-i-delete-using-inner-join-with-sql-server,1805,2323604.0,14.0,,,2013-05-10 11:38:21,2021-10-03 14:07:39,2021-10-02 07:17:40,,,sql;sql-server;sql-server-2008;inner-join;sql-delete,nettoon493,18653,1556907,registered,true,16481475,,CC BY-SA 4.0,2015-06-01 21:33:59,461,297,2,0,0,5,true,false,false,true,true,true,50,10,true,0.006,0.0008,4943,2013,5,11,Friday,false,false,false,false,false,true,false
49925,What is the difference between UNION and UNION ALL?,"What is the difference between UNION and UNION ALL?
",https://stackoverflow.com/questions/49925/what-is-the-difference-between-union-and-union-all,1736,1633512.0,19.0,,,2008-09-08 15:19:33,2024-07-20 20:22:26,2018-03-26 06:50:21,,,sql;union;union-all,Brian G,55466,3208,registered,true,49928,,CC BY-SA 3.0,2014-04-25 19:43:09,85,52,2,0,0,3,true,false,false,true,true,true,51,9,true,0.012,0.0011,6648,2008,9,15,Monday,false,false,false,false,false,true,false
1293330,How can I do an UPDATE statement with JOIN in SQL Server?,"I need to update this table in SQL Server with data from its 'parent' table, see below:
Table: sale
id (int)
udid (int)
assid (int)
Table: ud
id (int)
assid (int)
sale.assid contains the correct value to update ud.assid.
What query will do this? I'm thinking of a join but I'm not sure if it's possible.
",https://stackoverflow.com/questions/1293330/how-can-i-do-an-update-statement-with-join-in-sql-server,1704,2437200.0,18.0,,,2009-08-18 11:40:07,2023-10-27 06:12:14,2020-04-13 10:05:15,,,sql;sql-server;t-sql;sql-server-2005;sql-update,Ant Swift,21517,99297,registered,true,1293347,,CC BY-SA 4.0,2014-05-28 16:35:11,488,315,5,0,0,5,true,false,false,true,true,true,57,12,true,0.007,0.0007,6304,2009,8,11,Tuesday,false,false,false,false,false,true,false
7745609,SQL select only rows with max value on a column,"I have this table for documents (simplified version here):
id
rev
content
1
1
...
2
1
...
1
2
...
1
3
...
How do I select one row per id and only the greatest rev?
With the above data, the result should contain two rows: [1, 3, ...] and [2, 1, ..]. I'm using MySQL.
Currently I use checks in the while loop to detect and over-write old revs from the resultset. But is this the only method to achieve the result? Isn't there a SQL solution?
",https://stackoverflow.com/questions/7745609/sql-select-only-rows-with-max-value-on-a-column,1686,2239780.0,27.0,,,2011-10-12 19:42:07,2024-08-29 17:34:20,2021-10-04 09:30:36,2019-03-20 00:19:10,Duplicate,mysql;sql;aggregate-functions;greatest-n-per-group;groupwise-maximum,Majid Fouladpour,30454,66580,registered,true,7745635,,,2015-10-05 09:21:59,845,458,3,0,0,5,true,true,false,true,true,true,47,10,false,0.012,0.0008,5519,2011,10,19,Wednesday,false,false,false,false,false,true,false
8923114,How to reset AUTO_INCREMENT in MySQL,"How can I reset the AUTO_INCREMENT of a field?
I want it to start counting from 1 again.
",https://stackoverflow.com/questions/8923114/how-to-reset-auto-increment-in-mysql,1675,2037318.0,28.0,,,2012-01-19 08:37:49,2024-12-15 23:31:56,2021-08-05 18:28:29,,,mysql;sql;auto-increment,homerun,20965,3426825,registered,true,8923132,,CC BY-SA 4.0,2014-05-04 16:23:17,155,89,2,0,0,3,true,false,false,true,true,true,36,6,false,0.014,0.0008,5420,2012,1,8,Thursday,false,false,false,false,false,true,false
4048151,What are the options for storing hierarchical data in a relational database?,"Good Overviews
Generally speaking, you're making a decision between fast read times (for example, nested set) or fast write times (adjacency list). Usually, you end up with a combination of the options below that best fit your needs. The following provides some in-depth reading:
- One more Nested Intervals vs. Adjacency List comparison: the best comparison of Adjacency List, Materialized Path, Nested Set, and Nested Interval I've found.
- Models for hierarchical data: slides with good explanations of tradeoffs and example usage
- Representing hierarchies in MySQL: very good overview of Nested Set in particular
- Hierarchical data in RDBMSs: a most comprehensive and well-organized set of links I've seen, but not much in the way of explanation
Options
Ones I am aware of and general features:
- Columns: ID, ParentID
- Easy to implement.
- Cheap node moves, inserts, and deletes.
- Expensive to find the level, ancestry & descendants, path
- Avoid N+1 via Common Table Expressions in databases that support them
- Columns: Left, Right
- Cheap ancestry, descendants
- Very expensive
O(n/2) moves, inserts, deletes due to volatile encoding
- Bridge Table (a.k.a. Closure Table /w triggers)
- Uses separate join table with ancestor, descendant, depth (optional)
- Cheap ancestry and descendants
- Writes costs
O(log n) (size of the subtree) for insert, updates, deletes
- Normalized encoding: good for RDBMS statistics & query planner in joins
- Requires multiple rows per node
- Lineage Column (a.k.a. Materialized Path, Path Enumeration)
- Column: lineage (e.g. /parent/child/grandchild/etc...)
- Cheap descendants via prefix query (e.g.
LEFT(lineage, #) = '/enumerated/path')
- Writes costs
O(log n) (size of the subtree) for insert, updates, deletes
- Non-relational: relies on Array datatype or serialized string format
- Like nested set, but with real/float/decimal so that the encoding isn't volatile (inexpensive move/insert/delete)
- Has real/float/decimal representation/precision issues
- Matrix encoding variant adds ancestor encoding (materialized path) for "free", but with the added trickiness of linear algebra.
- A modified Adjacency List that adds a Level and Rank (e.g. ordering) column to each record.
- Cheap to iterate/paginate over
- Expensive move and delete
- Good Use: threaded discussion - forums / blog comments
- Columns: one for each lineage level, refers to all the parents up to the root, levels down from the item's level are set to NULL
- Cheap ancestors, descendants, level
- Cheap insert, delete, move of the leaves
- Expensive insert, delete, move of the internal nodes
- Hard limit to how deep the hierarchy can be
Database Specific Notes
MySQL/MariaDB
Use session variables for Adjacency List
- Use CTEs in MySQL 8.0 or MariaDB 10.2
Oracle
- Use CONNECT BY to traverse Adjacency Lists
PostgreSQL
- ltree datatype for Materialized Path
SQL Server
- General summary
- 2008 offers HierarchyId data type that appears to help with the Lineage Column approach and expand the depth that can be represented.
",https://stackoverflow.com/questions/4048151/what-are-the-options-for-storing-hierarchical-data-in-a-relational-database,1624,351673.0,8.0,,,2010-10-29 00:23:33,2024-01-22 16:09:31,2024-01-22 16:09:31,2025-03-03 23:50:09,Needs more focus,sql;database;tree;relational-database;hierarchical-data,orangepips,10001,470838,registered,true,,,,2018-10-29 04:07:20,6078,3148,4,21,0,5,false,true,false,true,true,true,76,12,true,0.023,0.0046,5867,2010,10,0,Friday,false,false,false,false,false,true,false
2421388,Using group by on multiple columns,"I understand the point of GROUP BY x.
But how does GROUP BY x, y work, and what does it mean?
",https://stackoverflow.com/questions/2421388/using-group-by-on-multiple-columns,1548,2370826.0,4.0,,,2010-03-10 23:11:23,2026-07-18 19:01:16,2020-07-22 14:47:34,,,sql;group-by;multiple-columns,Davide Tonietto,61698,117700,registered,true,2421441,,CC BY-SA 4.0,,134,94,2,0,0,3,true,false,false,true,true,true,34,6,false,0.002,0.0007,6100,2010,3,23,Wednesday,false,false,false,false,false,true,false
276927,Can I concatenate multiple MySQL rows into one field?,"Using MySQL, I can do something like:
SELECT hobbies FROM peoples_hobbies WHERE person_id = 5;
My Output:
shopping
fishing
coding
but instead I just want 1 row, 1 col:
Expected Output:
shopping, fishing, coding
The reason is that I'm selecting multiple values from multiple tables, and after all the joins I've got a lot more rows than I'd like.
I've looked for a function on MySQL Doc and it doesn't look like the CONCAT or CONCAT_WS functions accept result sets.
So does anyone here know how to do this?
",https://stackoverflow.com/questions/276927/can-i-concatenate-multiple-mysql-rows-into-one-field,1502,941761.0,16.0,,,2008-11-10 02:34:26,2023-03-17 19:19:48,2020-04-19 11:22:44,,,mysql;sql;concatenation;group-concat,Dean Rather,32562,14966,registered,true,276949,,CC BY-SA 4.0,2011-08-31 01:54:06,823,518,6,1,0,4,true,false,false,true,true,true,53,9,true,0.017,0.0016,6585,2008,11,2,Monday,false,false,false,false,false,true,false
565620,What is the difference between JOIN and INNER JOIN?,"Both these joins will give me the same results:
SELECT * FROM table JOIN otherTable ON table.ID = otherTable.FK
vs
SELECT * FROM table INNER JOIN otherTable ON table.ID = otherTable.FK
Is there any difference between the statements in performance or otherwise?
Does it differ between different SQL implementations?
",https://stackoverflow.com/questions/565620/what-is-the-difference-between-join-and-inner-join,1483,1086140.0,6.0,,,2009-02-19 14:47:29,2024-04-05 01:48:45,2024-04-05 01:48:45,,,sql;sql-server;join;inner-join,driis,164965,13627,registered,true,565640,,CC BY-SA 4.0,2012-05-15 16:08:10,417,324,2,0,0,4,true,false,false,true,true,true,51,9,true,0.006,0.0014,6484,2009,2,14,Thursday,false,false,false,false,false,true,false
82875,How can I list the tables in a SQLite database file that was opened with ATTACH?,"What SQL can be used to list the tables, and the rows within those tables in an SQLite database file – once I have attached it with the ATTACH command on the sqlite3 command line tool?
",https://stackoverflow.com/questions/82875/how-can-i-list-the-tables-in-a-sqlite-database-file-that-was-opened-with-attach,1462,1493264.0,19.0,,,2008-09-17 12:59:53,2024-04-29 16:18:33,2023-07-14 09:35:58,,,sql;sqlite;database-schema,izb,52420,974,registered,true,83195,,CC BY-SA 4.0,2011-09-17 23:31:06,218,185,2,0,0,3,true,false,false,true,true,true,80,16,true,0.013,0.001,6639,2008,9,12,Wednesday,false,false,false,false,false,true,false
1586560,How do I escape a single quote in SQL Server?,"I am trying to insert some text data into a table in SQL Server 9.
The text includes a single quote '.
How do I escape that?
I tried using two single quotes, but it threw me some errors.
eg. insert into my_table values('hi, my name''s tim.');
",https://stackoverflow.com/questions/1586560/how-do-i-escape-a-single-quote-in-sql-server,1441,1947945.0,15.0,,,2009-10-19 01:18:22,2024-05-03 15:56:28,2021-07-07 04:50:07,,,sql;sql-server;t-sql;delimiter;single-quotes,tim_wonil,16008,150703,registered,true,1586588,,CC BY-SA 4.0,2019-12-20 14:15:40,317,243,3,0,0,5,true,false,false,true,true,true,45,10,true,0.008,0.0007,6242,2009,10,1,Monday,false,false,false,false,false,true,false
470542,How do I limit the number of rows returned by an Oracle query after ordering?,"Is there a way to make an Oracle query behave like it contains a MySQL limit clause?
In MySQL, I can do this:
select *
from sometable
order by name
limit 20,10
to get the 21st to the 30th rows (skip the first 20, give the next 10). The rows are selected after the order by, so it really starts on the 20th name alphabetically.
In Oracle, the only thing people mention is the rownum pseudo-column, but it is evaluated before order by, which means this:
select *
from sometable
where rownum <= 10
order by name
will return a random set of ten rows ordered by name, which is not usually what I want. It also doesn't allow for specifying an offset.
",https://stackoverflow.com/questions/470542/how-do-i-limit-the-number-of-rows-returned-by-an-oracle-query-after-ordering,1400,2699442.0,16.0,,,2009-01-22 19:48:43,2024-04-19 17:18:17,2021-01-21 10:35:47,,,sql;oracle-database;pagination;sql-limit,Mathieu Longtin,16966,54320,registered,true,470571,,CC BY-SA 4.0,2013-04-21 07:41:19,809,652,7,0,0,4,true,false,false,true,true,true,77,15,true,0.006,0.0005,6512,2009,1,19,Thursday,false,false,false,false,false,true,false
42648,How to get the identity of an inserted row?,"How can I get the IDENTITY of an inserted row?
I know about @@IDENTITY and IDENT_CURRENT and SCOPE_IDENTITY, but don't understand the implications or impacts attached to each. How do these differ, and when would each be used?
",https://stackoverflow.com/questions/42648/how-to-get-the-identity-of-an-inserted-row,1395,1290339.0,15.0,,,2008-09-03 21:32:02,2026-07-08 04:45:57,2023-12-23 07:17:02,,,sql;sql-server;t-sql,Oded,501540,1583,registered,true,42655,,CC BY-SA 4.0,2015-10-28 22:40:00,292,226,4,0,0,3,true,false,false,true,true,true,43,9,true,0.012,0.0011,6653,2008,9,21,Wednesday,false,false,false,false,false,true,false
1313120,Retrieving the last record in each group - MySQL,"There is a table messages that contains data as shown below:
Id Name Other_Columns
-------------------------
1 A A_data_1
2 A A_data_2
3 A A_data_3
4 B B_data_1
5 B B_data_2
6 C C_data_1
If I run a query select * from messages group by name, I will get the result as:
1 A A_data_1
4 B B_data_1
6 C C_data_1
What query will return the following result?
3 A A_data_3
5 B B_data_2
6 C C_data_1
That is, the last record in each group should be returned.
At present, this is the query that I use:
SELECT
*
FROM (SELECT
*
FROM messages
ORDER BY id DESC) AS x
GROUP BY name
But this looks highly inefficient. Any other ways to achieve the same result?
",https://stackoverflow.com/questions/1313120/retrieving-the-last-record-in-each-group-mysql,1367,1267688.0,34.0,,,2009-08-21 17:04:04,2023-08-14 17:52:24,2022-02-22 15:13:40,,,mysql;sql;group-by;greatest-n-per-group;groupwise-maximum,Vijay Dev,27704,27474,registered,true,1313293,,CC BY-SA 4.0,2012-03-30 09:58:24,938,774,6,0,0,5,true,false,false,true,true,true,48,9,false,0.027,0.0011,6301,2009,8,17,Friday,false,false,false,false,false,true,false
224732,SQL Update from One Table to Another Based on a ID Match,"I have a database with account numbers and card numbers. I match these to a file to update any card numbers to the account number so that I am only working with account numbers.
I created a view linking the table to the account/card database to return the Table ID and the related account number, and now I need to update those records where the ID matches the Account Number.
This is the Sales_Import table, where the account number field needs to be updated:
LeadID
AccountNumber
147
5807811235
150
5807811326
185
7006100100007267039
And this is the RetrieveAccountNumber table, where I need to update from:
LeadID
AccountNumber
147
7006100100007266957
150
7006100100007267039
I tried the below, but no luck so far:
UPDATE [Sales_Lead].[dbo].[Sales_Import]
SET [AccountNumber] = (SELECT RetrieveAccountNumber.AccountNumber
FROM RetrieveAccountNumber
WHERE [Sales_Lead].[dbo].[Sales_Import]. LeadID =
RetrieveAccountNumber.LeadID)
It updates the card numbers to account numbers, but the account numbers get replaced by NULL
",https://stackoverflow.com/questions/224732/sql-update-from-one-table-to-another-based-on-a-id-match,1239,2780445.0,29.0,,,2008-10-22 07:14:03,2022-12-23 11:20:17,2022-05-23 16:50:05,,,sql;sql-server;select;join;sql-update,Boerseun,,,does_not_exist,true,,,CC BY-SA 4.0,2010-10-01 11:31:35,1722,1167,9,0,0,5,false,false,false,true,false,true,56,12,false,0.01,0.0004,6604,2008,10,7,Wednesday,false,false,false,false,false,true,false
205736,Get list of all tables in Oracle?,"How do I query an Oracle database to display the names of all tables in it?
",https://stackoverflow.com/questions/205736/get-list-of-all-tables-in-oracle,1235,2550406.0,24.0,,,2008-10-15 17:54:49,2024-07-28 02:01:15,2015-11-27 07:57:11,,,sql;oracle-database,vitule,16052,1287,registered,true,205746,,CC BY-SA 3.0,2010-12-11 11:36:13,83,76,0,0,0,2,true,false,false,true,true,true,33,7,true,0.009,0.0005,6611,2008,10,17,Wednesday,false,false,false,false,false,true,false
729197,Exclude a column using SELECT * [except columnA] FROM tableA?,"We all know that to select all columns from a table, we can use
SELECT * FROM tableA
Is there a way to exclude column(s) from a table without specifying all the columns?
SELECT * [except columnA] FROM tableA
The only way that I know is to manually specify all the columns and exclude the unwanted column. This is really time consuming so I'm looking for ways to save time and effort on this, as well as future maintenance should the table has more/less columns.
",https://stackoverflow.com/questions/729197/exclude-a-column-using-select-except-columna-from-tablea,1222,1810400.0,47.0,,,2009-04-08 09:15:28,2025-07-07 12:01:35,2021-07-24 07:57:11,,,sql;sql-server;t-sql,uuɐɯǝʃǝs,,,does_not_exist,true,,,CC BY-SA 4.0,2021-12-06 11:18:12,537,468,2,0,0,3,false,false,false,true,false,true,61,10,true,0.026,0.0007,6436,2009,4,9,Wednesday,false,false,false,false,false,true,false
4205181,Insert into a MySQL table or update if exists,"I want to add a row to a database table, but if a row exists with the same unique key I want to update the row.
For example:
INSERT INTO table_name (ID, NAME, AGE) VALUES(1, "A", 19);
Let’s say the unique key is ID, and in my Database, there is a row with ID = 1. In that case, I want to update that row with these values. Normally this gives an error.
If I use INSERT IGNORE it will ignore the error, but it still won’t update.
",https://stackoverflow.com/questions/4205181/insert-into-a-mysql-table-or-update-if-exists,1190,1390892.0,13.0,,,2010-11-17 14:08:52,2023-12-06 21:44:08,2020-08-12 12:55:51,,,mysql;sql;insert-update;upsert,Keshan,14763,434375,registered,true,4205207,,CC BY-SA 4.0,2015-09-01 10:34:45,585,440,4,0,0,4,true,false,false,true,true,true,45,9,false,0.009,0.0009,5848,2010,11,14,Wednesday,false,false,false,false,false,true,false
1139160,When should I use CROSS APPLY over INNER JOIN?,"What is the main purpose of using CROSS APPLY?
I have read (vaguely, through posts on the Internet) that cross apply can be more efficient when selecting over large data sets if you are partitioning. (Paging comes to mind)
I also know that CROSS APPLY doesn't require a UDF as the right-table.
In most INNER JOIN queries (one-to-many relationships), I could rewrite them to use CROSS APPLY, but they always give me equivalent execution plans.
Can anyone give me a good example of when CROSS APPLY makes a difference in those cases where INNER JOIN will work as well?
Edit:
Here's a trivial example, where the execution plans are exactly the same. (Show me one where they differ and where cross apply is faster/more efficient)
create table Company (
companyId int identity(1,1)
, companyName varchar(100)
, zipcode varchar(10)
, constraint PK_Company primary key (companyId)
)
GO
create table Person (
personId int identity(1,1)
, personName varchar(100)
, companyId int
, constraint FK_Person_CompanyId foreign key (companyId) references dbo.Company(companyId)
, constraint PK_Person primary key (personId)
)
GO
insert Company
select 'ABC Company', '19808' union
select 'XYZ Company', '08534' union
select '123 Company', '10016'
insert Person
select 'Alan', 1 union
select 'Bobby', 1 union
select 'Chris', 1 union
select 'Xavier', 2 union
select 'Yoshi', 2 union
select 'Zambrano', 2 union
select 'Player 1', 3 union
select 'Player 2', 3 union
select 'Player 3', 3
/* using CROSS APPLY */
select *
from Person p
cross apply (
select *
from Company c
where p.companyid = c.companyId
) Czip
/* the equivalent query using INNER JOIN */
select *
from Person p
inner join Company c on p.companyid = c.companyId
",https://stackoverflow.com/questions/1139160/when-should-i-use-cross-apply-over-inner-join,1167,1115696.0,15.0,,,2009-07-16 17:42:21,2021-10-08 20:42:26,2021-06-08 07:28:58,,,sql;sql-server;performance;t-sql;cross-apply,Jeff Meatball Yang,39397,111934,registered,true,1139231,,CC BY-SA 4.0,,2034,1761,8,1,0,5,true,false,false,true,true,true,46,9,true,0.013,0.001,6337,2009,7,17,Thursday,false,false,false,false,false,true,false
14704105,Search text in stored procedure in SQL Server,"I want to search a text from all my database stored procedures.
I use the below SQL:
SELECT DISTINCT
o.name AS Object_Name,
o.type_desc
FROM sys.sql_modules m
INNER JOIN sys.objects o
ON m.object_id = o.object_id
WHERE m.definition Like '%[ABD]%';
I want to search for [ABD] in all stored procedures including square brackets, but it's not giving the proper result.
How can I change my query to achieve this?
",https://stackoverflow.com/questions/14704105/search-text-in-stored-procedure-in-sql-server,1166,2919361.0,25.0,,,2013-02-05 09:30:39,2025-12-13 03:22:17,2025-12-13 03:22:17,,,sql;sql-server;stored-procedures,DharaPPatel,12903,815244,registered,true,14704157,,CC BY-SA 4.0,2018-04-07 01:11:24,486,422,2,0,0,3,true,false,false,true,true,true,45,8,false,0.009,0.0004,5037,2013,2,9,Tuesday,false,false,false,false,false,true,false
1517635,Save PL/pgSQL output from PostgreSQL to a CSV file,"What is the easiest way to save PL/pgSQL output from a PostgreSQL database to a CSV file?
I'm using PostgreSQL 8.4 with pgAdmin III and PSQL plugin where I run queries from.
",https://stackoverflow.com/questions/1517635/save-pl-pgsql-output-from-postgresql-to-a-csv-file,1163,1032235.0,21.0,,,2009-10-04 22:58:51,2023-09-07 20:15:27,2017-04-09 19:00:23,,,sql;postgresql;csv;postgresql-copy,Hoff,40266,102181,registered,true,1517692,,CC BY-SA 3.0,2023-03-06 12:31:38,190,176,0,0,0,4,true,false,false,true,true,true,50,9,false,0.02,0.0011,6257,2009,10,22,Sunday,true,false,false,false,false,true,false
2577174,Join vs. sub-query,"I am an old-school MySQL user and have always preferred JOIN over sub-query. But nowadays everyone uses sub-query, and I hate it; I don't know why.
I lack the theoretical knowledge to judge for myself if there is any difference. Is a sub-query as good as a JOIN and therefore is there nothing to worry about?
",https://stackoverflow.com/questions/2577174/join-vs-sub-query,1150,687068.0,20.0,,,2010-04-05 06:22:22,2021-08-23 21:09:58,2018-11-03 18:00:25,,,sql;mysql;subquery;join,Your Common Sense,158153,285587,registered,true,39588846,,CC BY-SA 4.0,2023-03-06 12:32:14,353,313,2,0,0,4,true,false,false,true,true,true,18,3,false,0.029,0.0017,6074,2010,4,6,Monday,false,false,false,false,false,true,false
337704,Parameterize an SQL IN clause,"How do I parameterize a query containing an IN clause with a variable number of arguments, like this one?
SELECT * FROM Tags
WHERE Name IN ('ruby','rails','scruffy','rubyonrails')
ORDER BY Count DESC
In this query, the number of arguments could be anywhere from 1 to 5.
I would prefer not to use a dedicated stored procedure for this (or XML), but if there is some elegant way specific to SQL Server 2008, I am open to that.
",https://stackoverflow.com/questions/337704/parameterize-an-sql-in-clause,1150,461797.0,41.0,,,2008-12-03 16:16:43,2024-01-14 19:50:21,2022-06-01 14:47:50,,,sql;sql-server-2008;parameters,Jeff Atwood,64189,1,registered,true,337817,,CC BY-SA 4.0,2012-09-20 12:17:04,585,430,2,1,0,3,true,false,false,true,true,true,29,5,false,0.089,0.0025,6562,2008,12,16,Wednesday,false,false,false,false,false,true,false
1018822,INNER JOIN ON vs WHERE clause,"For simplicity, assume all relevant fields are NOT NULL.
You can do:
SELECT
table1.this, table2.that, table2.somethingelse
FROM
table1, table2
WHERE
table1.foreignkey = table2.primarykey
AND (some other conditions)
Or else:
SELECT
table1.this, table2.that, table2.somethingelse
FROM
table1 INNER JOIN table2
ON table1.foreignkey = table2.primarykey
WHERE
(some other conditions)
Do these two work on the same way in MySQL?
",https://stackoverflow.com/questions/1018822/inner-join-on-vs-where-clause,1140,746768.0,12.0,,,2009-06-19 16:16:24,2021-02-24 18:49:59,2018-04-14 15:58:50,,,sql;mysql;join;inner-join,JCCyC,16874,110800,registered,true,1018825,,CC BY-SA 3.0,2015-10-05 09:21:39,564,462,4,0,0,4,true,false,false,true,true,true,29,6,false,0.016,0.0015,6364,2009,6,16,Friday,false,false,false,false,false,true,false
1361340,How can I do 'insert if not exists' in MySQL?,"I started by googling and found the article How to write INSERT if NOT EXISTS queries in standard SQL which talks about mutex tables.
I have a table with ~14 million records. If I want to add more data in the same format, is there a way to ensure the record I want to insert does not already exist without using a pair of queries (i.e., one query to check and one to insert is the result set is empty)?
Does a unique constraint on a field guarantee the insert will fail if it's already there?
It seems that with merely a constraint, when I issue the insert via PHP, the script croaks.
",https://stackoverflow.com/questions/1361340/how-can-i-do-insert-if-not-exists-in-mysql,1104,1190537.0,12.0,,,2009-09-01 08:56:41,2024-02-20 07:07:24,2024-02-17 07:35:36,,,sql;mysql;sql-insert;primary-key;unique-constraint,warren,33614,4418,registered,true,1361368,,CC BY-SA 4.0,2018-01-10 01:43:47,781,585,2,1,0,5,true,false,false,true,true,true,53,10,true,0.01,0.0009,6290,2009,9,8,Tuesday,false,false,false,false,false,true,false
1054984,How can I get column names from a table in SQL Server?,"I want to query the name of all columns of a table. I found how to do this in:
But I also need to know: how can this be done in Microsoft SQL Server (2008 in my case)?
",https://stackoverflow.com/questions/1054984/how-can-i-get-column-names-from-a-table-in-sql-server,1079,3424043.0,24.0,,,2009-06-28 14:05:50,2025-03-19 11:30:55,2020-08-12 18:38:14,,,sql;sql-server;sql-server-2008;t-sql,odiseh,26793,61156,registered,true,1054988,,CC BY-SA 4.0,2014-02-08 16:00:17,439,194,0,3,0,4,true,false,false,true,true,true,54,12,true,0.007,0.0003,6355,2009,6,14,Sunday,true,false,false,false,false,true,false
21824478,Reset identity seed after deleting records in SQL Server,"I have inserted records into a SQL Server database table. The table had a primary key defined and the auto increment identity seed is set to “Yes”. This is done primarily because in SQL Azure, each table has to have a primary key and identity defined.
But since I have to delete some records from the table, the identity seed for those tables will be disturbed and the index column (which is auto-generated with an increment of 1) will get disturbed.
How can I reset the identity column after I deleted the records so that the column has sequence in ascending numerical order?
The identity column is not used as a foreign key anywhere in database.
",https://stackoverflow.com/questions/21824478/reset-identity-seed-after-deleting-records-in-sql-server,1072,1930054.0,27.0,,,2014-02-17 08:51:48,2025-06-27 08:51:55,2016-07-14 15:48:00,,,sql;sql-server;database;sql-server-2008;azure-sql-database,xorpower,19301,224636,registered,true,21824729,,CC BY-SA 3.0,2023-01-24 20:23:32,697,652,0,0,0,5,true,false,false,true,true,true,56,9,false,0.014,0.0006,4660,2014,2,8,Monday,false,false,false,false,false,true,false
14290857,SQL SELECT WHERE field contains words,"I need a select which would return results like this:
SELECT * FROM MyTable WHERE Column1 CONTAINS 'word1 word2 word3'
And I need all results, i.e. this includes strings with 'word2 word3 word1' or 'word1 word3 word2' or any other combination of the three.
All words need to be in the result.
",https://stackoverflow.com/questions/14290857/sql-select-where-field-contains-words,1062,4966605.0,15.0,,,2013-01-12 06:19:50,2025-04-24 04:42:51,2023-05-31 09:48:54,,,sql;select;contains,Mario,15058,1106247,registered,true,14290878,,CC BY-SA 4.0,2018-03-05 15:53:24,342,297,1,0,0,3,true,false,false,true,true,true,37,6,false,0.003,0.0002,5061,2013,1,6,Saturday,true,false,false,false,false,true,false
1179758,Function vs. Stored Procedure in SQL Server,"When should I use a function rather than a stored procedure in SQL, and vice versa? What is the purpose of each?
",https://stackoverflow.com/questions/1179758/function-vs-stored-procedure-in-sql-server,1032,833902.0,19.0,,,2009-07-24 19:40:06,2024-06-29 18:43:40,2023-01-09 23:52:36,,,sql;sql-server;t-sql;stored-procedures;sql-function,Tarik,82411,44852,registered,true,1179778,,CC BY-SA 4.0,2012-02-01 14:10:52,120,113,0,0,0,5,true,false,false,true,true,true,43,7,false,0.023,0.0012,6329,2009,7,19,Friday,false,false,false,false,false,true,false
483193,How can I list all foreign keys referencing a given table in SQL Server?,"I need to remove a highly referenced table in a SQL Server database. How can I get a list of all the foreign key constraints I will need to remove in order to drop the table?
(SQL answers preferable over clicking about in the GUI of the management studio.)
",https://stackoverflow.com/questions/483193/how-can-i-list-all-foreign-keys-referencing-a-given-table-in-sql-server,1019,1070839.0,33.0,,,2009-01-27 12:17:59,2025-08-27 09:20:30,2014-11-22 17:43:06,,,sql;sql-server;t-sql,chillitom,25882,56679,registered,true,12956348,,CC BY-SA 3.0,2014-02-22 10:27:52,273,259,0,0,0,3,true,false,false,true,true,true,72,14,true,0.031,0.001,6507,2009,1,12,Tuesday,false,false,false,false,false,true,false
354070,SQL JOIN: what is the difference between WHERE clause and ON clause?,"What is the difference and what should go in each?
If I understand the theory correctly, the query optimizer should be able to use both interchangeably.
(Note: this question is not a duplicate of Explicit vs Implicit SQL Joins.
The answer may be related (or even the same) but the question is different.)
",https://stackoverflow.com/questions/354070/sql-join-what-is-the-difference-between-where-clause-and-on-clause,996,1085238.0,22.0,,,2008-12-09 20:14:52,2024-11-19 15:24:02,2023-12-31 19:40:12,,,sql;join;where-clause;on-clause,BCS,79461,1343,registered,true,354094,,CC BY-SA 4.0,2021-12-03 21:18:53,439,305,0,1,0,4,true,false,false,true,true,true,68,12,true,0.02,0.0009,6556,2008,12,20,Tuesday,false,false,false,false,false,true,false
2051162,SQL multiple column ordering,"How can I sort multiple columns in SQL and in different directions? For instance, 'column1' would be sorted descendingly and 'column2' ascendingly.
",https://stackoverflow.com/questions/2051162/sql-multiple-column-ordering,968,1537505.0,9.0,,,2010-01-12 18:02:09,2023-06-28 12:00:33,2023-06-28 12:00:33,,,sql;sorting;sql-order-by;multiple-columns,Señor Reginold Francis,17106,122105,registered,true,2051176,,CC BY-SA 4.0,,156,149,0,0,0,4,true,false,false,true,true,true,28,4,false,0.006,0.0006,6157,2010,1,18,Tuesday,false,false,false,false,false,true,false
2043259,How to Join to first row,"I'll use a concrete, but hypothetical, example.
Each Order normally has only one line item:
Orders:
OrderGUID OrderNumber
========= ============
{FFB2...} STL-7442-1
{3EC6...} MPT-9931-8A
LineItems:
LineItemGUID Order ID Quantity Description
============ ======== ======== =================================
{098FBE3...} 1 7 prefabulated amulite
{1609B09...} 2 32 spurving bearing
But occasionally there will be an order with two line items:
LineItemID Order ID Quantity Description
========== ======== ======== =================================
{A58A1...} 6,784,329 5 pentametric fan
{0E9BC...} 6,784,329 5 differential girdlespring
Normally when showing the orders to the user:
SELECT Orders.OrderNumber, LineItems.Quantity, LineItems.Description
FROM Orders
INNER JOIN LineItems
ON Orders.OrderID = LineItems.OrderID
I want to show the single item on the order. But with this occasional order containing two (or more) items, the orders would appear be duplicated:
OrderNumber Quantity Description
=========== ======== ====================
STL-7442-1 7 prefabulated amulite
MPT-9931-8A 32 spurving bearing
KSG-0619-81 5 panametric fan
KSG-0619-81 5 differential girdlespring
What I really want is to have SQL Server just pick one, as it will be good enough:
OrderNumber Quantity Description
=========== ======== ====================
STL-7442-1 7 prefabulated amulite
MPT-9931-8A 32 differential girdlespring
KSG-0619-81 5 panametric fan
If I get adventurous, I might show the user, an ellipsis to indicate that there's more than one:
OrderNumber Quantity Description
=========== ======== ====================
STL-7442-1 7 prefabulated amulite
MPT-9931-8A 32 differential girdlespring
KSG-0619-81 5 panametric fan, ...
So the question is how to either
- eliminate ""duplicate"" rows
- only join to one of the rows, to avoid duplication
First attempt
My first naive attempt was to only join to the ""TOP 1"" line items:
SELECT Orders.OrderNumber, LineItems.Quantity, LineItems.Description
FROM Orders
INNER JOIN (
SELECT TOP 1 LineItems.Quantity, LineItems.Description
FROM LineItems
WHERE LineItems.OrderID = Orders.OrderID) LineItems2
ON 1=1
But that gives the error:
The column or prefix 'Orders' does not
match with a table name or alias name
used in the query.
Presumably because the inner select doesn't see the outer table.
",https://stackoverflow.com/questions/2043259/how-to-join-to-first-row,964,912087.0,11.0,,,2010-01-11 16:44:37,2024-09-07 14:17:16,2020-05-30 23:24:56,,,sql;sql-server;t-sql;sql-server-2000,Ian Boyd,260241,12597,registered,true,2043290,,CC BY-SA 4.0,,3397,2637,8,0,0,4,true,false,false,true,true,true,24,6,false,0.012,0.0011,6158,2010,1,16,Monday,false,false,false,false,false,true,false
612231,"How can I SELECT rows with MAX(Column value), PARTITION by another column in MYSQL?","I have a table of player performance:
CREATE TABLE TopTen (
id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
home INT UNSIGNED NOT NULL,
`datetime`DATETIME NOT NULL,
player VARCHAR(6) NOT NULL,
resource INT NOT NULL
);
What query will return the rows for each distinct home holding its maximum value of datetime? In other words, how can I filter by the maximum datetime (grouped by home) and still include other non-grouped, non-aggregate columns (such as player) in the result?
For this sample data:
INSERT INTO TopTen
(id, home, `datetime`, player, resource)
VALUES
(1, 10, '04/03/2009', 'john', 399),
(2, 11, '04/03/2009', 'juliet', 244),
(5, 12, '04/03/2009', 'borat', 555),
(3, 10, '03/03/2009', 'john', 300),
(4, 11, '03/03/2009', 'juliet', 200),
(6, 12, '03/03/2009', 'borat', 500),
(7, 13, '24/12/2008', 'borat', 600),
(8, 13, '01/01/2009', 'borat', 700)
;
the result should be:
id
home
datetime
player
resource
1
10
04/03/2009
john
399
2
11
04/03/2009
juliet
244
5
12
04/03/2009
borat
555
8
13
01/01/2009
borat
700
I tried a subquery getting the maximum datetime for each home:
-- 1 ..by the MySQL manual:
SELECT DISTINCT
home,
id,
datetime AS dt,
player,
resource
FROM TopTen t1
WHERE `datetime` = (SELECT
MAX(t2.datetime)
FROM TopTen t2
GROUP BY home)
GROUP BY `datetime`
ORDER BY `datetime` DESC
The result-set has 130 rows although database holds 187, indicating the result includes some duplicates of home.
Then I tried joining to a subquery that gets the maximum datetime for each row id:
-- 2 ..join
SELECT
s1.id,
s1.home,
s1.datetime,
s1.player,
s1.resource
FROM TopTen s1
JOIN (SELECT
id,
MAX(`datetime`) AS dt
FROM TopTen
GROUP BY id) AS s2
ON s1.id = s2.id
ORDER BY `datetime`
Nope. Gives all the records.
I tried various exotic queries, each with various results, but nothing that got me any closer to solving this problem.
",https://stackoverflow.com/questions/612231/how-can-i-select-rows-with-maxcolumn-value-partition-by-another-column-in-mys,921,1913262.0,22.0,,,2009-03-04 20:14:26,2023-12-15 21:40:26,2022-05-10 23:59:19,,,mysql;sql;max;distinct;greatest-n-per-group,Kaptah,9907,73810,registered,true,612268,,CC BY-SA 4.0,2011-07-22 11:22:06,2578,1921,14,0,0,5,true,false,false,true,true,true,83,14,true,0.011,0.0005,6471,2009,3,20,Wednesday,false,false,false,false,false,true,false
723195,Should I use != or <> for not equal in T-SQL?,"I have seen SQL that uses both != and <> for not equal. What is the preferred syntax and why?
I like !=, because <> reminds me of Visual Basic.
",https://stackoverflow.com/questions/723195/should-i-use-or-for-not-equal-in-t-sql,920,1267340.0,14.0,,,2009-04-06 20:56:15,2026-02-24 13:41:41,2026-02-05 18:15:51,,,sql;sql-server;t-sql,Bob The Janitor,20887,55102,registered,true,723317,,CC BY-SA 4.0,2015-01-22 15:41:32,231,156,4,0,0,3,true,false,false,true,true,true,51,11,true,0.011,0.0007,6438,2009,4,20,Monday,false,false,false,false,false,true,false
4796872,How can I do a FULL OUTER JOIN in MySQL?,"I want to do a full outer join in MySQL. Is this possible? Is a full outer join supported by MySQL?
",https://stackoverflow.com/questions/4796872/how-can-i-do-a-full-outer-join-in-mysql,913,1209832.0,14.0,,,2011-01-25 17:34:18,2024-05-11 02:32:36,2021-08-07 22:06:29,,,sql;mysql;join;outer-join;full-outer-join,Spencer,22678,440266,registered,true,4796911,,CC BY-SA 4.0,2014-08-31 16:18:24,213,100,0,1,0,5,true,false,false,true,true,true,40,10,true,0.012,0.0008,5779,2011,1,17,Tuesday,false,false,false,false,false,true,false
1334143,DateTime2 vs DateTime in SQL Server,"Which one:
is the recommended way to store date and time in SQL Server 2008+?
I'm aware of differences in precision (and storage space probably), but ignoring those for now, is there a best practice document on when to use what, or maybe we should just use datetime2 only?
",https://stackoverflow.com/questions/1334143/datetime2-vs-datetime-in-sql-server,912,726477.0,18.0,,,2009-08-26 11:45:10,2026-11-01 10:48:47,2026-11-01 10:48:47,,,sql;sql-server;datetime;datetime2,Mikeon,10859,158801,registered,true,1884088,,CC BY-SA 4.0,2016-03-10 19:59:23,566,298,3,2,0,4,true,false,false,true,true,true,35,6,false,0.025,0.0013,6296,2009,8,11,Wednesday,false,false,false,false,false,true,false
1221559,Count(*) vs Count(1) - SQL Server,"Just wondering if any of you people use Count(1) over Count(*) and if there is a noticeable difference in performance or if this is just a legacy habit that has been brought forward from days gone past?
The specific database is SQL Server 2005.
",https://stackoverflow.com/questions/1221559/count-vs-count1-sql-server,907,572676.0,13.0,,,2009-08-03 10:15:10,2023-05-04 16:52:56,2020-01-04 09:43:55,,,sql;sql-server;performance,super9,30289,131238,registered,true,1221649,,CC BY-SA 4.0,2014-03-20 17:55:10,299,246,3,0,0,3,true,false,false,true,true,true,33,6,false,0.023,0.0016,6319,2009,8,10,Monday,false,false,false,false,false,true,false
15501673,How can I temporarily disable a foreign key constraint in MySQL?,"Is it possible to temporarily disable constraints in MySQL?
I have two Django models, each with a foreign key to the other one. Deleting instances of a model returns an error because of the foreign key constraint:
cursor.execute("DELETE FROM myapp_item WHERE n = %s", n)
transaction.commit_unless_managed() #a foreign key constraint fails here
cursor.execute("DELETE FROM myapp_style WHERE n = %s", n)
transaction.commit_unless_managed()
Is it possible to temporarily disable constraints and delete anyway?
",https://stackoverflow.com/questions/15501673/how-can-i-temporarily-disable-a-foreign-key-constraint-in-mysql,865,1037463.0,9.0,,,2013-03-19 14:03:58,2024-07-12 06:35:28,2024-02-05 10:04:39,,,python;sql;mysql;django;django-models,jul,37674,326849,registered,true,15501754,,CC BY-SA 4.0,2024-07-19 16:17:36,575,530,1,0,0,5,true,false,false,true,true,true,64,11,true,0.009,0.0008,4995,2013,3,14,Tuesday,false,true,false,false,false,true,false
982919,SQL update query using joins,"I have to update a field with a value which is returned by a join of 3 tables.
Example:
select
im.itemid
,im.sku as iSku
,gm.SKU as GSKU
,mm.ManufacturerId as ManuId
,mm.ManufacturerName
,im.mf_item_number
,mm.ManufacturerID
from
item_master im, group_master gm, Manufacturer_Master mm
where
im.mf_item_number like 'STA%'
and im.sku=gm.sku
and gm.ManufacturerID = mm.ManufacturerID
and gm.manufacturerID=34
I want to update the mf_item_number field values of table item_master with some other value which is joined in the above condition.
How can I do this in MS SQL Server?
",https://stackoverflow.com/questions/982919/sql-update-query-using-joins,844,1243051.0,13.0,,,2009-06-11 18:49:33,2024-03-09 11:53:37,2014-01-08 02:18:27,,,sql;sql-server;t-sql;sql-server-2005;sql-update,Shyju,219958,40521,registered,true,982947,,CC BY-SA 3.0,2016-10-11 17:46:08,709,631,3,0,0,5,true,false,false,true,true,true,28,5,false,0.01,0.0007,6372,2009,6,18,Thursday,false,false,false,false,false,true,false
16296622,Rename column SQL Server 2008,"I am using SQL Server 2008 and Navicat. I need to rename a column in a table using SQL.
ALTER TABLE table_name RENAME COLUMN old_name to new_name;
This statement doesn't work.
",https://stackoverflow.com/questions/16296622/rename-column-sql-server-2008,822,1651689.0,10.0,,,2013-04-30 09:34:48,2020-11-22 16:06:17,2018-01-15 10:10:59,,,sql;sql-server;sql-server-2008;alter-table,Serhio g. Lazin,9702,1303193,registered,true,16296669,,CC BY-SA 3.0,2014-02-26 22:53:52,217,179,1,0,0,4,true,false,false,true,true,true,29,5,false,0.006,0.0005,4953,2013,4,9,Tuesday,false,false,false,false,false,true,false
1049728,MySQL: Get character-set of database or table or column?,"What is the (default) charset for:
MySQL database
MySQL table
MySQL column
",https://stackoverflow.com/questions/1049728/mysql-get-character-set-of-database-or-table-or-column,821,892630.0,17.0,,,2009-06-26 15:22:20,2023-05-23 03:49:58,2023-05-23 03:11:05,,,sql;mysql;unicode;character-encoding;collation,Amandasaurus,61767,161922,registered,true,,,CC BY-SA 4.0,,142,78,0,0,0,5,false,false,false,true,true,true,56,9,true,0.019,0.0009,6357,2009,6,15,Friday,false,false,false,false,false,true,false
5940225,Fastest Way of Inserting in Entity Framework,"I'm looking for the fastest way of inserting in Entity Framework.
I'm asking this because of the scenario where you have an active TransactionScope and the insertion is huge (4000+). It can potentially last more than 10 minutes (default timeout of transactions), and this will lead to an incomplete transaction.
Currently I am doing it as follows. Is there a more efficient way?
- Creating the
TransactionScope
- instantiating the
DBContext
- Opening the connection
- In a for-each statement doing the insertions and SavingChanges (for each record).
NOTE: TransactionScope and DBContext are in using statements, and I'm closing the connection in a finally block.
",https://stackoverflow.com/questions/5940225/fastest-way-of-inserting-in-entity-framework,817,608706.0,31.0,,,2011-05-09 17:14:00,2025-06-22 08:33:35,2025-05-29 17:58:54,,,c#;sql;entity-framework,Bongo Sharp,9648,373768,registered,true,5942176,,CC BY-SA 4.0,2019-08-15 22:39:28,796,658,5,0,0,3,true,false,false,true,true,true,44,7,false,0.051,0.0013,5675,2011,5,17,Monday,false,false,false,false,true,true,false
508791,MySQL Query GROUP BY day / month / year,"Is it possible to make a simple query to count how many records I have in a determined period of time like a year, month, or day, having a TIMESTAMP field, like:
SELECT COUNT(id)
FROM stats
WHERE record_date.YEAR = 2009
GROUP BY record_date.YEAR
Or even:
SELECT COUNT(id)
FROM stats
GROUP BY record_date.YEAR, record_date.MONTH
To have a monthly statistic.
",https://stackoverflow.com/questions/508791/mysql-query-group-by-day-month-year,814,935547.0,19.0,,,2009-02-03 20:29:19,2025-04-04 08:17:08,2025-04-04 08:17:08,,,mysql;sql;date;datetime;group-by,Fernando Barrocal,13442,2274,registered,true,508806,,CC BY-SA 4.0,,441,359,3,0,0,5,true,false,false,true,true,true,39,9,false,0.02,0.0009,6500,2009,2,20,Tuesday,false,false,false,false,false,true,false
12316953,Insert text with single quotes in PostgreSQL,"I have a table test(id,name).
I need to insert values like: user's log, 'my user', customer's.
insert into test values (1,'user's log');
insert into test values (2,''my users'');
insert into test values (3,'customer's');
I am getting an error if I run any of the above statements.
If there is any method to do this correctly please share. I don't want any prepared statements.
Is it possible using sql escaping mechanism?
",https://stackoverflow.com/questions/12316953/insert-text-with-single-quotes-in-postgresql,812,822317.0,8.0,,,2012-09-07 11:11:11,2023-03-15 06:58:42,2021-09-16 05:05:37,,,sql;postgresql;quotes;string-literals,MAHI,10353,1179916,registered,true,12320729,,CC BY-SA 4.0,,543,432,5,0,0,4,true,false,false,true,true,true,44,7,false,0.01,0.001,5188,2012,9,11,Friday,false,false,false,false,false,true,false
6841605,Get top 1 row of each group,"I have a table which I want to get the latest entry for each group. Here's the table:
DocumentStatusLogs Table
ID
DocumentID
Status
DateCreated
2
1
S1
7/29/2011
3
1
S2
7/30/2011
6
1
S1
8/02/2011
1
2
S1
7/28/2011
4
2
S2
7/30/2011
5
2
S3
8/01/2011
6
3
S1
8/02/2011
The table will be grouped by DocumentID and sorted by DateCreated in descending order. For each DocumentID, I want to get the latest status.
My preferred output:
DocumentID
Status
DateCreated
1
S1
8/02/2011
2
S3
8/01/2011
3
S1
8/02/2011
Is there any aggregate function to get only the top from each group? See pseudo-code GetOnlyTheTop below:
SELECT
DocumentID,
GetOnlyTheTop(Status),
GetOnlyTheTop(DateCreated)
FROM DocumentStatusLogs
GROUP BY DocumentID
ORDER BY DateCreated DESC
If such function doesn't exist, is there any way I can achieve the output I want?
Or at the first place, could this be caused by unnormalized database? I'm thinking, since what I'm looking for is just one row, should that status also be located in the parent table?
Please see the parent table for more information:
Current Documents Table
DocumentID
Title
Content
DateCreated
1
TitleA
...
...
2
TitleB
...
...
3
TitleC
...
...
Should the parent table be like this so that I can easily access its status?
DocumentID
Title
Content
DateCreated
CurrentStatus
1
TitleA
...
...
s1
2
TitleB
...
...
s3
3
TitleC
...
...
s1
UPDATE
I just learned how to use "apply" which makes it easier to address such problems.
",https://stackoverflow.com/questions/6841605/get-top-1-row-of-each-group,800,1063862.0,17.0,,,2011-07-27 08:41:16,2025-02-17 13:35:31,2024-02-13 21:55:46,,,sql;sql-server;t-sql;greatest-n-per-group,kazinix,30421,724689,registered,true,6841644,,CC BY-SA 4.0,2022-07-21 13:07:37,3087,1550,8,0,0,4,true,false,false,true,true,true,27,7,false,0.016,0.0008,5596,2011,7,8,Wednesday,false,false,false,false,false,true,false
5951157,'IF' in 'SELECT' statement - choose output value based on column values,"SELECT id, amount FROM report
I need amount to be amount if report.type='P' and -amount if report.type='N'. How do I add this to the above query?
",https://stackoverflow.com/questions/5951157/if-in-select-statement-choose-output-value-based-on-column-values,774,1614162.0,8.0,,,2011-05-10 13:53:31,2024-05-09 06:09:21,2015-09-15 21:19:33,,,mysql;sql;database,Michael,14346,534994,registered,true,5951204,,CC BY-SA 3.0,2014-03-18 06:48:13,244,148,6,0,0,3,true,false,false,true,true,true,87,12,false,0.005,0.0005,5674,2011,5,13,Tuesday,false,false,false,false,false,true,false
1720244,Create new user in MySQL and give it full access to one database,"I want to create a new user in MySQL and give it full access only to one database, say dbTest that I create with a command like create database dbTest;. What would be the MySQL commands to do that?
",https://stackoverflow.com/questions/1720244/create-new-user-in-mysql-and-give-it-full-access-to-one-database,774,1020390.0,10.0,,,2009-11-12 06:10:31,2023-11-10 17:25:39,2023-10-21 18:35:56,,,sql;mysql;database;privileges;sql-grant,jimgh,7747,207008,unregistered,true,,,CC BY-SA 4.0,2013-02-25 17:10:25,231,198,2,0,0,5,false,false,false,true,true,true,64,13,false,0.01,0.0008,6218,2009,11,6,Thursday,false,false,false,false,false,true,false
2686254,How to select all records from one table that do not exist in another table?,"
table1 (id, name)
table2 (id, name)
Query:
SELECT name
FROM table2
-- that are not in table1 already
",https://stackoverflow.com/questions/2686254/how-to-select-all-records-from-one-table-that-do-not-exist-in-another-table,769,1588708.0,16.0,,,2010-04-21 20:18:25,2024-08-30 17:57:09,2013-07-30 13:51:22,,,sql;sql-server;t-sql,z-boss,17758,28098,registered,true,2686266,,CC BY-SA 3.0,2022-01-06 04:48:06,182,115,1,0,0,3,true,false,false,true,true,true,76,15,true,0.01,0.0005,6058,2010,4,20,Wednesday,false,false,false,false,false,true,false
244243,How to reset Postgres' primary key sequence when it falls out of sync?,"I ran into the problem that my primary key sequence is not in sync with my table rows.
That is, when I insert a new row I get a duplicate key error because the sequence implied in the serial datatype returns a number that already exists.
It seems to be caused by import/restores not maintaining the sequence properly.
",https://stackoverflow.com/questions/244243/how-to-reset-postgres-primary-key-sequence-when-it-falls-out-of-sync,762,483505.0,36.0,,,2008-10-28 18:08:21,2024-08-11 21:27:00,2022-08-20 02:01:01,,,sql;postgresql;primary-key;ddl;database-sequence,meleyal,33640,4196,registered,true,244265,,CC BY-SA 4.0,2020-10-21 01:24:33,342,321,0,0,0,5,true,false,false,true,true,true,74,13,true,0.074,0.0016,6598,2008,10,18,Tuesday,false,false,false,false,false,true,false
10757431,Postgres: upgrade a user to be a superuser?,"In postgres, how do I change an existing user to be a superuser? I don't want to delete the existing user, for various reasons.
# alter user myuser ...?
",https://stackoverflow.com/questions/10757431/postgres-upgrade-a-user-to-be-a-superuser,757,471954.0,12.0,,,2012-05-25 15:43:18,2023-10-23 09:02:15,2023-10-11 15:56:51,,,sql;database;postgresql;alter;superuser,flossfan,10954,1073252,registered,true,10757486,,CC BY-SA 4.0,,187,156,1,0,0,5,true,false,false,true,true,true,43,8,true,0.025,0.0016,5293,2012,5,15,Friday,false,false,false,false,false,true,false
108403,Solutions for INSERT OR UPDATE on SQL Server,"Assume a table structure of MyTable(KEY, datafield1, datafield2...).
Often I want to either update an existing record, or insert a new record if it doesn't exist.
Essentially:
IF (key exists)
run update command
ELSE
run insert command
What's the best performing way to write this?
",https://stackoverflow.com/questions/108403/solutions-for-insert-or-update-on-sql-server,751,991019.0,21.0,,,2008-09-20 15:00:47,2022-09-06 08:34:14,2014-04-09 14:17:05,,,sql;sql-server;database;insert;upsert,Chris Cudmore,30251,18907,registered,true,108420,,CC BY-SA 3.0,2019-03-21 01:42:26,355,290,2,0,0,5,true,false,false,true,true,true,44,8,false,0.021,0.0008,6636,2008,9,15,Saturday,true,false,false,false,false,true,false
31057,How to insert a line break in a SQL Server VARCHAR/NVARCHAR string,"I didn't see any similar questions asked on this topic, and I had to research this for something I'm working on right now. Thought I would post the answer for it in case anyone else had the same question.
",https://stackoverflow.com/questions/31057/how-to-insert-a-line-break-in-a-sql-server-varchar-nvarchar-string,723,1591407.0,12.0,,,2008-08-27 19:53:01,2024-09-12 17:51:46,2013-07-10 19:18:56,,,sql;sql-server;line-breaks,Mark Struzinski,33597,1284,registered,true,31063,,CC BY-SA 3.0,2016-10-31 10:15:24,212,205,0,0,0,3,true,false,false,true,true,true,66,12,false,0.008,0.0005,6660,2008,8,19,Wednesday,false,false,false,false,false,true,false
105776,How do I restore a dump file from mysqldump?,"I was given a MySQL database file that I need to restore as a database on my Windows Server 2008 machine.
I tried using MySQL Administrator, but I got the following error:
The selected file was generated by
mysqldump and cannot be restored by
this application.
How do I get this working?
",https://stackoverflow.com/questions/105776/how-do-i-restore-a-dump-file-from-mysqldump,701,1211785.0,19.0,,,2008-09-19 21:27:00,2024-10-13 19:20:11,2018-06-17 08:45:54,,,mysql;sql;database,Zack Peterson,57701,83,registered,true,105798,,CC BY-SA 4.0,2011-07-07 16:24:02,352,299,0,0,0,3,true,false,false,true,true,true,44,9,true,0.016,0.0006,6637,2008,9,21,Friday,false,false,false,false,false,true,false
425158,How to skip certain database tables with mysqldump?,"Is there a way to restrict certain tables from the mysqldump command?
For example, I'd use the following syntax to dump only table1 and table2:
mysqldump -u username -p database table1 table2 > database.sql
But is there a similar way to dump all the tables except table1 and table2? I haven't found anything in the mysqldump documentation, so is brute-force (specifying all the table names) the only way to go?
",https://stackoverflow.com/questions/425158/how-to-skip-certain-database-tables-with-mysqldump,695,485451.0,13.0,,,2009-01-08 17:30:17,2024-07-12 22:14:04,2023-11-05 21:56:09,,,sql;mysql;database;dump;database-dump,Zac,1008,5630,registered,true,425172,,CC BY-SA 4.0,,569,415,5,0,0,5,true,false,false,true,true,true,51,8,true,0.027,0.0014,6526,2009,1,17,Thursday,false,false,false,false,false,true,false
6175473,Export schema without data,"I'm using a MySql database with a Java program, now I want to give the program to somebody else.
How to export the MySQL database structure without the data in it, just the structure?
",https://stackoverflow.com/questions/6175473/export-schema-without-data,688,604931.0,16.0,,,2011-05-30 11:06:54,2023-12-01 13:21:20,2023-12-01 13:21:20,,,sql;mysql;database;database-schema;dump,Darth Blue Ray,9815,753983,registered,true,6175506,,CC BY-SA 4.0,,198,184,0,0,0,5,true,false,false,true,true,true,26,4,false,0.026,0.0011,5654,2011,5,11,Monday,false,false,false,false,false,true,false
1609637,How can I insert multiple rows with a single statement in SQLite?,"In MySQL you can insert multiple rows in a single statement:
INSERT INTO 'tablename' ('column1', 'column2') VALUES
('data1', 'data2'),
('data1', 'data2'),
('data1', 'data2'),
('data1', 'data2');
I am getting an error when I do this with an SQLite database What is the correct syntax?
",https://stackoverflow.com/questions/1609637/how-can-i-insert-multiple-rows-with-a-single-statement-in-sqlite,686,556229.0,25.0,,,2009-10-22 20:04:42,2026-05-02 01:45:20,2026-03-30 03:45:39,,,sql;database;sqlite;syntax;insert,Andrew,241827,48523,registered,true,5009740,,CC BY-SA 4.0,2014-01-07 15:14:07,339,301,1,0,0,5,true,false,false,true,true,true,65,12,true,0.045,0.0012,6239,2009,10,20,Thursday,false,false,false,false,false,true,false
121387,Fetch the rows which have the Max value for a column for each distinct value of another column,"Table:
UserId, Value, Date.
I want to get the UserId, Value for the max(Date) for each UserId. That is, the Value for each UserId that has the latest date.
How do I do this in SQL? (Preferably Oracle.)
I need to get ALL the UserIds. But for each UserId, only that row where that user has the latest date.
",https://stackoverflow.com/questions/121387/fetch-the-rows-which-have-the-max-value-for-a-column-for-each-distinct-value-of,685,709319.0,36.0,,,2008-09-23 14:34:13,2024-06-07 09:27:05,2023-05-13 10:31:59,,,sql;oracle-database;greatest-n-per-group,Umang,6885,21154,registered,true,121450,,CC BY-SA 4.0,2017-11-01 13:46:22,358,306,1,0,0,3,true,false,false,true,true,true,94,18,false,0.051,0.001,6633,2008,9,14,Tuesday,false,false,false,false,false,true,false
1521605,Selecting COUNT(*) with DISTINCT,"In SQL Server 2005 I have a table cm_production that lists all the code that's been put into production. The table has a ticket_number, program_type, program_name and push_number along with some other columns.
GOAL: Count all the DISTINCT program names by program type and push number.
What I have so far is:
DECLARE @push_number INT;
SET @push_number = [HERE_ADD_NUMBER];
SELECT DISTINCT COUNT(*) AS Count, program_type AS [Type]
FROM cm_production
WHERE push_number=@push_number
GROUP BY program_type
This gets me partway there, but it's counting all the program names, not the distinct ones (which I don't expect it to do in that query). I guess I just can't wrap my head around how to tell it to count only the distinct program names without selecting them. Or something.
",https://stackoverflow.com/questions/1521605/selecting-count-with-distinct,665,1943193.0,6.0,,,2009-10-05 18:19:16,2024-05-15 11:02:23,2024-01-19 13:58:35,,,sql;sql-server;t-sql;sql-server-2005;distinct,somacore,7164,53409,registered,true,1521656,,CC BY-SA 4.0,2017-12-19 07:30:31,898,781,6,0,0,5,true,false,false,true,true,true,32,4,false,0.003,0.0003,6256,2009,10,18,Monday,false,false,false,false,false,true,false
124417,Max function in SQL Server that takes two values like Math.Max in .NET,"I want to write a query like this:
SELECT o.OrderId, MAX(o.NegotiatedPrice, o.SuggestedPrice)
FROM Order o
But this isn't how the MAX function works, right? It is an aggregate function so it expects a single parameter and then returns the MAX of all rows.
Does anyone know how to do it my way?
",https://stackoverflow.com/questions/124417/max-function-in-sql-server-that-takes-two-values-like-math-max-in-net,661,725802.0,31.0,,,2008-09-23 22:52:03,2025-06-14 07:52:47,2025-06-14 07:51:06,,,sql;sql-server;max,skb,31344,14101,registered,true,124474,,CC BY-SA 4.0,2014-01-23 20:29:15,360,302,2,0,0,3,true,false,false,true,true,true,70,13,false,0.043,0.0009,6633,2008,9,22,Tuesday,false,false,false,false,false,true,false
947215,How do I get a list of table column names from an SQLite database?,"I want to migrate my iPhone app to a new database version. Since I don't have some version saved, I need to check if certain column names exist.
This answer suggests:
SELECT sql FROM sqlite_master
WHERE tbl_name = 'table_name' AND type = 'table'
And to parse the result.
Is that the common way? Alternatives?
",https://stackoverflow.com/questions/947215/how-do-i-get-a-list-of-table-column-names-from-an-sqlite-database,654,925289.0,27.0,,,2009-06-03 20:59:14,2026-11-16 17:22:40,2026-03-30 03:30:55,,,sql;sqlite;select;database-table,luebken,7099,55061,registered,true,,,CC BY-SA 4.0,,411,310,1,1,0,4,false,false,false,true,true,true,66,14,true,0.029,0.0007,6380,2009,6,20,Wednesday,false,false,false,false,false,true,false
173041,NOT IN vs NOT EXISTS,"Which of these queries is the faster?
NOT EXISTS:
SELECT ProductID, ProductName
FROM Northwind..Products p
WHERE NOT EXISTS (
SELECT 1
FROM Northwind..[Order Details] od
WHERE p.ProductId = od.ProductId)
Or NOT IN:
SELECT ProductID, ProductName
FROM Northwind..Products p
WHERE p.ProductID NOT IN (
SELECT ProductID
FROM Northwind..[Order Details])
The query execution plan says they both do the same thing. If that is the case, which is the recommended form?
This is based on the NorthWind database.
[Edit]
Just found this helpful article:
http://weblogs.sqlteam.com/mladenp/archive/2007/05/18/60210.aspx
I think I'll stick with NOT EXISTS.
",https://stackoverflow.com/questions/173041/not-in-vs-not-exists,653,2012394.0,11.0,,,2008-10-06 02:19:05,2023-06-21 10:20:19,2012-11-22 10:52:45,,,sql;sql-server;notin,ilitirit,16460,9825,registered,true,11074428,,CC BY-SA 3.0,2015-03-09 21:32:23,880,680,2,1,0,3,true,false,false,true,true,true,20,5,false,0.005,0.0003,6620,2008,10,2,Monday,false,false,false,false,false,true,false
7063501,How can I turn IDENTITY_INSERT on and off using SQL Server 2008?,"Why am I getting an error doing an insert when IDENTITY_INSERT is set to OFF?
How do I turn it on properly in SQL Server 2008? Is it by using SQL Server Management Studio?
I have run this query:
SET IDENTITY_INSERT Database. dbo. Baskets ON
Then I got the message back in the console that the Command(s) completed successfully.
However, when I run the application, it still gives me the error shown below:
Cannot insert explicit value for identity column in table 'Baskets' when
IDENTITY_INSERT is set to OFF.
",https://stackoverflow.com/questions/7063501/how-can-i-turn-identity-insert-on-and-off-using-sql-server-2008,652,1781419.0,8.0,,,2011-08-15 09:37:29,2026-05-14 01:38:12,2026-05-14 01:38:12,,,sql;sql-server-2008,Beginner,29811,569654,registered,true,7063527,,CC BY-SA 4.0,2015-10-13 13:25:00,777,512,3,1,0,2,true,false,false,true,true,true,64,12,true,0.004,0.0004,5577,2011,8,9,Monday,false,false,false,false,false,true,false
17365222,UPDATE and REPLACE part of a string,"I've got a table with two columns, ID and Value. I want to change a part of some strings in the second column.
Example of Table:
ID Value
---------------------------------
1 c:\temp\123\abc\111
2 c:\temp\123\abc\222
3 c:\temp\123\abc\333
4 c:\temp\123\abc\444
Now the 123\ in the Value string is not needed. I tried UPDATE and REPLACE:
UPDATE dbo.xxx
SET Value = REPLACE(Value, '%123%', '')
WHERE ID <= 4
When I execute the script SQL Server does not report an error, but it does not update anything either. Why is that?
",https://stackoverflow.com/questions/17365222/update-and-replace-part-of-a-string,631,1393095.0,9.0,,,2013-06-28 12:55:07,2022-01-31 12:11:53,2015-09-18 21:09:00,,,sql;sql-server;string;sql-server-2008;replace,aston_zh,6863,2531765,registered,true,17365278,,CC BY-SA 3.0,2018-01-24 23:56:40,783,590,8,0,0,5,true,false,false,true,true,true,35,7,false,0.006,0.0005,4894,2013,6,12,Friday,false,false,false,false,false,true,false
418898,UPSERT *not* INSERT or REPLACE,"http://en.wikipedia.org/wiki/Upsert
Insert Update stored proc on SQL Server
Is there some clever way to do this in SQLite that I have not thought of?
Basically I want to update three out of four columns if the record exists. If it does not exist, I want to INSERT the record with the default (NULL) value for the fourth column.
The ID is a primary key, so there will only ever be one record to UPSERT.
(I am trying to avoid the overhead of SELECT in order to determine if I need to UPDATE or INSERT obviously)
Suggestions?
I cannot confirm that syntax on the SQLite site for TABLE CREATE.
I have not built a demo to test it, but it doesn't seem to be supported.
If it was, I have three columns so it would actually look like:
CREATE TABLE table1(
id INTEGER PRIMARY KEY ON CONFLICT REPLACE,
Blob1 BLOB ON CONFLICT REPLACE,
Blob2 BLOB ON CONFLICT REPLACE,
Blob3 BLOB
);
but the first two blobs will not cause a conflict, only the ID would
So I assume Blob1 and Blob2 would not be replaced (as desired)
UPDATEs in SQLite when binding data are a complete transaction, meaning
Each sent row to be updated requires: Prepare/Bind/Step/Finalize statements unlike the INSERT which allows the use of the reset function
The life of a statement object goes something like this:
- Create the object using sqlite3_prepare_v2()
- Bind values to host parameters using sqlite3_bind_ interfaces.
- Run the SQL by calling sqlite3_step()
- Reset the statement using sqlite3_reset() then go back to step 2 and repeat.
- Destroy the statement object using sqlite3_finalize().
UPDATE I am guessing is slow compared to INSERT, but how does it compare to SELECT using the Primary key?
Perhaps I should use the select to read the 4th column (Blob3) and then use REPLACE to write a new record blending the original 4th Column with the new data for the first 3 columns?
",https://stackoverflow.com/questions/418898/upsert-not-insert-or-replace,629,405070.0,19.0,,,2009-01-07 01:47:23,2023-04-07 10:06:26,2023-04-07 10:06:26,,,sql;sqlite;upsert,Mike Trader,8714,18749,registered,true,4330694,,CC BY-SA 4.0,2019-03-21 01:42:10,2211,1860,1,2,0,3,true,false,false,true,true,true,30,5,false,0.047,0.0016,6527,2009,1,1,Wednesday,false,false,false,false,false,true,false
19412,How to request a random row in SQL?,"How can I request a random row (or as close to truly random as possible) in pure SQL?
",https://stackoverflow.com/questions/19412/how-to-request-a-random-row-in-sql,622,616608.0,32.0,,,2008-08-21 06:28:49,2024-01-27 07:23:46,2023-04-28 22:11:04,,,sql;random,sverrejoh,17000,473,registered,true,19419,,CC BY-SA 4.0,2019-05-02 05:22:17,93,86,0,0,0,2,true,false,false,true,true,true,35,8,true,0.052,0.001,6666,2008,8,6,Thursday,false,false,false,false,false,true,false
652770,Delete with Join in MySQL,"Here is the script to create my tables:
CREATE TABLE clients (
client_i INT(11),
PRIMARY KEY (client_id)
);
CREATE TABLE projects (
project_id INT(11) UNSIGNED,
client_id INT(11) UNSIGNED,
PRIMARY KEY (project_id)
);
CREATE TABLE posts (
post_id INT(11) UNSIGNED,
project_id INT(11) UNSIGNED,
PRIMARY KEY (post_id)
);
In my PHP code, when deleting a client, I want to delete all projects posts:
DELETE
FROM posts
INNER JOIN projects ON projects.project_id = posts.project_id
WHERE projects.client_id = :client_id;
The posts table does not have a foreign key client_id, only project_id. I want to delete the posts in projects that have the passed client_id.
This is not working right now because no posts are deleted.
",https://stackoverflow.com/questions/652770/delete-with-join-in-mysql,621,465309.0,14.0,,,2009-03-17 01:44:05,2024-06-09 21:52:16,2024-06-09 21:52:16,,,sql;mysql,GeekJock,11426,74980,registered,true,4192849,,CC BY-SA 4.0,,865,750,5,0,0,2,true,false,false,true,true,true,25,5,false,0.03,0.0013,6458,2009,3,1,Tuesday,false,false,false,false,false,true,false
109232,What is the best way to paginate results in SQL Server,"What is the best way (performance wise) to paginate results in SQL Server 2000, 2005, 2008, 2012 if you also want to get the total number of results (before paginating)?
",https://stackoverflow.com/questions/109232/what-is-the-best-way-to-paginate-results-in-sql-server,621,748451.0,19.0,,,2008-09-20 20:16:18,2023-07-05 11:02:29,2013-10-26 18:20:20,,,sql;sql-server;performance;pagination,Panagiotis Korros,11148,19331,registered,true,109290,,CC BY-SA 3.0,2019-08-14 04:13:17,177,170,0,0,0,4,true,false,false,true,true,true,54,11,false,0.025,0.0008,6636,2008,9,20,Saturday,true,false,false,false,false,true,false
54418,How do I (or can I) SELECT DISTINCT on multiple columns?,"I need to retrieve all rows from a table where 2 columns combined are all different. So I want all the sales that do not have any other sales that happened on the same day for the same price. The sales that are unique based on day and price will get updated to an active status.
So I'm thinking:
UPDATE sales
SET status = 'ACTIVE'
WHERE id IN (SELECT DISTINCT (saleprice, saledate), id, count(id)
FROM sales
HAVING count = 1)
But my brain hurts going any farther than that.
",https://stackoverflow.com/questions/54418/how-do-i-or-can-i-select-distinct-on-multiple-columns,618,1464160.0,5.0,,,2008-09-10 15:33:10,2024-10-19 03:48:22,2014-08-22 00:07:28,,,sql;postgresql;sql-update;duplicates;distinct,sheats,35062,4915,registered,true,54430,,CC BY-SA 3.0,,549,504,1,0,0,5,true,false,false,true,true,true,56,11,true,0.003,0.0004,6646,2008,9,15,Wednesday,false,false,false,false,false,true,false
18390574,Delete duplicate rows keeping the first row,"How can I delete duplicate rows where no unique row id exists?
My table is
col1 col2 col3 col4 col5 col6 col7
john 1 1 1 1 1 1
john 1 1 1 1 1 1
sally 2 2 2 2 2 2
sally 2 2 2 2 2 2
I want to be left with the following after the duplicate removal:
john 1 1 1 1 1 1
sally 2 2 2 2 2 2
I've tried a few queries but I think they depend on having a row id as I don't get the desired result. For example:
DELETE
FROM table
WHERE col1 IN (
SELECT id
FROM table
GROUP BY id
HAVING (COUNT(col1) > 1)
)
",https://stackoverflow.com/questions/18390574/delete-duplicate-rows-keeping-the-first-row,616,1557820.0,29.0,,,2013-08-22 20:51:14,2026-05-14 04:28:00,2024-03-21 06:46:32,,,sql;sql-server-2008;duplicates;sql-delete,Fearghal,11645,510981,registered,true,,,CC BY-SA 4.0,2016-02-29 06:29:12,744,614,4,0,0,4,false,false,false,true,true,true,43,7,false,0.019,0.0004,4839,2013,8,20,Thursday,false,false,false,false,false,true,false
11754781,How to declare a variable in MySQL?,"How to declare a variable in mysql, so that my second query can use it?
I would like to write something like:
SET start = 1;
SET finish = 10;
SELECT * FROM places WHERE place BETWEEN start AND finish;
",https://stackoverflow.com/questions/11754781/how-to-declare-a-variable-in-mysql,614,1200415.0,9.0,,,2012-08-01 07:47:52,2024-10-01 10:25:30,2016-11-22 03:42:53,,,mysql;sql,cdub,25919,665557,registered,true,11754790,,CC BY-SA 3.0,,243,205,1,0,0,2,true,false,false,true,true,true,35,7,true,0.007,0.0005,5225,2012,8,7,Wednesday,false,false,false,false,false,true,false
18907047,Postgres DB Size Command,"What is the command to find the size of all the databases?
I am able to find the size of a specific database by using following command:
select pg_database_size('databaseName');
",https://stackoverflow.com/questions/18907047/postgres-db-size-command,613,643912.0,15.0,,,2013-09-20 00:22:23,2025-04-29 15:34:08,2020-07-11 01:15:36,,,sql;postgresql;postgresql-9.2,S M Shamimul Hasan,7044,2151087,registered,true,,,CC BY-SA 4.0,,235,179,1,0,0,3,false,false,false,true,true,true,24,4,false,0.023,0.001,4810,2013,9,0,Friday,false,false,false,false,false,true,false
1177449,Best approach to remove time part of datetime,"Which method provides the best performance when removing the time portion from a datetime field in SQL Server?
select dateadd(dd, datediff(dd, 0, getdate()), 0) -- (a)
or
select cast(convert(char(11), getdate(), 113) as datetime) -- (b)
The second method does send a few more bytes either way but that might not be as important as the speed of the conversion.
Both also appear to be very fast, but there might be a difference in speed when dealing with hundreds-of-thousands or more rows?
Also, is it possible that there are even better methods to get rid of the time portion of a datetime in SQL?
",https://stackoverflow.com/questions/1177449/best-approach-to-remove-time-part-of-datetime,612,1047292.0,24.0,,,2009-07-24 12:49:54,2026-10-02 07:11:15,2026-10-02 07:11:15,,,sql;sql-server;t-sql;datetime;date,Stephen Perelson,6793,144355,registered,true,1177529,,CC BY-SA 4.0,2014-09-25 05:37:13,683,600,2,0,0,5,true,false,false,true,true,true,45,8,false,0.023,0.0006,6329,2009,7,12,Friday,false,false,false,false,false,true,false
5487892,OR is not supported with CASE expression,"The OR operator in the WHEN clause of a CASE expression is not supported. How can I do this?
CASE ebv.db_no
WHEN 22978 OR 23218 OR 23219 THEN 'WECS 9500'
ELSE 'WECS 9520'
END as wecs_system
",https://stackoverflow.com/questions/5487892/or-is-not-supported-with-case-expression,611,3110685.0,10.0,,,2011-03-30 14:45:11,2026-07-15 08:53:47,2026-07-15 08:53:47,,,sql;sql-server;t-sql;case,Werner,6233,455195,registered,true,5487936,,CC BY-SA 4.0,2017-02-10 19:20:42,273,203,4,0,0,4,true,false,false,true,true,true,40,7,false,0.003,0.0002,5715,2011,3,14,Wednesday,false,false,false,false,false,true,false
1400078,Is it possible to specify condition in Count()?,"Is it possible to specify a condition in Count()? I would like to count only the rows that have, for example, ""Manager"" in the Position column.
I want to do it in the count statement, not using WHERE; I'm asking about it because I need to count both Managers and Other in the same SELECT (something like Count(Position = Manager), Count(Position = Other)) so WHERE is no use for me in this example.
",https://stackoverflow.com/questions/1400078/is-it-possible-to-specify-condition-in-count,610,928039.0,13.0,,,2009-09-09 14:28:52,2022-12-16 10:03:24,2018-02-16 21:58:16,,,sql;sql-server;t-sql,agnieszka,15425,40872,registered,true,1400115,,CC BY-SA 3.0,,479,400,5,0,0,3,true,false,false,true,true,true,47,8,true,0.014,0.0007,6282,2009,9,14,Wednesday,false,false,false,false,false,true,false
6256610,updating table rows in postgres using subquery,"I have this table in a postgres 8.4 database:
CREATE TABLE public.dummy
(
address_id SERIAL,
addr1 character(40),
addr2 character(40),
city character(25),
state character(2),
zip character(5),
customer boolean,
supplier boolean,
partner boolean
)
WITH (
OIDS=FALSE
);
I want to update the table. Initially i tested my query using this insert statement:
insert into address customer,supplier,partner
SELECT
case when cust.addr1 is not null then TRUE else FALSE end customer,
case when suppl.addr1 is not null then TRUE else FALSE end supplier,
case when partn.addr1 is not null then TRUE else FALSE end partner
from (
SELECT *
from address) pa
left outer join cust_original cust
on (pa.addr1=cust.addr1 and pa.addr2=cust.addr2 and pa.city=cust.city
and pa.state=cust.state and substring(cust.zip,1,5) = pa.zip )
left outer join supp_original suppl
on (pa.addr1=suppl.addr1 and pa.addr2=suppl.addr2 and pa.city=suppl.city
and pa.state=suppl.state and pa.zip = substring(suppl.zip,1,5))
left outer join partner_original partn
on (pa.addr1=partn.addr1 and pa.addr2=partn.addr2 and pa.city=partn.city
and pa.state=partn.state and pa.zip = substring(partn.zip,1,5) )
where pa.address_id = address_id
How can I convert this to an update statement, i.e., update existing rows using values returned from a select statement?
",https://stackoverflow.com/questions/6256610/updating-table-rows-in-postgres-using-subquery,585,808020.0,8.0,,,2011-06-06 18:49:02,2025-06-12 19:06:23,2023-01-10 00:29:30,,,sql;postgresql;subquery;sql-update,stackover,7085,555064,registered,true,6258586,,CC BY-SA 4.0,,1561,1453,5,0,0,4,true,false,false,true,true,true,46,7,false,0.01,0.0007,5647,2011,6,18,Monday,false,false,false,false,false,true,false
41645309,MySQL Error: : 'Access denied for user 'root'@'localhost',"Consider:
./mysqladmin -u root -p** '_redacted_'
Output (including typing the password):
Enter password:
mysqladmin: connect to server at 'localhost' failed error:
'Access denied for user 'root'@'localhost' (using password: YES)'
How can I fix this?
",https://stackoverflow.com/questions/41645309/mysql-error-access-denied-for-user-rootlocalhost,584,2257046.0,29.0,,,2017-01-14 00:06:49,2024-05-29 07:25:34,2024-05-29 07:25:34,2024-06-17 15:11:15,Not suitable for this site,sql;mysql;database-connection,Harsh Trivedi,6075,6591743,registered,true,41793945,,,2018-02-09 07:10:37,362,255,1,0,0,3,true,true,false,true,true,true,77,8,false,0.013,0.0003,3598,2017,1,0,Saturday,true,false,false,false,false,true,false
2578194,What are DDL and DML?,"I have heard the terms DDL and DML in reference to databases, but I don't understand what they are.
What are they and how do they relate to SQL?
",https://stackoverflow.com/questions/2578194/what-are-ddl-and-dml,583,720433.0,13.0,,,2010-04-05 11:52:43,2024-01-15 04:16:28,2020-03-11 18:36:41,,,sql;ddl;dml,Sachindra,7299,197241,registered,true,44796508,,CC BY-SA 4.0,2018-07-18 07:55:07,161,147,0,0,0,3,true,false,false,true,true,true,21,5,true,0.018,0.0008,6074,2010,4,11,Monday,false,false,false,false,false,true,false
192220,What is the most efficient way to parse a flat table into a tree?,"Assume you have a flat table that stores an ordered tree hierarchy:
Id Name ParentId Order
1 'Node 1' 0 10
2 'Node 1.1' 1 10
3 'Node 2' 0 20
4 'Node 1.1.1' 2 10
5 'Node 2.1' 3 10
6 'Node 1.2' 1 20
Here's a diagram, where we have [id] Name. Root node 0 is fictional.
[0] ROOT
/ \
[1] Node 1 [3] Node 2
/ \ \
[2] Node 1.1 [6] Node 1.2 [5] Node 2.1
/
[4] Node 1.1.1
What is the most efficient approach to output that to HTML (or text, for that matter) as a correctly ordered and indented tree?
Assume that you only have basic data structures (arrays and hashmaps), no fancy objects with parent/children references, no ORM, no framework, just your two hands. The table is represented as a result set, which can be accessed randomly.
Pseudo code or plain English is okay, this is purely a conceptional question.
A root node is not necessary, because it is never going to be displayed anyway. ParentId = 0 is the convention to express "these are top level". The Order column defines how nodes with the same parent are going to be sorted.
The "result set" I spoke of can be pictured as an array of hashmaps (to stay in that terminology). For my example was meant to be already there. Some answers go the extra mile and construct it first, but thats okay.
The tree can be arbitrarily deep. Each node can have N children. I did not exactly have a "millions of entries" tree in mind, though.
Don't mistake my choice of node naming ('Node 1.1.1') for something to rely on. The nodes could equally well be called 'Frank' or 'Bob', no naming structure is implied, this was merely to make it readable.
",https://stackoverflow.com/questions/192220/what-is-the-most-efficient-way-to-parse-a-flat-table-into-a-tree,580,145936.0,15.0,,,2008-10-10 16:47:43,2025-08-21 15:06:22,2025-08-21 14:54:29,,,sql;algorithm;recursion;tree;hierarchical-data,Tomalak,339834,18771,registered,true,192462,,CC BY-SA 4.0,2014-08-26 08:53:07,1997,1886,2,0,0,5,true,false,false,true,true,true,65,14,true,0.103,0.004,6616,2008,10,16,Friday,false,false,false,false,false,true,false
1049210,Adding an identity to an existing column,"I need to change the primary key of a table to an identity column, and there's already a number of rows in table.
I've got a script to clean up the IDs to ensure they're sequential starting at 1, works fine on my test database.
What's the SQL command to alter the column to have an identity property?
",https://stackoverflow.com/questions/1049210/adding-an-identity-to-an-existing-column,577,1467859.0,21.0,,,2009-06-26 13:41:21,2026-02-26 13:42:22,2011-08-23 00:15:31,,,sql;sql-server;alter-table;identity-column,Kirschstein,14858,15691,registered,true,1049305,,CC BY-SA 3.0,2017-06-22 13:21:42,326,305,0,0,0,4,true,false,false,true,true,true,40,7,false,0.014,0.0004,6357,2009,6,13,Friday,false,false,false,false,false,true,false
1710476,How to print a query string with parameter values when using Hibernate,"Is it possible in Hibernate to print generated SQL queries with real values instead of question marks?
How would you suggest to print queries with real values if it is not possible with Hibernate API?
",https://stackoverflow.com/questions/1710476/how-to-print-a-query-string-with-parameter-values-when-using-hibernate,565,634043.0,35.0,,,2009-11-10 19:17:59,2024-04-15 06:29:29,2017-12-13 04:14:50,,,java;sql;hibernate;orm,craftsman,15751,162461,registered,true,1713464,,CC BY-SA 3.0,2016-07-21 11:06:33,216,202,0,0,0,4,true,false,false,true,true,true,70,12,false,0.055,0.0009,6220,2009,11,19,Tuesday,false,false,false,true,false,true,false
2305973,java.util.Date vs java.sql.Date,"java.util.Date vs java.sql.Date: when to use which and why?
",https://stackoverflow.com/questions/2305973/java-util-date-vs-java-sql-date,564,317580.0,7.0,,,2010-02-21 13:16:40,2024-09-19 23:53:32,2010-12-07 17:56:47,,,java;sql;datetime;date;jdbc,flybywire,277882,63051,registered,true,2306051,,CC BY-SA 2.5,,93,60,2,0,0,5,true,false,false,true,true,true,31,3,false,0.022,0.0018,6117,2010,2,13,Sunday,true,false,false,true,false,true,false
4329396,MySQL select 10 random rows from 600K rows fast,"How can I best write a query that selects 10 rows randomly from a total of 600k?
",https://stackoverflow.com/questions/4329396/mysql-select-10-random-rows-from-600k-rows-fast,562,598907.0,28.0,,,2010-12-01 21:35:14,2024-11-26 14:35:02,2020-06-16 04:35:56,,,mysql;sql;random,Francisc,81053,383148,registered,true,4329447,,CC BY-SA 4.0,2015-05-09 02:35:58,88,81,0,0,0,3,true,false,false,true,true,true,47,9,false,0.047,0.0009,5834,2010,12,21,Wednesday,false,false,false,false,false,true,false
1334012,Cannot insert explicit value for identity column in table 'table' when IDENTITY_INSERT is set to OFF,"I have the below error when I execute the following script. What is the error about, and how it can be resolved?
Insert table(OperationID,OpDescription,FilterID)
values (20,'Hierachy Update',1)
Error:
Server: Msg 544, Level 16, State 1, Line 1
Cannot insert explicit value for identity column in table 'table' when IDENTITY_INSERT is set to OFF.
",https://stackoverflow.com/questions/1334012/cannot-insert-explicit-value-for-identity-column-in-table-table-when-identity,560,1468957.0,34.0,,,2009-08-26 11:19:57,2026-07-16 20:28:52,2017-10-18 20:11:25,,,sql;sql-server;sybase,Jaison,,,does_not_exist,true,,,CC BY-SA 3.0,2018-06-09 11:18:32,436,359,1,0,0,3,false,false,false,true,false,true,108,16,false,0.023,0.0004,6296,2009,8,11,Wednesday,false,false,false,false,false,true,false
1481476,When to use "ON UPDATE CASCADE","I use ON DELETE CASCADE regularly but I never use ON UPDATE CASCADE as I am not so sure in what situation it will be useful.
For the sake of discussion let see some code.
CREATE TABLE parent (
id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (id)
);
CREATE TABLE child (
id INT NOT NULL AUTO_INCREMENT, parent_id INT,
INDEX par_ind (parent_id),
FOREIGN KEY (parent_id)
REFERENCES parent(id)
ON DELETE CASCADE
);
For ON DELETE CASCADE, if a parent with an id is deleted, a record in child with parent_id = parent.id will be automatically deleted. This should be no problem.
This means that ON UPDATE CASCADE will do the same thing when id of the parent is updated?
If (1) is true, it means that there is no need to use ON UPDATE CASCADE if parent.id is not updatable (or will never be updated) like when it is AUTO_INCREMENT or always set to be TIMESTAMP. Is that right?
If (2) is not true, in what other kind of situation should we use ON UPDATE CASCADE?
What if I (for some reason) update the child.parent_id to be something not existing, will it then be automatically deleted?
Well, I know, some of the question above can be test programmatically to understand but I want also know if any of this is database vendor dependent or not.
Please shed some light.
",https://stackoverflow.com/questions/1481476/when-to-use-on-update-cascade,556,486949.0,8.0,,,2009-09-26 15:41:49,2022-09-08 05:41:56,2021-12-28 16:52:17,,,sql;foreign-keys,NawaMan,25865,176180,registered,true,1481524,,CC BY-SA 4.0,2013-10-11 21:30:22,1600,1299,14,0,0,2,true,false,false,true,true,true,41,6,false,0.016,0.0011,6265,2009,9,15,Saturday,true,false,false,false,false,true,false
1009954,MySQL: @variable vs. variable. What's the difference?,"In another question I posted someone told me that there is a difference between:
@variable
and:
variable
in MySQL. He also mentioned how MSSQL has batch scope and MySQL has session scope. Can someone elaborate on this for me?
",https://stackoverflow.com/questions/1009954/mysql-variable-vs-variable-whats-the-difference,555,457348.0,6.0,,,2009-06-17 23:04:00,2024-04-14 16:17:59,2023-12-17 17:55:55,,,sql;mysql;database;local-variables;user-defined-variables,aarona,37844,43792,registered,true,1010042,,CC BY-SA 4.0,,373,228,2,0,0,5,true,false,false,true,true,true,57,7,true,0.013,0.0012,6366,2009,6,23,Wednesday,false,false,false,false,false,true,false
2129693,Restrict results to top N rows per group,"The following query:
SELECT
year, id, rate
FROM h
WHERE year BETWEEN 2000 AND 2009
ORDER BY id, rate DESC
yields:
year | id | rate
2006 | p01 | 8.0
2003 | p01 | 7.4
2008 | p01 | 6.8
2001 | p01 | 5.9
2007 | p01 | 5.3
2009 | p01 | 4.4
2002 | p01 | 3.9
2004 | p01 | 3.5
2005 | p01 | 2.1
2000 | p01 | 0.8
2001 | p02 | 12.5
2004 | p02 | 12.4
2002 | p02 | 12.2
2003 | p02 | 10.3
2000 | p02 | 8.7
2006 | p02 | 4.6
2007 | p02 | 3.3
I want only the top 5 rows for each id:
year | id | rate
2006 | p01 | 8.0
2003 | p01 | 7.4
2008 | p01 | 6.8
2001 | p01 | 5.9
2007 | p01 | 5.3
2001 | p02 | 12.5
2004 | p02 | 12.4
2002 | p02 | 12.2
2003 | p02 | 10.3
2000 | p02 | 8.7
Is there a way to do this using some kind of LIMIT like modifier that applies to each group?
",https://stackoverflow.com/questions/2129693/restrict-results-to-top-n-rows-per-group,548,573544.0,14.0,,,2010-01-25 01:25:02,2024-01-05 22:26:18,2024-01-05 22:06:51,,,sql;mysql;greatest-n-per-group;ranking,Wells,11089,160511,registered,true,,,CC BY-SA 4.0,2015-10-05 09:21:41,876,776,3,0,0,4,false,false,false,true,true,true,40,8,false,0.024,0.001,6144,2010,1,1,Monday,false,false,false,false,false,true,false
71022,SQL MAX of multiple columns?,"How do you return 1 value per row of the max of several columns:
TableName
[Number, Date1, Date2, Date3, Cost]
I need to return something like this:
[Number, Most_Recent_Date, Cost]
Query?
",https://stackoverflow.com/questions/71022/sql-max-of-multiple-columns,545,935787.0,24.0,,,2008-09-16 10:27:02,2024-05-14 07:07:36,2014-08-12 19:40:25,,,sql;sql-server;t-sql,BenB,10690,11703,registered,true,71045,,CC BY-SA 3.0,2016-12-14 23:37:31,289,196,2,0,0,3,true,false,false,true,true,true,28,5,true,0.026,0.0006,6640,2008,9,10,Tuesday,false,false,false,false,false,true,false
2955459,What is an index in SQL?,"What is an index in SQL, and when is it appropriate to use one?
",https://stackoverflow.com/questions/2955459/what-is-an-index-in-sql,541,817336.0,13.0,,,2010-06-02 06:26:54,2026-02-09 17:44:40,2026-02-09 17:44:40,,,sql;indexing,Surya sasidhar,30491,164002,registered,true,2955470,,CC BY-SA 4.0,2019-09-08 10:16:22,71,64,0,0,0,2,true,false,false,true,true,true,24,6,true,0.016,0.0007,6016,2010,6,6,Wednesday,false,false,false,false,false,true,false
1827063,MySQL error: key specification without a key length,"I have a table with a primary key that is a varchar(255). Some cases have arisen where 255 characters isn't enough. I tried changing the field to a text, but I get the following error:
BLOB/TEXT column 'message_id' used in key specification without a key length
how can I fix this?
edit: I should also point out this table has a composite primary key with multiple columns.
",https://stackoverflow.com/questions/1827063/mysql-error-key-specification-without-a-key-length,538,648326.0,20.0,,,2009-12-01 15:50:45,2026-02-23 16:06:58,2014-09-12 16:43:37,,,mysql;sql;mysql-error-1170,GSto,42574,89761,registered,true,1827099,,CC BY-SA 3.0,,423,378,1,0,0,3,true,false,false,true,true,true,51,8,false,0.031,0.0008,6199,2009,12,15,Tuesday,false,false,false,false,false,true,false
11296361,How to create id with AUTO_INCREMENT on Oracle?,"It appears that there is no concept of AUTO_INCREMENT in Oracle, up until and including version 11g.
How can I create a column that behaves like auto increment in Oracle 11g?
",https://stackoverflow.com/questions/11296361/how-to-create-id-with-auto-increment-on-oracle,538,1427166.0,18.0,,,2012-07-02 15:09:48,2022-09-26 04:19:53,2017-05-08 07:41:14,,,sql;oracle-database;auto-increment,Sushan Ghimire,7597,1143828,registered,true,11296469,,CC BY-SA 3.0,2016-03-23 20:11:37,190,176,0,0,0,3,true,false,false,true,true,true,47,8,true,0.013,0.0004,5255,2012,7,15,Monday,false,false,false,false,false,true,false
1198364,How can I update top 100 records in SQL server?,"I want to update the top 100 records in SQL Server. I have a table T1 with fields F1 and F2. T1 has 200 records. I want to update the F1 field in the top 100 records. How can I update based on TOP 100 in SQL Server?
",https://stackoverflow.com/questions/1198364/how-can-i-update-top-100-records-in-sql-server,537,661041.0,11.0,,,2009-07-29 06:37:18,2025-08-18 12:09:46,2024-05-28 06:55:09,,,sql;sql-server;t-sql;sql-update,Rajesh,6629,130289,registered,true,1198404,,CC BY-SA 4.0,2015-03-09 21:32:01,302,217,6,0,0,4,true,false,false,true,true,true,47,10,true,0.017,0.0008,6324,2009,7,6,Wednesday,false,false,false,false,false,true,false
2647,How do I split a delimited string so I can access individual items?,"Using SQL Server, how do I split a string so I can access item x?
Take a string ""Hello John Smith"". How can I split the string by space and access the item at index 1 which should return ""John""?
",https://stackoverflow.com/questions/2647/how-do-i-split-a-delimited-string-so-i-can-access-individual-items,535,1002847.0,46.0,,,2008-08-05 18:15:47,2025-10-23 12:12:01,2022-06-13 15:19:11,,,sql;sql-server;t-sql;split,GateKiller,76456,383,registered,true,2657,,CC BY-SA 4.0,2010-08-21 16:38:22,210,196,0,0,0,4,true,false,false,true,true,true,67,13,true,0.046,0.0005,6682,2008,8,18,Tuesday,false,false,false,false,false,true,false
970562,Postgres and indexes on foreign keys and primary keys,"Does Postgres automatically put indexes on foreign keys and primary keys? How can I tell? Is there a command that will return all indexes on a table?
",https://stackoverflow.com/questions/970562/postgres-and-indexes-on-foreign-keys-and-primary-keys,532,261524.0,9.0,,,2009-06-09 14:56:40,2024-04-29 19:40:16,2024-04-29 19:40:16,,,sql;postgresql;indexing;foreign-keys;primary-key,mainstringargs,14153,33863,registered,true,970605,,CC BY-SA 4.0,,159,152,0,0,0,5,true,false,false,true,true,true,53,9,false,0.034,0.002,6374,2009,6,14,Tuesday,false,false,false,false,false,true,false
8674718,Best way to select random rows PostgreSQL,"I want a random selection of rows in PostgreSQL, I tried this:
select * from table where random() < 0.01;
But some other recommend this:
select * from table order by random() limit 1000;
I have a very large table with 500 Million rows, I want it to be fast.
Which approach is better? What are the differences? What is the best way to select random rows?
",https://stackoverflow.com/questions/8674718/best-way-to-select-random-rows-postgresql,531,439861.0,13.0,,,2011-12-29 23:30:11,2024-10-17 20:35:46,2021-04-08 03:59:26,,,sql;performance;postgresql;random,nanounanue,8482,754176,registered,true,8675160,,CC BY-SA 4.0,,437,361,2,0,0,4,true,false,false,true,true,true,41,7,false,0.03,0.0012,5441,2011,12,23,Thursday,false,false,false,false,false,true,false
10025032,What is the meaning of the prefix N in T-SQL statements and when should I use it?,"I have seen prefix N in some insert T-SQL queries. Many people have used N before inserting the value in a table.
I searched, but I was not able to understand what is the purpose of including the N before inserting any strings into the table.
INSERT INTO Personnel.Employees
VALUES(N'29730', N'Philippe', N'Horsford', 20.05, 1),
What purpose does this 'N' prefix serve, and when should it be used?
",https://stackoverflow.com/questions/10025032/what-is-the-meaning-of-the-prefix-n-in-t-sql-statements-and-when-should-i-use-it,530,504725.0,4.0,,,2012-04-05 08:19:53,2021-04-16 08:11:07,2020-02-16 17:53:46,,,sql;sql-server;t-sql,Kartik Patel,9713,1253970,registered,true,10025043,,CC BY-SA 4.0,,473,402,3,0,0,3,true,false,false,true,true,true,81,17,true,0.008,0.0011,5343,2012,4,8,Thursday,false,false,false,false,false,true,false
3556890,Altering a column to be nullable,"I want to alter a table column to be nullable. I have used:
ALTER TABLE Merchant_Pending_Functions Modify NumberOfLocations NULL
This gives an error at Modify. What is the correct syntax?
",https://stackoverflow.com/questions/3556890/altering-a-column-to-be-nullable,527,836953.0,12.0,,,2010-08-24 13:26:40,2025-06-25 22:27:12,2016-03-06 14:12:20,2026-02-24 05:56:21,Not suitable for this site,sql,challengeAccepted,7786,397062,registered,true,3556942,,,,243,192,2,0,0,1,true,true,false,true,true,true,32,6,false,0.014,0.0006,5933,2010,8,13,Tuesday,false,false,false,false,false,true,false
4629979,Nested select statement in SQL Server,"Why doesn't the following work?
SELECT name FROM (SELECT name FROM agentinformation)
I guess my understanding of SQL is wrong, because I would have thought this would return the same thing as
SELECT name FROM agentinformation
Doesn't the inner select statement create a result set which the outer SELECT statement then queries?
",https://stackoverflow.com/questions/4629979/nested-select-statement-in-sql-server,526,1097063.0,3.0,,,2011-01-07 20:27:26,2022-08-01 21:33:18,2019-04-25 15:19:00,,,sql;sql-server;nested;subquery;querying,Brennan Vincent,11078,242814,registered,true,4630000,,CC BY-SA 4.0,,405,336,2,0,0,5,true,false,false,true,true,true,37,6,false,0.003,0.0005,5797,2011,1,20,Friday,false,false,false,false,false,true,false
10643379,How do I query for all dates greater than a certain date in SQL Server?,"I'm trying:
SELECT *
FROM dbo.March2010 A
WHERE A.Date >= 2010-04-01;
A.Date looks like: 2010-03-04 00:00:00.000
However, this is not working.
Can anyone provide a reference for why?
",https://stackoverflow.com/questions/10643379/how-do-i-query-for-all-dates-greater-than-a-certain-date-in-sql-server,526,2157833.0,8.0,,,2012-05-17 20:56:14,2022-11-15 04:42:04,2018-08-16 08:21:42,,,sql;sql-server;datetime,Eric Francis,24725,843542,registered,true,10643403,,CC BY-SA 4.0,,272,194,3,0,0,3,true,false,false,true,true,true,71,15,true,0.004,0.0002,5301,2012,5,20,Thursday,false,false,false,false,false,true,false
31211506,How Stuff and 'For Xml Path' work in SQL Server?,"Table is:
Id
Name
1
aaa
1
bbb
1
ccc
1
ddd
1
eee
Required output:
Id
abc
1
aaa,bbb,ccc,ddd,eee
Query:
SELECT ID,
abc = STUFF(
(SELECT ',' + name FROM temp1 FOR XML PATH ('')), 1, 1, ''
)
FROM temp1 GROUP BY id
This query is working properly. But I just need the explanation how it works or is there any other or short way to do this.
I am getting very confused to understand this.
",https://stackoverflow.com/questions/31211506/how-stuff-and-for-xml-path-work-in-sql-server,523,992353.0,9.0,,,2015-07-03 17:03:05,2025-01-25 09:42:04,2020-12-08 10:14:22,,,sql;sql-server;for-xml-path;stuff,Puneet Chawla,6081,4823805,registered,true,,,CC BY-SA 4.0,2018-07-17 14:45:56,922,451,1,0,0,4,false,false,false,true,true,true,56,10,true,0.009,0.0005,4159,2015,7,17,Friday,false,false,false,false,false,true,false
24929,Difference between EXISTS and IN in SQL?,"What is the difference between the EXISTS and IN clause in SQL?
When should we use EXISTS, and when should we use IN?
",https://stackoverflow.com/questions/24929/difference-between-exists-and-in-in-sql,520,692471.0,22.0,,,2008-08-24 08:42:23,2025-10-22 04:39:42,2022-02-05 15:58:10,,,sql;exists;sql-in,Krantz,6323,2528,registered,true,,,CC BY-SA 4.0,2013-09-20 15:20:15,185,119,4,0,0,3,false,false,false,true,true,true,40,7,true,0.032,0.0008,6663,2008,8,8,Sunday,true,false,false,false,false,true,false
722221,How to log PostgreSQL queries?,"How to enable logging of all SQL executed by PostgreSQL 8.3?
Edited (more info)
I changed these lines :
log_directory = 'pg_log'
log_filename = 'postgresql-%Y-%m-%d_%H%M%S.log'
log_statement = 'all'
And restart PostgreSQL service... but no log was created...
I'm using Windows Server 2003.
Any ideas?
",https://stackoverflow.com/questions/722221/how-to-log-postgresql-queries,519,701053.0,14.0,,,2009-04-06 16:34:32,2023-09-26 09:49:57,2023-01-06 13:09:19,,,sql;database;postgresql;logging,Paul,12859,83313,registered,true,722236,,CC BY-SA 4.0,,422,322,1,0,0,4,true,false,false,true,true,true,30,5,true,0.02,0.0007,6438,2009,4,16,Monday,false,false,false,false,false,true,false
530012,How to convert java.util.Date to java.sql.Date?,"I am trying to use a java.util.Date as input and then creating a query with it - so I need a java.sql.Date.
I was surprised to find that it couldn't do the conversion implicitly or explicitly - but I don't even know how I would do this, as the Java API is still fairly new to me.
",https://stackoverflow.com/questions/530012/how-to-convert-java-util-date-to-java-sql-date,517,800701.0,17.0,,,2009-02-09 21:16:18,2022-08-03 17:23:22,2016-08-20 00:34:43,,,java;sql;datetime;date,David Ackerman,12729,2504,registered,true,31238011,,CC BY-SA 3.0,2021-05-23 09:59:31,506,283,2,2,0,4,true,false,false,true,true,true,47,6,true,0.021,0.0006,6494,2009,2,21,Monday,false,false,false,true,false,true,false
1490942,Declare a variable in a PostgreSQL query,"How do I declare a variable for use in a PostgreSQL 8.3 query?
In MS SQL Server I can do this:
DECLARE @myvar INT;
SET @myvar = 5/
SELECT * FROM somewhere WHERE something = @myvar;
How do I do the same in PostgreSQL? According to the documentation variables are declared simply as "name type;", but this gives me a syntax error:
myvar INTEGER;
Could someone give me an example of the correct syntax?
",https://stackoverflow.com/questions/1490942/declare-a-variable-in-a-postgresql-query,516,947015.0,18.0,,,2009-09-29 06:41:05,2024-04-25 09:01:25,2023-12-02 18:46:58,,,sql;database;postgresql;postgresql-8.3;user-variables,EMP,62793,20336,registered,true,1491329,,CC BY-SA 4.0,2015-10-31 22:40:47,569,417,2,0,0,5,true,false,false,true,true,true,40,7,false,0.019,0.0005,6262,2009,9,6,Tuesday,false,false,false,false,false,true,false
30290880,Rename a column in MySQL,"I am trying to rename a column in MySQL community server 5.5.27 using this SQL expression:
ALTER TABLE table_name RENAME COLUMN old_col_name TO new_col_name;
I also tried
ALTER TABLE table_name RENAME old_col_name TO new_col_name;
But it says:
Error: check the Manual that corresponds to your MySQL server version
",https://stackoverflow.com/questions/30290880/rename-a-column-in-mysql,513,798113.0,18.0,,,2015-05-17 18:59:13,2024-11-25 17:24:24,2024-01-25 12:11:57,,,sql;mysql;rename;alter,Michael Okoli,5337,4831534,registered,true,30290915,,CC BY-SA 4.0,,445,318,4,0,0,4,true,false,false,true,true,true,24,5,false,0.023,0.0006,4206,2015,5,18,Sunday,true,false,false,false,false,true,false
1515969,Exporting data In SQL Server as INSERT INTO,"I am using SQL Server 2008 Management Studio and have a table I want to migrate to a different db server.
Is there any option to export the data as an insert into SQL script??
",https://stackoverflow.com/questions/1515969/exporting-data-in-sql-server-as-insert-into,512,566944.0,11.0,,,2009-10-04 08:57:36,2025-06-04 19:26:44,2015-11-03 14:49:49,,,sql;sql-server;insert;data-migration,Jack Kada,25512,122528,registered,true,1515975,,CC BY-SA 3.0,,192,178,0,0,0,4,true,false,false,true,true,true,43,8,false,0.019,0.0009,6257,2009,10,8,Sunday,true,false,false,false,false,true,false
34115174,Error related to only_full_group_by when executing a query in MySql,"I have upgraded my system and have installed MySql 5.7.9 with php for a web application I am working on. I have a query that is dynamically created, and when run in older versions of MySQL it works fine. Since upgrading to 5.7 I get this error:
Expression #1 of SELECT list is not in GROUP BY clause and contains
non-aggregated column 'support_desk.mod_users_groups.group_id' which is
not functionally dependent on columns in GROUP BY clause; this is
incompatible with sql_mode=only_full_group_by
Note the manual page for Mysql 5.7 on the topic of Server SQL Modes.
This is the query that is giving me trouble:
SELECT mod_users_groups.group_id AS 'value',
group_name AS 'text'
FROM mod_users_groups
LEFT JOIN mod_users_data ON mod_users_groups.group_id = mod_users_data.group_id
WHERE mod_users_groups.active = 1
AND mod_users_groups.department_id = 1
AND mod_users_groups.manage_work_orders = 1
AND group_name != 'root'
AND group_name != 'superuser'
GROUP BY group_name
HAVING COUNT(`user_id`) > 0
ORDER BY group_name
I don't understand only_full_group_by enough to figure out what I need to do to fix the query. Can I just turn off the only_full_group_by option, or is there something else I need to do?
",https://stackoverflow.com/questions/34115174/error-related-to-only-full-group-by-when-executing-a-query-in-mysql,511,751215.0,18.0,,,2015-12-06 07:42:07,2024-01-15 01:27:02,2023-05-31 00:36:22,,,mysql;sql;group-by;mysql-error-1055,Dan Bemowski,5385,2604999,registered,true,34115425,,CC BY-SA 4.0,2017-07-13 10:17:18,1471,1239,3,1,0,4,true,false,false,true,true,true,67,10,false,0.024,0.0007,4003,2015,12,7,Sunday,true,false,false,false,false,true,false
273238,How to use GROUP BY to concatenate strings in SQL Server?,"How do I get:
id Name Value
1 A 4
1 B 8
2 C 9
to
id Column
1 A:4, B:8
2 C:9
",https://stackoverflow.com/questions/273238/how-to-use-group-by-to-concatenate-strings-in-sql-server,510,948797.0,23.0,,,2008-11-07 19:08:00,2024-03-07 03:19:59,2011-09-20 14:46:12,,,sql;sql-server;string-concatenation;sql-server-group-concat,Eldila,15866,889,registered,true,273330,,CC BY-SA 3.0,,236,174,2,0,0,4,true,false,false,true,true,true,57,11,true,0.024,0.0005,6588,2008,11,19,Friday,false,false,false,false,false,true,false
1912095,How to insert a value that contains an apostrophe (single quote)?,"What is the correct SQL syntax to insert a value with an apostrophe in it?
Insert into Person
(First, Last)
Values
'Joe',
'O'Brien'
I keep getting an error as I think the apostrophe after the O is the ending tag for the value.
",https://stackoverflow.com/questions/1912095/how-to-insert-a-value-that-contains-an-apostrophe-single-quote,510,1319547.0,13.0,,,2009-12-16 03:34:44,2025-01-06 20:03:19,2016-01-25 16:29:52,,,sql;sql-update;sql-insert,leora,198533,4653,registered,true,1912100,,CC BY-SA 3.0,2014-09-19 03:05:18,274,236,1,0,0,3,true,false,false,true,true,true,65,11,true,0.01,0.0004,6184,2009,12,3,Wednesday,false,false,false,false,false,true,false
4076098,How to select rows with no matching entry in another table?,"I'm doing some maintenance work on a database application and I've discovered that, joy of joys, even though values from one table are being used in the style of foreign keys, there's no foreign key constraints on the tables.
I'm trying to add FK constraints on these columns, but I'm finding that, because there's already a whole load of bad data in the tables from previous errors which have been naively corrected, I need to find the rows which don't match up to the other table and then delete them.
I've found some examples of this kind of query on the web, but they all seem to provide examples rather than explanations, and I don't understand why they work.
Can someone explain to me how to construct a query which returns all the rows with no matches in another table, and what it's doing, so that I can make these queries myself, rather than coming running to SO for every table in this mess that has no FK constraints?
",https://stackoverflow.com/questions/4076098/how-to-select-rows-with-no-matching-entry-in-another-table,509,756476.0,11.0,,,2010-11-02 08:47:50,2024-10-02 15:28:49,2017-05-26 21:34:18,,,sql;foreign-keys,Frosty840,8445,82037,registered,true,4076157,,CC BY-SA 3.0,2022-07-24 23:34:39,969,932,0,0,0,2,true,false,false,true,true,true,59,11,true,0.015,0.0007,5863,2010,11,8,Tuesday,false,false,false,false,false,true,false
27435839,How to list active connections on PostgreSQL?,"Is there a command in PostgreSQL to select active connections to a given database?
psql states that I can't drop one of my databases because there are active connections to it, so I would like to see what the connections are (and from which machines)
",https://stackoverflow.com/questions/27435839/how-to-list-active-connections-on-postgresql,507,789532.0,5.0,,,2014-12-12 02:20:06,2024-06-22 19:46:03,2020-04-15 17:57:03,,,sql;postgresql;database-connection;listings,Tregoreg,23426,1137187,registered,true,27435868,,CC BY-SA 4.0,,296,252,1,0,0,4,true,false,false,true,true,true,45,7,true,0.006,0.0006,4362,2014,12,2,Friday,false,false,false,false,false,true,false
15745042,Efficiently convert rows to columns,"I'm looking for an efficient way to convert rows to columns in SQL Server, I heard that PIVOT is not very fast, and I need to deal with lot of records.
This is my example:
Id
Value
ColumnName
1
John
FirstName
2
2.4
Amount
3
ZH1E4A
PostalCode
4
Fork
LastName
5
857685
AccountNumber
This is my result:
FirstName
Amount
PostalCode
LastName
AccountNumber
John
2.4
ZH1E4A
Fork
857685
How can I build the result?
",https://stackoverflow.com/questions/15745042/efficiently-convert-rows-to-columns,507,1555968.0,4.0,,,2013-04-01 14:11:17,2025-09-03 08:30:15,2025-09-03 08:30:15,,,sql;sql-server;sql-server-2008;pivot,tbag,5111,2218311,registered,true,15745076,,CC BY-SA 4.0,2014-06-13 12:40:34,996,435,1,0,0,4,true,false,false,true,true,true,35,5,false,0.003,0.0003,4982,2013,4,14,Monday,false,false,false,false,false,true,false
164319,Is there any difference between GROUP BY and DISTINCT?,"The following two queries each give the same result:
SELECT column FROM table GROUP BY column
SELECT DISTINCT column FROM table
Is there anything different in the way these commands are processed, or are they the same thing?
(This is not a question about aggregates. The use of GROUP BY with aggregate functions is understood.)
",https://stackoverflow.com/questions/164319/is-there-any-difference-between-group-by-and-distinct,505,429802.0,25.0,,,2008-10-02 20:09:06,2023-12-31 19:08:13,2023-12-31 19:08:13,,,sql;group-by;distinct,Brettski,20341,5836,registered,true,164544,,CC BY-SA 4.0,2018-08-04 11:58:50,425,329,2,0,0,3,true,false,false,true,true,true,54,9,true,0.058,0.0012,6624,2008,10,20,Thursday,false,false,false,false,false,true,false
44917,Explicit vs implicit SQL joins,"Is there any efficiency difference in an explicit vs implicit inner join?
For example:
SELECT * FROM
table a INNER JOIN table b
ON a.id = b.id;
vs.
SELECT a.*, b.*
FROM table a, table b
WHERE a.id = b.id;
",https://stackoverflow.com/questions/44917/explicit-vs-implicit-sql-joins,503,249729.0,12.0,,,2008-09-04 22:49:58,2023-02-21 21:18:54,2017-10-26 19:14:11,,,sql;join,dmanxiii,52273,4316,registered,true,44932,,CC BY-SA 3.0,2015-10-05 09:21:55,272,210,2,0,0,2,true,false,false,true,true,true,30,5,false,0.048,0.002,6652,2008,9,22,Thursday,false,false,false,false,false,true,false
13674031,How to get the top 10 values in postgresql?,"I have simple question:
I have a postgresql table: Scores(score integer).
How would I get the highest 10 scores the fastest?
UPDATE:
I will be doing this query multiple times and am aiming for the fastest solution.
",https://stackoverflow.com/questions/13674031/how-to-get-the-top-10-values-in-postgresql,502,1063925.0,4.0,,,2012-12-02 21:27:03,2022-06-08 19:09:26,2021-11-07 18:41:57,,,sql;postgresql;sql-limit,Joey Franklin,7063,1181215,registered,true,,,CC BY-SA 4.0,,310,215,2,0,0,3,false,false,false,true,true,true,43,9,true,0.004,0.0005,5102,2012,12,21,Sunday,true,false,false,false,false,true,false
4812933,How to change a PG column to NULLABLE TRUE?,"How can I accomplish this using Postgres? I've tried the code below but it doesn't work:
ALTER TABLE mytable ALTER COLUMN mycolumn BIGINT NULL;
",https://stackoverflow.com/questions/4812933/how-to-change-a-pg-column-to-nullable-true,501,296028.0,1.0,,,2011-01-27 05:05:23,2022-11-01 20:43:30,2016-03-29 17:20:59,,,sql;postgresql;nullable,mateusmaso,8623,420661,registered,true,4813062,,CC BY-SA 3.0,,178,147,1,0,0,3,true,false,false,true,true,true,43,9,true,0.003,0.0017,5777,2011,1,5,Thursday,false,false,false,false,false,true,false
43870,How to concatenate strings of a string field in a PostgreSQL 'group by' query?,"I am looking for a way to concatenate the strings of a field within a group by query. So for example, I have a table:
ID
COMPANY_ID
EMPLOYEE
1
1
Anna
2
1
Bill
3
2
Carol
4
2
Dave
and I wanted to group by company_id to get something like:
COMPANY_ID
EMPLOYEE
1
Anna, Bill
2
Carol, Dave
There is a built-in function in mySQL to do this group_concat
",https://stackoverflow.com/questions/43870/how-to-concatenate-strings-of-a-string-field-in-a-postgresql-group-by-query,501,459437.0,15.0,,,2008-09-04 14:27:16,2025-01-21 16:09:11,2023-02-28 09:42:21,,,sql;postgresql;group-by;string-aggregation,Guy C,7390,4045,registered,true,43944,,CC BY-SA 4.0,,972,378,0,1,0,4,true,false,false,true,true,true,86,14,true,0.033,0.0011,6652,2008,9,14,Thursday,false,false,false,false,false,true,false
3805958,How to delete a record in Django models?,"I want to delete a particular record like:
delete from table_name where id = 1;
How can I do this in a django model?
",https://stackoverflow.com/questions/3805958/how-to-delete-a-record-in-django-models,499,643869.0,10.0,,,2010-09-27 16:48:06,2024-12-15 16:47:23,2022-11-20 03:16:08,,,python;sql;django;django-models;django-queryset,user426795,11741,426795,registered,true,,,CC BY-SA 4.0,,156,118,1,0,0,5,false,false,false,true,true,true,40,8,true,0.016,0.0008,5899,2010,9,16,Monday,false,true,false,false,false,true,false
12789396,How to get multiple filtered counts with one SQL query,"I am wondering how to write this query.
I know this actual syntax is bogus, but it will help you understand what I want.
I need it in this format, because it is part of a much bigger query.
SELECT distributor_id,
COUNT(*) AS TOTAL,
COUNT(*) WHERE level = 'exec',
COUNT(*) WHERE level = 'personal'
I need this all returned in one query.
Also, it need to be in one row, so the following won't work:
'SELECT distributor_id, COUNT(*)
GROUP BY distributor_id'
",https://stackoverflow.com/questions/12789396/how-to-get-multiple-filtered-counts-with-one-sql-query,498,666953.0,12.0,,,2012-10-08 21:00:05,2026-05-27 22:15:56,2026-05-27 22:15:56,,,sql;filter;count,Crobzilla,5101,759568,registered,true,12789493,,CC BY-SA 4.0,2018-03-22 07:14:09,540,457,2,0,0,3,true,false,false,true,true,true,54,10,false,0.018,0.0007,5157,2012,10,21,Monday,false,false,false,false,false,true,false
16568,How to select the nth row in a SQL database table?,"I'm interested in learning some (ideally) database agnostic ways of selecting the nth row from a database table. It would also be interesting to see how this can be achieved using the native functionality of the following databases:
- SQL Server
- MySQL
- PostgreSQL
- SQLite
- Oracle
I am currently doing something like the following in SQL Server 2005, but I'd be interested in seeing other's more agnostic approaches:
WITH Ordered AS (
SELECT ROW_NUMBER() OVER (ORDER BY OrderID) AS RowNumber, OrderID, OrderDate
FROM Orders)
SELECT *
FROM Ordered
WHERE RowNumber = 1000000
Credit for the above SQL: Firoz Ansari's Weblog
Update: See Troels Arvin's answer regarding the SQL standard. Troels, have you got any links we can cite?
",https://stackoverflow.com/questions/16568/how-to-select-the-nth-row-in-a-sql-database-table,497,1110397.0,34.0,,,2008-08-19 17:13:11,2023-06-15 19:17:20,2019-07-19 22:51:47,,,mysql;sql;database;oracle-database;postgresql,Charles Roper,20705,1944,registered,true,16777,,CC BY-SA 4.0,2011-02-27 00:56:55,1117,730,1,2,0,5,true,false,false,true,true,true,50,11,true,0.031,0.0004,6668,2008,8,17,Tuesday,false,false,false,false,false,true,false
19601948,must appear in the GROUP BY clause or be used in an aggregate function,"I have a table that looks like this caller 'makerar'
cname
wmname
avg
canada
zoro
2.0000000000000000
spain
luffy
1.00000000000000000000
spain
usopp
5.0000000000000000
And I want to select the maximum avg for each cname.
SELECT cname, wmname, MAX(avg) FROM makerar GROUP BY cname;
but I will get an error,
ERROR: column "makerar.wmname" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: SELECT cname, wmname, MAX(avg) FROM makerar GROUP BY cname;
so i do this
SELECT cname, wmname, MAX(avg) FROM makerar GROUP BY cname, wmname;
however this will not give the intented results, and the incorrect output below is shown.
cname
wmname
max
canada
zoro
2.0000000000000000
spain
luffy
1.00000000000000000000
spain
usopp
5.0000000000000000
Actual Results should be
cname
wmname
max
canada
zoro
2.0000000000000000
spain
usopp
5.0000000000000000
How can I go about fixing this issue?
Note: This table is a VIEW created from a previous operation.
",https://stackoverflow.com/questions/19601948/must-appear-in-the-group-by-clause-or-be-used-in-an-aggregate-function,496,851250.0,7.0,,,2013-10-26 01:50:26,2023-03-02 11:50:07,2023-03-02 11:50:07,,,sql;group-by;aggregate-functions;postgresql-9.1,RandomGuy,5299,1767006,registered,true,19602031,,CC BY-SA 4.0,,1849,1031,3,0,0,4,true,false,false,true,true,true,70,14,false,0.008,0.0006,4774,2013,10,1,Saturday,true,false,false,false,false,true,false
6127338,"MySQL: Select DISTINCT / UNIQUE, but return all columns?","SELECT DISTINCT field1, field2, field3, ......
FROM table;
I am trying to accomplish the following SQL statement, but I want it to return all columns.
Is this possible?
Something like this:
SELECT DISTINCT field1, *
FROM table;
",https://stackoverflow.com/questions/6127338/mysql-select-distinct-unique-but-return-all-columns,495,1170221.0,19.0,,,2011-05-25 15:55:16,2022-11-22 06:17:11,2022-09-06 04:55:49,,,sql;select;distinct,aryaxt,77976,242769,registered,true,6127471,,CC BY-SA 4.0,2019-10-20 07:03:28,316,231,2,0,0,3,true,false,false,true,true,true,56,9,true,0.016,0.0004,5659,2011,5,15,Wednesday,false,false,false,false,false,true,false
2111384,SQL join: selecting the last records in a one-to-many relationship,"Suppose I have a table of customers and a table of purchases. Each purchase belongs to one customer. I want to get a list of all customers along with their last purchase in one SELECT statement. What is the best practice? Any advice on building indexes?
Please use these table/column names in your answer:
- customer:
id, name
- purchase:
id, customer_id, item_id, date
And in more complicated situations, would it be (performance-wise) beneficial to denormalize the database by putting the last purchase into the customer table?
If the (purchase) id is guaranteed to be sorted by date, can the statements be simplified by using something like LIMIT 1?
",https://stackoverflow.com/questions/2111384/sql-join-selecting-the-last-records-in-a-one-to-many-relationship,494,445752.0,14.0,,,2010-01-21 17:29:50,2026-05-05 07:03:45,2020-12-14 17:47:21,,,sql;select;join;indexing;greatest-n-per-group,netvope,8057,250827,registered,true,2111420,,CC BY-SA 4.0,2017-12-12 08:22:03,823,651,9,0,0,5,true,false,false,true,true,true,66,10,false,0.031,0.0011,6148,2010,1,17,Thursday,false,false,false,false,false,true,false
37324,What is the syntax for an inner join in LINQ to SQL?,"I'm writing a LINQ to SQL statement, and I'm after the standard syntax for a normal inner join with an ON clause in C#.
How do you represent the following in LINQ to SQL:
select DealerContact.*
from Dealer
inner join DealerContact on Dealer.DealerID = DealerContact.DealerID
",https://stackoverflow.com/questions/37324/what-is-the-syntax-for-an-inner-join-in-linq-to-sql,490,701471.0,18.0,,,2008-09-01 01:00:24,2024-10-04 07:45:10,2017-08-21 10:31:09,,,c#;.net;sql;linq-to-sql;join,Glenn Slaven,34323,2975,registered,true,37332,,CC BY-SA 3.0,,330,279,2,0,0,5,true,false,false,true,true,true,52,12,true,0.026,0.0007,6655,2008,9,1,Monday,false,false,false,false,true,true,false
861778,How to avoid the "divide by zero" error in SQL?,"I have this error message:
Msg 8134, Level 16, State 1, Line 1 Divide by zero error encountered.
What is the best way to write SQL code so that I will never see this error message again?
I could do either of the following:
- Add a where clause so that my divisor is never zero
Or
- I could add a case expression, so that there is a special treatment for zero.
Is the best way to use a NULLIF clause?
Is there better way, or how can this be enforced?
",https://stackoverflow.com/questions/861778/how-to-avoid-the-divide-by-zero-error-in-sql,489,1323639.0,19.0,,,2009-05-14 06:06:05,2026-06-03 08:27:10,2026-06-03 08:26:41,,,sql;sql-server;sql-server-2008;sql-server-2005;dividebyzeroexception,Henrik Staun Poulsen,14084,106843,registered,true,861791,,CC BY-SA 4.0,2018-05-28 23:13:44,575,452,1,0,0,5,true,false,false,true,true,true,57,10,true,0.014,0.0004,6400,2009,5,6,Thursday,false,false,false,false,false,true,false
4685173,Delete all Duplicate Rows except for One in MySQL?,"How would I delete all duplicate data from a MySQL Table?
For example, with the following data:
SELECT * FROM names;
+----+--------+
| id | name |
+----+--------+
| 1 | google |
| 2 | yahoo |
| 3 | msn |
| 4 | google |
| 5 | google |
| 6 | yahoo |
+----+--------+
I would use SELECT DISTINCT name FROM names; if it were a SELECT query.
How would I do this with DELETE to only remove duplicates and keep just one record of each?
",https://stackoverflow.com/questions/4685173/delete-all-duplicate-rows-except-for-one-in-mysql,485,554767.0,2.0,,,2011-01-13 20:58:38,2020-01-31 06:51:00,2018-03-28 10:37:22,2020-01-31 06:51:01,Duplicate,mysql;sql;duplicates,Highway of Life,24727,463038,registered,true,5016434,,,,539,448,4,0,0,3,true,true,false,true,true,true,50,9,true,0.004,0.0009,5791,2011,1,20,Thursday,false,false,false,false,false,true,false
2404565,What is the difference between PARTITION BY and GROUP BY,"I've been using GROUP BY for all types of aggregate queries over the years. Recently, I've been reverse-engineering some code that uses PARTITION BY to perform aggregations.
In reading through all the documentation I can find about PARTITION BY, it sounds a lot like GROUP BY, maybe with a little extra functionality added in.
Are they two versions of the same general functionality or are they something different entirely?
",https://stackoverflow.com/questions/2404565/what-is-the-difference-between-partition-by-and-group-by,481,800313.0,13.0,,,2010-03-08 20:40:45,2024-08-09 08:27:37,2024-08-09 08:27:37,,,sql;aggregate-functions;window-functions,Mike Mooney,12075,203479,registered,true,2404587,,CC BY-SA 4.0,,508,426,4,0,0,3,true,false,false,true,true,true,56,10,false,0.016,0.0006,6102,2010,3,20,Monday,false,false,false,false,false,true,false
13405572,SQL statement to get column type,"Is there a SQL statement that can return the type of a column in a table?
",https://stackoverflow.com/questions/13405572/sql-statement-to-get-column-type,481,1338308.0,31.0,,,2012-11-15 20:24:27,2025-06-23 17:26:01,,,,sql;schema,daniely,7813,1255620,registered,true,13405667,,CC BY-SA 3.0,2024-10-14 12:31:06,81,74,0,0,0,2,true,false,false,true,true,false,32,6,false,0.023,0.0004,5119,2012,11,20,Thursday,false,false,false,false,false,true,false
5125076,SQL query to select dates between two dates,"I have a start_date and end_date. I want to get the list of dates in between these two dates. Can anyone help me pointing the mistake in my query.
select Date,TotalAllowance
from Calculation
where EmployeeId=1
and Date between 2011/02/25 and 2011/02/27
Here Date is a datetime variable.
",https://stackoverflow.com/questions/5125076/sql-query-to-select-dates-between-two-dates,480,3057418.0,26.0,,,2011-02-26 04:29:16,2025-07-03 16:48:08,2017-09-10 06:50:26,,,sql;sql-server;t-sql;datetime;sql-server-2005,Neeraj,8605,615814,registered,true,5125106,,CC BY-SA 3.0,2017-09-10 15:01:30,384,294,5,0,0,5,true,false,false,true,true,true,43,8,false,0.009,0.0002,5747,2011,2,4,Saturday,true,false,false,false,false,true,false
5836623,Getting "Lock wait timeout exceeded; try restarting transaction" even though I'm not using a transaction,"I'm running the following MySQL UPDATE statement:
mysql> update customer set account_import_id = 1;
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction
I'm not using a transaction, so why would I be getting this error? I even tried restarting my MySQL server and it didn't help.
The table has 406,733 rows.
",https://stackoverflow.com/questions/5836623/getting-lock-wait-timeout-exceeded-try-restarting-transaction-even-though-im,477,1247337.0,30.0,,,2011-04-29 19:40:25,2025-03-10 07:52:18,2022-08-19 13:08:55,,,mysql;sql,Jason Swett,45524,199712,registered,true,5837308,,CC BY-SA 4.0,2019-09-09 05:22:47,395,337,2,0,0,2,true,false,false,true,true,true,118,15,false,0.024,0.0004,5685,2011,4,19,Friday,false,false,false,false,false,true,false
1074212,How can I see the raw SQL queries Django is running?,"Is there a way to show the SQL that Django is running while performing a query?
",https://stackoverflow.com/questions/1074212/how-can-i-see-the-raw-sql-queries-django-is-running,477,348686.0,26.0,,,2009-07-02 13:03:07,2024-06-08 14:36:46,2023-10-28 03:26:38,,,python;sql;django;database;django-database,spence91,80869,15616,registered,true,1074224,,CC BY-SA 4.0,,87,80,0,0,0,5,true,false,false,true,true,true,52,11,true,0.075,0.0014,6351,2009,7,13,Thursday,false,true,false,false,false,true,false
7573590,Can a foreign key be NULL and/or duplicate?,"Please clarify two things for me:
- Can a Foreign key be NULL?
- Can a Foreign key be duplicate?
As fair as I know, NULL shouldn't be used in foreign keys, but in some application of mine I'm able to input NULL in both Oracle and SQL Server, and I don't know why.
",https://stackoverflow.com/questions/7573590/can-a-foreign-key-be-null-and-or-duplicate,475,688628.0,11.0,,,2011-09-27 17:57:45,2023-01-28 05:30:02,2017-03-11 15:30:06,,,sql;sql-server;oracle-database;foreign-keys,Amit,22216,673924,registered,true,7574042,,CC BY-SA 3.0,2019-02-22 13:49:50,331,264,2,0,0,4,true,false,false,true,true,true,43,8,true,0.016,0.0007,5534,2011,9,17,Tuesday,false,false,false,false,false,true,false
1056323,"Difference between numeric, float and decimal in SQL Server","What are the differences between numeric, float and decimal datatypes and which should be used in which situations?
For any kind of financial transaction (e.g. for salary field), which one is preferred and why?
",https://stackoverflow.com/questions/1056323/difference-between-numeric-float-and-decimal-in-sql-server,475,1152837.0,8.0,,,2009-06-29 02:22:15,2025-03-21 10:58:00,2020-06-05 18:33:28,,,sql;sql-server;types,priyanka.sarkar,26732,111663,registered,true,7158770,,CC BY-SA 4.0,,265,212,3,0,0,3,true,false,false,true,true,true,59,9,false,0.007,0.0004,6354,2009,6,2,Monday,false,false,false,false,false,true,false
4101739,SQL Server SELECT into existing table,"I am trying to select some fields from one table and insert them into an existing table from a stored procedure. Here is what I am trying:
SELECT col1, col2
INTO dbo.TableTwo
FROM dbo.TableOne
WHERE col3 LIKE @search_key
I think SELECT ... INTO ... is for temporary tables which is why I get an error that dbo.TableTwo already exists.
How can I insert multiple rows from dbo.TableOne into dbo.TableTwo?
",https://stackoverflow.com/questions/4101739/sql-server-select-into-existing-table,471,674096.0,7.0,,,2010-11-04 21:49:42,2023-06-16 22:15:04,2019-03-07 23:21:08,,,sql;sql-server;t-sql;stored-procedures,Daniel,4907,379284,registered,true,4101761,,CC BY-SA 4.0,,506,409,5,0,0,4,true,false,false,true,true,true,37,6,false,0.01,0.0007,5861,2010,11,21,Thursday,false,false,false,false,false,true,false
3014940,Is there a combination of "LIKE" and "IN" in SQL?,"In SQL I (sadly) often have to use ""LIKE"" conditions due to databases that violate nearly every rule of normalization. I can't change that right now. But that's irrelevant to the question.
Further, I often use conditions like WHERE something in (1,1,2,3,5,8,13,21) for better readability and flexibility of my SQL statements.
Is there any possible way to combine these two things without writing complicated sub-selects?
I want something as easy as WHERE something LIKE ('bla%', '%foo%', 'batz%') instead of this:
WHERE something LIKE 'bla%'
OR something LIKE '%foo%'
OR something LIKE 'batz%'
I'm working with SQl Server and Oracle here but I'm interested if this is possible in any RDBMS at all.
",https://stackoverflow.com/questions/3014940/is-there-a-combination-of-like-and-in-in-sql,469,879684.0,29.0,,,2010-06-10 13:44:16,2024-01-06 17:16:52,2018-09-26 17:29:26,,,sql;sql-server;oracle-database;t-sql;plsql,selfawaresoup,15923,235308,registered,true,3016918,,CC BY-SA 4.0,2019-02-22 13:48:18,802,704,4,0,0,5,true,false,false,true,true,true,69,10,true,0.033,0.0005,6008,2010,6,13,Thursday,false,false,false,false,false,true,false
10177208,"Update a column value, replacing part of a string","I have a table with the following columns in a MySQL database
[id, url]
And the URLs are like:
http://domain1.example/images/img1.jpg
I want to update all the URLs to another domain
http://domain2.example/otherfolder/img1.jpg
keeping the name of the file as is.
What's the query must I run?
",https://stackoverflow.com/questions/10177208/update-a-column-value-replacing-part-of-a-string,468,603404.0,6.0,,,2012-04-16 15:36:37,2022-06-25 11:05:43,2022-06-25 11:04:45,,,mysql;sql,Addev,32471,853836,registered,true,10177250,,CC BY-SA 4.0,2022-03-16 12:37:40,403,296,3,0,0,2,true,false,false,true,true,true,49,9,false,0.01,0.0008,5332,2012,4,15,Monday,false,false,false,false,false,true,false
1492411,How to SELECT FROM stored procedure,"I have a stored procedure that returns rows:
CREATE PROCEDURE MyProc
AS
BEGIN
SELECT * FROM MyTable
END
My actual procedure is a little more complicated, which is why a stored procedure is necessary.
Is it possible to select the output by calling this procedure?
Something like:
SELECT * FROM (EXEC MyProc) AS TEMP
I need to use SELECT TOP X, ROW_NUMBER, and an additional WHERE clause to page my data, and I don't really want to pass these values as parameters.
",https://stackoverflow.com/questions/1492411/how-to-select-from-stored-procedure,466,1384755.0,15.0,,,2009-09-29 13:05:57,2023-05-23 12:29:28,2021-04-07 11:56:44,,,sql;sql-server;sql-server-2005;stored-procedures,jonathanpeppers,26605,132442,registered,true,1492446,,CC BY-SA 4.0,,591,469,5,0,0,4,true,false,false,true,true,true,35,6,false,0.011,0.0003,6262,2009,9,13,Tuesday,false,false,false,false,false,true,false
12475850,SQL query return data from multiple tables,"I would like to know the following:
- how to get data from multiple tables in my database?
- what types of methods are there to do this?
- what are joins and unions and how are they different from one another?
- When should I use each one compared to the others?
I am planning to use this in my (for example - PHP) application, but don't want to run multiple queries against the database, what options do I have to get data from multiple tables in a single query?
Note: I am writing this as I would like to be able to link to a well written guide on the numerous questions that I constantly come across in the PHP queue, so I can link to this for further detail when I post an answer.
The answers cover off the following:
- Part 1 - Joins and Unions
- Part 2 - Subqueries
- Part 3 - Tricks and Efficient Code
- Part 4 - Subqueries in the From Clause
- Part 5 - Mixed Bag of John's Tricks
",https://stackoverflow.com/questions/12475850/sql-query-return-data-from-multiple-tables,466,930699.0,6.0,,,2012-09-18 11:11:39,2018-04-12 20:51:36,2018-04-12 20:51:36,,,mysql;sql;select,Fluffeh,33597,1450077,registered,true,12475851,,CC BY-SA 3.0,2012-09-21 07:53:21,1518,880,0,5,0,3,true,false,false,true,true,true,42,7,false,0.006,0.0005,5177,2012,9,11,Tuesday,false,false,false,false,false,true,false
149772,How to use GROUP BY to concatenate strings in MySQL?,"Basically the question is how to get from this:
foo_id foo_name
1 A
1 B
2 C
to this:
foo_id foo_name
1 A B
2 C
",https://stackoverflow.com/questions/149772/how-to-use-group-by-to-concatenate-strings-in-mysql,465,384144.0,6.0,,,2008-09-29 17:32:45,2020-12-29 00:38:07,2019-08-29 07:56:52,,,sql;mysql;string;aggregate;concatenation,Paweł Hajdan,18662,9403,registered,true,149799,,CC BY-SA 4.0,2014-09-30 11:13:24,193,157,0,0,0,5,true,false,false,true,true,true,52,10,true,0.016,0.0012,6627,2008,9,17,Monday,false,false,false,false,false,true,false
3974683,How to set variable from a SQL query?,"I'm trying to set a variable from a SQL query:
declare @ModelID uniqueidentifer
Select @ModelID = select modelid from models
where areaid = 'South Coast'
Obviously I'm not doing this right as it doesn't work. Can somebody suggest a solution?
",https://stackoverflow.com/questions/3974683/how-to-set-variable-from-a-sql-query,465,1303566.0,10.0,,,2010-10-20 04:02:50,2025-04-07 09:52:21,2025-04-07 09:52:21,,,sql;sql-server;t-sql,Mr Cricket,6013,474018,unregistered,true,,,CC BY-SA 4.0,,282,244,1,0,0,3,false,false,false,true,true,true,37,8,true,0.008,0.0004,5876,2010,10,4,Wednesday,false,false,false,false,false,true,false
2876789,How can I search (case-insensitive) in a column using LIKE wildcard?,"I looked around some and didn't find what I was after so here goes.
SELECT * FROM trees WHERE trees.`title` LIKE '%elm%'
This works fine, but not if the tree is named Elm or ELM etc...
How do I make SQL case insensitive for this wild-card search?
I'm using MySQL 5 and Apache.
",https://stackoverflow.com/questions/2876789/how-can-i-search-case-insensitive-in-a-column-using-like-wildcard,463,633690.0,16.0,,,2010-05-20 18:39:45,2024-08-09 09:17:29,2019-09-17 06:53:35,,,mysql;sql;sql-like;case-insensitive,David Morrow,9464,279558,registered,true,2876820,,CC BY-SA 4.0,,335,283,1,0,0,4,true,false,false,true,true,true,68,11,true,0.025,0.0007,6029,2010,5,18,Thursday,false,false,false,false,false,true,false
439056,Is a view faster than a simple query?,"Is a
select * from myView
faster than the query itself to create the view (in order to have the same resultSet):
select * from ([query to create same resultSet as myView])
?
It's not totally clear to me if the view uses some sort of caching making it faster compared to a simple query.
",https://stackoverflow.com/questions/439056/is-a-view-faster-than-a-simple-query,462,359928.0,16.0,,,2009-01-13 14:09:03,2022-08-12 19:32:17,2012-08-27 18:13:43,,,sql;sql-server;performance,JohnIdol,50466,1311500,registered,true,439061,,CC BY-SA 3.0,2022-08-25 14:20:14,372,296,2,0,0,3,true,false,false,true,true,true,37,8,true,0.044,0.0013,6521,2009,1,14,Tuesday,false,false,false,false,false,true,false
4429319,You can't specify target table for update in FROM clause,"I have a simple mysql table:
CREATE TABLE IF NOT EXISTS `pers` (
`persID` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(35) NOT NULL,
`gehalt` int(11) NOT NULL,
`chefID` int(11) DEFAULT NULL,
PRIMARY KEY (`persID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
INSERT INTO `pers` (`persID`, `name`, `gehalt`, `chefID`) VALUES
(1, 'blb', 1000, 3),
(2, 'as', 1000, 3),
(3, 'chef', 1040, NULL);
I tried to run following update, but I get only the error 1093:
UPDATE pers P
SET P.gehalt = P.gehalt * 1.05
WHERE (P.chefID IS NOT NULL
OR gehalt <
(SELECT (
SELECT MAX(gehalt * 1.05)
FROM pers MA
WHERE MA.chefID = MA.chefID)
AS _pers
))
I searched for the error and found from mysql following page http://dev.mysql.com/doc/refman/5.1/en/subquery-restrictions.html, but it doesn't help me.
What shall I do to correct the sql query?
",https://stackoverflow.com/questions/4429319/you-cant-specify-target-table-for-update-in-from-clause,460,374487.0,12.0,,,2010-12-13 13:36:50,2024-01-22 11:33:08,2010-12-13 17:19:15,,,sql;mysql;mysql-error-1093,CSchulz,11102,390177,registered,true,14302701,,CC BY-SA 2.5,,1059,886,2,1,0,3,true,false,false,true,true,true,60,10,false,0.032,0.0012,5822,2010,12,13,Monday,false,false,false,false,false,true,false
286039,Get record counts for all tables in MySQL database,"Is there a way to get the count of rows in all tables in a MySQL database without running a SELECT count() on each table?
",https://stackoverflow.com/questions/286039/get-record-counts-for-all-tables-in-mysql-database,459,496855.0,24.0,,,2008-11-13 01:41:32,2023-03-12 20:04:21,2018-04-04 12:59:17,,,mysql;sql;rowcount,Mark,4979,37204,registered,true,286048,,CC BY-SA 3.0,2014-03-27 15:24:51,142,122,1,0,0,3,true,false,false,true,true,true,50,9,false,0.048,0.0009,6582,2008,11,1,Thursday,false,false,false,false,false,true,false
8289100,Create unique constraint with null columns,"I have a table with this layout:
CREATE TABLE Favorites (
FavoriteId uuid NOT NULL PRIMARY KEY,
UserId uuid NOT NULL,
RecipeId uuid NOT NULL,
MenuId uuid
);
I want to create a unique constraint similar to this:
ALTER TABLE Favorites
ADD CONSTRAINT Favorites_UniqueFavorite UNIQUE(UserId, MenuId, RecipeId);
However, this will allow multiple rows with the same (UserId, RecipeId), if MenuId IS NULL. I want to allow NULL in MenuId to store a favorite that has no associated menu, but I only want at most one of these rows per user/recipe pair.
The ideas I have so far are:
Use some hard-coded UUID (such as all zeros) instead of null.
However, MenuId has a FK constraint on each user's menus, so I'd then have to create a special "null" menu for every user which is a hassle.
Check for existence of a null entry using a trigger instead.
I think this is a hassle and I like avoiding triggers wherever possible. Plus, I don't trust them to guarantee my data is never in a bad state.
Just forget about it and check for the previous existence of a null entry in the middle-ware or in a insert function, and don't have this constraint.
I'm using Postgres 9.0. Is there any method I'm overlooking?
",https://stackoverflow.com/questions/8289100/create-unique-constraint-with-null-columns,457,276811.0,6.0,,,2011-11-27 21:16:12,2026-01-05 17:32:18,2022-06-03 22:14:24,,,sql;postgresql;database-design;null;referential-integrity,Mike Christensen,91974,392044,registered,true,8289253,,CC BY-SA 4.0,,1471,1216,7,0,0,5,true,false,false,true,true,true,42,6,false,0.022,0.0017,5473,2011,11,21,Sunday,true,false,false,false,false,true,false
20215744,How to create a MySQL hierarchical recursive query?,"I have a MySQL table which is as follows:
id
name
parent_id
19
category1
0
20
category2
19
21
category3
20
22
category4
21
...
...
...
Now, I want to have a single MySQL query to which I simply supply the id [for instance say id=19] then I should get all its child ids [i.e. result should have ids '20,21,22']....
The hierarchy of the children is not known; it can vary....
I know how to do it using a for loop... but how to achieve the same using a single MySQL query?
",https://stackoverflow.com/questions/20215744/how-to-create-a-mysql-hierarchical-recursive-query,457,472195.0,17.0,,,2013-11-26 11:22:57,2024-02-16 00:38:44,2021-01-11 18:53:17,,,mysql;sql;hierarchical-data;recursive-query,Tarun Parswani,4823,3036105,registered,true,,,CC BY-SA 4.0,2016-09-12 15:19:37,1362,490,2,0,0,4,false,false,false,true,true,true,51,8,true,0.036,0.001,4743,2013,11,11,Tuesday,false,false,false,false,false,true,false
141562,SQL to find the number of distinct values in a column,"I can select all the distinct values in a column in the following ways:
SELECT DISTINCT column_name FROM table_name;
SELECT column_name FROM table_name GROUP BY column_name;
But how do I get the row count from that query? Is a subquery required?
",https://stackoverflow.com/questions/141562/sql-to-find-the-number-of-distinct-values-in-a-column,456,831160.0,14.0,,,2008-09-26 19:52:48,2023-04-18 13:38:44,2019-04-05 21:38:22,,,sql;distinct,Christian Oudard,50476,3757,registered,true,141574,,CC BY-SA 4.0,,317,250,2,0,0,2,true,false,false,true,true,true,53,11,false,0.017,0.0005,6630,2008,9,19,Friday,false,false,false,false,false,true,false
93539,What is the difference between Views and Materialized Views in Oracle?,"What is the difference between Views and Materialized Views in Oracle?
",https://stackoverflow.com/questions/93539/what-is-the-difference-between-views-and-materialized-views-in-oracle,456,805501.0,9.0,,,2008-09-18 15:23:18,2025-12-15 12:06:15,2018-12-24 19:58:03,,,sql;oracle-database;view;relational-database;materialized-views,juan,82342,1782,registered,true,93559,,CC BY-SA 4.0,2011-06-14 18:55:38,78,71,0,0,0,5,true,false,false,true,true,true,70,11,true,0.011,0.0006,6638,2008,9,15,Thursday,false,false,false,false,false,true,false
5342440,Reset auto increment counter in postgres,"I would like to force the auto increment field of a table to some value, I tried with this:
ALTER TABLE product AUTO_INCREMENT = 1453
AND
ALTER SEQUENCE product RESTART WITH 1453;
ERROR: relation "your_sequence_name" does not exist
I have a table product with Id and name field
",https://stackoverflow.com/questions/5342440/reset-auto-increment-counter-in-postgres,454,482987.0,18.0,,,2011-03-17 16:55:03,2022-12-29 00:48:28,2022-12-29 00:48:28,,,sql;postgresql;reset;auto-increment,Rad,5031,287964,registered,true,5342503,,CC BY-SA 4.0,,400,292,5,0,0,4,true,false,false,true,true,true,40,6,false,0.037,0.0009,5728,2011,3,16,Thursday,false,false,false,false,false,true,false
3311903,Remove duplicate rows in MySQL,"I have a table with the following fields:
id (Unique)
url (Unique)
title
company
site_id
Now, I need to remove rows having same title, company and site_id. One way to do it will be using the following SQL along with a script (PHP):
SELECT title, site_id, location, id, count( * )
FROM jobs
GROUP BY site_id, company, title, location
HAVING count( * ) >1
After running this query, I can remove duplicates using a server side script.
But, I want to know if this can be done only using SQL query.
",https://stackoverflow.com/questions/3311903/remove-duplicate-rows-in-mysql,454,494711.0,28.0,,,2010-07-22 18:03:56,2023-07-24 01:57:39,2023-07-24 01:57:39,,,mysql;sql;duplicates;subquery;sql-delete,Chetan,5005,161216,registered,true,3312066,,CC BY-SA 4.0,2015-03-17 08:08:32,607,501,3,0,0,5,true,false,false,true,true,true,30,5,false,0.057,0.0009,5966,2010,7,18,Thursday,false,false,false,false,false,true,false
3432,Multiple Updates in MySQL,"I know that you can insert multiple rows at once, is there a way to update multiple rows at once (as in, in one query) in MySQL?
Edit:
For example I have the following
Name id Col1 Col2
Row1 1 6 1
Row2 2 2 3
Row3 3 9 5
Row4 4 16 8
I want to combine all the following Updates into one query
UPDATE table SET Col1 = 1 WHERE id = 1;
UPDATE table SET Col1 = 2 WHERE id = 2;
UPDATE table SET Col2 = 3 WHERE id = 3;
UPDATE table SET Col1 = 10 WHERE id = 4;
UPDATE table SET Col2 = 12 WHERE id = 4;
",https://stackoverflow.com/questions/3432/multiple-updates-in-mysql,454,516893.0,21.0,,,2008-08-06 14:12:09,2025-02-24 13:07:40,2013-06-25 20:03:23,,,mysql;sql;sql-update,Teifion,111981,1384652,registered,true,3466,,CC BY-SA 3.0,,606,537,2,0,0,3,true,false,false,true,true,true,25,4,false,0.041,0.0009,6681,2008,8,14,Wednesday,false,false,false,false,false,true,false
1110998,Get day of week in SQL Server 2005/2008,"If I have a date 01/01/2009, I want to find out what day it was e.g. Monday, Tuesday, etc...
Is there a built-in function for this in SQL Server 2005/2008? Or do I need to use an auxiliary table?
",https://stackoverflow.com/questions/1110998/get-day-of-week-in-sql-server-2005-2008,454,995852.0,13.0,,,2009-07-10 17:49:14,2025-04-23 22:27:23,2019-07-18 15:08:53,,,sql;sql-server;datetime,aaaa,,,does_not_exist,true,1111013,,CC BY-SA 4.0,2015-07-16 04:34:06,211,197,0,0,0,3,true,false,false,true,false,true,39,8,false,0.013,0.0005,6343,2009,7,17,Friday,false,false,false,false,false,true,false
1885630,What's the difference between VARCHAR and CHAR?,"What's the difference between VARCHAR and CHAR in MySQL?
I am trying to store MD5 hashes.
",https://stackoverflow.com/questions/1885630/whats-the-difference-between-varchar-and-char,452,801930.0,17.0,,,2009-12-11 03:32:31,2021-09-22 11:48:01,2009-12-11 03:36:20,,,sql;mysql,steven,13617,174719,registered,true,1885635,,CC BY-SA 2.5,2016-01-21 11:22:19,105,91,0,0,0,2,true,false,false,true,true,true,51,7,true,0.021,0.0006,6189,2009,12,3,Friday,false,false,false,false,false,true,false
1520789,How can I select the first day of a month in SQL?,"How can one select the first day of the month of a given DateTime variable?
I know it's quite easy to do using this kind of code:
select CAST(CAST(YEAR(@mydate) AS VARCHAR(4))
+ '/' + CAST(MONTH(@mydate) AS VARCHAR(2)) + '/01' AS DATETIME)
This is not very elegant, and not very fast either.
Is there a better way to do this?
",https://stackoverflow.com/questions/1520789/how-can-i-select-the-first-day-of-a-month-in-sql,451,1609140.0,35.0,,,2009-10-05 15:30:06,2025-07-10 16:50:08,2022-12-10 17:00:45,,,sql;sql-server;t-sql;sql-server-2008;datetime,Brann,32720,47341,registered,true,1520803,,CC BY-SA 4.0,,387,329,1,0,0,5,true,false,false,true,true,true,49,12,true,0.022,0.0003,6256,2009,10,15,Monday,false,false,false,false,false,true,false
6567831,How to perform OR condition in django queryset?,"I want to write a Django query equivalent to this SQL query:
SELECT * from user where income >= 5000 or income is NULL.
How to construct the Django queryset filter?
User.objects.filter(income__gte=5000, income=0)
This doesn't work, because it ANDs the filters. I want to OR the filters to get union of individual querysets.
",https://stackoverflow.com/questions/6567831/how-to-perform-or-condition-in-django-queryset,451,316876.0,6.0,,,2011-07-04 06:04:16,2023-02-02 08:40:39,2018-06-08 21:56:54,,,python;sql;django;django-queryset;django-orm,Elisa,7153,633650,registered,true,6567918,,CC BY-SA 4.0,,428,333,4,0,0,5,true,false,false,true,true,true,47,8,true,0.019,0.0014,5619,2011,7,6,Monday,false,true,false,false,false,true,false
2536829,Hibernate show real SQL,"if I set
<property name=""show_sql"">true</property>
in my hibernate.cfg.xml configuration file in the console I can see the SQL.
But it's not real SQL... Can I see the SQL code that will be passed directly to database?
Example:
I see
select this_.code from true.employee this_ where this_.code=?
Can I see
select employee.code from employee where employee.code=12
the real SQL?
",https://stackoverflow.com/questions/2536829/hibernate-show-real-sql,446,683288.0,5.0,,,2010-03-29 09:17:21,2017-05-11 17:49:48,2013-03-04 22:08:27,2013-03-15 16:30:08,exact duplicate,java;sql;hibernate;orm,Tommaso Taruffi,9252,109227,registered,true,2538954,,,,558,402,3,0,0,4,true,true,false,true,true,true,23,4,false,0.007,0.0007,6081,2010,3,9,Monday,false,false,false,true,false,true,false
2698151,Entity Framework VS LINQ to SQL VS ADO.NET with stored procedures?,"How would you rate each of them in terms of:
- Performance
- Speed of development
- Neat, intuitive, maintainable code
- Flexibility
- Overall
I like my SQL and so have always been a die-hard fan of ADO.NET and stored procedures but I recently had a play with Linq to SQL and was blown away by how quickly I was writing out my DataAccess layer and have decided to spend some time really understanding either Linq to SQL or EF... or neither?
I just want to check, that there isn't a great flaw in any of these technologies that would render my research time useless. E.g. performance is terrible, it's cool for simple apps but can only take you so far.
Update:
Can you concentrate on EF VS L2S VS SPs rather than ORM VS SPs. I'm mainly interested by EF VS L2S. But am keen to have them compared against stored procs too since plain SQl is something I know a lot about.
",https://stackoverflow.com/questions/2698151/entity-framework-vs-linq-to-sql-vs-ado-net-with-stored-procedures,445,187800.0,5.0,,,2010-04-23 11:36:37,2020-02-21 21:50:45,2010-04-23 13:48:40,2019-02-13 15:55:09,Not suitable for this site,sql;linq-to-sql;entity-framework;ado.net;linq-to-entities,BritishDeveloper,13380,305955,registered,true,2698306,,,,963,864,0,0,0,5,true,true,false,true,true,true,66,11,true,0.027,0.0024,6056,2010,4,11,Friday,false,false,false,false,false,true,false
1915166,How to get the insert ID in JDBC?,"I want to INSERT a record in a database (which is Microsoft SQL Server in my case) using JDBC in Java. At the same time, I want to obtain the insert ID. How can I achieve this using JDBC API?
",https://stackoverflow.com/questions/1915166/how-to-get-the-insert-id-in-jdbc,443,383191.0,16.0,,,2009-12-16 14:57:58,2025-01-10 13:36:45,2017-10-29 03:51:10,,,java;sql;jdbc;insert-id,Satya,8386,232867,registered,true,1915197,,CC BY-SA 3.0,,212,192,1,0,0,4,true,false,false,true,true,true,33,8,true,0.042,0.0012,6184,2009,12,14,Wednesday,false,false,false,true,false,true,false
1144051,Selecting data from two different servers in SQL Server,"How can I select data in the same query from two different databases that are on two different servers in SQL Server?
",https://stackoverflow.com/questions/1144051/selecting-data-from-two-different-servers-in-sql-server,442,1044509.0,17.0,,,2009-07-17 15:34:43,2024-02-14 00:09:18,2021-12-30 16:31:29,,,sql;sql-server;t-sql,Don Of Qau,,,does_not_exist,true,,,CC BY-SA 4.0,,125,118,0,0,0,3,false,false,false,true,false,true,55,9,false,0.016,0.0004,6336,2009,7,15,Friday,false,false,false,false,false,true,false
7296846,"How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?","How do I implement one-to-one, one-to-many and many-to-many relationships while designing tables, with some examples?
",https://stackoverflow.com/questions/7296846/how-to-implement-one-to-one-one-to-many-and-many-to-many-relationships-while-de,439,569767.0,4.0,,,2011-09-04 01:17:36,2026-08-22 22:09:42,2026-08-22 22:09:42,,,sql;database-design;foreign-keys;relational-database;relationship,arsenal,24316,663148,registered,true,7296873,,CC BY-SA 4.0,2019-02-22 13:50:51,125,118,0,0,0,5,true,false,false,true,true,true,95,11,true,0.007,0.0008,5557,2011,9,1,Sunday,true,false,false,false,false,true,false
20971680,SQL Server Insert if not exists,"I want to insert data into my table, but insert only data that doesn't already exist in my database.
Here is my code:
ALTER PROCEDURE [dbo].[EmailsRecebidosInsert]
(@_DE nvarchar(50),
@_ASSUNTO nvarchar(50),
@_DATA nvarchar(30) )
AS
BEGIN
INSERT INTO EmailsRecebidos (De, Assunto, Data)
VALUES (@_DE, @_ASSUNTO, @_DATA)
WHERE NOT EXISTS ( SELECT * FROM EmailsRecebidos
WHERE De = @_DE
AND Assunto = @_ASSUNTO
AND Data = @_DATA);
END
And the error is:
Msg 156, Level 15, State 1, Procedure EmailsRecebidosInsert, Line 11
Incorrect syntax near the keyword 'WHERE'.
",https://stackoverflow.com/questions/20971680/sql-server-insert-if-not-exists,438,1231956.0,14.0,,,2014-01-07 12:30:08,2024-01-29 07:14:51,2023-09-01 22:19:07,,,sql;sql-server;sql-server-2008;stored-procedures;sql-insert,Francisco Carvalho,4503,2792186,registered,true,20971775,,CC BY-SA 4.0,2015-05-02 22:07:35,731,650,1,0,0,5,true,false,false,true,true,true,31,6,false,0.011,0.0004,4701,2014,1,12,Tuesday,false,false,false,false,false,true,false
7917695,Return value after INSERT,"I'm trying to get the key-value back after an INSERT statement.
Example: I've got a table with the attributes name and id. id is a generated value.
INSERT INTO table (name)
VALUES('bob');
Now I want to get the id back in the same step. How is this done?
I'm using Microsoft SQL Server 2008.
",https://stackoverflow.com/questions/7917695/return-value-after-insert,437,875383.0,15.0,,,2011-10-27 14:46:40,2026-08-02 10:25:36,2026-08-02 10:25:36,,,sql;sql-server;sql-server-2008,melbic,12277,270265,registered,true,7917874,,CC BY-SA 4.0,,345,293,1,0,0,3,true,false,false,true,true,true,25,4,false,0.017,0.0005,5504,2011,10,14,Thursday,false,false,false,false,false,true,false
4005409,"Error 1046 No database selected, how to resolve?","Error
SQL query:
--
-- Database: `work`
--
-- --------------------------------------------------------
--
-- Table structure for table `administrators`
--
CREATE TABLE IF NOT EXISTS `administrators` (
`user_id` varchar( 30 ) NOT NULL ,
`password` varchar( 30 ) NOT NULL ) ENGINE = InnoDB DEFAULT CHARSET = latin1;
MySQL said:
#1046 - No database selected
need some help here.
",https://stackoverflow.com/questions/4005409/error-1046-no-database-selected-how-to-resolve,437,1315395.0,21.0,,,2010-10-23 18:19:23,2023-11-23 01:57:12,2023-11-16 01:39:54,,,sql;mysql;database;mysqlcommand;mysql-error-1046,steph,4367,485219,unregistered,true,,,CC BY-SA 4.0,2016-03-10 13:21:28,455,386,2,0,0,5,false,false,false,true,true,true,48,8,true,0.016,0.0003,5873,2010,10,18,Saturday,true,false,false,false,false,true,false
3913620,Get all table names of a particular database by SQL query?,"I am working on application which can deal with multiple database servers like "MySQL" and "MS SQL Server".
I want to get tables' names of a particular database using a general query which should suitable for all database types. I have tried following:
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE='BASE TABLE'
But it is giving table names of all databases of a particular server but I want to get tables names of selected database only. How can I restrict this query to get tables of a particular database?
",https://stackoverflow.com/questions/3913620/get-all-table-names-of-a-particular-database-by-sql-query,436,1822545.0,21.0,,,2010-10-12 10:23:48,2024-05-19 20:36:08,2020-11-26 17:57:16,,,sql;sql-server,Awan,18710,300118,registered,true,3914051,,CC BY-SA 4.0,2016-05-10 12:47:19,595,550,1,0,0,2,true,false,false,true,true,true,58,11,true,0.012,0.0002,5884,2010,10,10,Tuesday,false,false,false,false,false,true,false
6133107,Extract date (yyyy/mm/dd) from a timestamp in PostgreSQL,"I want to extract just the date part from a timestamp in PostgreSQL.
I need it to be a postgresql DATE type so I can insert it into another table that expects a DATE value.
For example, if I have 2011/05/26 09:00:00, I want 2011/05/26
I tried casting, but I only get 2011:
timestamp:date
cast(timestamp as date)
I tried to_char() with to_date():
SELECT to_date(to_char(timestamp, 'YYYY/MM/DD'), 'YYYY/MM/DD')
FROM val3 WHERE id=1;
I tried to make it a function:
CREATE OR REPLACE FUNCTION testing() RETURNS void AS '
DECLARE i_date DATE;
BEGIN
SELECT to_date(to_char(val1, ""YYYY/MM/DD""),""YYYY/MM/DD"")
INTO i_date FROM exampTable WHERE id=1;
INSERT INTO foo(testd) VALUES (i);
END
What is the best way to extract date (yyyy/mm/dd) from a timestamp in PostgreSQL?
",https://stackoverflow.com/questions/6133107/extract-date-yyyy-mm-dd-from-a-timestamp-in-postgresql,435,971993.0,8.0,,,2011-05-26 02:32:22,2022-06-02 14:03:35,2019-02-28 11:17:46,,,sql;postgresql;casting;timestamp,keren,4417,720172,registered,true,6133144,,CC BY-SA 4.0,2020-09-23 16:57:28,1040,790,9,0,0,4,true,false,false,true,true,true,56,8,false,0.008,0.0004,5658,2011,5,2,Thursday,false,false,false,false,false,true,false
319354,What is the equivalent of 'describe table' in SQL Server?,"I have a SQL Server database and I want to know what columns and types it has. I'd prefer to do this through a query rather than using a GUI like Enterprise Manager. Is there a way to do this?
",https://stackoverflow.com/questions/319354/what-is-the-equivalent-of-describe-table-in-sql-server,435,964498.0,24.0,,,2008-11-26 00:22:14,2022-07-08 22:57:00,2021-11-08 15:01:50,,,sql;sql-server;t-sql,dbg,,,does_not_exist,true,,,CC BY-SA 4.0,2022-07-10 18:24:12,200,193,0,0,0,3,false,false,false,true,false,true,65,10,true,0.025,0.0005,6569,2008,11,0,Wednesday,false,false,false,false,false,true,false
3748295,Getting the SQL from a Django QuerySet,"How do I get the SQL that Django will use on the database from a QuerySet object? I'm trying to debug some strange behavior, but I'm not sure what queries are going to the database.
",https://stackoverflow.com/questions/3748295/getting-the-sql-from-a-django-queryset,435,301138.0,6.0,,,2010-09-20 02:11:54,2025-03-20 15:02:24,2021-04-21 23:10:25,,,python;sql;django;django-queryset,exupero,9506,158002,registered,true,3748307,,CC BY-SA 4.0,,189,182,0,0,0,4,true,false,false,true,true,true,38,7,false,0.02,0.0014,5906,2010,9,2,Monday,false,true,false,false,false,true,false
1248423,How do I see active SQL Server connections?,"I am using SQL Server 2008 Enterprise. I want to see any active SQL Server connections, and the related information of all the connections, like from which IP address, connect to which database or something.
Are there existing commands to solve this issue?
",https://stackoverflow.com/questions/1248423/how-do-i-see-active-sql-server-connections,433,1688562.0,8.0,,,2009-08-08 09:26:37,2022-11-05 07:23:38,2019-01-21 21:33:45,,,sql;sql-server;sql-server-2008,George2,46101,63235,registered,true,1248426,,CC BY-SA 4.0,2018-04-14 21:16:03,272,258,0,0,0,3,true,false,false,true,true,true,43,8,true,0.005,0.0003,6314,2009,8,9,Saturday,true,false,false,false,false,true,false
6308594,How can I copy data from one column to another in the same table?,"Is it possible to copy data from column A to column B for all records in a table in SQL?
",https://stackoverflow.com/questions/6308594/how-can-i-copy-data-from-one-column-to-another-in-the-same-table,432,531576.0,5.0,,,2011-06-10 15:30:50,2025-05-26 14:02:44,2016-12-09 23:55:11,,,sql,jonney,4445,715605,unregistered,true,6308620,,CC BY-SA 3.0,2017-04-22 23:23:35,96,89,0,0,0,1,true,false,false,true,true,true,65,14,true,0.009,0.0008,5643,2011,6,15,Friday,false,false,false,false,false,true,false
219569,Best database field type for a URL,"I need to store a url in a MySQL table. What's the best practice for defining a field that will hold a URL with an undetermined length?
",https://stackoverflow.com/questions/219569/best-database-field-type-for-a-url,431,354350.0,11.0,,,2008-10-20 19:29:04,2022-11-10 14:27:56,2010-06-29 16:21:21,,,sql;mysql;database,user22325,,,does_not_exist,true,219664,,CC BY-SA 2.5,,143,136,0,0,0,3,true,false,false,true,false,true,34,7,false,0.031,0.0012,6606,2008,10,19,Monday,false,false,false,false,false,true,false
4434118,Select statement to find duplicates on certain fields,"Can you help me with SQL statements to find duplicates on multiple fields?
For example, in pseudo code:
select count(field1,field2,field3)
from table
where the combination of field1, field2, field3 occurs multiple times
and from the above statement if there are multiple occurrences I would like to select every record except the first one.
",https://stackoverflow.com/questions/4434118/select-statement-to-find-duplicates-on-certain-fields,430,815926.0,9.0,,,2010-12-13 22:30:06,2023-01-19 05:32:42,2014-09-03 09:40:45,,,sql;sql-server;t-sql;sql-server-2008,JOE SKEET,8128,518201,unregistered,true,4434161,,CC BY-SA 3.0,,410,347,1,0,0,4,true,false,false,true,true,true,53,8,false,0.011,0.0005,5822,2010,12,22,Monday,false,false,false,false,false,true,false
1676551,Best way to test if a row exists in a MySQL table,"I'm trying to find out if a row exists in a table. Using MySQL, is it better to do a query like this:
SELECT COUNT(*) AS total FROM table1 WHERE ...
and check to see if the total is non-zero or is it better to do a query like this:
SELECT * FROM table1 WHERE ... LIMIT 1
and check to see if any rows were returned?
In both queries, the WHERE clause uses an index.
",https://stackoverflow.com/questions/1676551/best-way-to-test-if-a-row-exists-in-a-mysql-table,429,505254.0,12.0,,,2009-11-04 20:55:47,2020-11-03 11:48:09,2009-11-04 21:09:12,,,sql;mysql;performance;exists,Bernard Chen,6587,118218,registered,true,1676573,,CC BY-SA 2.5,,447,371,2,0,0,4,true,false,false,true,true,true,49,12,false,0.024,0.0008,6226,2009,11,20,Wednesday,false,false,false,false,false,true,false
2602252,MySQL query String contains,"I've been trying to figure out how I can make a query with MySQL that checks if the value (string $haystack ) in a certain column contains certain data (string $needle), like this:
SELECT *
FROM `table`
WHERE `column`.contains('textABC')
In PHP, the function is called substr, so maybe:
WHERE substr(`column`, 'textABC')=1
",https://stackoverflow.com/questions/2602252/mysql-query-string-contains,428,1335904.0,8.0,,,2010-04-08 17:51:25,2025-12-21 19:41:08,2025-12-21 19:38:10,,,mysql;sql;string-comparison,arik,29620,299711,registered,true,2602274,,CC BY-SA 4.0,2014-03-03 21:41:04,426,325,5,0,0,3,true,false,false,true,true,true,27,4,false,0.006,0.0003,6071,2010,4,17,Thursday,false,false,false,false,false,true,false
1865353,Combining "LIKE" and "IN" for SQL Server,"Is it possible to combine LIKE and IN in a SQL Server-Query?
So, that this query
SELECT * FROM table WHERE column LIKE IN ('Text%', 'Link%', 'Hello%', '%World%')
Finds any of these possible matches:
Text, Textasd, Text hello, Link2, Linkomg, HelloWorld, ThatWorldBusiness
etc...
",https://stackoverflow.com/questions/1865353/combining-like-and-in-for-sql-server,428,1426153.0,5.0,,,2009-12-08 07:51:09,2024-02-12 23:33:03,2014-01-12 16:15:28,2013-07-06 01:24:05,Duplicate,sql;sql-like,F.P,17989,204693,registered,true,1865377,,,,388,286,4,0,0,2,true,true,false,true,true,true,60,7,false,0.004,0.0003,6192,2009,12,7,Tuesday,false,false,false,false,false,true,false
1196415,What datatype to use when storing latitude and longitude data in SQL databases?,"When storing latitude or longitude data in an ANSI SQL compliant database, what datatype would be most appropriate? Should float be used, or decimal, or ...?
I'm aware that Oracle, MySql, and SQL Server have added some special datatypes specifically for handling geo data, but I'm interested in how you would store the information in a ""plain vanilla"" SQL database.
",https://stackoverflow.com/questions/1196415/what-datatype-to-use-when-storing-latitude-and-longitude-data-in-sql-databases,427,374279.0,7.0,,,2009-07-28 20:04:59,2023-12-12 21:11:26,2013-09-11 11:46:15,2015-06-16 08:11:59,Duplicate,sql;database;geocoding;latitude-longitude,dthrasher,42122,19112,registered,true,1196429,,,,407,367,2,0,0,4,true,true,false,true,true,true,79,13,true,0.019,0.0011,6325,2009,7,20,Tuesday,false,false,false,false,false,true,false
1799128,Oracle: If Table Exists,"I'm writing some migration scripts for an Oracle database, and was hoping Oracle had something similar to MySQL's IF EXISTS construct.
Specifically, whenever I want to drop a table in MySQL, I do something like
DROP TABLE IF EXISTS `table_name`;
This way, if the table doesn't exist, the DROP doesn't produce an error, and the script can continue.
Does Oracle have a similar mechanism? I realize I could use the following query to check if a table exists or not
SELECT * FROM dba_tables where table_name = 'table_name';
but the syntax for tying that together with a DROP is escaping me.
",https://stackoverflow.com/questions/1799128/oracle-if-table-exists,426,713378.0,16.0,,,2009-11-25 18:46:10,2023-04-12 23:25:30,2013-12-13 12:59:59,,,sql;oracle-database;sql-drop,Alana Storm,166598,4668,registered,true,1801453,,CC BY-SA 3.0,,718,596,5,0,0,3,true,false,false,true,true,true,23,4,false,0.022,0.0006,6205,2009,11,18,Wednesday,false,false,false,false,false,true,false
5629111,How can I make SQL case sensitive string comparison on MySQL?,"I have a function that returns five characters with mixed case. If I do a query on this string it will return the value regardless of case.
How can I make MySQL string queries case sensitive?
",https://stackoverflow.com/questions/5629111/how-can-i-make-sql-case-sensitive-string-comparison-on-mysql,425,381125.0,12.0,,,2011-04-12 00:36:17,2024-05-02 01:26:30,2012-10-01 15:51:57,,,mysql;sql;interop;case-sensitive;string-comparison,StevenB,4285,686781,unregistered,true,5629129,,CC BY-SA 3.0,,207,193,0,0,0,5,true,false,false,true,true,true,61,11,true,0.031,0.0011,5702,2011,4,0,Tuesday,false,false,false,false,false,true,false
7354588,What's the difference between CharField and TextField in Django?,"The documentation says that CharField() should be used for smaller strings and TextField() should be used for larger strings.
Okay, but where is the line drawn between "small" and "large"? What's going on under the hood here that makes this the case?
",https://stackoverflow.com/questions/7354588/whats-the-difference-between-charfield-and-textfield-in-django,424,218113.0,6.0,,,2011-09-08 21:13:47,2025-03-20 15:07:24,2025-02-04 12:56:58,,,sql;django;database;storage;django-model-field,Jonathan Gleason,4747,925958,registered,true,7354680,,CC BY-SA 4.0,,428,272,2,1,0,5,true,false,false,true,true,true,68,9,true,0.028,0.0019,5553,2011,9,21,Thursday,false,false,false,false,false,true,false
21738408,postgresql list and order tables by size,"How can I list all the tables of a PostgreSQL database and order them by size?
",https://stackoverflow.com/questions/21738408/postgresql-list-and-order-tables-by-size,422,531803.0,18.0,,,2014-02-12 20:02:59,2026-10-16 08:06:16,2020-07-11 01:46:36,,,sql;postgresql;postgresql-9.3,nothing-special-here,13068,418518,registered,true,21738505,,CC BY-SA 4.0,,120,79,0,0,0,3,true,false,false,true,true,true,40,7,false,0.034,0.0008,4665,2014,2,20,Wednesday,false,false,false,false,false,true,false
7392730,What does SQL clause "GROUP BY 1" mean?,"Someone sent me a SQL query where the GROUP BY clause consisted of the statement: GROUP BY 1.
This must be a typo right? No column is given the alias 1. What could this mean? Am I right to assume that this must be a typo?
",https://stackoverflow.com/questions/7392730/what-does-sql-clause-group-by-1-mean,421,269657.0,6.0,,,2011-09-12 19:10:53,2022-07-28 12:58:46,2015-09-12 12:16:49,,,mysql;sql;group-by,Spencer,22678,440266,registered,true,7392753,,CC BY-SA 3.0,,263,223,2,0,0,3,true,false,false,true,true,true,49,8,true,0.022,0.0016,5549,2011,9,19,Monday,false,false,false,false,false,true,false
10138116,Altering column size in SQL Server,"How to change the column size of the salary column in the employee table from numeric(18,0) to numeric(22,5)
",https://stackoverflow.com/questions/10138116/altering-column-size-in-sql-server,416,1270105.0,9.0,,,2012-04-13 09:09:20,2025-02-28 19:42:20,2018-07-07 06:14:20,,,sql;sql-server;database;t-sql;alter-table,Sreedhar Danturthi,7719,653622,registered,true,10138150,,CC BY-SA 4.0,2013-10-27 19:50:45,168,109,4,0,0,5,true,false,false,true,true,true,34,6,false,0.007,0.0003,5335,2012,4,9,Friday,false,false,false,false,false,true,false
814548,How to replace a string in a SQL Server Table Column,"I have a table (SQL Sever) which references paths (UNC or otherwise), but now the path is going to change.
In the path column, I have many records and I need to change just a portion of the path, but not the entire path. And I need to change the same string to the new one, in every record.
How can I do this with a simple update?
",https://stackoverflow.com/questions/814548/how-to-replace-a-string-in-a-sql-server-table-column,415,937146.0,10.0,,,2009-05-02 09:43:52,2019-05-10 13:30:54,2018-03-27 11:08:51,,,sql;sql-server;database;database-administration,Iralda Mitro,7406,98655,registered,true,814551,,CC BY-SA 3.0,2013-12-30 09:41:41,394,334,3,0,0,4,true,false,false,true,true,true,52,11,false,0.011,0.0004,6412,2009,5,9,Saturday,true,false,false,false,false,true,false
12126991,Cast from VARCHAR to INT - MySQL,"My Current Data for
SELECT PROD_CODE FROM `PRODUCT`
is
PROD_CODE
2
5
7
8
22
10
9
11
I have tried all the four queries and none work. (Ref)
SELECT CAST(PROD_CODE) AS INT FROM PRODUCT;
SELECT CAST(PROD_CODE AS INT) FROM PRODUCT;
SELECT CAST(PROD_CODE) AS INTEGER FROM PRODUCT;
SELECT CAST(PROD_CODE AS INTEGER) FROM PRODUCT;
All throw syntax errors such as below:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use
near ') AS INT FROM PRODUCT LIMIT 0, 30' at line 1
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'INTEGER) FROM PRODUCT LIMIT 0, 30' at line 1
What is the right syntax to cast varchar to integer in MySQL?
MySQL Version: 5.5.16
",https://stackoverflow.com/questions/12126991/cast-from-varchar-to-int-mysql,412,1003239.0,2.0,,,2012-08-26 01:26:30,2018-01-22 12:31:44,2012-08-26 01:33:45,,,mysql;sql,Raj,23092,184184,registered,true,12127022,,CC BY-SA 3.0,2018-12-17 00:50:12,1093,836,3,1,0,2,true,false,false,true,true,true,32,7,false,0.002,0.0004,5200,2012,8,1,Sunday,true,false,false,false,false,true,false
367863,Find records from one table which don't exist in another,"I've got the following two tables (in MySQL):
Phone_book
+----+------+--------------+
| id | name | phone_number |
+----+------+--------------+
| 1 | John | 111111111111 |
+----+------+--------------+
| 2 | Jane | 222222222222 |
+----+------+--------------+
Call
+----+------+--------------+
| id | date | phone_number |
+----+------+--------------+
| 1 | 0945 | 111111111111 |
+----+------+--------------+
| 2 | 0950 | 222222222222 |
+----+------+--------------+
| 3 | 1045 | 333333333333 |
+----+------+--------------+
How do I find out which calls were made by people whose phone_number is not in the Phone_book? The desired output would be:
Call
+----+------+--------------+
| id | date | phone_number |
+----+------+--------------+
| 3 | 1045 | 333333333333 |
+----+------+--------------+
",https://stackoverflow.com/questions/367863/find-records-from-one-table-which-dont-exist-in-another,411,627126.0,9.0,,,2008-12-15 09:33:09,2022-11-17 12:07:06,2021-01-14 14:21:25,,,sql;mysql,Philip Morton,132419,21709,registered,true,367865,,CC BY-SA 4.0,2013-12-26 05:04:27,891,803,4,0,0,2,true,false,false,true,true,true,60,10,false,0.014,0.0007,6550,2008,12,9,Monday,false,false,false,false,false,true,false
4034976,Difference between "read commited" and "repeatable read" in SQL Server,"I think the above isolation levels are so alike. Could someone please describe with some nice examples what the main difference is?
",https://stackoverflow.com/questions/4034976/difference-between-read-commited-and-repeatable-read-in-sql-server,410,286833.0,9.0,,,2010-10-27 15:35:34,2023-11-28 04:01:21,2022-12-12 09:26:25,,,sql;sql-server;isolation-level,Fore,6296,482783,registered,true,4036063,,CC BY-SA 4.0,,139,132,0,0,0,3,true,false,false,true,true,true,90,10,false,0.031,0.0014,5869,2010,10,15,Wednesday,false,false,false,false,false,true,false
6346120,How to DROP multiple columns with a single ALTER TABLE statement in SQL Server?,"I would like to write a single SQL command to drop multiple columns from a single table in one ALTER TABLE statement.
From MSDN's ALTER TABLE documentation...
DROP { [CONSTRAINT] constraint_name | COLUMN column_name }
Specifies that constraint_name or column_name is removed from the table. DROP COLUMN is not allowed if the compatibility level is 65 or earlier. Multiple columns and constraints can be listed.
It says that mutliple columns can be listed in the the statement but the syntax doesn't show an optional comma or anything that would even hint at the syntax.
How should I write my SQL to drop multiple columns in one statement (if possible)?
",https://stackoverflow.com/questions/6346120/how-to-drop-multiple-columns-with-a-single-alter-table-statement-in-sql-server,409,674950.0,12.0,,,2011-06-14 15:32:34,2025-01-14 19:18:27,2018-09-07 10:36:18,,,sql;sql-server;t-sql;alter,Jesse Webb,45681,346561,registered,true,6346185,,CC BY-SA 4.0,,861,665,2,1,0,4,true,false,false,true,true,true,79,14,true,0.018,0.0006,5639,2011,6,15,Tuesday,false,false,false,false,false,true,false
14221775,"In Postgresql, force unique on combination of two columns","I would like to set up a table in PostgreSQL such that two columns together must be unique. There can be multiple values of either value, so long as there are not two that share both.
For instance:
CREATE TABLE someTable (
id int PRIMARY KEY AUTOINCREMENT,
col1 int NOT NULL,
col2 int NOT NULL
)
So, col1 and col2 can repeat, but not at the same time. So, this would be allowed (Not including the id)
1 1
1 2
2 1
2 2
but not this:
1 1
1 2
1 1 -- would reject this insert for violating constraints
",https://stackoverflow.com/questions/14221775/in-postgresql-force-unique-on-combination-of-two-columns,409,283879.0,4.0,,,2013-01-08 18:36:14,2021-09-28 19:02:33,2019-12-01 18:25:54,,,sql;postgresql;unique,PearsonArtPhoto,39898,544198,registered,true,14221810,,CC BY-SA 4.0,,645,519,5,0,0,3,true,false,false,true,true,true,57,9,false,0.014,0.0014,5065,2013,1,18,Tuesday,false,false,false,false,false,true,false
19979532,Convert INT to VARCHAR SQL,"I am using Sybase and I am doing a select which returns me a column called ""iftype"", but its type is int and I need to convert into varchar. When I try to do the select without the convert function I get this error:
Error code 257, SQL state 37000: Implicit conversion from datatype 'VARCHAR' to 'INT' is not allowed. Use the CONVERT function to run this query.
I dont know how to implement the function CONVERT. Can anyone help me, please ?
",https://stackoverflow.com/questions/19979532/convert-int-to-varchar-sql,409,1773219.0,6.0,,,2013-11-14 13:54:42,2023-04-19 03:14:26,2015-03-06 20:05:19,,,sql;select;type-conversion;sybase,Murilo,4573,2941390,registered,true,19979620,,CC BY-SA 3.0,,508,449,1,0,0,4,true,false,false,true,true,true,26,5,false,0.003,0.0002,4755,2013,11,13,Thursday,false,false,false,false,false,true,false
659188,SQL Server - stop or break execution of a SQL script,"Is there a way to immediately stop execution of a SQL script in SQL server, like a ""break"" or ""exit"" command?
I have a script that does some validation and lookups before it starts doing inserts, and I want it to stop if any of the validations or lookups fail.
",https://stackoverflow.com/questions/659188/sql-server-stop-or-break-execution-of-a-sql-script,406,533404.0,22.0,,,2009-03-18 17:04:20,2024-09-23 10:28:17,2010-12-02 14:52:54,,,sql;sql-server;scripting;exit,Andy White,88889,60096,registered,true,804811,,CC BY-SA 2.5,2013-10-03 20:35:38,276,262,0,0,0,4,true,false,false,true,true,true,52,11,false,0.041,0.0008,6457,2009,3,17,Wednesday,false,false,false,false,false,true,false
139630,What's the difference between TRUNCATE and DELETE in SQL,"What's the difference between TRUNCATE and DELETE in SQL?
If your answer is platform specific, please indicate that.
",https://stackoverflow.com/questions/139630/whats-the-difference-between-truncate-and-delete-in-sql,406,615982.0,32.0,,,2008-09-26 13:53:31,2024-02-07 13:12:15,2019-06-03 16:39:34,,,sql;database;truncate,David Aldridge,52546,6742,registered,true,139633,,CC BY-SA 4.0,2017-06-19 23:43:57,158,118,2,0,0,3,true,false,false,true,true,true,60,9,false,0.052,0.0007,6630,2008,9,13,Friday,false,false,false,false,false,true,false
39576,Best way to do multi-row insert in Oracle?,"I'm looking for a good way to perform multi-row inserts into an Oracle 9 database. The following works in MySQL but doesn't seem to be supported in Oracle.
INSERT INTO TMP_DIM_EXCH_RT
(EXCH_WH_KEY,
EXCH_NAT_KEY,
EXCH_DATE, EXCH_RATE,
FROM_CURCY_CD,
TO_CURCY_CD,
EXCH_EFF_DATE,
EXCH_EFF_END_DATE,
EXCH_LAST_UPDATED_DATE)
VALUES
(1, 1, '28-AUG-2008', 109.49, 'USD', 'JPY', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),
(2, 1, '28-AUG-2008', .54, 'USD', 'GBP', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),
(3, 1, '28-AUG-2008', 1.05, 'USD', 'CAD', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),
(4, 1, '28-AUG-2008', .68, 'USD', 'EUR', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),
(5, 1, '28-AUG-2008', 1.16, 'USD', 'AUD', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),
(6, 1, '28-AUG-2008', 7.81, 'USD', 'HKD', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008');
",https://stackoverflow.com/questions/39576/best-way-to-do-multi-row-insert-in-oracle,404,947998.0,9.0,,,2008-09-02 13:56:19,2023-05-27 04:03:45,2020-12-07 00:43:08,,,sql;oracle-database;sql-insert;oracle9i,jamz,5381,3734,registered,true,39602,,CC BY-SA 4.0,2016-02-21 07:46:36,929,898,1,0,0,4,true,false,false,true,true,true,42,8,true,0.009,0.0004,6654,2008,9,13,Tuesday,false,false,false,false,false,true,false
18797608,Update multiple rows in same query using PostgreSQL,"I'm looking to update multiple rows in PostgreSQL in one statement. Is there a way to do something like the following?
UPDATE table
SET
column_a = 1 where column_b = '123',
column_a = 2 where column_b = '345'
",https://stackoverflow.com/questions/18797608/update-multiple-rows-in-same-query-using-postgresql,400,330463.0,10.0,,,2013-09-14 02:11:36,2021-10-25 17:37:45,2013-11-23 15:45:40,,,sql;postgresql,newUserNameHere,18107,2229277,registered,true,18799497,,CC BY-SA 3.0,,246,215,1,0,0,2,true,false,false,true,true,true,51,8,false,0.03,0.0012,4816,2013,9,2,Saturday,true,false,false,false,false,true,false
8745051,Postgres manually alter sequence,"I'm trying to set a sequence to a specific value.
SELECT setval('payments_id_seq'), 21, true;
This gives an error:
ERROR: function setval(unknown) does not exist
Using ALTER SEQUENCE doesn't seem to work either?
ALTER SEQUENCE payments_id_seq LASTVALUE 22;
How can this be done?
Ref: https://www.postgresql.org/docs/current/functions-sequence.html
",https://stackoverflow.com/questions/8745051/postgres-manually-alter-sequence,397,513378.0,9.0,,,2012-01-05 15:28:58,2025-02-16 10:12:03,2022-08-20 01:42:23,,,sql;postgresql;ddl;database-sequence,stef,28006,149664,registered,true,8745101,,CC BY-SA 4.0,,589,353,4,1,0,4,true,false,false,true,true,true,32,4,false,0.018,0.0008,5434,2012,1,15,Thursday,false,false,false,false,false,true,false
2411559,how do I query sql for a latest record date for each user,"I have a table that is a collection entries as to when a user was logged on.
username, date, value
--------------------------
brad, 1/2/2010, 1.1
fred, 1/3/2010, 1.0
bob, 8/4/2009, 1.5
brad, 2/2/2010, 1.2
fred, 12/2/2009, 1.3
etc..
How do I create a query that would give me the latest date for each user?
Update: I forgot that I needed to have a value that goes along with the latest date.
",https://stackoverflow.com/questions/2411559/how-do-i-query-sql-for-a-latest-record-date-for-each-user,397,1414523.0,25.0,,,2010-03-09 18:35:38,2024-11-04 11:20:07,2018-08-27 06:18:27,,,sql;greatest-n-per-group,fishhead,6129,247069,registered,true,2411703,,CC BY-SA 4.0,,488,426,1,0,0,2,true,false,false,true,true,true,57,13,false,0.018,0.0003,6101,2010,3,18,Tuesday,false,false,false,false,false,true,false
148398,Are there any disadvantages to always using nvarchar(MAX)?,"In SQL Server 2005, are there any disadvantages to making all character fields nvarchar(MAX) rather than specifying a length explicitly, e.g. nvarchar(255)? (Apart from the obvious one that you aren't able to limit the field length at the database level)
",https://stackoverflow.com/questions/148398/are-there-any-disadvantages-to-always-using-nvarcharmax,397,202018.0,24.0,,,2008-09-29 12:01:11,2024-07-20 01:24:34,2016-02-03 13:05:15,,,sql;sql-server;sql-server-2005,stucampbell,6633,21379,registered,true,148465,,CC BY-SA 3.0,,262,255,0,0,0,3,true,false,false,true,true,true,58,8,true,0.119,0.002,6627,2008,9,12,Monday,false,false,false,false,false,true,false
1498648,Make nulls come last when sorting ascending,"I have a SQL table with a datetime field that can be null.
What is a simple way to sort query results ascending by datetime, but with rows where datetime is null at the end, not at the beginning?
",https://stackoverflow.com/questions/1498648/make-nulls-come-last-when-sorting-ascending,396,421511.0,15.0,,,2009-09-30 14:56:50,2025-07-30 10:35:00,2025-07-30 09:16:09,,,sql;sorting;sql-order-by;sql-null,David Božjak,17817,55377,registered,true,1498667,,CC BY-SA 4.0,2017-03-11 08:22:04,210,196,0,0,0,4,true,false,false,true,true,true,43,7,false,0.036,0.0009,6261,2009,9,14,Wednesday,false,false,false,false,false,true,false
1043265,"What is the difference between SQL, PL-SQL and T-SQL?","What is the difference between SQL, PL-SQL and T-SQL?
Can anyone explain what the differences between these three are, and provide scenarios where each would be relevantly used?
",https://stackoverflow.com/questions/1043265/what-is-the-difference-between-sql-pl-sql-and-t-sql,396,509143.0,6.0,,,2009-06-25 10:54:48,2025-07-15 18:12:08,2015-01-26 11:18:57,2026-06-04 17:42:05,Needs more focus,sql;t-sql;plsql,Goober,13574,99900,registered,true,1043290,,,2012-02-20 07:49:38,193,179,0,0,0,3,true,true,false,true,true,true,53,9,true,0.012,0.0008,6358,2009,6,10,Thursday,false,false,false,false,false,true,false
707335,T-SQL Cast versus Convert,"What is the general guidance on when you should use CAST versus CONVERT? Is there any performance issues related to choosing one versus the other? Is one closer to ANSI-SQL?
",https://stackoverflow.com/questions/707335/t-sql-cast-versus-convert,396,186554.0,7.0,,,2009-04-01 21:05:48,2023-12-07 13:55:26,2012-10-16 16:56:56,,,sql;sql-server;database;t-sql,BuddyJoe,71523,36590,registered,true,707433,,CC BY-SA 3.0,,207,174,2,0,0,4,true,false,false,true,true,true,25,4,false,0.038,0.0021,6443,2009,4,21,Wednesday,false,false,false,false,false,true,false
792294,How to get first character of a string in SQL?,"I have a SQL column with a length of 6. Now want to take only the first char of that column. Is there any string function in SQL to do this?
",https://stackoverflow.com/questions/792294/how-to-get-first-character-of-a-string-in-sql,395,1173098.0,9.0,,,2009-04-27 05:02:48,2025-07-11 15:41:30,2016-08-08 14:32:10,,,sql;sql-server;sql-server-2005,Vinod,33221,20951,registered,true,792302,,CC BY-SA 3.0,2019-11-14 00:51:56,148,141,0,0,0,3,true,false,false,true,true,true,46,10,true,0.008,0.0003,6417,2009,4,5,Monday,false,false,false,false,false,true,false
7718585,How to set auto increment primary key in PostgreSQL?,"I have a table in PostgreSQL with many columns, and I want to add an auto increment primary key.
I tried to create a column called id of type BIGSERIAL but pgadmin responded with an error:
ERROR: sequence must have same owner as table it is linked to.
Does anyone know how to fix this issue? How do I add or create an auto-incrementing primary key in PostgreSQL without recreating the table?
",https://stackoverflow.com/questions/7718585/how-to-set-auto-increment-primary-key-in-postgresql,394,852413.0,10.0,,,2011-10-10 20:56:40,2023-10-01 15:29:12,2020-10-23 12:02:54,,,sql;postgresql;auto-increment,mkn,13361,385275,registered,true,7718734,,CC BY-SA 4.0,,492,396,3,0,0,3,true,false,false,true,true,true,52,9,true,0.012,0.0005,5521,2011,10,20,Monday,false,false,false,false,false,true,false
849149,Connect different Windows User in SQL Server Management Studio (2005 or later),"Is there a way in SQL Server Management Studio 2005 (or later) to change the Windows Authentication user (as you could in SQL Server 2000 and older)?
This is the general connection properties dialog(note the greyed out UID/PWD when selecting Windows Auth):
![]()
FYI - One workaround is to use runas but I'm looking for a solution that will allow me to work with multiple Windows accounts across multiple servers (and across multiple domains).
",https://stackoverflow.com/questions/849149/connect-different-windows-user-in-sql-server-management-studio-2005-or-later,394,414878.0,10.0,,,2009-05-11 17:31:21,2023-07-27 11:19:47,2016-04-22 00:10:58,,,sql;sql-server-2008,Matt P.,3941,104925,registered,true,,,CC BY-SA 3.0,2018-12-10 15:52:03,540,443,1,0,1,2,false,false,false,true,true,true,78,12,false,0.024,0.0009,6403,2009,5,17,Monday,false,false,false,false,false,true,false
28550679,What is the difference between LATERAL JOIN and a subquery in PostgreSQL?,"Since Postgres came out with the ability to do LATERAL joins, I've been reading up on it, since I currently do complex data dumps for my team with lots of inefficient subqueries that make the overall query take four minutes or more.
I understand that LATERAL joins may be able to help me, but even after reading articles like this one from Heap Analytics, I still don't quite follow.
What is the use case for a LATERAL join? What is the difference between a LATERAL join and a subquery?
",https://stackoverflow.com/questions/28550679/what-is-the-difference-between-lateral-join-and-a-subquery-in-postgresql,394,487604.0,5.0,,,2015-02-16 21:29:08,2026-02-19 03:02:15,2024-10-11 10:54:55,,,sql;postgresql;subquery;lateral-join,jdotjdot,17512,1351335,registered,true,28557803,,CC BY-SA 4.0,,665,487,4,1,0,4,true,false,false,true,true,true,73,12,true,0.01,0.0008,4296,2015,2,21,Monday,false,false,false,false,false,true,false
7359702,How do I obtain a Query Execution Plan in SQL Server?,"In Microsoft SQL Server how can I get a query execution plan for a query / stored procedure?
",https://stackoverflow.com/questions/7359702/how-do-i-obtain-a-query-execution-plan-in-sql-server,394,547660.0,13.0,,,2011-09-09 09:37:21,2021-09-30 19:06:17,2020-02-13 13:12:11,,,sql;sql-server;performance;t-sql;sql-execution-plan,Justin,87455,113141,registered,true,7359705,,CC BY-SA 4.0,,100,93,0,0,0,5,true,false,false,true,true,true,53,11,true,0.024,0.0007,5552,2011,9,9,Friday,false,false,false,false,false,true,false
1209181,What represents a double in sql server?,"I have a couple of properties in C# which are double and I want to store these in a table in SQL Server, but noticed there is no double type, so what is best to use, decimal or float?
This will store latitude and longitude values, so I need the most accurate precision.
Thanks for the responses so far.
",https://stackoverflow.com/questions/1209181/what-represents-a-double-in-sql-server,393,520926.0,9.0,,,2009-07-30 20:34:03,2024-07-04 07:12:51,2011-08-13 13:09:43,,,c#;sql;sql-server;sql-server-2005;t-sql,Xaisoft,46923,33690,registered,true,1209190,,CC BY-SA 3.0,2019-07-30 12:53:45,391,305,5,0,0,5,true,false,false,true,true,true,39,7,true,0.017,0.0008,6323,2009,7,20,Thursday,false,false,false,false,true,true,false
7674786,How can I return pivot table output in MySQL?,"If I have a MySQL table looking something like this:
company_name
action
pagecount
Company A
PRINT
3
Company A
PRINT
2
Company A
PRINT
3
Company B
EMAIL
Company B
PRINT
2
Company B
PRINT
2
Company B
PRINT
1
Company A
PRINT
3
Is it possible to run a MySQL query to get output like this:
company_name
EMAIL
PRINT 1 pages
PRINT 2 pages
PRINT 3 pages
CompanyA
0
0
1
3
CompanyB
1
1
2
0
The idea is that pagecount can vary so the output column amount should reflect that, one column for each action/pagecount pair and then number of hits per company_name. I'm not sure if this is called a pivot table but someone suggested that?
",https://stackoverflow.com/questions/7674786/how-can-i-return-pivot-table-output-in-mysql,392,500128.0,10.0,,,2011-10-06 13:20:14,2024-02-29 07:34:36,2024-02-29 07:34:36,,,mysql;sql;pivot;pivot-table,peku,5113,136262,registered,true,7675121,,CC BY-SA 4.0,2015-10-05 09:00:36,1415,660,4,0,0,4,true,false,false,true,true,true,45,9,true,0.02,0.0008,5525,2011,10,13,Thursday,false,false,false,false,false,true,false
175962,Dynamic SELECT TOP @var In SQL Server,"How can I have a dynamic variable setting the amount of rows to return in SQL Server? Below is not valid syntax in SQL Server 2005+:
DECLARE @count int
SET @count = 20
SELECT TOP @count * FROM SomeTable
",https://stackoverflow.com/questions/175962/dynamic-select-top-var-in-sql-server,391,181610.0,6.0,,,2008-10-06 20:05:42,2025-02-18 11:27:13,2025-02-18 11:27:13,,,sql;sql-server;sql-server-2005,Eddie Groves,35224,5769,registered,true,175965,,CC BY-SA 4.0,,237,206,1,0,0,3,true,false,false,true,true,true,37,7,false,0.033,0.0022,6620,2008,10,20,Monday,false,false,false,false,false,true,false
5658457,Not equal <> != operator on NULL,"Could someone please explain the following behavior in SQL?
SELECT * FROM MyTable WHERE MyColumn != NULL (0 Results)
SELECT * FROM MyTable WHERE MyColumn <> NULL (0 Results)
SELECT * FROM MyTable WHERE MyColumn IS NOT NULL (568 Results)
",https://stackoverflow.com/questions/5658457/not-equal-operator-on-null,390,632219.0,10.0,,,2011-04-14 04:15:31,2022-05-19 12:33:54,2014-10-09 12:24:23,,,sql;sql-server;t-sql;null,Maxim Gershkovich,47477,314661,registered,true,5658472,,CC BY-SA 3.0,,276,245,1,0,0,4,true,false,false,true,true,true,38,7,false,0.016,0.0006,5700,2011,4,4,Thursday,false,false,false,false,false,true,false
2446764,Update statement with inner join on Oracle,"I have a query which works fine in MySQL, but when I run it on Oracle I get the following error:
SQL Error: ORA-00933: SQL command not properly ended
00933. 00000 - ""SQL command not properly ended""
The query is:
UPDATE table1
INNER JOIN table2 ON table1.value = table2.DESC
SET table1.value = table2.CODE
WHERE table1.UPDATETYPE='blah';
",https://stackoverflow.com/questions/2446764/update-statement-with-inner-join-on-oracle,389,1126498.0,16.0,,,2010-03-15 11:40:21,2025-08-20 08:48:18,2018-11-20 09:39:20,,,sql;oracle-database;inner-join;ora-00933,user169743,4307,169743,registered,true,2446834,,CC BY-SA 4.0,2017-09-18 06:11:14,423,348,1,0,0,4,true,false,false,true,true,true,42,7,false,0.014,0.0003,6095,2010,3,11,Monday,false,false,false,false,false,true,false
28156795,How to find duplicate records in PostgreSQL,"I have a PostgreSQL database table called ""user_links"" which currently allows the following duplicate fields:
year, user_id, sid, cid
The unique constraint is currently the first field called ""id"", however I am now looking to add a constraint to make sure the year, user_id, sid and cid are all unique but I cannot apply the constraint because duplicate values already exist which violate this constraint.
Is there a way to find all duplicates?
",https://stackoverflow.com/questions/28156795/how-to-find-duplicate-records-in-postgresql,388,535326.0,9.0,,,2015-01-26 18:55:46,2023-08-25 16:35:23,2017-04-14 17:18:47,,,sql;postgresql;duplicates,John,7297,2533510,registered,true,28157109,,CC BY-SA 3.0,,546,449,5,0,0,3,true,false,false,true,true,true,43,7,false,0.017,0.0007,4317,2015,1,18,Monday,false,false,false,false,false,true,false
34708509,How to use RETURNING with ON CONFLICT in PostgreSQL?,"I have the following UPSERT in PostgreSQL 9.5:
INSERT INTO chats (""user"", ""contact"", ""name"")
VALUES ($1, $2, $3),
($2, $1, NULL)
ON CONFLICT(""user"", ""contact"") DO NOTHING
RETURNING id;
If there are no conflicts it returns something like this:
----------
| id |
----------
1 | 50 |
----------
2 | 51 |
----------
But if there are conflicts it doesn't return any rows:
----------
| id |
----------
I want to return the new id columns if there are no conflicts or return the existing id columns of the conflicting columns.
Can this be done? If so, how?
",https://stackoverflow.com/questions/34708509/how-to-use-returning-with-on-conflict-in-postgresql,387,253970.0,12.0,,,2016-01-10 17:25:52,2026-07-17 21:42:19,2018-01-21 14:23:34,,,sql;postgresql;upsert;sql-returning,zolamk,6647,5288071,registered,true,37543015,,CC BY-SA 3.0,,847,605,5,0,0,4,true,false,false,true,true,true,52,9,true,0.047,0.0015,3968,2016,1,17,Sunday,true,false,false,false,false,true,false
8660203,How to check for Is not Null And Is not Empty string in SQL server?,"How can we check in a SQL Server WHERE condition whether the column is not null and not the empty string ('')?
",https://stackoverflow.com/questions/8660203/how-to-check-for-is-not-null-and-is-not-empty-string-in-sql-server,385,1075114.0,10.0,,,2011-12-28 19:13:20,2023-09-26 07:10:48,2016-11-13 06:42:47,,,sql;sql-server,user993935,4003,993935,registered,true,8660220,,CC BY-SA 3.0,,145,112,2,0,0,2,true,false,false,true,true,true,67,15,true,0.009,0.0004,5442,2011,12,19,Wednesday,false,false,false,false,false,true,false
10195451,join 3 tables in a view,"A table contains information for Students who are applying to live on this college campus. Another table lists the Hall Preferences (3 of them) for each Student.
I INNER JOIN the tables with their information and preferences:
John Doe | 923423 | Incoming Student | 005
005 is the HallID.
Each of these preferences is an ID Number that has a corresponding Hall Name in a third table that contains a HallID and HallName.
Desired result:
John Doe | 923423 | Incoming Student | Foley Hall
Foley Hall is instead of 005.
I have:
SELECT
s.StudentID, s.FName,
s.LName, s.Gender, s.BirthDate, s.Email,
r.HallPref1, r.HallPref2, r.HallPref3
FROM
dbo.StudentSignUp AS s
INNER JOIN RoomSignUp.dbo.Incoming_Applications_Current AS r
ON s.StudentID = r.StudentID
INNER JOIN HallData.dbo.Halls AS h
ON r.HallPref1 = h.HallID
",https://stackoverflow.com/questions/10195451/join-3-tables-in-a-view,385,1625790.0,12.0,,,2012-04-17 16:45:29,2024-12-04 10:24:40,2024-12-04 10:24:40,,,sql;join;inner-join,Bob Sanders,4377,1241677,registered,true,10195633,,CC BY-SA 4.0,2019-07-17 07:04:25,1053,841,10,0,0,3,true,false,false,true,true,true,23,6,false,0.007,0.0002,5331,2012,4,16,Tuesday,false,false,false,false,false,true,false
758945,What's the fastest way to do a bulk insert into Postgres?,"I need to programmatically insert tens of millions of records into a Postgres database. Presently, I'm executing thousands of insert statements in a single query.
Is there a better way to do this, some bulk insert statement I do not know about?
",https://stackoverflow.com/questions/758945/whats-the-fastest-way-to-do-a-bulk-insert-into-postgres,385,610283.0,11.0,,,2009-04-17 03:50:46,2022-12-17 11:25:12,2022-12-17 11:25:12,2024-01-05 13:35:56,Opinion-based,sql;database;postgresql;sql-insert;bulkinsert,Ash,26060,11194,registered,true,758956,,,,259,245,0,0,0,5,true,true,false,true,true,true,61,11,true,0.018,0.0006,6427,2009,4,3,Friday,false,false,false,false,false,true,false
15220411,Entity Framework. Delete all rows in table,"How can I quickly remove all rows in the table using Entity Framework?
I am currently using:
var rows = from o in dataDb.Table
select o;
foreach (var row in rows)
{
dataDb.Table.Remove(row);
}
dataDb.SaveChanges();
However, it takes a long time to execute.
Are there any alternatives?
",https://stackoverflow.com/questions/15220411/entity-framework-delete-all-rows-in-table,384,419644.0,26.0,,,2013-03-05 09:39:53,2025-03-26 12:38:19,2021-02-13 07:32:10,,,c#;sql;linq;entity-framework,Zhenia,4229,1794316,registered,true,,,CC BY-SA 4.0,,390,301,1,0,0,4,false,false,false,true,true,true,42,7,false,0.062,0.0009,5009,2013,3,9,Tuesday,false,false,false,false,true,true,false
13999817,Reason for Column is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause,"I got an error -
Column 'Employee.EmpID' is invalid in the select list because it is
not contained in either an aggregate function or the GROUP BY clause.
select loc.LocationID, emp.EmpID
from Employee as emp full join Location as loc
on emp.LocationID = loc.LocationID
group by loc.LocationID
This situation fits into the answer given by Bill Karwin.
correction for above, fits into answer by ExactaBox -
select loc.LocationID, count(emp.EmpID) -- not count(*), don't want to count nulls
from Employee as emp full join Location as loc
on emp.LocationID = loc.LocationID
group by loc.LocationID
ORIGINAL QUESTION -
For the SQL query -
select *
from Employee as emp full join Location as loc
on emp.LocationID = loc.LocationID
group by (loc.LocationID)
I don't understand why I get this error. All I want to do is join the tables and then group all the employees in a particular location together.
I think I have a partial explanation for my own question. Tell me if its ok -
To group all employees that work in the same location we have to first mention the LocationID.
Then, we cannot/do not mention each employee ID next to it. Rather, we mention the total number of employees in that location, ie we should SUM() the employees working in that location. Why do we do it the latter way, i am not sure.
So, this explains the ""it is not contained in either an aggregate function"" part of the error.
What is the explanation for the GROUP BY clause part of the error ?
",https://stackoverflow.com/questions/13999817/reason-for-column-is-invalid-in-the-select-list-because-it-is-not-contained-in-e,384,1178178.0,4.0,,,2012-12-22 03:31:35,2020-01-31 06:45:21,2018-05-11 22:29:27,2020-01-31 06:45:21,Duplicate,sql;group-by;aggregate-functions,david blaine,5961,1667147,registered,true,13999903,,,,1749,1503,4,0,0,3,true,true,false,true,true,true,130,24,false,0.003,0.0003,5082,2012,12,3,Saturday,true,false,false,false,false,true,false
2560946,Postgresql GROUP_CONCAT equivalent?,"I have a table and I'd like to pull one row per id with field values concatenated.
In my table, for example, I have this:
TM67 | 4 | 32556
TM67 | 9 | 98200
TM67 | 72 | 22300
TM99 | 2 | 23009
TM99 | 3 | 11200
And I'd like to output:
TM67 | 4,9,72 | 32556,98200,22300
TM99 | 2,3 | 23009,11200
In MySQL I was able to use the aggregate function GROUP_CONCAT, but that doesn't seem to work here... Is there an equivalent for PostgreSQL, or another way to accomplish this?
",https://stackoverflow.com/questions/2560946/postgresql-group-concat-equivalent,383,339146.0,9.0,,,2010-04-01 14:09:53,2025-08-07 19:03:44,2016-10-17 08:53:09,,,sql;postgresql;group-concat;string-aggregation,TwixxyKit,11003,287813,unregistered,true,2561297,,CC BY-SA 3.0,,570,481,3,0,0,4,true,false,false,true,true,true,35,3,true,0.027,0.0011,6078,2010,4,14,Thursday,false,false,false,false,false,true,false
451415,Simulating group_concat MySQL function in Microsoft SQL Server 2005?,"I'm trying to migrate a MySQL-based app over to Microsoft SQL Server 2005 (not by choice, but that's life).
In the original app, we used almost entirely ANSI-SQL compliant statements, with one significant exception -- we used MySQL's group_concat function fairly frequently.
group_concat, by the way, does this: given a table of, say, employee names and projects...
SELECT empName, projID FROM project_members;
returns:
ANDY | A100
ANDY | B391
ANDY | X010
TOM | A100
TOM | A510
... and here's what you get with group_concat:
SELECT
empName, group_concat(projID SEPARATOR ' / ')
FROM
project_members
GROUP BY
empName;
returns:
ANDY | A100 / B391 / X010
TOM | A100 / A510
So what I'd like to know is: Is it possible to write, say, a user-defined function in SQL Server which emulates the functionality of group_concat?
I have almost no experience using UDFs, stored procedures, or anything like that, just straight-up SQL, so please err on the side of too much explanation :)
",https://stackoverflow.com/questions/451415/simulating-group-concat-mysql-function-in-microsoft-sql-server-2005,383,197057.0,10.0,,,2009-01-16 18:14:52,2023-07-13 18:11:57,2019-02-13 12:52:00,,,sql;sql-server;sql-server-2005;string-aggregation,DanM,7227,47450,registered,true,451441,,CC BY-SA 4.0,2013-04-25 09:03:34,1231,1031,7,0,0,4,true,false,false,true,true,true,68,9,true,0.051,0.0019,6518,2009,1,18,Friday,false,false,false,false,false,true,false
848872,Select n random rows from SQL Server table,"I've got a SQL Server table with about 50,000 rows in it. I want to select about 5,000 of those rows at random. I've thought of a complicated way, creating a temp table with a ""random number"" column, copying my table into that, looping through the temp table and updating each row with RAND(), and then selecting from that table where the random number column < 0.1. I'm looking for a simpler way to do it, in a single statement if possible.
This article suggest using the NEWID() function. That looks promising, but I can't see how I could reliably select a certain percentage of rows.
Anybody ever do this before? Any ideas?
",https://stackoverflow.com/questions/848872/select-n-random-rows-from-sql-server-table,379,526826.0,19.0,,,2009-05-11 16:19:11,2024-07-19 07:23:28,2013-09-30 04:06:16,,,sql;sql-server;random,John M Gant,19376,44586,registered,true,848908,,CC BY-SA 3.0,2012-06-09 11:07:31,777,632,2,1,0,3,true,false,false,true,true,true,42,8,false,0.036,0.0007,6403,2009,5,16,Monday,false,false,false,false,false,true,false
5125609,How to select date without time in SQL,"When I select date in SQL it is returned as 2011-02-25 21:17:33.933. But I need only the Date part, that is 2011-02-25. How can I do this?
",https://stackoverflow.com/questions/5125609/how-to-select-date-without-time-in-sql,378,1036468.0,22.0,,,2011-02-26 07:17:03,2023-11-29 20:46:53,2011-11-17 02:41:49,2025-03-25 09:51:16,Duplicate,sql;sql-server;sql-server-2005,Neeraj,8605,615814,registered,true,5125767,,,,173,140,2,0,0,3,true,true,false,true,true,true,38,8,false,0.021,0.0004,5747,2011,2,7,Saturday,true,false,false,false,false,true,false
543580,What are the benefits of using = instead of LIKE in SQL?,"When using SQL, are there any benefits of using = in a WHERE clause instead of LIKE?
Without any special operators, LIKE and = are the same, right?
",https://stackoverflow.com/questions/543580/what-are-the-benefits-of-using-instead-of-like-in-sql,376,454453.0,16.0,,,2009-02-12 21:57:40,2026-08-21 10:29:51,2026-04-17 18:24:30,,,sql;performance;sql-like,Travis,12419,307338,registered,true,2336940,,CC BY-SA 4.0,,228,149,5,0,0,3,true,false,false,true,true,true,56,12,true,0.035,0.0008,6491,2009,2,21,Thursday,false,false,false,false,false,true,false
8470813,How do I check if a column is empty or null in MySQL?,"I have a column in a table which might contain null or empty values. How do I check if a column is empty or null in the rows present in a table?
(e.g. null or '' or ' ' or ' ' and ...)
",https://stackoverflow.com/questions/8470813/how-do-i-check-if-a-column-is-empty-or-null-in-mysql,375,1107021.0,22.0,,,2011-12-12 06:49:36,2023-03-14 03:52:27,2019-11-29 18:22:36,,,mysql;sql,priya,27177,1004443,registered,true,8470865,,CC BY-SA 4.0,,224,193,1,0,0,2,true,false,false,true,true,true,53,13,true,0.02,0.0003,5458,2011,12,6,Monday,false,false,false,false,false,true,false
22483555,PostgreSQL: Give all permissions to a user on a PostgreSQL database,"I would like to give a user all the permissions on a database without making it an admin.
The reason why I want to do that is that at the moment DEV and PROD are different DBs on the same cluster so I don't want a user to be able to change production objects but it must be able to change objects on DEV.
I tried:
grant ALL on database MY_DB to group MY_GROUP;
but it doesn't seem to give any permission.
Then I tried:
grant all privileges on schema MY_SCHEMA to group MY_GROUP;
and it seems to give me permission to create objects but not to query\delete objects on that schema that belong to other users
I could go on by giving USAGE permission to the user on MY_SCHEMA but then it would complain about not having permissions on the table ...
So I guess my question is: is there any easy way of giving all the permissions to a user on a DB?
I'm working on PostgreSQL 8.1.23.
",https://stackoverflow.com/questions/22483555/postgresql-give-all-permissions-to-a-user-on-a-postgresql-database,373,897001.0,11.0,,,2014-03-18 15:16:35,2026-02-21 05:13:51,2021-03-09 19:11:44,,,sql;postgresql;ddl;privileges;sql-grant,Diego,36626,1169020,registered,true,22486012,,CC BY-SA 4.0,,983,879,2,0,0,5,true,false,false,true,true,true,67,11,false,0.012,0.0004,4631,2014,3,15,Tuesday,false,false,false,false,false,true,false
5375634,Can I use multiple "with"?,"Just for example:
With DependencedIncidents AS
(
SELECT INC.[RecTime],INC.[SQL] AS [str] FROM
(
SELECT A.[RecTime] As [RecTime],X.[SQL] As [SQL] FROM [EventView] AS A
CROSS JOIN [Incident] AS X
WHERE
patindex('%' + A.[Col] + '%', X.[SQL]) > 0
) AS INC
)
With lalala AS
(
SELECT INC.[RecTime],INC.[SQL] AS [str] FROM
(
SELECT A.[RecTime] As [RecTime],X.[SQL] As [SQL] FROM [EventView] AS A
CROSS JOIN [Incident] AS X
WHERE
patindex('%' + A.[Col] + '%', X.[SQL]) > 0
) AS INC
)
...doesn't work. ""Error near With"".
Also, I want to use first with inside second with. Is it real or I need to use temp tables?
",https://stackoverflow.com/questions/5375634/can-i-use-multiple-with,371,456110.0,3.0,,,2011-03-21 09:13:22,2023-02-16 11:31:32,2019-12-13 22:35:06,,,sql;t-sql;sql-server-2008,cnd,34026,238232,registered,true,5375695,,CC BY-SA 4.0,,775,730,1,0,0,3,true,false,false,true,true,true,36,5,true,0.007,0.0008,5724,2011,3,9,Monday,false,false,false,false,false,true,false
13113096,How to round an average to 2 decimal places in PostgreSQL?,"I am using PostgreSQL via the Ruby gem 'sequel'.
I'm trying to round to two decimal places.
Here's my code:
SELECT ROUND(AVG(some_column),2)
FROM table
I get the following error:
PG::Error: ERROR: function round(double precision, integer) does
not exist (Sequel::DatabaseError)
I get no error when I run the following code:
SELECT ROUND(AVG(some_column))
FROM table
Does anyone know what I am doing wrong?
",https://stackoverflow.com/questions/13113096/how-to-round-an-average-to-2-decimal-places-in-postgresql,371,689499.0,8.0,,,2012-10-28 21:15:11,2022-04-01 05:41:59,2020-02-09 22:21:07,,,sql;ruby;postgresql;sequel,user1626730,4243,1626730,registered,true,13113623,,CC BY-SA 4.0,2020-06-05 00:28:11,538,424,3,0,0,4,true,false,false,true,true,true,58,11,true,0.012,0.0005,5137,2012,10,21,Sunday,true,false,false,false,false,true,false
8295131,Best practices for SQL varchar column length,"Every time is set up a new SQL table or add a new varchar column to an existing table, I am wondering one thing: what is the best value for the length.
So, lets say, you have a column called name of type varchar. So, you have to choose the length. I cannot think of a name > 20 chars, but you will never know. But instead of using 20, I always round up to the next 2^n number. In this case, I would choose 32 as the length. I do that, because from an computer scientist point of view, a number 2^n looks more even to me than other numbers and I'm just assuming that the architecture underneath can handle those numbers slightly better than others.
On the other hand, MSSQL server for example, sets the default length value to 50, when you choose to create a varchar column. That makes me thinking about it. Why 50? is it just a random number, or based on average column length, or what?
It could also be - or probably is - that different SQL servers implementations (like MySQL, MSSQL, Postgres, ...) have different best column length values.
",https://stackoverflow.com/questions/8295131/best-practices-for-sql-varchar-column-length,371,376840.0,8.0,,,2011-11-28 11:26:43,2019-07-05 11:56:22,2014-05-30 14:41:06,2020-02-26 22:47:54,Opinion-based,mysql;sql;sql-server;postgresql,esskar,11020,282144,registered,true,8295254,,,,1140,1047,5,0,0,4,true,true,false,true,true,true,44,7,false,0.021,0.001,5472,2011,11,11,Monday,false,false,false,false,false,true,false
512451,How can I add a column that doesn't allow nulls in a Postgresql database?,"I'm adding a new, ""NOT NULL"" column to my Postgresql database using the following query (sanitized for the Internet):
ALTER TABLE mytable ADD COLUMN mycolumn character varying(50) NOT NULL;
Each time I run this query, I receive the following error message:
ERROR: column ""mycolumn"" contains null values
I'm stumped. Where am I going wrong?
NOTE: I'm using pgAdmin III (1.8.4) primarily, but I received the same error when I ran the SQL from within Terminal.
",https://stackoverflow.com/questions/512451/how-can-i-add-a-column-that-doesnt-allow-nulls-in-a-postgresql-database,370,395838.0,8.0,,,2009-02-04 17:33:34,2024-11-18 06:26:37,2020-08-17 01:38:51,,,sql;postgresql;alter-table,Huuuze,16687,10040,registered,true,512485,,CC BY-SA 4.0,,570,469,2,0,0,3,true,false,false,true,true,true,77,14,true,0.02,0.0009,6499,2009,2,17,Wednesday,false,false,false,false,false,true,false
12102200,How do you get the rows that contain the max value for each grouped set in MySQL,"I've seen some overly-complicated variations on this question, and none with a good answer. I've tried to put together the simplest possible example:
Given a table like that below, with person, group, and age columns, how would you get the oldest person in each group? (A tie within a group should give the first alphabetical result)
Person
Group
Age
Bob
1
32
Jill
1
34
Shawn
1
42
Jake
2
29
Paul
2
36
Laura
2
39
Desired result set:
Person
Group
Age
Shawn
1
42
Laura
2
39
",https://stackoverflow.com/questions/12102200/how-do-you-get-the-rows-that-contain-the-max-value-for-each-grouped-set-in-mysql,369,414139.0,21.0,,,2012-08-24 01:36:50,2026-03-16 11:44:17,2026-03-16 11:44:17,,,mysql;sql;greatest-n-per-group,Yarin,186649,165673,registered,true,12102288,,CC BY-SA 4.0,2019-07-23 19:42:39,1080,503,0,0,0,3,true,false,false,true,true,true,80,17,false,0.051,0.0009,5202,2012,8,1,Friday,false,false,false,false,false,true,false
2366854,Can table columns with a Foreign Key be NULL?,"I have a table which has several ID columns to other tables.
I want a foreign key to force integrity only if I put data in there. If I do an update at a later time to populate that column, then it should also check the constraint.
(This is likely database server dependant, I'm using MySQL & InnoDB table type)
I believe this is a reasonable expectation, but correct me if I am wrong.
",https://stackoverflow.com/questions/2366854/can-table-columns-with-a-foreign-key-be-null,369,406652.0,7.0,,,2010-03-02 21:20:07,2024-02-25 10:03:04,2018-11-27 12:06:01,,,sql;mysql;database;foreign-keys,bender,3896,267392,registered,true,2366979,,CC BY-SA 4.0,,437,392,0,0,0,4,true,false,false,true,true,true,45,9,true,0.017,0.0009,6108,2010,3,21,Tuesday,false,false,false,false,false,true,false
42385099,#1273 – Unknown collation: ‘utf8mb4_unicode_520_ci’,"I have a WordPress website on my local WAMP server. But when I upload its database to live server, I get error
#1273 – Unknown collation: ‘utf8mb4_unicode_520_ci’
",https://stackoverflow.com/questions/42385099/1273-unknown-collation-utf8mb4-unicode-520-ci,368,810803.0,25.0,,,2017-02-22 07:23:15,2025-02-06 23:51:27,2023-03-07 09:57:50,,,mysql;sql;wordpress;collation,Shishil Patel,4047,4543797,registered,true,42385164,,CC BY-SA 4.0,2018-06-15 00:32:58,212,164,1,0,0,4,true,false,false,true,true,true,51,5,false,0.031,0.0005,3559,2017,2,7,Wednesday,false,false,false,false,false,true,false
1483732,SET NOCOUNT ON usage,"Inspired by this question where there are differing views on SET NOCOUNT...
Should we use SET NOCOUNT ON for SQL Server? If not, why not?
What it does Edit 6, on 22 Jul 2011
It suppresses the ""xx rows affected"" message after any DML. This is a resultset and when sent, the client must process it. It's tiny, but measurable (see answers below)
For triggers etc, the client will receive multiple ""xx rows affected"" and this causes all manner of errors for some ORMs, MS Access, JPA etc (see edits below)
Background:
General accepted best practice (I thought until this question) is to use SET NOCOUNT ON in triggers and stored procedures in SQL Server. We use it everywhere and a quick google shows plenty of SQL Server MVPs agreeing too.
MSDN says this can break a .net SQLDataAdapter.
Now, this means to me that the SQLDataAdapter is limited to utterly simply CRUD processing because it expects the ""n rows affected"" message to match. So, I can't use:
- IF EXISTS to avoid duplicates (no rows affected message) Note: use with caution
- WHERE NOT EXISTS (less rows then expected
- Filter out trivial updates (eg no data actually changes)
- Do any table access before (such as logging)
- Hide complexity or denormlisation
- etc
In the question marc_s (who knows his SQL stuff) says do not use it. This differs to what I think (and I regard myself as somewhat competent at SQL too).
It's possible I'm missing something (feel free to point out the obvious), but what do you folks out there think?
Note: it's been years since I saw this error because I don't use SQLDataAdapter nowadays.
Edits after comments and questions:
Edit: More thoughts...
We have multiple clients: one may use a C# SQLDataAdaptor, another may use nHibernate from Java. These can be affected in different ways with SET NOCOUNT ON.
If you regard stored procs as methods, then it's bad form (anti-pattern) to assume some internal processing works a certain way for your own purposes.
Edit 2: a trigger breaking nHibernate question, where SET NOCOUNT ON can not be set
(and no, it's not a duplicate of this)
Edit 3: Yet more info, thanks to my MVP colleague
- KB 240882, issue causing disconnects on SQL 2000 and earlier
- Demo of performance gain
Edit 4: 13 May 2011
Breaks Linq 2 SQL too when not specified?
Edit 5: 14 Jun 2011
Breaks JPA, stored proc with table variables: Does JPA 2.0 support SQL Server table variables?
Edit 6: 15 Aug 2011
The SSMS ""Edit rows"" data grid requires SET NOCOUNT ON: Update trigger with GROUP BY
Edit 7: 07 Mar 2013
More in depth details from @RemusRusanu:
Does SET NOCOUNT ON really make that much of a performance difference
",https://stackoverflow.com/questions/1483732/set-nocount-on-usage,367,327944.0,17.0,,,2009-09-27 14:52:29,2024-05-14 07:31:07,2017-05-23 11:47:26,,,sql;sql-server;t-sql;ado.net;concurrency,gbn,435173,27535,registered,true,1547539,,CC BY-SA 3.0,,3948,2648,3,10,0,5,true,false,false,true,true,true,20,4,false,0.052,0.0011,6264,2009,9,14,Sunday,true,false,false,false,false,true,false
1127088,MySQL LIKE IN()?,"My current query looks like this:
SELECT * FROM fiberbox f WHERE f.fiberBox LIKE '%1740 %' OR f.fiberBox LIKE '%1938 %' OR f.fiberBox LIKE '%1940 %'
I did some looking around and can't find anything similar to a LIKE IN() - I envision it working like this:
SELECT * FROM fiberbox f WHERE f.fiberbox LIKE IN('%140 %', '%1938 %', '%1940 %')
Any ideas? Am I just thinking of the problem the wrong way - some obscure command I've never seen.
MySQL 5.0.77-community-log
",https://stackoverflow.com/questions/1127088/mysql-like-in,363,427832.0,12.0,,,2009-07-14 18:19:08,2022-01-16 18:12:31,2009-07-14 18:21:41,,,sql;mysql,Michael Wales,10718,2001511,registered,true,1127106,,CC BY-SA 2.5,,548,472,2,0,0,2,true,false,false,true,true,true,16,3,true,0.028,0.0008,6339,2009,7,18,Tuesday,false,false,false,false,false,true,false
15534977,MySQL Cannot Add Foreign Key Constraint,"So I'm trying to add Foreign Key constraints to my database as a project requirement and it worked the first time or two on different tables, but I have two tables on which I get an error when trying to add the Foreign Key Constraints.
The error message that I get is:
ERROR 1215 (HY000): Cannot add foreign key constraint
This is the SQL I'm using to create the tables, the two offending tables are Patient and Appointment.
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=1;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
CREATE SCHEMA IF NOT EXISTS `doctorsoffice` DEFAULT CHARACTER SET utf8 ;
USE `doctorsoffice` ;
-- -----------------------------------------------------
-- Table `doctorsoffice`.`doctor`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `doctorsoffice`.`doctor` ;
CREATE TABLE IF NOT EXISTS `doctorsoffice`.`doctor` (
`DoctorID` INT(11) NOT NULL AUTO_INCREMENT ,
`FName` VARCHAR(20) NULL DEFAULT NULL ,
`LName` VARCHAR(20) NULL DEFAULT NULL ,
`Gender` VARCHAR(1) NULL DEFAULT NULL ,
`Specialty` VARCHAR(40) NOT NULL DEFAULT 'General Practitioner' ,
UNIQUE INDEX `DoctorID` (`DoctorID` ASC) ,
PRIMARY KEY (`DoctorID`) )
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
-- -----------------------------------------------------
-- Table `doctorsoffice`.`medicalhistory`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `doctorsoffice`.`medicalhistory` ;
CREATE TABLE IF NOT EXISTS `doctorsoffice`.`medicalhistory` (
`MedicalHistoryID` INT(11) NOT NULL AUTO_INCREMENT ,
`Allergies` TEXT NULL DEFAULT NULL ,
`Medications` TEXT NULL DEFAULT NULL ,
`ExistingConditions` TEXT NULL DEFAULT NULL ,
`Misc` TEXT NULL DEFAULT NULL ,
UNIQUE INDEX `MedicalHistoryID` (`MedicalHistoryID` ASC) ,
PRIMARY KEY (`MedicalHistoryID`) )
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
-- -----------------------------------------------------
-- Table `doctorsoffice`.`Patient`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `doctorsoffice`.`Patient` ;
CREATE TABLE IF NOT EXISTS `doctorsoffice`.`Patient` (
`PatientID` INT unsigned NOT NULL AUTO_INCREMENT ,
`FName` VARCHAR(30) NULL ,
`LName` VARCHAR(45) NULL ,
`Gender` CHAR NULL ,
`DOB` DATE NULL ,
`SSN` DOUBLE NULL ,
`MedicalHistory` smallint(5) unsigned NOT NULL,
`PrimaryPhysician` smallint(5) unsigned NOT NULL,
PRIMARY KEY (`PatientID`) ,
UNIQUE INDEX `PatientID_UNIQUE` (`PatientID` ASC) ,
CONSTRAINT `FK_MedicalHistory`
FOREIGN KEY (`MEdicalHistory` )
REFERENCES `doctorsoffice`.`medicalhistory` (`MedicalHistoryID` )
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `FK_PrimaryPhysician`
FOREIGN KEY (`PrimaryPhysician` )
REFERENCES `doctorsoffice`.`doctor` (`DoctorID` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `doctorsoffice`.`Appointment`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `doctorsoffice`.`Appointment` ;
CREATE TABLE IF NOT EXISTS `doctorsoffice`.`Appointment` (
`AppointmentID` smallint(5) unsigned NOT NULL AUTO_INCREMENT ,
`Date` DATE NULL ,
`Time` TIME NULL ,
`Patient` smallint(5) unsigned NOT NULL,
`Doctor` smallint(5) unsigned NOT NULL,
PRIMARY KEY (`AppointmentID`) ,
UNIQUE INDEX `AppointmentID_UNIQUE` (`AppointmentID` ASC) ,
CONSTRAINT `FK_Patient`
FOREIGN KEY (`Patient` )
REFERENCES `doctorsoffice`.`Patient` (`PatientID` )
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `FK_Doctor`
FOREIGN KEY (`Doctor` )
REFERENCES `doctorsoffice`.`doctor` (`DoctorID` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `doctorsoffice`.`InsuranceCompany`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `doctorsoffice`.`InsuranceCompany` ;
CREATE TABLE IF NOT EXISTS `doctorsoffice`.`InsuranceCompany` (
`InsuranceID` smallint(5) NOT NULL AUTO_INCREMENT ,
`Name` VARCHAR(50) NULL ,
`Phone` DOUBLE NULL ,
PRIMARY KEY (`InsuranceID`) ,
UNIQUE INDEX `InsuranceID_UNIQUE` (`InsuranceID` ASC) )
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `doctorsoffice`.`PatientInsurance`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `doctorsoffice`.`PatientInsurance` ;
CREATE TABLE IF NOT EXISTS `doctorsoffice`.`PatientInsurance` (
`PolicyHolder` smallint(5) NOT NULL ,
`InsuranceCompany` smallint(5) NOT NULL ,
`CoPay` INT NOT NULL DEFAULT 5 ,
`PolicyNumber` smallint(5) NOT NULL AUTO_INCREMENT ,
PRIMARY KEY (`PolicyNumber`) ,
UNIQUE INDEX `PolicyNumber_UNIQUE` (`PolicyNumber` ASC) ,
CONSTRAINT `FK_PolicyHolder`
FOREIGN KEY (`PolicyHolder` )
REFERENCES `doctorsoffice`.`Patient` (`PatientID` )
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `FK_InsuranceCompany`
FOREIGN KEY (`InsuranceCompany` )
REFERENCES `doctorsoffice`.`InsuranceCompany` (`InsuranceID` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
USE `doctorsoffice` ;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
",https://stackoverflow.com/questions/15534977/mysql-cannot-add-foreign-key-constraint,362,576257.0,27.0,,,2013-03-20 21:21:24,2024-10-04 08:54:21,2013-03-20 21:55:17,,,mysql;sql;foreign-keys,joshuaegclark,3919,1064427,registered,true,15535110,,CC BY-SA 3.0,2016-10-16 18:02:13,5511,5415,3,0,0,3,true,false,false,true,true,true,39,6,false,0.047,0.0006,4994,2013,3,21,Wednesday,false,false,false,false,false,true,false
6069024,Syntax of for-loop in SQL Server,"What is the syntax of a for loop in TSQL?
",https://stackoverflow.com/questions/6069024/syntax-of-for-loop-in-sql-server,362,1078990.0,10.0,,,2011-05-20 07:55:22,2024-04-28 05:01:53,2017-09-22 10:24:48,,,sql;sql-server;loops;t-sql;syntax,Macho,3717,762340,unregistered,true,6069036,,CC BY-SA 3.0,,62,42,1,0,0,5,true,false,false,true,true,true,32,6,false,0.009,0.0003,5664,2011,5,7,Friday,false,false,false,false,false,true,false
7747327,SQL RANK() versus ROW_NUMBER(),"I'm confused about the differences between these. Running the following SQL gets me two idential result sets. Can someone please explain the differences?
SELECT ID, [Description], RANK() OVER(PARTITION BY StyleID ORDER BY ID) as 'Rank' FROM SubStyle
SELECT ID, [Description], ROW_NUMBER() OVER(PARTITION BY StyleID ORDER BY ID) as 'RowNumber' FROM SubStyle
",https://stackoverflow.com/questions/7747327/sql-rank-versus-row-number,360,492517.0,8.0,,,2011-10-12 22:26:38,2022-10-07 13:57:59,2014-05-15 21:37:38,,,sql;sql-server;t-sql,dotNET Hobbiest,3685,992371,registered,true,7747406,,CC BY-SA 3.0,,403,372,1,0,0,3,true,false,false,true,true,true,30,4,false,0.016,0.0007,5519,2011,10,22,Wednesday,false,false,false,false,false,true,false
5317889,"SQL keys, MUL vs PRI vs UNI","What is the difference between MUL, PRI and UNI in MySQL?
I'm working on a MySQL query, using the command:
desc mytable;
One of the fields is shown as being a MUL key, others show up as UNI or PRI.
I know that if a key is PRI, only one record per table can be associated with that key. If a key is MUL, does that mean that there could be more than one associated record?
Here's the response of mytable.
+-----------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------+------+-----+---------+-------+
| courseid | int(11) | YES | MUL | NULL | |
| dept | char(3) | YES | | NULL | |
| coursenum | char(4) | YES | | NULL | |
+-----------+---------+------+-----+---------+-------+
",https://stackoverflow.com/questions/5317889/sql-keys-mul-vs-pri-vs-uni,360,399019.0,7.0,,,2011-03-15 20:51:01,2023-03-24 19:03:42,2019-09-05 08:35:03,,,mysql;sql;key,themaestro,14376,370639,registered,true,5318278,,CC BY-SA 4.0,2018-10-16 23:02:57,1000,800,11,0,0,3,true,false,false,true,true,true,27,7,false,0.018,0.0009,5730,2011,3,20,Tuesday,false,false,false,false,false,true,false
8388093,SELECT * FROM X WHERE id IN (...) with Dapper ORM,"What is the best way to write a query with an IN clause using the Dapper ORM when the list of values for the IN clause is coming from business logic? For example let's say I have a query:
SELECT *
FROM SomeTable
WHERE id IN (commaSeparatedListOfIDs)
The commaSeparatedListOfIDs is being passed in from business logic and it can be any type of IEnumerable(of Integer). How would I construct a query in this case? Do I have to do what I've been doing so far which is basically string concatenation or is there some sort of advanced parameter mapping technique that I'm not aware of?
",https://stackoverflow.com/questions/8388093/select-from-x-where-id-in-with-dapper-orm,359,237778.0,11.0,,,2011-12-05 15:59:31,2026-03-25 08:12:50,2026-03-25 08:11:57,,,.net;sql;dapper,Marko,13433,758093,registered,true,8388333,,CC BY-SA 4.0,,713,585,5,0,0,3,true,false,false,true,true,true,49,11,false,0.046,0.0015,5465,2011,12,15,Monday,false,false,false,false,false,true,false
34627026,IN vs ANY operator in PostgreSQL,"What is the difference between IN and ANY operator in PostgreSQL?
The working mechanism of both seems to be the same. Can anyone explain this with an example?
",https://stackoverflow.com/questions/34627026/in-vs-any-operator-in-postgresql,359,533302.0,3.0,,,2016-01-06 06:33:15,2023-01-11 15:50:26,2022-02-10 18:16:48,,,sql;postgresql;sql-in,mohangraj,11642,5063789,registered,true,,,CC BY-SA 4.0,,196,159,2,0,0,3,false,false,false,true,true,true,32,6,false,0.006,0.0007,3972,2016,1,6,Wednesday,false,false,false,false,false,true,false
9795660,PostgreSQL DISTINCT ON with different ORDER BY,"I want to run this query:
SELECT DISTINCT ON (address_id) purchases.address_id, purchases.*
FROM purchases
WHERE purchases.product_id = 1
ORDER BY purchases.purchased_at DESC
But I get this error:
PG::Error: ERROR: SELECT DISTINCT ON expressions must match initial ORDER BY expressions
Adding address_id as first ORDER BY expression silences the error, but I really don't want to add sorting over address_id. Is it possible to do without ordering by address_id?
",https://stackoverflow.com/questions/9795660/postgresql-distinct-on-with-different-order-by,359,395328.0,7.0,,,2012-03-20 21:59:36,2022-08-31 14:51:02,2017-05-30 12:42:12,,,sql;postgresql;sql-order-by;distinct-on,sl_bug,5406,804554,registered,true,9795768,,CC BY-SA 3.0,,601,472,5,0,0,4,true,false,false,true,true,true,46,7,false,0.018,0.0009,5359,2012,3,21,Tuesday,false,false,false,false,false,true,false
2072086,How to check if a stored procedure exists before creating it,"I have a SQL script that has to be run every time a client executes the ""database management"" functionality. The script includes creating stored procedures on the client database. Some of these clients might already have the stored procedure upon running the script, and some may not. I need to have the missing stored procedures added to the client database, but it doesn't matter how much I try to bend T-SQL syntax, I get
CREATE/ALTER PROCEDURE' must be the first statement in a query batch
I've read that dropping before creating works, but I don't like doing it that way.
IF EXISTS (SELECT * FROM sys.objects WHERE type = 'P' AND name = 'MyProc')
DROP PROCEDURE MyProc
GO
CREATE PROCEDURE MyProc
...
How can I add check for the existence of a stored procedure and create it if it doesn't exist but alter it if it does exist?
",https://stackoverflow.com/questions/2072086/how-to-check-if-a-stored-procedure-exists-before-creating-it,358,748270.0,16.0,,,2010-01-15 14:13:34,2022-12-24 00:34:14,2019-04-21 15:42:06,,,sql;sql-server;t-sql;stored-procedures,The Shaper,3665,251581,unregistered,true,2072174,,CC BY-SA 4.0,2015-09-14 15:57:21,927,841,1,0,0,4,true,false,false,true,true,true,60,11,false,0.021,0.0005,6154,2010,1,14,Friday,false,false,false,false,false,true,false
187770,Copy tables from one database to another in SQL Server,"I have a database called foo and a database called bar. I have a table in foo called tblFoobar that I want to move (data and all) to database bar from database foo. What is the SQL statement to do this?
",https://stackoverflow.com/questions/187770/copy-tables-from-one-database-to-another-in-sql-server,358,978924.0,8.0,,,2008-10-09 15:20:58,2026-09-01 14:15:54,2013-12-08 02:19:43,,,sql;sql-server;copy;migrate;database-table,RyanKeeter,6269,7952,registered,true,187785,,CC BY-SA 3.0,2011-08-10 02:47:13,210,203,0,0,0,5,true,false,false,true,true,true,54,10,false,0.008,0.0004,6617,2008,10,15,Thursday,false,false,false,false,false,true,false
3822648,How do I query between two dates using MySQL?,"The following query:
SELECT * FROM `objects`
WHERE (date_field BETWEEN '2010-09-29 10:15:55' AND '2010-01-30 14:15:55')
returns nothing.
I should have more than enough data to for the query to work though. What am I doing wrong?
",https://stackoverflow.com/questions/3822648/how-do-i-query-between-two-dates-using-mysql,356,1040572.0,12.0,,,2010-09-29 14:35:13,2024-01-30 21:36:08,2014-08-21 16:21:27,,,mysql;sql,NullVoxPopuli,65732,356849,registered,true,3822668,,CC BY-SA 3.0,,279,234,1,0,0,2,true,false,false,true,true,true,45,9,true,0.012,0.0003,5897,2010,9,14,Wednesday,false,false,false,false,false,true,false
4823880,SQL Server SELECT INTO @variable?,"I have the following code in one of my Sql (2008) Stored Procs which executes perfectly fine:
CREATE PROCEDURE [dbo].[Item_AddItem]
@CustomerId uniqueidentifier,
@Description nvarchar(100),
@Type int,
@Username nvarchar(100),
AS
BEGIN
DECLARE @TopRelatedItemId uniqueidentifier;
SET @TopRelatedItemId =
(
SELECT top(1) RelatedItemId
FROM RelatedItems
WHERE CustomerId = @CustomerId
)
DECLARE @TempItem TABLE
(
ItemId uniqueidentifier,
CustomerId uniqueidentifier,
Description nvarchar(100),
Type int,
Username nvarchar(100),
TimeStamp datetime
);
INSERT INTO Item
OUTPUT INSERTED.* INTO @TempItem
SELECT NEWID(), @CustomerId, @Description, @Type, @Username, GETDATE()
SELECT
ItemId,
CustomerId,
@TopRelatedItemId,
Description,
Type,
Username,
TimeStamp
FROM
@TempItem
END
GO
So the question for you guys is is there a possibility to do something along the lines of:
DECLARE @TempCustomer TABLE
(
CustomerId uniqueidentifier,
FirstName nvarchar(100),
LastName nvarchar(100),
Email nvarchar(100)
);
SELECT
CustomerId,
FirstName,
LastName,
Email
INTO
@TempCustomer
FROM
Customer
WHERE
CustomerId = @CustomerId
So that I could reuse this data from memory in other following statements? SQL Server throws a fit with the above statement, however i don't want to have to create separate variables and initialize each one of them via a separate SELECT statement against the same table.... UGH!!!
Any suggestions on how to achieve something along the lines without multiple queries against the same table?
",https://stackoverflow.com/questions/4823880/sql-server-select-into-variable,355,1096168.0,8.0,,,2011-01-28 01:22:23,2025-03-31 14:36:59,2011-01-28 01:53:29,,,sql;sql-server;t-sql;sql-server-2008,bleepzter,10141,499636,registered,true,4823953,,CC BY-SA 2.5,,1995,1902,2,0,0,4,true,false,false,true,true,true,33,5,true,0.007,0.0003,5776,2011,1,1,Friday,false,false,false,false,false,true,false
5391344,INSERT with SELECT,"I have a query that inserts using a SELECT statement:
INSERT INTO courses (name, location, gid)
SELECT name, location, gid
FROM courses
WHERE cid = $cid
Is it possible to only select "name, location" for the insert, and set gid to something else in the query?
",https://stackoverflow.com/questions/5391344/insert-with-select,355,491078.0,7.0,,,2011-03-22 12:38:52,2021-10-06 13:11:34,2021-01-14 20:55:13,,,mysql;sql;insert-select,Kyle,3561,671185,unregistered,true,5391390,,CC BY-SA 4.0,2021-10-06 13:11:44,338,274,3,0,0,3,true,false,false,true,true,true,18,3,false,0.014,0.0007,5723,2011,3,12,Tuesday,false,false,false,false,false,true,false
3726758,Is there any boolean type in Oracle databases?,"Is there any Boolean type in Oracle databases, similar to the BIT datatype in Ms SQL Server?
",https://stackoverflow.com/questions/3726758/is-there-any-boolean-type-in-oracle-databases,355,610379.0,12.0,,,2010-09-16 12:43:08,2025-04-04 13:39:05,2018-09-04 04:05:43,,,sql;database;oracle-database;boolean;sqldatatypes,Peder,3551,449499,unregistered,true,,,CC BY-SA 4.0,2016-03-17 13:35:45,113,93,1,0,0,5,false,false,false,true,true,true,46,8,true,0.02,0.0006,5910,2010,9,12,Thursday,false,false,false,false,false,true,false
11753904,PostgreSQL delete with inner join,"DELETE B.*
FROM m_productprice B
INNER JOIN m_product C ON B.m_product_id = C.m_product_id
WHERE C.upc = '7094' AND B.m_pricelist_version_id = '1000020'
i am getting the following error PostgreSQL 8.2.11
ERROR: syntax error at or near ""B""
LINE 1: DELETE B.* from m_productprice B INNER JOIN m_product C ON ...
i tried giving
DELETE B from m_productprice B INNER JOIN m_product C ON B....
ERROR: syntax error at or near ""B""
i tried giving
ERROR: syntax error at or near ""INNER""
LINE 1: DELETE from m_productprice B INNER JOIN m_product C ON B.m_...
what is the problem with my query?
",https://stackoverflow.com/questions/11753904/postgresql-delete-with-inner-join,352,297054.0,7.0,,,2012-08-01 06:45:22,2023-06-02 05:22:26,2014-11-03 06:04:14,,,sql;postgresql,dude,5092,545138,registered,true,11754123,,CC BY-SA 3.0,,740,616,4,0,0,2,true,false,false,true,true,true,33,5,false,0.024,0.0012,5225,2012,8,6,Wednesday,false,false,false,false,false,true,false
1992314,What is the difference between single and double quotes in SQL?,"What is the difference between single quotes and double quotes in SQL?
",https://stackoverflow.com/questions/1992314/what-is-the-difference-between-single-and-double-quotes-in-sql,351,308465.0,6.0,,,2010-01-02 18:18:16,2025-02-04 19:34:13,2010-02-24 05:51:17,,,sql;database;quotes,Vineet,5449,201925,registered,true,1992331,,CC BY-SA 2.5,,78,71,0,0,0,3,true,false,false,true,true,true,63,11,true,0.019,0.0011,6167,2010,1,18,Saturday,true,false,false,false,false,true,false
1471250,Counting DISTINCT over multiple columns,"Is there a better way of doing a query like this:
SELECT COUNT(*)
FROM (SELECT DISTINCT DocumentId, DocumentSessionId
FROM DocumentOutputItems) AS internalQuery
I need to count the number of distinct items from this table but the distinct is over two columns.
My query works fine but I was wondering if I can get the final result using just one query (without using a sub-query)
",https://stackoverflow.com/questions/1471250/counting-distinct-over-multiple-columns,351,817382.0,22.0,,,2009-09-24 12:03:50,2026-01-13 18:24:38,2020-01-06 17:06:23,,,sql;sql-server;performance;t-sql;query-optimization,Novitzky,4906,124438,registered,true,1480381,,CC BY-SA 4.0,2019-03-21 21:21:16,435,390,1,0,0,5,true,false,false,true,true,true,39,5,false,0.027,0.0004,6267,2009,9,12,Thursday,false,false,false,false,false,true,false
23766084,Best way to check for "empty or null value","What is best way to check if value is null or empty string in Postgres sql statements?
Value can be long expression so it is preferable that it is written only once in check.
Currently I'm using:
coalesce( trim(stringexpression),'')=''
But it looks a bit ugly.
stringexpression may be char(n) column or expression containing char(n) columns with trailing spaces.
What is best way?
",https://stackoverflow.com/questions/23766084/best-way-to-check-for-empty-or-null-value,350,628751.0,11.0,,,2014-05-20 17:13:52,2024-03-11 22:02:53,2014-05-20 18:50:29,,,sql;database;postgresql;null;coalesce,Andrus,28375,742402,registered,true,23767625,,CC BY-SA 3.0,,493,388,4,0,0,5,true,false,false,true,true,true,53,9,false,0.017,0.0006,4568,2014,5,17,Tuesday,false,false,false,false,false,true,false
20856,Recommended SQL database design for tags or tagging,"I've heard of a few ways to implement tagging; using a mapping table between TagID and ItemID (makes sense to me, but does it scale?), adding a fixed number of possible TagID columns to ItemID (seems like a bad idea), Keeping tags in a text column that's comma separated (sounds crazy but could work). I've even heard someone recommend a sparse matrix, but then how do the tag names grow gracefully?
Am I missing a best practice for tags?
",https://stackoverflow.com/questions/20856/recommended-sql-database-design-for-tags-or-tagging,350,153617.0,6.0,,,2008-08-21 19:18:05,2015-11-28 09:51:15,2015-02-11 23:09:51,2016-01-03 12:44:16,Opinion-based,sql;database-design;tags;data-modeling;tagging,dlamblin,45787,459,registered,true,20871,,,,454,440,0,0,0,5,true,true,false,true,true,true,51,8,false,0.039,0.0023,6666,2008,8,19,Thursday,false,false,false,false,false,true,false
9325017,ERROR: permission denied for sequence cities_id_seq using Postgres,"I ran following sql script on my database:
create table cities (
id serial primary key,
name text not null
);
create table reports (
id serial primary key,
cityid integer not null references cities(id),
reportdate date not null,
reporttext text not null
);
create user www with password 'www';
grant select on cities to www;
grant insert on cities to www;
grant delete on cities to www;
grant select on reports to www;
grant insert on reports to www;
grant delete on reports to www;
grant select on cities_id_seq to www;
grant insert on cities_id_seq to www;
grant delete on cities_id_seq to www;
grant select on reports_id_seq to www;
grant insert on reports_id_seq to www;
grant delete on reports_id_seq to www;
When, as the user www, trying to:
insert into cities (name) values ('London');
I get the following error:
ERROR: permission denied for sequence cities_id_seq
I get that the problem lies with the serial type. That's why I grant select, insert and delete rights for the *_id_seq to www. Yet this does not fix my problem. What am I missing?
",https://stackoverflow.com/questions/9325017/error-permission-denied-for-sequence-cities-id-seq-using-postgres,349,363289.0,5.0,,,2012-02-17 08:24:31,2023-03-16 17:19:13,2022-12-29 00:53:52,,,sql;postgresql;permissions;auto-increment,Tõnis Ojandu,3836,1211315,registered,true,9325195,,CC BY-SA 4.0,,1161,1061,3,0,0,4,true,false,false,true,true,true,66,8,false,0.014,0.001,5391,2012,2,8,Friday,false,false,false,false,false,true,false
1152260,How to list table foreign keys,"Is there a way using SQL to list all foreign keys for a given table? I know the table name / schema and I can plug that in.
",https://stackoverflow.com/questions/1152260/how-to-list-table-foreign-keys,348,342332.0,32.0,,,2009-07-20 08:14:13,2025-06-24 19:30:22,2023-12-13 18:12:13,,,sql;postgresql;foreign-keys;database-schema,smack0007,11436,26566,registered,true,1152321,,CC BY-SA 4.0,2022-07-31 13:50:17,131,124,0,0,0,4,true,false,false,true,true,true,30,6,false,0.093,0.001,6333,2009,7,8,Monday,false,false,false,false,false,true,false
805363,How do I rename a column in an SQLite database table?,"I need to rename table columns in an SQLite database. This similar question doesn't mention SQLite. From the documentation of ALTER TABLE I gather that it's not a single statement.
What is a generic SQL way of doing this with SQLite?
",https://stackoverflow.com/questions/805363/how-do-i-rename-a-column-in-an-sqlite-database-table,348,239847.0,15.0,,,2009-04-30 04:43:45,2026-10-13 08:11:19,2024-07-10 23:27:46,,,sql;sqlite;alter-table,joce,10000,82682,registered,true,52346199,,CC BY-SA 4.0,,447,234,1,2,0,3,true,false,false,true,true,true,53,11,true,0.063,0.0015,6414,2009,4,4,Thursday,false,false,false,false,false,true,false
15367696,Storing JSON in database vs. having a new column for each key,"I am implementing the following model for storing user-related data in my table. I have column uid (primary key) and column meta which stores other data about the user in JSON format.
uid | meta
--------------------------------------------------
1 | {name:['foo'],
| emailid:['foo@bar.com','bar@foo.com']}
--------------------------------------------------
2 | {name:['sann'],
| emailid:['sann@bar.com','sann@foo.com']}
What is a better way (performance-wise, design-wise) than the one-column-per-property model, where the table will have many columns like uid, name, and emailid?
What I like about the first model is, you can add as many fields as desired.
Now that I have implemented the first model, how do I perform a query on it to fetch all the users who have name like 'foo'?
Which is the better way to store user related data (keeping in mind that the number of fields is not fixed) - JSON or column-per-field?
Since there won't be too many columns on which I need to perform search, why might I use both the models - key-per-column for the data I need to search and JSON for others (in the same MySQL database)?
",https://stackoverflow.com/questions/15367696/storing-json-in-database-vs-having-a-new-column-for-each-key,347,293565.0,10.0,,,2013-03-12 17:11:49,2026-05-12 21:46:46,2026-05-12 21:46:46,,,sql;mysql;database;database-normalization;first-normal-form,ShuklaSannidhya,9066,1908235,registered,true,,,CC BY-SA 4.0,,1285,1154,6,0,0,5,false,false,false,true,true,true,61,12,false,0.034,0.0012,5002,2013,3,17,Tuesday,false,false,false,false,false,true,false
19469154,How to compare dates in datetime fields in Postgresql?,"I have been facing a strange scenario when comparing dates in postgresql(version 9.2.4 in windows).
I have a column in my table say update_date with type timestamp without timezone.
Client can search over this field with only date (e.g: 2013-05-03) or date with time (e.g.: 2013-05-03 12:20:00).
This column has the value as timestamp for all rows currently and have the same date part 2013-05-03, but difference in time part.
When I'm comparing over this column, I'm getting different results. Like the followings:
select * from table where update_date >= '2013-05-03' AND update_date <= '2013-05-03' -> No results
select * from table where update_date >= '2013-05-03' AND update_date < '2013-05-03' -> No results
select * from table where update_date >= '2013-05-03' AND update_date <= '2013-05-04' -> results found
select * from table where update_date >= '2013-05-03' -> results found
My question is how can I make the first query possible to get results, I mean why the 3rd query is working but not the first one?
",https://stackoverflow.com/questions/19469154/how-to-compare-dates-in-datetime-fields-in-postgresql,346,744800.0,6.0,,,2013-10-19 17:52:45,2024-04-29 11:12:28,2022-03-14 18:58:16,,,sql;database;postgresql;date,user2866264,3479,2866264,registered,true,19469689,,CC BY-SA 4.0,,1186,1057,6,0,0,4,true,false,false,true,true,true,54,9,true,0.008,0.0005,4781,2013,10,17,Saturday,true,false,false,false,false,true,false
15931607,Convert Rows to columns using 'Pivot',"I have a temp table that is being created, we will say that column 1 is a Store number, and column 2 is a week number and lastly column 3 is a total of some type. Also the week numbers are dynamic, the store numbers are static.
Store Week xCount
------- ---- ------
102 1 96
101 1 138
105 1 37
109 1 59
101 2 282
102 2 212
105 2 78
109 2 97
105 3 60
102 3 123
101 3 220
109 3 87
I would like it to come out as a pivot table, like this:
Store 1 2 3 4 5 6....
-----
101 138 282 220
102 96 212 123
105 37
109
Store numbers down the side and weeks across the top.
",https://stackoverflow.com/questions/15931607/convert-rows-to-columns-using-pivot,346,1160633.0,9.0,,,2013-04-10 16:38:38,2026-09-02 21:19:46,2026-09-02 21:18:54,,,sql;sql-server;pivot;pivot-table,Lynn,3710,2267015,registered,true,15931734,,CC BY-SA 4.0,2015-11-05 08:46:04,921,852,2,0,0,4,true,false,false,true,true,true,45,6,false,0.008,0.0003,4973,2013,4,16,Wednesday,false,false,false,false,false,true,false
17972020,How to execute raw SQL in Flask-SQLAlchemy app,"How do you execute raw SQL in SQLAlchemy?
I have a python web app that runs on flask and interfaces to the database through SQLAlchemy.
I need a way to run the raw SQL. The query involves multiple table joins along with Inline views.
I've tried:
connection = db.session.connection()
connection.execute( <sql here> )
But I keep getting gateway errors.
",https://stackoverflow.com/questions/17972020/how-to-execute-raw-sql-in-flask-sqlalchemy-app,345,489992.0,10.0,,,2013-07-31 13:39:42,2024-06-27 23:03:59,2019-06-13 16:57:59,,,python;sql;sqlalchemy;flask;flask-sqlalchemy,starwing123,3563,1848523,registered,true,17987782,,CC BY-SA 4.0,,424,365,1,0,0,5,true,false,false,true,true,true,46,8,false,0.02,0.0007,4861,2013,7,13,Wednesday,false,true,false,false,false,true,false
1580450,How do I list all the columns in a table?,"For the various popular database systems, how do you list all the columns in a table?
",https://stackoverflow.com/questions/1580450/how-do-i-list-all-the-columns-in-a-table,344,1366202.0,14.0,,,2009-10-16 21:10:05,2024-12-30 23:21:21,2024-12-30 23:20:52,,,sql;mysql;sql-server;oracle-database,MattGrommes,12444,3098,registered,true,,,CC BY-SA 4.0,,93,86,0,0,0,4,false,false,false,true,true,true,41,10,true,0.01,0.0003,6245,2009,10,21,Friday,false,false,false,false,false,true,false
4253960,SQL: How to properly check if a record exists,"While reading some SQL Tuning-related documentation, I found this:
SELECT COUNT(*) :
- Counts the number of rows.
- Often is improperly used to verify the existence of a record.
Is SELECT COUNT(*) really that bad?
What's the proper way to verify the existence of a record?
",https://stackoverflow.com/questions/4253960/sql-how-to-properly-check-if-a-record-exists,344,782164.0,9.0,,,2010-11-23 08:15:25,2021-10-12 14:06:44,2020-06-01 19:48:24,,,sql;optimization;query-optimization,systempuntoout,74804,130929,registered,true,4254003,,CC BY-SA 4.0,,358,277,2,0,0,3,true,false,false,true,true,true,45,9,false,0.012,0.0004,5842,2010,11,8,Tuesday,false,false,false,false,false,true,false
7197574,Script to kill all connections to a database (More than RESTRICTED_USER ROLLBACK),"I have a development database that re-deploy frequently from a Visual Studio Database project (via a TFS Auto Build).
Sometimes when I run my build I get this error:
ALTER DATABASE failed because a lock could not be placed on database 'MyDB'. Try again later.
ALTER DATABASE statement failed.
Cannot drop database ""MyDB"" because it is currently in use.
I tried this:
ALTER DATABASE MyDB SET RESTRICTED_USER WITH ROLLBACK IMMEDIATE
but I still cannot drop the database. (My guess is that most of the developers have dbo access.)
I can manually run SP_WHO and start killing connections, but I need an automatic way to do this in the auto build. (Though this time my connection is the only one on the db I am trying to drop.)
Is there a script that can drop my database regardless of who is connected?
",https://stackoverflow.com/questions/7197574/script-to-kill-all-connections-to-a-database-more-than-restricted-user-rollback,343,883708.0,15.0,,,2011-08-25 21:42:47,2025-04-08 17:03:18,2018-07-03 21:36:22,,,sql;sql-server;t-sql;sql-server-2008;sql-server-2008-r2,Vaccano,83670,16241,registered,true,7201350,,CC BY-SA 4.0,2025-04-14 10:54:45,932,816,4,0,0,5,true,false,false,true,true,true,81,12,false,0.017,0.0004,5567,2011,8,21,Thursday,false,false,false,false,false,true,false
1766046,PostgreSQL create table if not exists,"In a MySQL script you can write:
CREATE TABLE IF NOT EXISTS foo ...;
... other stuff ...
and then you can run the script many times without re-creating the table.
How do you do this in PostgreSQL?
",https://stackoverflow.com/questions/1766046/postgresql-create-table-if-not-exists,342,530493.0,6.0,,,2009-11-19 19:48:41,2022-01-18 06:24:26,2019-08-17 06:11:42,,,sql;postgresql;ddl;create-table;database-table,peter2108,6260,205063,registered,true,,,CC BY-SA 4.0,,254,202,1,0,0,5,false,false,false,true,true,true,37,6,false,0.011,0.0006,6211,2009,11,19,Thursday,false,false,false,false,false,true,false
1895110,ROW_NUMBER() in MySQL,"Is there a nice way in MySQL to replicate the SQL Server function ROW_NUMBER()?
For example:
SELECT
col1, col2,
ROW_NUMBER() OVER (PARTITION BY col1, col2 ORDER BY col3 DESC) AS intRow
FROM Table1
Then I could, for example, add a condition to limit intRow to 1 to get a single row with the highest col3 for each (col1, col2) pair.
",https://stackoverflow.com/questions/1895110/row-number-in-mysql,342,807587.0,23.0,,,2009-12-12 23:58:44,2025-09-02 05:43:55,2015-05-21 09:20:48,,,mysql;sql;greatest-n-per-group;rank;row-number,Paul,16963,63416,registered,true,1895149,,CC BY-SA 3.0,2018-12-31 14:00:12,442,345,5,0,0,5,true,false,false,true,true,true,21,3,false,0.028,0.0004,6188,2009,12,23,Saturday,true,false,false,false,false,true,false
74385,How to convert DateTime to VarChar,"I need to convert a value which is in a DateTime variable into a varchar variable formatted as yyyy-mm-dd format (without time part).
How do I do that?
",https://stackoverflow.com/questions/74385/how-to-convert-datetime-to-varchar,341,1696847.0,24.0,,,2008-09-16 16:44:22,2025-07-30 14:16:09,2021-01-11 21:28:57,,,sql;sql-server;datetime;sql-convert,Ali,5609,7604,registered,true,74469,,CC BY-SA 4.0,,205,152,3,0,0,4,true,false,false,true,true,true,34,6,false,0.014,0.0002,6640,2008,9,16,Tuesday,false,false,false,false,false,true,false
14824453,Rails raw SQL example,"How can I convert this code to raw sql and use in rails? Because When I deploy this code in heroku,there is a request timeout error.I think this will be faster if I use raw sql.
@payments = PaymentDetail.joins(:project).order('payment_details.created_at desc')
@payment_errors = PaymentError.joins(:project).order('payment_errors.created_at desc')
@all_payments = (@payments + @payment_errors)
",https://stackoverflow.com/questions/14824453/rails-raw-sql-example,340,409495.0,6.0,,,2013-02-12 02:22:51,2023-03-28 16:12:01,2017-04-24 23:29:19,,,sql;ruby-on-rails,Johnny Cash,5187,2015350,registered,true,14840547,,CC BY-SA 3.0,,428,397,1,0,0,2,true,false,false,true,true,true,21,4,false,0.015,0.0008,5030,2013,2,2,Tuesday,false,false,false,false,false,true,false
5400530,Validation failed for one or more entities while saving changes to SQL Server Database using Entity Framework,"I want to save my Edit to Database and I am using Entity FrameWork Code-First in ASP.NET MVC 3 / C# but I am getting errors. In my Event class, I have DateTime and TimeSpan datatypes but in my database, I've got Date and time respectively. Could this be the reason? How can I cast to the appropriate datatype in the code before saving changes to database.
public class Event
{
public int EventId { get; set; }
public int CategoryId { get; set; }
public int PlaceId { get; set; }
public string Title { get; set; }
public decimal Price { get; set; }
public DateTime EventDate { get; set; }
public TimeSpan StartTime { get; set; }
public TimeSpan EndTime { get; set; }
public string Description { get; set; }
public string EventPlaceUrl { get; set; }
public Category Category { get; set; }
public Place Place { get; set; }
}
Method in the controller >>>> Problem at storeDB.SaveChanges();
// POST: /EventManager/Edit/386
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
var theEvent = storeDB.Events.Find(id);
if (TryUpdateModel(theEvent))
{
storeDB.SaveChanges();
return RedirectToAction(""Index"");
}
else
{
ViewBag.Categories = storeDB.Categories.OrderBy(g => g.Name).ToList();
ViewBag.Places = storeDB.Places.OrderBy(a => a.Name).ToList();
return View(theEvent);
}
}
with
public class EventCalendarEntities : DbContext
{
public DbSet<Event> Events { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<Place> Places { get; set; }
}
SQL Server 2008 R2 Database / T-SQL
EventDate (Datatype = date)
StartTime (Datatype = time)
EndTime (Datatype = time)
Http Form
EventDate (Datatype = DateTime) e.g. 4/8/2011 12:00:00 AM
StartTime (Datatype = Timespan/time not sure) e.g. 08:30:00
EndTime (Datatype = Timespan/time not sure) e.g. 09:00:00
Server Error in '/' Application.
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
Source Error:
Line 75: if (TryUpdateModel(theEvent))
Line 76: {
Line 77: storeDB.SaveChanges();
Line 78: return RedirectToAction(""Index"");
Line 79: }
Source File: C:\sep\MvcEventCalendar\MvcEventCalendar\Controllers\EventManagerController.cs Line: 77
Stack Trace:
[DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.]
",https://stackoverflow.com/questions/5400530/validation-failed-for-one-or-more-entities-while-saving-changes-to-sql-server-da,339,325623.0,17.0,,,2011-03-23 03:18:45,2019-02-20 11:39:47,2015-08-11 21:26:12,,,c#;sql;asp.net-mvc;entity-framework;code-first,user522767,4033,522767,registered,true,,,CC BY-SA 3.0,,3200,2965,6,0,0,5,false,false,false,true,true,true,109,17,false,0.052,0.001,5722,2011,3,3,Wednesday,false,false,false,false,true,true,false
3969059,SQL Case Sensitive String Compare,"How do you compare strings so that the comparison is true only if the cases of each of the strings are equal as well. For example:
Select * from a_table where attribute = 'k'
...will return a row with an attribute of 'K'. I do not want this behaviour.
",https://stackoverflow.com/questions/3969059/sql-case-sensitive-string-compare,338,332560.0,6.0,,,2010-10-19 13:52:58,2021-02-26 22:18:45,2019-05-17 19:52:36,,,sql;sql-server,amccormack,14057,228489,registered,true,3969095,,CC BY-SA 4.0,2014-12-02 05:07:58,294,256,1,0,0,2,true,false,false,true,true,true,33,5,false,0.018,0.001,5877,2010,10,13,Tuesday,false,false,false,false,false,true,false
237327,How to UPSERT (update or insert into a table?),"The UPSERT operation either updates or inserts a row in a table, depending if the table already has a row that matches the data:
if table t has a row exists that has key X:
update t set mystuff... where mykey=X
else
insert into t mystuff...
Since Oracle doesn't have a specific UPSERT statement, what's the best way to do this?
",https://stackoverflow.com/questions/237327/how-to-upsert-update-or-insert-into-a-table,338,567288.0,11.0,,,2008-10-26 01:24:06,2025-12-20 23:17:47,2023-09-08 16:41:39,,,sql;oracle-database;merge;upsert,Mark Harrison,306839,116,registered,true,239579,,CC BY-SA 4.0,2019-02-22 13:49:13,377,339,1,0,0,4,true,false,false,true,true,true,46,9,false,0.019,0.0006,6600,2008,10,1,Sunday,true,false,false,false,false,true,false
329931,SQL select join: is it possible to prefix all columns as 'prefix.*'?,"I'm wondering if this is possible in SQL. Say you have two tables A and B, and you do a select on table A and join on table B:
SELECT a.*, b.* FROM TABLE_A a JOIN TABLE_B b USING (some_id);
If table A has columns 'a_id', 'name', and 'some_id', and table B has 'b_id', 'name', and 'some_id', the query will return columns 'a_id', 'name', 'some_id', 'b_id', 'name', 'some_id'. Is there any way to prefix the column names of table B without listing every column individually? The equivalent of this:
SELECT a.*, b.b_id as 'b.b_id', b.name as 'b.name', b.some_id as 'b.some_id'
FROM TABLE_A a JOIN TABLE_B b USING (some_id);
But, as mentioned, without listing every column, so something like:
SELECT a.*, b.* as 'b.*'
FROM TABLE_A a JOIN TABLE_B b USING (some_id);
Basically something to say, "prefix every column returned by b.* with 'something'". Is this possible or am I out of luck?
EDITS
Advice on not using SELECT * and so on is valid advice but not relevant in my context, so please stick to the problem at hand -- is it possible to add a prefix (a constant specified in the SQL query) to all the column names of a table in a join?
My ultimate goal is to be able to do a SELECT * on two tables with a join, and be able to tell, from the names of the columns I get in my result set, which columns came from table A and which columns came from table B. Again, I don't want to have to list columns individually, I need to be able to do a SELECT *.
",https://stackoverflow.com/questions/329931/sql-select-join-is-it-possible-to-prefix-all-columns-as-prefix,338,278868.0,29.0,,,2008-12-01 03:15:58,2026-08-11 16:20:27,2020-08-30 11:54:02,,,sql;join,foxdonut,7997,26353,registered,true,329984,,CC BY-SA 4.0,2022-02-03 19:47:49,1623,1461,6,0,0,2,true,false,false,true,true,true,76,12,true,0.104,0.0012,6564,2008,12,3,Monday,false,false,false,false,false,true,false
2221555,How to fetch the row count for all tables in a SQL SERVER database,"I am searching for a SQL Script that can be used to determine if there is any data (i.e. row count) in any of the tables of a given database.
The idea is to re-incarnate the database in case there are any rows existing (in any of the database).
The database being spoken of is Microsoft SQL Sserver.
Could someone suggest a sample script?
",https://stackoverflow.com/questions/2221555/how-to-fetch-the-row-count-for-all-tables-in-a-sql-server-database,337,921986.0,13.0,,,2010-02-08 12:37:21,2023-11-30 08:38:39,2023-08-21 08:37:53,2014-08-04 22:54:50,Duplicate,sql;sql-server;rowcount,vijaysylvester,5080,146383,registered,true,2221898,,,,367,339,0,0,0,3,true,true,false,true,true,true,66,14,false,0.014,0.0004,6130,2010,2,12,Monday,false,false,false,false,false,true,false
7030699,Update a table with data from another table,"Table 1:
id name desc
-----------------------
1 a abc
2 b def
3 c adf
Table 2:
id name desc
-----------------------
1 x 123
2 y 345
In oracle SQL, how do I run an sql update query that can update Table 1 with Table 2's name and desc using the same id? So the end result I would get is
Table 1:
id name desc
-----------------------
1 x 123
2 y 345
3 c adf
Question is taken from update one table with data from another, but specifically for oracle SQL.
",https://stackoverflow.com/questions/7030699/update-a-table-with-data-from-another-table,337,1422897.0,8.0,,,2011-08-11 18:05:54,2024-05-24 09:37:44,2023-06-21 06:08:39,,,sql;oracle-database;sql-update,Muhd,25886,446921,registered,true,7031405,,CC BY-SA 4.0,2015-09-23 20:25:30,827,560,6,1,0,3,true,false,false,true,true,true,43,8,false,0.006,0.0002,5581,2011,8,18,Thursday,false,false,false,false,false,true,false
3945361,SET versus SELECT when assigning variables?,"What are the differences between the SET and SELECT statements when assigning variables in T-SQL?
",https://stackoverflow.com/questions/3945361/set-versus-select-when-assigning-variables,336,470210.0,5.0,,,2010-10-15 19:17:01,2023-12-25 12:40:35,2015-06-15 09:23:08,,,sql;sql-server;sql-server-2005;t-sql;sql-server-2008,juur,5781,368537,unregistered,true,3945396,,CC BY-SA 3.0,,131,98,2,0,0,5,true,false,false,true,true,true,43,6,true,0.011,0.0007,5881,2010,10,19,Friday,false,false,false,false,false,true,false
905379,What is the difference between JOIN and UNION?,"What is the difference between JOIN and UNION? Can I have an example?
",https://stackoverflow.com/questions/905379/what-is-the-difference-between-join-and-union,335,606776.0,14.0,,,2009-05-25 04:55:16,2024-09-04 21:13:23,2016-12-19 15:37:03,,,sql;database;join;union,Gold,62928,43907,registered,true,905383,,CC BY-SA 3.0,,103,70,2,0,0,4,true,false,false,true,true,true,46,8,true,0.023,0.0006,6389,2009,5,4,Monday,false,false,false,false,false,true,false
7162903,How to alter a column's data type in a PostgreSQL table?,"Entering the following command into a PostgreSQL interactive terminal results in an error:
ALTER TABLE tbl_name ALTER COLUMN col_name varchar (11);
What is the correct command to alter the data type of a column?
",https://stackoverflow.com/questions/7162903/how-to-alter-a-columns-data-type-in-a-postgresql-table,335,575844.0,3.0,,,2011-08-23 14:45:19,2023-09-28 06:42:13,2017-05-13 00:14:53,,,sql;postgresql;psql;alter-table;alter-column,tree em,22035,128618,registered,true,7162961,,CC BY-SA 3.0,2015-11-24 20:53:43,253,215,1,0,0,5,true,false,false,true,true,true,60,11,true,0.005,0.0006,5569,2011,8,14,Tuesday,false,false,false,false,false,true,false
459457,What is a stored procedure?,"What is a ""stored procedure"" and how do they work?
What is the make-up of a stored procedure (things each must have to be a stored procedure)?
",https://stackoverflow.com/questions/459457/what-is-a-stored-procedure,335,603342.0,18.0,,,2009-01-19 22:33:24,2023-09-02 13:42:09,2019-12-31 15:56:02,,,sql;sql-server;t-sql;stored-procedures,George Stocker,58056,16587,registered,true,459531,,CC BY-SA 4.0,,177,145,0,0,0,4,true,false,false,true,true,true,27,5,true,0.03,0.0006,6515,2009,1,22,Monday,false,false,false,false,false,true,false
11709043,mysql update column with value from another table,"I have two tables, both looking like
id name value
===================
1 Joe 22
2 Derk 30
I need to copy the value of value from tableA to tableB based on check name in each table.
Any tips for this UPDATE statement?
",https://stackoverflow.com/questions/11709043/mysql-update-column-with-value-from-another-table,334,583607.0,9.0,,,2012-07-29 11:54:04,2025-01-17 06:30:50,2013-10-04 11:12:20,,,mysql;sql;sql-update,LeoSam,5011,898454,registered,true,19346375,,CC BY-SA 3.0,,331,234,5,0,0,3,true,false,false,true,true,true,49,8,false,0.015,0.0006,5228,2012,7,11,Sunday,true,false,false,false,false,true,false
11169550,"Is there a performance difference between CTE , Sub-Query, Temporary Table or Table Variable?","In this excellent SO question, differences between CTE and sub-queries were discussed.
I would like to specifically ask:
In what circumstance is each of the following more efficient/faster?
- CTE
- Sub-Query
- Temporary Table
- Table Variable
Traditionally, I've used lots of temp tables in developing stored procedures - as they seem more readable than lots of intertwined sub-queries.
Non-recursive CTEs encapsulate sets of data very well, and are very readable, but are there specific circumstances where one can say they will always perform better? or is it a case of having to always fiddle around with the different options to find the most efficient solution?
EDIT
I've recently been told that in terms of efficiency, temporary tables are a good first choice as they have an associated histogram i.e. statistics.
",https://stackoverflow.com/questions/11169550/is-there-a-performance-difference-between-cte-sub-query-temporary-table-or-ta,332,290806.0,4.0,,,2012-06-23 12:36:14,2018-03-28 05:46:33,2018-03-28 05:46:33,,,sql;sql-server;t-sql;subquery;common-table-expression,whytheq,35823,1179880,registered,true,11169910,,CC BY-SA 3.0,2012-12-30 21:40:45,1099,826,5,1,0,5,true,false,false,true,true,true,93,14,true,0.014,0.0011,5264,2012,6,12,Saturday,true,false,false,false,false,true,false
11231544,Check if value exists in Postgres array,"Using Postgres 9.0, I need a way to test if a value exists in a given array. So far I came up with something like this:
select '{1,2,3}'::int[] @> (ARRAY[]::int[] || value_variable::int)
But I keep thinking there should be a simpler way to this, I just can't see it. This seems better:
select '{1,2,3}'::int[] @> ARRAY[value_variable::int]
I believe it will suffice. But if you have other ways to do it, please share!
",https://stackoverflow.com/questions/11231544/check-if-value-exists-in-postgres-array,331,524743.0,8.0,,,2012-06-27 17:07:40,2023-03-09 12:09:25,2020-05-15 16:04:27,,,sql;arrays;postgresql,Mike Starov,7496,18297,registered,true,11231965,,CC BY-SA 4.0,,499,430,2,0,0,3,true,false,false,true,true,true,39,7,false,0.015,0.0006,5260,2012,6,17,Wednesday,false,false,false,false,false,true,false
9156340,How to copy a row and insert in same table with a autoincrement field in MySQL?,"In MySQL I am trying to copy a row with an autoincrement column ID=1 and insert the data into same table as a new row with column ID=2.
How can I do this in a single query?
",https://stackoverflow.com/questions/9156340/how-to-copy-a-row-and-insert-in-same-table-with-a-autoincrement-field-in-mysql,331,706181.0,16.0,,,2012-02-06 06:26:31,2023-06-21 08:14:26,2020-05-05 13:06:48,,,mysql;sql;insert;copy,Navdroid,4563,1151433,registered,true,9156386,,CC BY-SA 4.0,,248,174,2,0,0,4,true,false,false,true,true,true,79,16,true,0.023,0.0005,5402,2012,2,6,Monday,false,false,false,false,false,true,false
8318911,Why does HTML think “chucknorris” is a color?,"Why do certain random strings produce colors when entered as background colors in HTML?
For example, bgcolor="chucknorris" produces a red background:
<body bgcolor=""chucknorris""> test </body>
Conversely, bgcolor="chucknorr" produces a yellow background:
<body bgcolor=""chucknorr""> test </body>
This holds true across various browsers and platforms. What’s going on here?
",https://stackoverflow.com/questions/8318911/why-does-html-think-chucknorris-is-a-color,8956,818523.0,9.0,,,2011-11-29 22:54:22,2024-01-24 02:40:12,2022-06-06 07:37:27,,,html;browser;background-color,user456584,89481,456584,registered,true,8333464,,CC BY-SA 4.0,2013-02-06 14:22:14,964,436,4,0,0,3,true,false,false,true,true,true,45,8,true,0.011,0.0109,5471,2011,11,22,Tuesday,false,false,false,false,false,false,false
114543,How can I horizontally center an element?,"How can I horizontally center a <div> within another <div> using CSS?
<div id="outer">
<div id="inner">Foo foo</div>
</div>
",https://stackoverflow.com/questions/114543/how-can-i-horizontally-center-an-element,5098,5010904.0,127.0,,,2008-09-22 12:27:57,2024-06-03 14:55:17,2022-08-10 00:26:06,,,html;css;alignment;centering,Lukas,9476,20403,registered,true,114549,,CC BY-SA 4.0,2010-07-13 00:03:41,280,184,3,0,0,4,true,false,false,true,true,true,41,7,true,0.025,0.001,6634,2008,9,12,Monday,false,false,false,false,false,false,false
2610497,Change an HTML input's placeholder color with CSS,"Chrome v4 supports the placeholder attribute on input[type=text] elements (others probably do too).
However, the following CSS doesn't do anything to the placeholder's value:
input[placeholder], [placeholder], *[placeholder] {
color: red !important;
}
<input type=""text"" placeholder=""Value"">
Value will still remain grey instead of red.
Is there a way to change the color of the placeholder text?
",https://stackoverflow.com/questions/2610497/change-an-html-inputs-placeholder-color-with-css,4419,2065749.0,42.0,,,2010-04-09 19:54:53,2025-01-02 19:09:34,2023-04-18 16:29:52,,,css;html;placeholder;html-input,David Murdoch,89670,160173,registered,true,2610741,,CC BY-SA 4.0,2012-07-05 12:56:27,967,418,6,1,0,4,true,false,false,true,true,true,53,8,false,0.02,0.0021,6070,2010,4,19,Friday,false,false,false,false,false,false,false
339923,Set cellpadding and cellspacing in CSS?,"In an HTML table, the cellpadding and cellspacing can be set like this:
<table cellspacing=""1"" cellpadding=""1"">
How can the same be accomplished using CSS?
",https://stackoverflow.com/questions/339923/set-cellpadding-and-cellspacing-in-css,3727,2801253.0,19.0,,,2008-12-04 08:45:47,2024-02-28 14:11:59,2018-06-06 19:40:48,,,html;css;html-table;alignment,kokos,43744,1065,registered,true,3209434,,CC BY-SA 4.0,2013-05-08 06:43:10,268,165,3,0,0,4,true,false,false,true,true,true,39,6,true,0.007,0.0013,6561,2008,12,8,Thursday,false,false,false,false,false,false,false
5235142,How do I disable the resizable property of a textarea?,"I want to disable the resizable property of a textarea.
Currently, I can resize a textarea by clicking on the bottom right corner of the textarea and dragging the mouse. How can I disable this?
",https://stackoverflow.com/questions/5235142/how-do-i-disable-the-resizable-property-of-a-textarea,3351,1928685.0,17.0,,,2011-03-08 16:15:40,2025-10-13 05:56:39,2024-07-31 03:27:46,,,html;css;resize;textarea,user549757,34142,549757,registered,true,5235160,,CC BY-SA 4.0,2014-05-11 15:03:39,398,197,3,1,1,4,true,false,false,true,true,true,54,10,true,0.009,0.0017,5737,2011,3,16,Tuesday,false,false,false,false,false,false,false
2530,How do you disable browser autocomplete on web form field / input tags?,"How do you disable autocomplete in the major browsers for a specific input (or form field)?
",https://stackoverflow.com/questions/2530/how-do-you-disable-browser-autocomplete-on-web-form-field-input-tags,3272,1513346.0,109.0,,,2008-08-05 16:22:32,2026-07-17 13:56:50,2021-04-08 23:01:03,,,html;forms;browser;autocomplete,Brett Veenstra,48712,307,registered,true,2531,,CC BY-SA 4.0,2013-04-15 20:35:12,99,92,0,0,0,4,true,false,false,true,true,true,71,13,true,0.072,0.0022,6682,2008,8,16,Tuesday,false,false,false,false,false,false,false
1027354,I need an unordered list without any bullets,"I have created an unordered list. I feel that the bullets in the unordered list are bothersome, so I want to remove them.
Is it possible to have a list without bullets?
",https://stackoverflow.com/questions/1027354/i-need-an-unordered-list-without-any-bullets,2951,2511412.0,16.0,,,2009-06-22 13:57:53,2026-07-13 19:08:33,2026-07-13 19:08:33,,,html;css,praveenjayapal,38819,38172,registered,true,1027367,,CC BY-SA 4.0,2013-03-15 11:03:40,183,169,0,0,0,2,true,false,false,true,true,true,44,8,false,0.006,0.0012,6361,2009,6,13,Monday,false,false,false,false,false,false,false
90178,Make a div fill the height of the remaining screen space,"I am working on a web application where I want the content to fill the height of the entire screen.
The page has a header, which contains a logo, and account information. This could be an arbitrary height. I want the content div to fill the rest of the page to the bottom.
I have a header div and a content div. At the moment I am using a table for the layout like so:
CSS and HTML
#page {
height: 100%;
width: 100%
}
#tdcontent {
height: 100%;
}
#content {
overflow: auto; /* or overflow: hidden; */
}
<table id=""page"">
<tr>
<td id=""tdheader"">
<div id=""header"">...</div>
</td>
</tr>
<tr>
<td id=""tdcontent"">
<div id=""content"">...</div>
</td>
</tr>
</table>
The entire height of the page is filled, and no scrolling is required.
For anything inside the content div, setting top: 0; will put it right underneath the header. Sometimes the content will be a real table, with its height set to 100%. Putting header inside content will not allow this to work.
Is there a way to achieve the same effect without using the table?
Update:
Elements inside the content div will have heights set to percentages as well. So something at 100% inside the div will fill it to the bottom. As will two elements at 50%.
Update 2:
For instance, if the header takes up 20% of the screen's height, a table specified at 50% inside #content would take up 40% of the screen space. So far, wrapping the entire thing in a table is the only thing that works.
",https://stackoverflow.com/questions/90178/make-a-div-fill-the-height-of-the-remaining-screen-space,2861,2071181.0,43.0,,,2008-09-18 05:06:17,2024-07-23 17:26:02,2023-06-27 02:02:00,,,html;css;html-table,Vincent McNabb,35059,16299,registered,true,24979148,,CC BY-SA 4.0,2014-04-27 11:55:51,2100,1573,11,0,0,3,true,false,false,true,true,true,56,11,false,0.021,0.0014,6638,2008,9,5,Thursday,false,false,false,false,false,false,false
8865458,How do I vertically center text with CSS?,"I have a <div> element which contains text and I want to align the contents of this <div> vertically center.
Here is my <div> style:
#box {
height: 170px;
width: 270px;
background: #000;
font-size: 48px;
color: #FFF;
text-align: center;
}
<div id=""box"">
Lorem ipsum dolor sit
</div>
What is the best way to achieve this goal?
",https://stackoverflow.com/questions/8865458/how-do-i-vertically-center-text-with-css,2811,4539824.0,37.0,,,2012-01-14 21:25:10,2024-11-19 14:19:08,2020-09-16 07:13:30,2019-01-03 20:17:33,Duplicate,html;css;vertical-alignment,Irakli Lekishvili,34368,508284,registered,true,8865463,,,2014-09-20 19:50:15,740,381,5,0,0,3,true,true,false,true,true,true,41,8,true,0.008,0.0006,5425,2012,1,21,Saturday,true,false,false,false,false,false,false
2906582,How do I create an HTML button that acts like a link?,"How do I create an HTML button that acts like a link? So that clicking the button redirects the user to a page.
I want it to be accessible, and with minimal extra characters or parameters in the URL.
",https://stackoverflow.com/questions/2906582/how-do-i-create-an-html-button-that-acts-like-a-link,2777,10154088.0,38.0,,,2010-05-25 16:39:47,2026-06-14 04:20:26,2022-07-05 08:17:06,,,html;button;hyperlink;anchor,Andrew,241827,48523,registered,true,2906586,,CC BY-SA 4.0,2013-10-28 22:25:35,214,200,0,0,0,4,true,false,false,true,true,true,53,12,true,0.004,0.0003,6024,2010,5,16,Tuesday,false,false,false,false,false,false,false
1575141,How to make a div 100% height of the browser window,"I have a layout with two columns - a left div and a right div.
The right div has a grey background-color, and I need it to expand vertically depending on the height of the user's browser window. Right now, the background-color ends at the last piece of content in that div.
I've tried height: 100%;, min-height: 100%;, etc.
",https://stackoverflow.com/questions/1575141/how-to-make-a-div-100-height-of-the-browser-window,2706,2856584.0,44.0,,,2009-10-15 21:18:43,2025-06-05 10:33:29,2025-06-05 10:33:29,,,html;css;height,mike,27125,190874,unregistered,true,,,CC BY-SA 4.0,2014-10-11 23:13:07,449,324,8,0,0,3,false,false,false,true,true,true,51,11,false,0.015,0.0009,6246,2009,10,21,Thursday,false,false,false,false,false,false,false
806000,How do I reduce the opacity of an element's background using CSS?,"Is it possible, using CSS only, to make the background of an element semi-transparent but have the content (text & images) of the element opaque?
I'd like to accomplish this without having the text and the background as two separate elements.
When trying:
p {
position: absolute;
background-color: green;
filter: alpha(opacity=60);
opacity: 0.6;
}
span {
color: white;
filter: alpha(opacity=100);
opacity: 1;
}
<p>
<span>Hello world</span>
</p>
It looks like child elements are subjected to the opacity of their parents, so opacity:1 is relative to the opacity:0.6 of the parent.
",https://stackoverflow.com/questions/806000/how-do-i-reduce-the-opacity-of-an-elements-background-using-css,2554,1600049.0,30.0,,,2009-04-30 09:00:02,2026-09-15 10:47:17,2023-02-24 01:17:09,,,html;css;opacity,Stijn Sanders,37143,87971,registered,true,806189,,CC BY-SA 4.0,2011-11-08 15:56:38,1019,653,5,0,0,3,true,false,false,true,true,true,69,12,true,0.019,0.0016,6414,2009,4,9,Thursday,false,false,false,false,false,false,false
450903,How can I make a div not larger than its contents?,"I have a layout similar to:
<div>
<table>
</table>
</div>
I would like for the div to only expand to as wide as my table becomes.
",https://stackoverflow.com/questions/450903/how-can-i-make-a-div-not-larger-than-its-contents,2536,1952428.0,44.0,,,2009-01-16 16:03:07,2025-08-13 21:11:46,2019-11-19 12:51:17,,,html;css;width,George Snider,,,does_not_exist,true,,,CC BY-SA 4.0,2011-08-26 08:18:47,229,165,3,0,0,3,false,false,false,true,false,true,50,11,true,0.023,0.0013,6518,2009,1,16,Friday,false,false,false,false,false,false,false
1732348,RegEx match open tags except XHTML self-contained tags,"I need to match all of these opening tags:
<p>
<a href="foo">
But not self-closing tags:
<br />
<hr class="foo" />
I came up with this and wanted to make sure I've got it right. I am only capturing the a-z.
<([a-z]+) *[^/]*?>
I believe it says:
- Find a less-than, then
- Find (and capture) a-z one or more times, then
- Find zero or more spaces, then
- Find any character zero or more times, greedy, except
/, then
- Find a greater-than
Do I have that right? And more importantly, what do you think?
",https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags,2385,4099285.0,36.0,,,2009-11-13 22:38:26,2026-05-23 00:07:42,2024-01-22 09:15:29,,,html;regex;xhtml,Jeff,6156,142233,registered,true,1732454,,CC BY-SA 4.0,2010-12-06 13:29:47,733,546,5,0,0,3,true,false,false,true,true,true,54,8,false,0.009,0.0006,6217,2009,11,22,Friday,false,false,false,false,false,false,false
70579,HTML: Valid id attribute values?,"When creating the id attributes for HTML elements, what rules are there for the value?
",https://stackoverflow.com/questions/70579/html-valid-id-attribute-values,2313,578390.0,27.0,,,2008-09-16 09:08:52,2023-04-29 02:13:39,2023-03-18 06:42:04,,,html,Mr Shark,26558,6093,registered,true,79022,,CC BY-SA 4.0,2012-09-12 12:43:25,107,87,1,0,0,1,true,false,false,true,true,true,32,5,true,0.047,0.004,6640,2008,9,9,Tuesday,false,false,false,false,false,false,false
1041344,How can I select an element with multiple classes in jQuery?,"I want to select all the elements that have the two classes a and b.
<element class=""a b"">
So, only the elements that have both classes.
When I use $("".a, .b"") it gives me the union, but I want the intersection.
",https://stackoverflow.com/questions/1041344/how-can-i-select-an-element-with-multiple-classes-in-jquery,2304,1134593.0,14.0,,,2009-06-24 22:28:58,2024-05-10 14:28:08,2022-04-11 21:42:39,,,html;jquery;css;jquery-selectors;htmlelements,Mladen,25896,115873,registered,true,1041352,,CC BY-SA 4.0,2013-06-23 14:56:12,315,222,4,0,0,5,true,false,false,true,true,true,60,11,true,0.012,0.002,6359,2009,6,22,Wednesday,false,false,false,false,false,false,false
489340,Vertically align text next to an image?,"Why won't vertical-align: middle work? And yet, vertical-align: top does work.
span{
vertical-align: middle;
}
<div>
<img src=""https://via.placeholder.com/30"" alt=""small img"" />
<span>Doesn't work.</span>
</div>
",https://stackoverflow.com/questions/489340/vertically-align-text-next-to-an-image,2279,1660761.0,26.0,,,2009-01-28 21:01:50,2025-08-15 20:20:07,2021-02-19 19:14:49,,,html;css;alignment;vertical-alignment,sam,23363,58249,unregistered,true,489394,,CC BY-SA 4.0,2014-01-23 21:08:41,600,260,4,0,0,4,true,false,false,true,true,true,39,7,true,0.016,0.0014,6506,2009,1,21,Wednesday,false,false,false,false,false,false,false
1946426,"HTML 5: Is it <br>, <br/>, or <br />?","I've tried checking other answers, but I'm still confused — especially after seeing W3schools HTML 5 reference.
I thought HTML 4.01 was supposed to ""allow"" single-tags to just be <img> and <br>. Then XHTML came along with <img /> and <br /> (where someone said that the space is there for older browsers).
Now I'm wondering how I'm supposed to format my code when practicing HTML 5.
Is it <br>, <br/> or <br />?
",https://stackoverflow.com/questions/1946426/html-5-is-it-br-br-or-br,2197,1838138.0,17.0,,,2009-12-22 13:39:08,2023-06-26 03:34:07,2019-07-30 14:15:30,,,html,ehm,23757,15214,registered,true,1946446,,CC BY-SA 4.0,2013-06-23 10:10:54,824,458,7,3,0,1,true,false,false,true,true,true,55,9,true,0.009,0.0012,6178,2009,12,13,Tuesday,false,false,false,false,false,false,false
3029422,How to auto-resize an image while maintaining aspect ratio,"How do you auto-resize a large image so that it will fit into a smaller width div container whilst maintaining its width:height ratio?
Example: stackoverflow.com - when an image is inserted onto the editor panel and the image is too large to fit onto the page, the image is automatically resized.
",https://stackoverflow.com/questions/3029422/how-to-auto-resize-an-image-while-maintaining-aspect-ratio,2139,3844738.0,33.0,,,2010-06-12 17:00:37,2025-02-08 05:36:44,2023-10-11 12:54:14,,,html;css;image;aspect-ratio,001,65741,103264,registered,true,3029434,,CC BY-SA 4.0,2014-07-07 16:51:40,357,298,3,0,0,4,true,false,false,true,true,true,58,9,false,0.009,0.0006,6006,2010,6,17,Saturday,true,false,false,false,false,false,false
5805059,How do I make a placeholder for a 'select' box?,"I'm using placeholders for text inputs which is working out just fine. But I'd like to use a placeholder for my selectboxes as well. Of course I can just use this code:
<select>
<option value="""">Select your option</option>
<option value=""hurr"">Durr</option>
</select>
But the 'Select your option' is in black instead of lightgrey. So my solution could possibly be CSS-based. jQuery is fine too.
This only makes the option grey in the dropdown (so after clicking the arrow):
option:first {
color: #999;
}
The question is: How do people create placeholders in selectboxes? But it has already been answered, cheers.
And using this results in the selected value always being grey (even after selecting a real option):
select {
color: #999;
}
",https://stackoverflow.com/questions/5805059/how-do-i-make-a-placeholder-for-a-select-box,2093,2644267.0,44.0,,,2011-04-27 13:39:15,2025-05-29 12:47:09,2019-09-01 13:05:18,,,html;css;html-select;placeholder,Thomas,21731,632844,registered,true,5859221,,CC BY-SA 4.0,2014-08-30 21:50:28,983,800,3,0,0,4,true,false,false,true,true,true,55,10,true,0.017,0.0008,5687,2011,4,13,Wednesday,false,false,false,false,false,false,false
3518002,How can I set the default value for an HTML <select> element?,"I thought that adding a ""value"" attribute set on the <select> element below would cause the <option> containing my provided ""value"" to be selected by default:
<select name=""hall"" id=""hall"" value=""3"">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
However, this did not work as I had expected. How can I set which <option> element is selected by default?
",https://stackoverflow.com/questions/3518002/how-can-i-set-the-default-value-for-an-html-select-element,2025,4050493.0,36.0,,,2010-08-19 01:10:51,2025-03-13 15:13:23,2019-01-24 18:50:03,,,html;html-select,Jichao,42253,193251,registered,true,3518011,,CC BY-SA 4.0,2014-04-21 22:37:32,828,530,6,0,0,2,true,false,false,true,true,true,67,12,true,0.009,0.0005,5938,2010,8,1,Thursday,false,false,false,false,false,false,false
16670931,"Hide scroll bar, but while still being able to scroll","I want to be able to scroll through the whole page, but without the scrollbar being shown.
In Google Chrome it's:
::-webkit-scrollbar {
display: none;
}
But Mozilla Firefox and Internet Explorer don't seem to work like that.
I also tried this in CSS:
overflow: hidden;
That does hide the scrollbar, but I can't scroll any more.
Is there a way I can remove the scrollbar while still being able to scroll the whole page?
With just CSS or HTML, please.
",https://stackoverflow.com/questions/16670931/hide-scroll-bar-but-while-still-being-able-to-scroll,2022,3251559.0,44.0,,,2013-05-21 13:11:37,2025-06-09 11:40:05,2019-11-10 11:47:50,,,html;css;google-chrome;internet-explorer;firefox,user_2215528,20454,2215528,registered,true,16671476,,CC BY-SA 4.0,2016-02-12 09:23:58,561,464,2,0,0,5,true,false,false,true,true,true,53,10,false,0.014,0.0006,4932,2013,5,13,Tuesday,false,false,false,false,false,false,false
4526273,What does enctype='multipart/form-data' mean?,"What does enctype='multipart/form-data' mean in an HTML form and when should we use it?
",https://stackoverflow.com/questions/4526273/what-does-enctype-multipart-form-data-mean,1960,1981980.0,9.0,,,2010-12-24 12:19:27,2025-10-23 13:30:42,2019-02-02 14:21:21,,,html;http-headers;multipartform-data,EBAG,22771,127193,registered,true,4526286,,CC BY-SA 4.0,2013-11-04 07:17:22,108,88,1,0,0,3,true,false,false,true,true,true,53,4,true,0.005,0.001,5811,2010,12,12,Friday,false,false,false,false,false,false,false
469059,<button> vs. <input type="button"> -- which to use?,"When looking at most sites (including SO), most of them use:
<input type=""button"" />
instead of:
<button></button>
- What are the main differences between the two, if any?
- Are there valid reasons to use one instead of the other?
- Are there valid reasons to use combine them?
- Does using
<button> come with compatibility issues, seeing it is not very widely used?
",https://stackoverflow.com/questions/469059/button-vs-input-type-button-which-to-use,1929,717415.0,17.0,,,2009-01-22 13:14:11,2025-03-31 20:40:56,2024-07-02 21:57:19,,,html;button;compatibility,Aron Rotteveel,83496,11568,registered,true,469084,,CC BY-SA 4.0,2015-10-05 09:18:32,511,391,3,0,0,3,true,false,false,true,true,true,73,8,true,0.024,0.0027,6512,2009,1,13,Thursday,false,false,false,false,false,false,false
306252,How to align checkboxes and their labels consistently cross-browsers,"This is one of the minor CSS problems that plague me constantly.
How do folks around Stack Overflow vertically align checkboxes and their labels consistently cross-browser?
Whenever I align them correctly in Safari (usually using vertical-align: baseline on the input), they're completely off in Firefox and IE.
Fix it in Firefox, and Safari and IE are inevitably messed up. I waste time on this every time I code a form.
Here's the standard code that I work with:
<form>
<div>
<label><input type=""checkbox"" /> Label text</label>
</div>
</form>
I usually use Eric Meyer's reset, so form elements are relatively clean of overrides. Looking forward to any tips or tricks that you have to offer!
",https://stackoverflow.com/questions/306252/how-to-align-checkboxes-and-their-labels-consistently-cross-browsers,1904,1277007.0,40.0,,,2008-11-20 18:02:01,2025-01-16 19:53:52,2021-04-01 09:14:18,,,html;css;cross-browser;alignment;forms,One Crayon,19279,38666,registered,true,306593,,CC BY-SA 4.0,2012-07-11 21:44:55,1144,761,5,0,0,5,true,false,false,true,true,true,68,9,false,0.031,0.0015,6575,2008,11,18,Thursday,false,false,false,false,false,false,false
5411538,How to redirect one HTML page to another on load,"Is it possible to set up a basic HTML page to redirect to another page on load?
",https://stackoverflow.com/questions/5411538/how-to-redirect-one-html-page-to-another-on-load,1879,3787930.0,24.0,,,2011-03-23 20:58:29,2026-06-28 07:07:09,2025-04-14 22:45:50,,,html;http-redirect;html-meta,chobo,32611,173432,registered,true,5411567,,CC BY-SA 4.0,2014-01-08 23:24:17,87,80,0,0,0,3,true,false,false,true,true,true,48,10,false,0.006,0.0005,5722,2011,3,20,Wednesday,false,false,false,false,false,false,false
6771258,What does <meta http-equiv="X-UA-Compatible" content="IE=edge"> do?,"What's the difference if one web page starts with
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=""X-UA-Compatible"" content=""IE=edge"">
and If page starts with
<!DOCTYPE html>
<html>
<head>
<!-- without X-UA-Compatible meta -->
If there is no difference, I suppose I can just ignore the X-UA-Compatible meta header, since I just want it to be rendered in most standard mode in all IE versions.
",https://stackoverflow.com/questions/6771258/what-does-meta-http-equiv-x-ua-compatible-content-ie-edge-do,1755,1567425.0,12.0,,,2011-07-21 04:29:43,2021-11-16 18:44:44,2019-11-08 14:37:43,,,html;internet-explorer;browser;x-ua-compatible,Morgan Cheng,76508,26349,registered,true,6771584,,CC BY-SA 4.0,2014-01-14 20:06:18,548,466,3,0,0,4,true,false,false,true,true,true,93,6,true,0.008,0.0011,5602,2011,7,4,Thursday,false,false,false,false,false,false,false
396145,How can I vertically center a div element for all browsers using CSS?,"I want to center a div vertically with CSS. I don't want tables or JavaScript, but only pure CSS. I found some solutions, but all of them are missing Internet Explorer 6 support.
<body>
<div>Div to be aligned vertically</div>
</body>
How can I center a div vertically in all major browsers, including Internet Explorer 6?
",https://stackoverflow.com/questions/396145/how-can-i-vertically-center-a-div-element-for-all-browsers-using-css,1694,1932534.0,51.0,,,2008-12-28 12:57:16,2026-03-06 09:41:56,2022-04-11 21:48:53,,,html;css;alignment;vertical-alignment;centering,Burak Erdem,20118,49380,registered,true,6182661,,CC BY-SA 4.0,2014-03-16 01:10:10,415,351,3,0,0,5,true,false,false,true,true,true,69,13,true,0.026,0.0009,6537,2008,12,12,Sunday,true,false,false,false,false,false,false
4696499,<meta charset="utf-8"> vs <meta http-equiv="Content-Type">,"In order to define charset for HTML5 Doctype, which notation should I use?
Short:
<meta charset="utf-8" />
Long:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
",https://stackoverflow.com/questions/4696499/meta-charset-utf-8-vs-meta-http-equiv-content-type,1660,1254605.0,8.0,,,2011-01-14 22:06:47,2025-10-04 13:28:09,2025-10-04 10:36:53,,,html;html-meta;doctype,CuriousMind,34285,367985,registered,true,4696517,,CC BY-SA 4.0,2013-06-22 17:29:40,358,232,3,0,0,3,true,false,false,true,true,true,90,5,false,0.006,0.0013,5790,2011,1,22,Friday,false,false,false,false,false,false,false
1895476,How do I style a <select> dropdown with only CSS?,"Is there a CSS-only way to style a <select> dropdown?
I need to style a <select> form as much as humanly possible, without any JavaScript. What are the properties I can use to do so in CSS?
This code needs to be compatible with all major browsers:
- Internet Explorer 6, 7, and 8
- Firefox
- Safari
I know I can make it with JavaScript: Example.
And I'm not talking about simple styling. I want to know, what the best we can do with CSS only.
I found similar questions on Stack Overflow.
And this one on Doctype.com.
",https://stackoverflow.com/questions/1895476/how-do-i-style-a-select-dropdown-with-only-css,1656,2236122.0,27.0,,,2009-12-13 03:33:56,2025-04-02 11:09:55,2019-09-07 19:15:07,,,html;css;combobox;cross-browser;skinning,Jitendra Vyas,154325,84201,registered,true,13968900,,CC BY-SA 4.0,2013-01-02 18:05:43,932,537,2,3,0,5,true,false,false,true,true,true,55,10,true,0.012,0.0007,6187,2009,12,3,Sunday,true,false,false,false,false,false,false
2939914,How do I vertically align text in a div?,"I am trying to find the most effective way to align text with a div. I have tried a few things and none seem to work.
.testimonialText {
position: absolute;
left: 15px;
top: 15px;
width: 150px;
height: 309px;
vertical-align: middle;
text-align: center;
font-family: Georgia, ""Times New Roman"", Times, serif;
font-style: italic;
padding: 1em 0 1em 0;
}
<div class=""testimonialText"">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
",https://stackoverflow.com/questions/2939914/how-do-i-vertically-align-text-in-a-div,1614,2448221.0,36.0,,,2010-05-30 19:02:13,2025-02-18 00:28:47,2018-06-23 16:04:06,,,html;css;vertical-alignment,shinjuo,21210,271534,registered,true,2939979,,CC BY-SA 4.0,2014-09-23 07:38:13,1203,898,2,0,0,3,true,false,false,true,true,true,40,9,true,0.015,0.0007,6019,2010,5,19,Sunday,true,false,false,false,false,false,false
3220660,Local Storage vs Cookies,"Are there any differences in using local storage to replace cookie functionality other than the obvious compatibility issues?
I want to reduce load times on my websites by moving all cookies into local storage since they seem to have the same functionality.
",https://stackoverflow.com/questions/3220660/local-storage-vs-cookies,1515,686886.0,9.0,,,2010-07-10 20:02:10,2025-07-08 13:48:40,2025-07-05 00:05:08,,,html;cookies;browser;local-storage;httprequest,Gio Borje,21284,259311,registered,true,3220802,,CC BY-SA 4.0,2017-04-09 17:54:44,272,258,0,0,0,5,true,false,false,true,true,true,24,4,false,0.013,0.0022,5978,2010,7,20,Saturday,true,false,false,false,false,false,false
1495407,Maintain the aspect ratio of a div with CSS,"I want to create a responsive div that can change its width/height as the window's width changes.
Are there any CSS rules that would allow the height to change according to the width, while maintaining its aspect ratio?
I know I can do this via JavaScript, but I would prefer using only CSS.
",https://stackoverflow.com/questions/1495407/maintain-the-aspect-ratio-of-a-div-with-css,1471,914532.0,34.0,,,2009-09-29 23:11:05,2025-10-11 15:48:04,2023-02-16 14:25:03,,,html;css;responsive-design;aspect-ratio,jackb,14731,77821,registered,true,10441480,,CC BY-SA 4.0,2015-05-15 06:32:57,519,293,1,1,1,4,true,false,false,true,true,true,43,9,false,0.037,0.0016,6262,2009,9,23,Tuesday,false,false,false,false,false,false,false
585945,How to align content of a div to the bottom,"Say I have the following CSS and HTML code:
#header {
height: 150px;
}
<div id=""header"">
<h1>Header title</h1>
Header content (one or multiple lines)
</div>
The header section is fixed height, but the header content may change.
I would like the content of the header to be vertically aligned to the bottom of the header section, so the last line of text ""sticks"" to the bottom of the header section.
So if there is only one line of text, it would be like:
-----------------------------
| Header title
|
|
|
| header content (resulting in one line)
-----------------------------
And if there were three lines:
-----------------------------
| Header title
|
| header content (which is so
| much stuff that it perfectly
| spans over three lines)
-----------------------------
How can this be done in CSS?
",https://stackoverflow.com/questions/585945/how-to-align-content-of-a-div-to-the-bottom,1470,2945739.0,29.0,,,2009-02-25 13:15:09,2023-02-05 17:44:43,2020-04-19 10:51:39,,,html;css;vertical-alignment,kristof,54054,3241,registered,true,585965,,CC BY-SA 4.0,2013-12-01 14:20:35,1223,860,2,0,0,3,true,false,false,true,true,true,43,10,false,0.01,0.0005,6478,2009,2,13,Wednesday,false,false,false,false,false,false,false
2701192,What characters can be used for up/down triangle (arrow without stem) for display in HTML?,"I'm looking for a HTML or ASCII character which is a triangle pointing up or down so that I can use it as a toggle switch.
I found ↑ (↑), and ↓ (↓) - but those have a narrow stem. I'm looking just for the HTML arrow ""head"".
",https://stackoverflow.com/questions/2701192/what-characters-can-be-used-for-up-down-triangle-arrow-without-stem-for-displa,1417,1507036.0,20.0,,,2010-04-23 18:51:54,2024-04-16 10:07:17,2024-01-12 19:34:10,2024-01-12 19:32:29,Duplicate,html;css;unicode;icons;symbols,Timj,14327,323920,unregistered,true,2701226,,,2013-07-31 17:15:37,327,253,2,0,0,5,true,true,false,true,true,true,90,15,true,0.013,0.0009,6056,2010,4,18,Friday,false,false,false,false,false,false,false
10403138,What is the purpose of the "role" attribute in HTML?,"I keep seeing role attributes in some people's work. I use it too, but I'm not sure about its effect.
For example:
<header id="header" role="banner">
Header stuff in here
</header>
Or:
<section id="facebook" role="contentinfo">
Facebook stuff in here
</section>
Or:
<section id="main" role="main">
Main content stuff in here
</section>
Is this role attribute necessary, better for semantics, and does it improve SEO?
A list of roles can be found here, but I see some people make up their own. Is that allowed or a correct use of the role attribute?
",https://stackoverflow.com/questions/10403138/what-is-the-purpose-of-the-role-attribute-in-html,1411,830265.0,8.0,,,2012-05-01 10:11:45,2023-08-19 02:30:18,2023-05-03 14:40:42,,,html;optimization;attributes;seo;roles,jeroen,14218,707544,registered,true,18664038,,,2015-04-10 06:33:14,847,662,3,1,0,5,true,false,false,true,true,true,62,10,true,0.01,0.0017,5317,2012,5,10,Tuesday,false,false,false,false,false,false,false
8839753,How do I reformat HTML code using Sublime Text 2?,"I've got some poorly-formatted HTML code that I'd like to reformat. Is there a command that will automatically reformat HTML code in Sublime Text 2 so it looks better and is easier to read?
",https://stackoverflow.com/questions/8839753/how-do-i-reformat-html-code-using-sublime-text-2,1403,1153535.0,17.0,,,2012-01-12 17:49:30,2024-11-08 00:41:30,2015-12-21 19:29:03,,,html;sublimetext2;sublimetext;indentation;reformat,Ravi Ram,24556,665387,registered,true,10888837,,CC BY-SA 3.0,2015-10-05 09:20:12,197,190,0,0,0,5,true,false,false,true,true,true,49,10,true,0.015,0.0012,5427,2012,1,17,Thursday,false,false,false,false,false,false,false
291813,Recommended way to embed PDF in HTML?,"What is the recommended way to embed PDF in HTML?
- iFrame?
- Object?
- Embed?
What does Adobe say itself about it?
In my case, the PDF is generated on the fly, so it can't be uploaded to a third-party solution prior to flushing it.
",https://stackoverflow.com/questions/291813/recommended-way-to-embed-pdf-in-html,1398,2019706.0,24.0,,,2008-11-14 23:55:13,2025-02-10 13:50:12,2012-10-06 12:28:28,2024-07-18 00:26:13,Opinion-based,html;pdf,Daniel Silveira,42751,1100,registered,true,291823,,,2011-05-06 17:46:15,291,234,0,0,0,2,true,true,false,true,true,true,37,7,true,0.012,0.0007,6581,2008,11,23,Friday,false,false,false,false,false,false,false
2941189,How to overlay one div over another div,"I need assistance with overlaying one individual div over another individual div.
My code looks like this:
<div class=""navi""></div>
<div id=""infoi"">
<img src=""info_icon2.png"" height=""20"" width=""32""/>
</div>
Unfortunately I cannot nest the div#infoi or the img, inside the first div.navi.
It has to be two separate divs as shown, but I need to know how I could place the div#infoi over the div.navi and to the right most side and centered on top of the div.navi.
",https://stackoverflow.com/questions/2941189/how-to-overlay-one-div-over-another-div,1382,2847387.0,9.0,,,2010-05-31 03:15:23,2023-04-24 12:53:53,2019-07-15 23:35:00,,,html;css;position;overlay,tonyf,35845,111479,registered,true,2941203,,CC BY-SA 4.0,2013-05-06 06:50:16,670,501,10,0,0,4,true,false,false,true,true,true,39,8,false,0.003,0.0005,6018,2010,5,3,Monday,false,false,false,false,false,false,false
1033156,How can I write 'a:hover' in inline CSS?,"I have a case where I must write inline CSS code, and I want to apply a hover style on an anchor.
How can I use a:hover in inline CSS inside the HTML style attribute?
E.g., you can't reliably use CSS classes in HTML emails.
",https://stackoverflow.com/questions/1033156/how-can-i-write-ahover-in-inline-css,1382,1750059.0,25.0,,,2009-06-23 15:07:28,2024-10-26 08:19:16,2022-12-10 02:48:54,,,html;css;inline-styles,Amr Elgarhy,69286,20126,registered,true,1033166,,CC BY-SA 4.0,2014-02-02 18:38:13,258,224,1,0,0,3,true,false,false,true,true,true,48,8,true,0.014,0.0008,6360,2009,6,15,Tuesday,false,false,false,false,false,false,false
3790935,Can I hide the HTML5 number input’s spin box?,"Is there a consistent way across browsers to hide the new spin boxes that some browsers (such as Chrome) render for HTML input of type number? I am looking for a CSS or JavaScript method to prevent the up/down arrows from appearing.
<input id=""test"" type=""number"">
",https://stackoverflow.com/questions/3790935/can-i-hide-the-html5-number-input-s-spin-box,1377,983535.0,20.0,,,2010-09-24 20:58:22,2025-03-15 12:48:06,2023-09-15 13:30:09,,,html;css;input;numbers,Alan,14002,345164,registered,true,4298216,,CC BY-SA 4.0,2025-03-16 11:19:57,508,282,1,0,0,4,true,false,false,true,true,true,45,9,true,0.02,0.0014,5902,2010,9,20,Friday,false,false,false,false,false,false,false
15551779,Open link in new tab or window,"Is it possible to open an a href link in a new tab instead of the same tab?
<a href=""http://your_url_here.html"">Link</a>
",https://stackoverflow.com/questions/15551779/open-link-in-new-tab-or-window,1357,1842922.0,4.0,,,2013-03-21 15:33:40,2023-03-07 21:00:12,2016-09-15 11:14:40,2013-03-21 21:34:56,exact duplicate,html;tabs;hyperlink;window;href,Rene,13835,2190971,registered,true,15551842,,,,179,135,2,0,0,5,true,true,false,true,true,true,30,7,false,0.002,0.0007,4993,2013,3,15,Thursday,false,false,false,false,false,false,false
5078239,How to remove the space between inline/inline-block elements?,"There will be a 4 pixel wide space between these span elements:
span {
display: inline-block;
width: 100px;
background-color: palevioletred;
}
<p>
<span> Foo </span>
<span> Bar </span>
</p>
I understand that I could get rid of that space by removing the white-space between the span elements in the HTML:
<p>
<span> Foo </span><span> Bar </span>
</p>
I'm Looking for a CSS solution that doesn't involve:
- Altering the HTML.
- JavaScript.
",https://stackoverflow.com/questions/5078239/how-to-remove-the-space-between-inline-inline-block-elements,1299,522010.0,37.0,,,2011-02-22 12:41:14,2026-03-10 20:31:53,2022-05-22 05:40:53,,,html;css;flexbox,Šime Vidas,186742,425275,registered,true,5078297,,CC BY-SA 4.0,2026-03-10 20:32:13,1046,545,5,1,0,3,true,false,false,true,true,true,61,8,true,0.071,0.0025,5751,2011,2,12,Tuesday,false,false,false,false,false,false,false
5195452,WebSockets vs. Server-Sent events/EventSource,"Both WebSockets and Server-Sent Events are capable of pushing data to browsers. To me they seem to be competing technologies. What is the difference between them? When would you choose one over the other?
Please answer with facts and citations.
",https://stackoverflow.com/questions/5195452/websockets-vs-server-sent-events-eventsource,1283,383512.0,7.0,,,2011-03-04 15:07:32,2024-06-02 13:48:56,2024-06-02 13:48:56,2024-01-01 20:25:25,Opinion-based,html;browser;websocket;server-sent-events,Mads Mobæk,36288,76799,registered,true,5326159,,,,439,245,0,2,0,4,true,true,false,true,true,true,45,4,false,0.018,0.0033,5741,2011,3,15,Friday,false,false,false,false,false,false,false
5703552,How can I center text (horizontally and vertically) inside a div block?,"I have a div set to display:block (90px height and width), and I have some text inside.
I need the text to be aligned in the center both vertically and horizontally.
I have tried text-align:center, but it doesn't do the vertical centering part, so I tried vertical-align:middle, but it didn't work.
Any ideas?
",https://stackoverflow.com/questions/5703552/how-can-i-center-text-horizontally-and-vertically-inside-a-div-block,1262,2712277.0,32.0,,,2011-04-18 13:22:47,2025-10-27 22:40:36,2021-09-29 12:45:58,,,html;css,Satch3000,49758,683553,registered,true,5703632,,CC BY-SA 4.0,2018-07-07 14:12:31,429,310,7,0,0,2,true,false,false,true,true,true,71,12,true,0.012,0.0005,5696,2011,4,13,Monday,false,false,false,false,false,false,false
8499633,How to display Base64 images in HTML,"I'm having trouble displaying a Base64 image inline.
How can I do it?
<!DOCTYPE html>
<html>
<head>
<title>Display Image</title>
</head>
<body>
<img style='display:block; width:100px;height:100px;' id='base64image'
src='data:image/jpeg;base64, LzlqLzRBQ... <!-- Base64 data -->' />
</body>
</html>
",https://stackoverflow.com/questions/8499633/how-to-display-base64-images-in-html,1238,2984214.0,14.0,,,2011-12-14 04:53:21,2025-11-14 14:42:29,2023-07-19 15:42:58,,,html;image;base64,Christopher,13487,619734,registered,true,8499716,,CC BY-SA 4.0,2015-09-16 16:21:32,426,388,1,0,0,3,true,false,false,true,true,true,36,7,false,0.005,0.0004,5456,2011,12,4,Wednesday,false,false,false,false,false,false,false
217776,How to apply CSS to iframe?,"I have a simple page that has some iframe sections (to display RSS links). How can I apply the same CSS format from the main page to the page displayed in the iframe?
",https://stackoverflow.com/questions/217776/how-to-apply-css-to-iframe,1237,1744431.0,29.0,,,2008-10-20 08:27:14,2024-10-30 14:28:26,2019-12-16 04:55:34,,,html;css;iframe;rss,John,,,does_not_exist,true,,,CC BY-SA 4.0,2011-05-29 15:23:05,174,167,0,0,0,4,false,false,false,true,false,true,27,6,true,0.017,0.0007,6606,2008,10,8,Monday,false,false,false,false,false,false,false
6293588,How to create a checkbox with a clickable label?,"How can I create an HTML checkbox with a label that is clickable (this means that clicking on the label turns the checkbox on/off)?
",https://stackoverflow.com/questions/6293588/how-to-create-a-checkbox-with-a-clickable-label,1217,1056309.0,12.0,,,2011-06-09 13:33:46,2024-07-02 07:16:47,2019-06-11 14:25:36,,,html;checkbox;click;label,laurent,91357,561309,registered,true,6293626,,CC BY-SA 4.0,2014-12-29 21:04:02,139,132,0,0,0,4,true,false,false,true,true,true,48,9,true,0.011,0.0012,5644,2011,6,13,Thursday,false,false,false,false,false,false,false
2487747,Selecting element by data attribute with jQuery,"Is there an easy and straight-forward method to select elements based on their data attribute? For example, select all anchors that has data attribute named customerID which has value of 22.
I am kind of hesitant to use rel or other attributes to store such information, but I find it much harder to select an element based on what data is stored in it.
",https://stackoverflow.com/questions/2487747/selecting-element-by-data-attribute-with-jquery,1210,1355492.0,11.0,,,2010-03-21 16:13:15,2025-03-26 17:02:43,2021-02-10 14:36:51,,,jquery;html;custom-data-attribute,Hazem Salama,15171,279482,registered,true,2487751,,CC BY-SA 4.0,2016-02-01 07:26:08,424,358,4,0,0,3,true,false,false,true,true,true,47,7,false,0.008,0.0009,6089,2010,3,16,Sunday,true,false,false,false,false,false,false
19011861,Is there a float input type in HTML5?,"According to html5.org, the ""number"" input type's ""value attribute, if specified and not empty, must have a value that is a valid floating point number.""
Yet it is simply (in the latest version of Chrome, anyway), an ""updown"" control with integers, not floats:
<input type=""number"" id=""totalAmt""></input>
Is there a floating point input element native to HTML5, or a way to make the number input type work with floats, not ints? Or must I resort to a jQuery UI plugin?
",https://stackoverflow.com/questions/19011861/is-there-a-float-input-type-in-html5,1209,1216595.0,13.0,,,2013-09-25 17:51:41,2022-10-31 09:30:39,2018-06-08 12:38:45,,,html;input;floating-point,B. Clay Shannon-B. Crow Raven,10955,875317,registered,true,19012837,,CC BY-SA 4.0,,802,494,1,1,0,3,true,false,false,true,true,true,37,8,true,0.011,0.001,4805,2013,9,17,Wednesday,false,false,false,false,false,false,false
6939864,What is the difference between <section> and <div>?,"What is the difference between <section> and <div> in HTML?
Aren't we defining sections in both cases?
",https://stackoverflow.com/questions/6939864/what-is-the-difference-between-section-and-div,1195,853928.0,14.0,,,2011-08-04 10:33:13,2025-05-12 12:29:14,2020-01-02 09:56:27,,,html,Simplicity,49466,588855,registered,true,,,CC BY-SA 4.0,2018-09-12 12:10:47,167,115,3,0,0,1,false,false,false,true,true,true,63,8,true,0.016,0.0014,5588,2011,8,10,Thursday,false,false,false,false,false,false,false
7372038,Is there any way to change input type="date" format?,"By default, the input type="date" shows date as YYYY-MM-DD.
The question is, is it possible to force it's format to something like: DD-MM-YYYY?
",https://stackoverflow.com/questions/7372038/is-there-any-way-to-change-input-type-date-format,1163,2364895.0,25.0,,,2011-09-10 13:33:36,2026-09-09 13:11:27,2022-05-12 10:36:15,,,html;css;date;input,Tural Ali,22883,800639,registered,true,9519493,,CC BY-SA 4.0,2015-08-19 09:23:06,207,154,3,0,0,4,true,false,false,true,true,true,62,9,true,0.011,0.0005,5551,2011,9,13,Saturday,true,false,false,false,false,false,false
572768,Styling an <input type="file"> button,"How do you style an input type="file" button?
<input type=""file"" />
",https://stackoverflow.com/questions/572768/styling-an-input-type-file-button,1158,2033467.0,49.0,,,2009-02-21 10:36:49,2026-02-07 10:37:40,2026-02-07 10:37:40,,,html;css,Shivanand,12087,34642,registered,true,714626,,CC BY-SA 4.0,2014-10-15 23:20:52,333,94,2,0,0,2,true,false,false,true,true,true,53,5,false,0.024,0.0006,6482,2009,2,10,Saturday,true,false,false,false,false,false,false
190396,Adding HTML entities using CSS content,"How do you use the CSS content property to add HTML entities?
Using something like this just prints to the screen instead of the non-breaking space:
.breadcrumbs a:before {
content: ' ';
}
",https://stackoverflow.com/questions/190396/adding-html-entities-using-css-content,1143,520075.0,11.0,,,2008-10-10 07:19:25,2025-10-29 21:22:04,2021-08-20 10:32:14,,,html;css;html-entities;css-content,nickf,548426,9021,registered,true,190412,,CC BY-SA 4.0,2013-05-31 12:38:56,348,212,3,0,0,4,true,false,false,true,true,true,38,6,false,0.021,0.0022,6616,2008,10,7,Friday,false,false,false,false,false,false,false
4782068,Can I set subject/content of email using mailto:?,"Is it possible to set the subject/content of email when I use mailto:?
",https://stackoverflow.com/questions/4782068/can-i-set-subject-content-of-email-using-mailto,1135,1197313.0,15.0,,,2011-01-24 12:41:08,2023-05-12 07:32:49,2017-12-08 21:04:06,,,html;email;mailto,Jiew Meng,89473,292291,registered,true,4782084,,CC BY-SA 3.0,2016-08-10 21:13:34,78,71,0,0,0,3,true,false,false,true,true,true,49,8,true,0.013,0.0009,5780,2011,1,12,Monday,false,false,false,false,false,false,false
4088467,Get the value in an input text box,"What are the ways to get and render an input value using jQuery?
Here is one:
$(document).ready(function() {
$(""#txt_name"").keyup(function() {
alert($(this).val());
});
})
<script src=""https://cdnjs.cloudflare.com/ajax/libs/jquery/1.4.3/jquery.min.js""></script>
<input type=""text"" id=""txt_name"" />
",https://stackoverflow.com/questions/4088467/get-the-value-in-an-input-text-box,1128,2840045.0,13.0,,,2010-11-03 15:07:17,2021-12-14 12:08:01,2020-06-27 21:44:39,,,html;jquery;jquery-selectors;textinput;html-input,Bharanikumar,25803,246963,registered,true,15903284,,CC BY-SA 4.0,2015-11-03 17:18:46,653,343,2,0,0,5,true,false,false,true,true,true,34,8,false,0.005,0.0004,5862,2010,11,15,Wednesday,false,false,false,false,false,false,false
6654958,Make body have 100% of the browser height,"I want to make body have 100% of the browser height. Can I do that using CSS?
I tried setting height: 100%, but it doesn't work.
I want to set a background color for a page to fill the entire browser window, but if the page has little content I get a ugly white bar at the bottom.
",https://stackoverflow.com/questions/6654958/make-body-have-100-of-the-browser-height,1125,1337934.0,25.0,,,2011-07-11 18:50:56,2024-08-15 04:16:03,2022-06-24 16:36:05,,,html;css;height,bodyofheat,11253,839463,unregistered,true,6654996,,CC BY-SA 4.0,2014-05-12 22:36:30,328,281,2,0,0,3,true,false,false,true,true,true,41,8,false,0.019,0.0008,5612,2011,7,18,Monday,false,false,false,false,false,false,false
79461,How can I vertically align elements in a div?,"I have a div with two images and an h1. All of them need to be vertically aligned within the div, next to each other. One of the images needs to be absolute positioned within the div.
What is the CSS needed for this to work on all common browsers?
<div id="header">
<img src=".." ></img>
<h1>testing...</h1>
<img src="..."></img>
</div>
",https://stackoverflow.com/questions/79461/how-can-i-vertically-align-elements-in-a-div,1097,2114359.0,31.0,,,2008-09-17 02:53:36,2025-02-13 05:58:28,2022-07-12 06:57:47,,,html;css;vertical-alignment,Abdu,16677,5232,registered,true,84616,,CC BY-SA 4.0,2014-09-23 09:50:13,551,422,5,0,0,3,true,false,false,true,true,true,45,9,true,0.015,0.0005,6639,2008,9,2,Wednesday,false,false,false,false,false,false,false
4148499,How to style a checkbox using CSS,"I am trying to style a checkbox using the following:
<input type=""checkbox"" style=""border:2px dotted #00f;display:block;background:#ff0000;"" />
But the style is not applied. The checkbox still displays its default style. How do I give it the specified style?
",https://stackoverflow.com/questions/4148499/how-to-style-a-checkbox-using-css,1093,2493091.0,43.0,,,2010-11-10 19:57:01,2025-06-01 00:06:58,2019-07-17 15:35:22,,,html;css;checkbox,Salman Virk,12347,395881,registered,true,,,CC BY-SA 4.0,2021-09-14 01:16:25,510,277,1,0,0,3,false,false,false,true,true,true,33,7,false,0.017,0.0004,5855,2010,11,19,Wednesday,false,false,false,false,false,false,false
8554043,What is a clearfix?,"Recently I was looking through some website's code, and saw that every <div> had a class clearfix.
After a quick Google search, I learned that it is for IE6 sometimes, but what actually is a clearfix?
Could you provide some examples of a layout with a clearfix, compared to a layout without a clearfix?
",https://stackoverflow.com/questions/8554043/what-is-a-clearfix,1089,720282.0,10.0,,,2011-12-18 19:02:44,2023-01-30 08:46:58,2016-09-12 17:03:48,,,html;css;layout;cross-browser;clearfix,H Bellamy,22833,1020773,registered,true,8554054,,CC BY-SA 3.0,2013-09-10 09:05:24,377,313,2,0,0,5,true,false,false,true,true,true,19,4,true,0.014,0.0015,5452,2011,12,19,Sunday,true,false,false,false,false,false,false
218760,How do you keep parents of floated elements from collapsing?,"Although elements like <div>s normally grow to fit their contents, using the float property can cause a startling problem for CSS newbies: If floated elements have non-floated parent elements, the parent will collapse.
For example:
<div>
<div style=""float: left;"">Div 1</div>
<div style=""float: left;"">Div 2</div>
</div>
The parent div in this example will not expand to contain its floated children - it will appear to have height: 0.
How do you solve this problem?
I would like to create an exhaustive list of solutions here. If you're aware of cross-browser compatibility issues, please point them out.
Solution 1
Float the parent.
<div style=""float: left;"">
<div style=""float: left;"">Div 1</div>
<div style=""float: left;"">Div 2</div>
</div>
Pros: Semantic code.
Cons: You may not always want the parent floated. Even if you do, do you float the parents' parent, and so on? Must you float every ancestor element?
Solution 2
Give the parent an explicit height.
<div style=""height: 300px;"">
<div style=""float: left;"">Div 1</div>
<div style=""float: left;"">Div 2</div>
</div>
Pros: Semantic code.
Cons: Not flexible - if the content changes or the browser is resized, the layout will break.
Solution 3
Append a "spacer" element inside the parent element, like this:
<div>
<div style=""float: left;"">Div 1</div>
<div style=""float: left;"">Div 2</div>
<div class=""spacer"" style=""clear: both;""></div>
</div>
Pros: Straightforward to code.
Cons: Not semantic; the spacer div exists only as a layout hack.
Solution 4
Set parent to overflow: auto.
<div style=""overflow: auto;"">
<div style=""float: left;"">Div 1</div>
<div style=""float: left;"">Div 2</div>
</div>
Pros: Doesn't require extra div.
Cons: Seems like a hack - that's not the overflow property's stated purpose.
Comments? Other suggestions?
",https://stackoverflow.com/questions/218760/how-do-you-keep-parents-of-floated-elements-from-collapsing,1075,326139.0,15.0,,,2008-10-20 15:10:25,2020-04-19 13:39:39,2020-06-20 09:12:55,2014-12-20 16:44:04,Duplicate,html;css;layout;css-float;clearfix,Nathan Long,126990,4376,registered,true,,,,2014-03-15 00:26:56,3572,2071,10,0,0,5,false,true,false,true,true,true,60,10,true,0.046,0.0033,6606,2008,10,15,Monday,false,false,false,false,false,false,false
1403615,Use jQuery to hide a DIV when the user clicks outside of it,"I am using this code:
$('body').click(function() {
$('.form_wrapper').hide();
});
$('.form_wrapper').click(function(event){
event.stopPropagation();
});
And this HTML:
<div class=""form_wrapper"">
<a class=""agree"" href=""javascript:;"">I Agree</a>
<a class=""disagree"" href=""javascript:;"">Disagree</a>
</div>
The problem is that I have links inside the div and when they no longer work when clicked.
",https://stackoverflow.com/questions/1403615/use-jquery-to-hide-a-div-when-the-user-clicks-outside-of-it,1074,931143.0,41.0,,,2009-09-10 06:11:27,2024-12-18 03:23:48,2020-04-17 14:27:46,,,jquery;html;hide;styling,Scott Yu - builds stuff,11753,157173,registered,true,7385673,,CC BY-SA 4.0,2014-09-26 16:33:54,549,450,3,0,0,4,true,false,false,true,true,true,59,13,false,0.044,0.0012,6281,2009,9,6,Thursday,false,false,false,false,false,false,false
4912092,Using HTML5/Canvas/JavaScript to take in-browser screenshots,"Google's "Report a Bug" or "Feedback Tool" lets you select an area of your browser window to create a screenshot that is submitted with your feedback about a bug.
Screenshot by Jason Small, posted in a duplicate question.
How are they doing this? Google's JavaScript feedback API is loaded from here and their overview of the feedback module will demonstrate the screenshot capability.
",https://stackoverflow.com/questions/4912092/using-html5-canvas-javascript-to-take-in-browser-screenshots,1059,643429.0,7.0,,,2011-02-06 06:58:53,2025-06-23 06:45:15,2021-09-10 09:24:34,,,javascript;html;canvas;screenshot;html2canvas,joelvh,17218,105565,registered,true,6678156,,CC BY-SA 4.0,2013-06-23 10:11:20,780,409,0,3,1,5,true,false,false,true,true,true,60,6,false,0.011,0.0016,5767,2011,2,6,Sunday,true,false,true,false,false,false,false
5309926,How can I get the data-id attribute?,"I'm using the jQuery Quicksand plugin. I need to get the data-id of the clicked item and pass it to a webservice.
How do I get the data-id attribute? I'm using the .on() method to re-bind the click event for sorted items.
$(""#list li"").on('click', function() {
// ret = DetailsView.GetProject($(this).attr(""#data-id""), OnComplete, OnTimeOut, OnError);
alert($(this).attr(""#data-id""));
});
<script src=""https://code.jquery.com/jquery-3.3.1.slim.min.js""></script>
<ul id=""list"" class=""grid"">
<li data-id=""id-40"" class=""win"">
<a id=""ctl00_cphBody_ListView1_ctrl0_SelectButton"" class=""project"" href=""#"">
<img src=""themes/clean/images/win.jpg"" class=""project-image"" alt=""get data-id"" />
</a>
</li>
</ul>
",https://stackoverflow.com/questions/5309926/how-can-i-get-the-data-id-attribute,1056,2380629.0,17.0,,,2011-03-15 09:44:30,2023-02-24 15:21:21,2021-07-31 18:50:13,,,javascript;html;jquery;custom-data-attribute,ba01,12360,121470,registered,true,5309947,,CC BY-SA 4.0,2016-02-01 07:25:31,1190,788,3,1,0,4,true,false,false,true,true,true,36,7,true,0.007,0.0004,5730,2011,3,9,Tuesday,false,false,true,false,false,false,false
1571648,Tab character instead of multiple non-breaking spaces ("nbsp")?,"Is it possible to insert a tab character in HTML instead of having to type four times?
",https://stackoverflow.com/questions/1571648/tab-character-instead-of-multiple-non-breaking-spaces-nbsp,1052,3365351.0,37.0,,,2009-10-15 11:03:39,2024-10-11 21:04:42,2023-02-17 02:21:39,,,html,Roch,22069,83475,registered,true,1571662,,CC BY-SA 4.0,2014-07-19 17:23:20,118,98,1,0,0,1,true,false,false,true,true,true,73,8,true,0.011,0.0003,6246,2009,10,11,Thursday,false,false,false,false,false,false,false
9419263,How to play audio?,"I am making a game with HTML5 and JavaScript.
How could I play game audio via JavaScript?
",https://stackoverflow.com/questions/9419263/how-to-play-audio,1036,1724740.0,22.0,,,2012-02-23 18:49:06,2023-03-22 17:47:19,2020-07-30 20:27:03,,,javascript;html;html5-audio,rshea0,12349,1148973,registered,true,18628124,,CC BY-SA 4.0,2019-06-28 00:33:02,105,91,0,0,0,3,true,false,false,true,true,true,18,4,true,0.013,0.0006,5385,2012,2,18,Thursday,false,false,true,false,false,false,false
155291,Can HTML checkboxes be set to readonly?,"I thought they could be, but as I'm not putting my money where my mouth was (so to speak) setting the readonly attribute doesn't actually seem to do anything.
I'd rather not use Disabled, since I want the checked check boxes to be submitted with the rest of the form, I just don't want the client to be able to change them under certain circumstances.
",https://stackoverflow.com/questions/155291/can-html-checkboxes-be-set-to-readonly,1036,1230563.0,53.0,,,2008-09-30 21:58:58,2025-07-17 18:24:48,,,,html;checkbox,Electrons_Ahoy,39171,19074,registered,true,,,CC BY-SA 2.5,2012-10-22 01:20:02,367,353,0,0,0,2,false,false,false,true,true,false,39,7,true,0.043,0.0008,6626,2008,9,21,Tuesday,false,false,false,false,false,false,false
5898656,Check if an element contains a class in JavaScript?,"Using plain JavaScript (not jQuery), Is there any way to check if an element contains a class?
Currently, I'm doing this:
var test = document.getElementById(""test"");
var testClass = test.className;
switch (testClass) {
case ""class1"":
test.innerHTML = ""I have class1"";
break;
case ""class2"":
test.innerHTML = ""I have class2"";
break;
case ""class3"":
test.innerHTML = ""I have class3"";
break;
case ""class4"":
test.innerHTML = ""I have class4"";
break;
default:
test.innerHTML = """";
}
<div id=""test"" class=""class1""></div>
The issue is that if I change the HTML to this...
<div id=""test"" class=""class1 class5""></div>
...there's no longer an exact match, so I get the default output of nothing (""""). But I still want the output to be I have class1 because the <div> still contains the .class1 class.
",https://stackoverflow.com/questions/5898656/check-if-an-element-contains-a-class-in-javascript,1027,1638392.0,30.0,,,2011-05-05 13:40:19,2022-08-29 15:45:32,2019-04-28 16:04:21,,,javascript;html;css;dom,daGUY,29105,778581,registered,true,5898748,,CC BY-SA 4.0,,1318,900,7,0,0,4,true,false,false,true,true,true,51,9,true,0.018,0.0006,5679,2011,5,13,Thursday,false,false,true,false,false,false,false
895171,Prevent users from submitting a form by hitting Enter,"I have a survey on a website, and there seems to be some issues with the users hitting enter (I don't know why) and accidentally submitting the survey (form) without clicking the submit button. Is there a way to prevent this?
I'm using HTML, PHP 5.2.9, and jQuery on the survey.
",https://stackoverflow.com/questions/895171/prevent-users-from-submitting-a-form-by-hitting-enter,1021,962312.0,37.0,,,2009-05-21 21:09:25,2024-05-31 16:38:10,2016-12-17 10:23:29,,,jquery;html;forms;form-submit,DForck42,20669,95710,registered,true,895231,,CC BY-SA 3.0,2014-01-03 22:51:48,296,282,0,0,0,4,true,false,false,true,true,true,53,9,false,0.038,0.0011,6393,2009,5,21,Thursday,false,false,false,false,false,false,false
248011,How do I wrap text in a pre tag?,"pre tags are super-useful for code blocks in HTML and for debugging output while writing scripts, but how do I make the text word-wrap instead of printing out one long line?
",https://stackoverflow.com/questions/248011/how-do-i-wrap-text-in-a-pre-tag,1018,445984.0,18.0,,,2008-10-29 19:03:23,2025-04-01 19:31:24,2014-07-11 13:32:48,,,html;css,adambox,25909,2462,registered,true,248013,,CC BY-SA 3.0,2019-06-09 17:13:11,194,174,1,0,0,2,true,false,false,true,true,true,32,9,true,0.04,0.0023,6597,2008,10,19,Wednesday,false,false,false,false,false,false,false
22429003,How to Right-align flex item?,"Is there a more flexbox-ish way to right-align "Contact" than to use position: absolute?
.main {
display: flex;
}
.a,
.b,
.c {
background: #efefef;
border: 1px solid #999;
}
.b {
flex: 1;
text-align: center;
}
.c {
position: absolute;
right: 0;
}
<h2>With title</h2>
<div class=""main"">
<div class=""a""><a href=""#"">Home</a></div>
<div class=""b""><a href=""#"">Some title centered</a></div>
<div class=""c""><a href=""#"">Contact</a></div>
</div>
<h2>Without title</h2>
<div class=""main"">
<div class=""a""><a href=""#"">Home</a></div>
<!--<div class=""b""><a href=""#"">Some title centered</a></div>-->
<div class=""c""><a href=""#"">Contact</a></div>
</div>
",https://stackoverflow.com/questions/22429003/how-to-right-align-flex-item,1017,1369823.0,14.0,,,2014-03-15 19:56:31,2024-07-04 15:14:50,2021-06-02 07:40:21,,,html;css;flexbox,Mark Boulder,14407,1037526,registered,true,22429853,,CC BY-SA 4.0,2021-03-10 18:29:31,1296,913,3,1,0,3,true,false,false,true,true,true,29,5,true,0.01,0.0007,4634,2014,3,19,Saturday,true,false,false,false,false,false,false
19026884,Flexbox: center horizontally and vertically,"How to center a div horizontally and vertically within the container using flexbox?
In the example below, I want each number below each other (in rows), which are centered horizontally.
.flex-container {
padding: 0;
margin: 0;
list-style: none;
display: flex;
align-items: center;
justify-content: center;
}
row {
width: 100%;
}
.flex-item {
background: tomato;
padding: 5px;
width: 200px;
height: 150px;
margin: 10px;
line-height: 150px;
color: white;
font-weight: bold;
font-size: 3em;
text-align: center;
}
<div class=""flex-container"">
<div class=""row"">
<span class=""flex-item"">1</span>
</div>
<div class=""row"">
<span class=""flex-item"">2</span>
</div>
<div class=""row"">
<span class=""flex-item"">3</span>
</div>
<div class=""row"">
<span class=""flex-item"">4</span>
</div>
</div>
https://codepen.io/anon/pen/zLxBo
",https://stackoverflow.com/questions/19026884/flexbox-center-horizontally-and-vertically,1006,1874652.0,14.0,,,2013-09-26 11:22:41,2026-05-13 20:18:35,2026-05-13 20:18:35,,,html;css;flexbox,bsr,59056,303477,registered,true,19027949,,CC BY-SA 4.0,2020-09-09 15:40:40,1445,991,2,1,0,3,true,false,false,true,true,true,43,5,false,0.007,0.0005,4804,2013,9,11,Thursday,false,false,false,false,false,false,false
9110300,Can I write a CSS selector selecting elements NOT having a certain class or attribute?,"I would like to write a CSS selector rule that selects all elements that don't have a certain class. For example, given the following HTML:
<html class=""printable"">
<body class=""printable"">
<h1 class=""printable"">Example</h1>
<nav>
<!-- Some menu links... -->
</nav>
<a href=""javascript:void(0)"" onclick=""javascript:self.print()"">Print me!</a>
<p class=""printable"">
This page is super interresting and you should print it!
</p>
</body>
</html>
I would like to write a selector that selects all elements that don't have the ""printable"" class which, in this case, are the nav and a elements.
Is this possible?
NOTE: in the actual HTML where I would like to use this, there are going to be a lot more elements that don't have the ""printable"" class than do (I realize it's the other way around in the above example).
",https://stackoverflow.com/questions/9110300/can-i-write-a-css-selector-selecting-elements-not-having-a-certain-class-or-attr,999,903719.0,10.0,,,2012-02-02 09:59:06,2023-11-13 10:43:55,2019-08-18 01:14:33,,,html;css;css-selectors,David Nordvall,13636,20398,registered,true,9110350,,CC BY-SA 4.0,2019-08-12 02:13:56,1063,975,1,0,0,3,true,false,false,true,true,true,86,15,true,0.011,0.0011,5406,2012,2,9,Thursday,false,false,false,false,false,false,false
22148080,An invalid form control with name='' is not focusable,"In Google Chrome some customers are not able to proceed to my payment page.
When trying to submit a form I get this error:
An invalid form control with name='' is not focusable.
This is from the JavaScript console.
I read that the problem could be due to hidden fields having the required attribute.
Now the problem is that we are using .net webforms required field validators, and not the html5 required attribute.
It seems random who gets this error.
Is there anyone who knows a solution for this?
",https://stackoverflow.com/questions/22148080/an-invalid-form-control-with-name-is-not-focusable,991,1024803.0,47.0,,,2014-03-03 13:29:20,2025-03-28 23:19:04,2020-11-19 14:56:58,,,html;validation,mp1990,10379,3375051,registered,true,28340579,,CC BY-SA 4.0,2015-06-11 14:42:31,562,502,0,0,0,2,true,false,false,true,true,true,61,9,false,0.046,0.001,4646,2014,3,13,Monday,false,false,false,false,false,false,false
995183,How to allow only numeric (0-9) in HTML inputbox using jQuery?,"I am creating a web page where I have an input text field in which I want to allow only numeric characters like (0,1,2,3,4,5...9) 0-9.
How can I do this using jQuery?
",https://stackoverflow.com/questions/995183/how-to-allow-only-numeric-0-9-in-html-inputbox-using-jquery,987,1901989.0,70.0,,,2009-06-15 09:22:07,2025-09-26 18:13:26,2011-09-03 22:13:45,,,jquery;html;validation;numeric,djmzfKnm,27329,45261,registered,true,995193,,CC BY-SA 3.0,2012-02-15 17:00:47,182,168,0,0,0,4,true,false,false,true,true,true,63,11,true,0.037,0.0005,6368,2009,6,9,Monday,false,false,false,false,false,false,false
1594952,jQuery disable/enable submit button,"I have this HTML:
<input type=""text"" name=""textField"" />
<input type=""submit"" value=""send"" />
How can I do something like this:
- When the text field is empty the submit should be disabled (disabled=""disabled"").
- When something is typed in the text field to remove the disabled attribute.
- If the text field becomes empty again(the text is deleted) the submit button should be disabled again.
I tried something like this:
$(document).ready(function(){
$('input[type=""submit""]').attr('disabled','disabled');
$('input[type=""text""]').change(function(){
if($(this).val != ''){
$('input[type=""submit""]').removeAttr('disabled');
}
});
});
…but it doesn't work. Any ideas?
",https://stackoverflow.com/questions/1594952/jquery-disable-enable-submit-button,987,2223824.0,22.0,,,2009-10-20 14:21:12,2024-01-01 13:28:28,2020-06-09 21:23:37,,,javascript;html;jquery,kmunky,15673,185555,registered,true,1594992,,CC BY-SA 4.0,2020-07-04 04:54:57,836,724,2,0,0,3,true,false,false,true,true,true,35,4,false,0.01,0.0004,6241,2009,10,14,Tuesday,false,false,true,false,false,false,false
8508275,How to center a "position: absolute" element,"I'm having a problem centering an element that has the attribute position set to absolute.
Does anyone know why the images are not centered?
body {
text-align: center;
}
#slideshowWrapper {
margin-top: 50px;
text-align: center;
}
ul#slideshow {
list-style: none;
position: relative;
margin: auto;
}
ul#slideshow li {
position: absolute;
}
ul#slideshow li img {
border: 1px solid #ccc;
padding: 4px;
height: 450px;
}
<body>
<div id=""slideshowWrapper"">
<ul id=""slideshow"">
<li><img src=""https://source.unsplash.com/random/300*300?technology"" alt=""Dummy 1"" /></li>
<li><img src=""https://source.unsplash.com/random/301*301?technology"" alt=""Dummy 2"" /></li>
</ul>
</div>
</body>
",https://stackoverflow.com/questions/8508275/how-to-center-a-position-absolute-element,984,1527077.0,32.0,,,2011-12-14 16:47:14,2024-04-15 12:11:23,2020-08-26 21:46:45,,,html;css;css-position;centering,user1098278,9857,1098278,registered,true,,,CC BY-SA 4.0,2014-09-14 20:29:30,1136,805,4,0,0,4,false,false,false,true,true,true,54,7,false,0.021,0.0006,5456,2011,12,16,Wednesday,false,false,false,false,false,false,false
953918,How to align a <div> to the middle (horizontally/width) of the page,"I have a div tag with width set to 800 pixels. When the browser width is greater than 800 pixels, it shouldn't stretch the div, but it should bring it to the middle of the page.
",https://stackoverflow.com/questions/953918/how-to-align-a-div-to-the-middle-horizontally-width-of-the-page,978,3328636.0,27.0,,,2009-06-05 01:44:38,2025-02-23 06:30:25,2019-03-24 10:51:28,2018-09-28 00:56:29,Duplicate,css;html;alignment;center,Shimmy Weitzhandler,105613,75500,registered,true,953934,,,2013-03-15 09:58:02,258,178,3,0,0,4,true,true,false,true,true,true,73,12,false,0.008,0.0003,6378,2009,6,1,Friday,false,false,false,false,false,false,false
6382023,Changing the color of an hr element,"I want to change the color of my hr tag using CSS. The code I've tried below doesn't seem to work:
hr {
color: #123455;
}
<hr>
",https://stackoverflow.com/questions/6382023/changing-the-color-of-an-hr-element,976,1480048.0,28.0,,,2011-06-17 06:15:50,2025-03-18 06:15:23,2024-05-09 17:19:27,,,html;css,koool,15627,726212,registered,true,6382036,,CC BY-SA 4.0,2016-03-31 02:04:19,464,146,3,0,0,2,true,false,false,true,true,true,35,7,false,0.019,0.0007,5636,2011,6,6,Friday,false,false,false,false,false,false,false
66837,When is a CDATA section necessary within a script tag?,"Are CDATA tags ever necessary in script tags and if so when?
In other words, when and where is this:
<script type=""text/javascript"">
//<![CDATA[
...code...
//]]>
</script>
preferable to this:
<script type=""text/javascript"">
...code...
</script>
",https://stackoverflow.com/questions/66837/when-is-a-cdata-section-necessary-within-a-script-tag,976,394513.0,15.0,,,2008-09-15 20:52:14,2023-10-19 12:49:14,2020-04-19 17:09:06,,,javascript;html;xhtml;cdata,brad,75904,208,registered,true,66865,,CC BY-SA 4.0,2016-01-21 19:35:17,367,281,2,0,0,4,true,false,false,true,true,true,54,10,true,0.038,0.0025,6641,2008,9,20,Monday,false,false,true,false,false,false,false
4328947,Limit file format when using <input type="file">?,"I'd like to restrict the type of file that can be chosen from the native OS file chooser when the user clicks the Browse button in the <input type=""file""> element in HTML. I have a feeling it's impossible, but I'd like to know if there is a solution. I'd like to keep solely to HTML and JavaScript; no Flash please.
",https://stackoverflow.com/questions/4328947/limit-file-format-when-using-input-type-file,970,854782.0,12.0,,,2010-12-01 20:44:40,2026-03-01 05:39:13,2017-02-27 12:45:33,,,html;file;types,Bojangles,101941,383609,registered,true,23706177,,CC BY-SA 3.0,2014-08-10 16:07:25,351,322,1,0,0,3,true,false,false,true,true,true,65,7,true,0.014,0.0011,5834,2010,12,20,Wednesday,false,false,false,false,false,false,false
20547819,vertical-align with Bootstrap 3,"I'm using Twitter Bootstrap 3, and I have problems when I want to align vertically two div, for example — JSFiddle link:
<!-- Latest compiled and minified CSS -->
<link rel=""stylesheet"" href=""https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"">
<!-- Optional theme -->
<link rel=""stylesheet"" href=""https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css"">
<!-- Latest compiled and minified JavaScript -->
<script src=""https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js""></script>
<div class=""row"">
<div class=""col-xs-5"">
<div style=""height:5em;border:1px solid #000"">Big</div>
</div>
<div class=""col-xs-5"">
<div style=""height:3em;border:1px solid #F00"">Small</div>
</div>
</div>
The grid system in Bootstrap uses float: left, not display:inline-block, so the property vertical-align doesn't work. I tried using margin-top to fix it, but I think this is not a good solution for the responsive design.
",https://stackoverflow.com/questions/20547819/vertical-align-with-bootstrap-3,968,1572811.0,26.0,,,2013-12-12 15:43:23,2022-08-17 08:22:15,2015-11-26 04:55:03,,,html;css;twitter-bootstrap;twitter-bootstrap-3,corinem,9835,2892056,registered,true,20548578,,CC BY-SA 3.0,2014-09-14 18:35:43,1411,1103,6,1,0,4,true,false,false,true,true,true,31,4,false,0.017,0.0006,4727,2013,12,15,Thursday,false,false,false,false,false,false,false
526035,How can I position my div at the bottom of its container?,"Given the following HTML:
<div id=""container"">
<!-- Other elements here -->
<div id=""copyright"">
Copyright Foo web designs
</div>
</div>
I would like #copyright to stick to the bottom of #container. Can I achieve this without using absolute positioning?
",https://stackoverflow.com/questions/526035/how-can-i-position-my-div-at-the-bottom-of-its-container,960,1777145.0,25.0,,,2009-02-08 17:08:57,2022-09-12 15:14:49,2020-08-31 19:40:20,,,html;css,Dónal,187883,2648,registered,true,27812717,,CC BY-SA 4.0,2014-05-02 20:09:47,564,304,3,0,0,2,true,false,false,true,true,true,57,12,true,0.014,0.0005,6495,2009,2,17,Sunday,true,false,false,false,false,false,false
271743,"What's the difference between <b> and <strong>, <i> and <em>?","What's the difference between <b> and <strong>, <i> and <em> in HTML/XHTML? When should you use each?
",https://stackoverflow.com/questions/271743/whats-the-difference-between-b-and-strong-i-and-em,959,567470.0,24.0,,,2008-11-07 10:56:08,2024-05-17 05:11:28,,,,html;xhtml,Philip Morton,132419,21709,registered,true,271776,,CC BY-SA 2.5,2016-01-16 08:46:33,185,126,4,0,0,2,true,false,false,true,true,false,89,10,true,0.042,0.0017,6588,2008,11,10,Friday,false,false,false,false,false,false,false
2091168,How to disable a link using only CSS,"Is there a way to disable a link using CSS?
I have a class called current-page and want links with this class to be disabled so that no action occurs when they are clicked.
",https://stackoverflow.com/questions/2091168/how-to-disable-a-link-using-only-css,957,1464293.0,29.0,,,2010-01-19 04:55:03,2026-07-09 09:55:34,2021-05-30 00:33:10,,,html;css,RSK,17586,250470,registered,true,4416239,,CC BY-SA 4.0,2011-09-21 11:20:55,200,173,1,0,0,2,true,false,false,true,true,true,36,8,false,0.02,0.0007,6150,2010,1,4,Tuesday,false,false,false,false,false,false,false
2989263,Disable Auto Zoom in Input "Text" tag - Safari on iPhone,"I made an HTML page that has an <input> tag with type=""text"". When I click on it using Safari on iPhone, the page becomes larger (auto zoom). Does anybody know how to disable this?
",https://stackoverflow.com/questions/2989263/disable-auto-zoom-in-input-text-tag-safari-on-iphone,949,906389.0,49.0,,,2010-06-07 12:06:57,2026-06-19 07:03:39,2021-02-07 10:29:47,,,html;iphone;zooming;mobile-safari;html-input,Eduardo Montenegro,9479,360383,unregistered,true,,,CC BY-SA 4.0,2015-06-08 06:57:04,220,187,2,0,0,5,false,false,false,true,true,true,66,11,false,0.054,0.001,6011,2010,6,12,Monday,false,false,false,false,false,false,false
1397592,Difference between id and name attributes in HTML,"What is the difference between the id and name attributes? They both seem to serve the same purpose of providing an identifier.
I would like to know (specifically with regards to HTML forms) whether or not using both is necessary or encouraged for any reasons.
",https://stackoverflow.com/questions/1397592/difference-between-id-and-name-attributes-in-html,928,578199.0,21.0,,,2009-09-09 04:53:48,2024-08-22 22:31:47,2019-07-08 16:54:35,,,html;attributes,yogibear,15075,167511,registered,true,1397613,,CC BY-SA 4.0,,302,262,2,0,0,2,true,false,false,true,true,true,49,8,false,0.036,0.0016,6282,2009,9,4,Wednesday,false,false,false,false,false,false,false
5592345,How to select a radio button by default?,"I have some radio buttons and I want one of them to be set as selected by default when the page is loaded. How can I do that?
<input type=""radio"" name=""imgsel"" value="""" />
",https://stackoverflow.com/questions/5592345/how-to-select-a-radio-button-by-default,924,2092309.0,5.0,,,2011-04-08 08:18:04,2019-06-05 14:20:42,2014-09-11 07:30:46,2015-12-16 18:04:27,Duplicate,html;radio-button,jslearner,22411,611181,unregistered,true,5592370,,,,214,183,1,0,0,2,true,true,false,true,true,true,40,8,true,0.002,0.0004,5706,2011,4,8,Friday,false,false,false,false,false,false,false
351058,Space between two rows in a table?,"Is this possible via CSS?
I'm trying
tr.classname {
border-spacing: 5em;
}
to no avail. Maybe I'm doing something wrong?
",https://stackoverflow.com/questions/351058/space-between-two-rows-in-a-table,913,1600017.0,26.0,,,2008-12-08 21:49:59,2024-10-04 22:56:12,2020-04-15 17:20:08,,,html;css,Marin,12998,419730,registered,true,,,CC BY-SA 4.0,2014-10-15 11:48:31,212,129,1,0,0,2,false,false,false,true,true,true,34,7,true,0.016,0.0006,6557,2008,12,21,Monday,false,false,false,false,false,false,false
2587669,Can I use a :before or :after pseudo-element on an input field?,"I am trying to use the :after CSS pseudo-element on an input field, but it does not work. If I use it with a span, it works OK.
<style type=""text/css"">
.mystyle:after {content:url(smiley.gif);}
.mystyle {color:red;}
</style>
This works (puts the smiley after ""buu!"" and before ""some more"")
<span class=""mystyle"">buuu!</span>a some more
This does not work - it only colors someValue in red, but there is no smiley.
<input class=""mystyle"" type=""text"" value=""someValue"">
What am I doing wrong? should I use another pseudo-selector?
Note: I cannot add a span around my input, because it is being generated by a third-party control.
",https://stackoverflow.com/questions/2587669/can-i-use-a-before-or-after-pseudo-element-on-an-input-field,905,744721.0,25.0,,,2010-04-06 19:28:08,2026-05-08 20:56:36,2017-11-14 04:16:52,,,html;css;pseudo-element;css-content,matra,10331,174638,registered,true,2591460,,CC BY-SA 3.0,2017-02-24 19:08:39,841,669,8,0,0,4,true,false,false,true,true,true,63,12,true,0.034,0.0012,6073,2010,4,19,Tuesday,false,false,false,false,false,false,false
10422949,CSS Background Opacity,"I am using something similar to the following code:
<div style=""opacity:0.4; background-image:url(...);"">
<div style=""opacity:1.0;"">
Text
</div>
</div>
I expected this to make the background have an opacity of 0.4 and the text to have 100% opacity. Instead they both have an opacity of 0.4.
",https://stackoverflow.com/questions/10422949/css-background-opacity,898,3098096.0,8.0,,,2012-05-02 23:05:00,2026-09-15 10:41:43,2019-03-23 00:24:09,2016-07-29 14:37:17,Duplicate,html;css;opacity,John Wheal,10448,1227172,registered,true,10422974,,,,374,336,1,0,0,3,true,true,false,true,true,true,22,3,false,0.003,0.0003,5316,2012,5,23,Wednesday,false,false,false,false,false,false,false
2116162,How to display HTML in TextView?,"I have simple HTML:
<h2>Title</h2><br>
<p>description here</p>
I want to display HTML styled text it in TextView. How to do this?
",https://stackoverflow.com/questions/2116162/how-to-display-html-in-textview,895,848330.0,29.0,,,2010-01-22 09:14:22,2022-12-22 04:08:18,2017-08-29 22:07:23,,,android;html;xml-parsing;textview,UMAR-MOBITSOLUTIONS,78124,249991,registered,true,2116191,,CC BY-SA 3.0,2016-08-19 08:24:02,231,163,2,0,0,4,true,false,false,true,true,true,32,6,true,0.034,0.0011,6147,2010,1,9,Friday,false,false,false,false,false,false,false
10808109,Script Tag - async & defer,"I have a couple of questions about the attributes async & defer for the <script> tag which to my understanding only works in HTML5 browsers.
One of my sites has two external JavaScript files that currently sit just above the </body> tag; the first is jquery sourced from Google and the second is a local external script.
To site load speed
Is there any advantage in adding async to the two scripts I have at the bottom of the page?
Would there be any advantage in adding the async option to the two scripts and putting them at the top of the page in the <head>?
Would this mean they download as the page loads?
I assume this would cause delays for HTML4 browsers, but would it speed up page load for HTML5 browsers?
Using <script defer src=...
- Would loading the two scripts inside
<head> with the attribute defer have the same effect as having the scripts before </body>?
- Once again I assume this would slow up HTML4 browsers.
Using <script async src=...
If I have two scripts with async enabled
- Would they download at the same time?
- Or one at a time with the rest of the page?
- Does the order of scripts then become a problem? For example, one script depends on the other so if one downloads faster, the second one might not execute correctly, etc.
Finally am I best to leave things as they are until HTML5 is more commonly used?
",https://stackoverflow.com/questions/10808109/script-tag-async-defer,879,442846.0,13.0,,,2012-05-29 23:28:01,2024-12-02 07:05:42,2024-03-01 09:53:06,,,javascript;html,Adam,21190,880413,registered,true,10808243,,CC BY-SA 4.0,,1953,1381,13,1,0,2,true,false,false,true,true,true,30,6,false,0.029,0.002,5289,2012,5,23,Tuesday,false,false,true,false,false,false,false
822452,Strip HTML tags from text using plain JavaScript,"How to strip off HTML tags from a string using plain JavaScript only, not using a library?
",https://stackoverflow.com/questions/822452/strip-html-tags-from-text-using-plain-javascript,874,964808.0,46.0,,,2009-05-04 22:39:54,2023-07-06 23:18:22,2023-06-06 23:53:06,,,javascript;html;string,Bryan,17681,55124,registered,true,822486,,CC BY-SA 4.0,2018-04-05 03:32:43,98,91,0,0,0,3,true,false,false,true,true,true,48,8,false,0.048,0.0009,6410,2009,5,22,Monday,false,false,true,false,false,false,false
2655925,How to apply !important using .css()?,"I am having trouble applying a style that is !important. I’ve tried:
$(""#elem"").css(""width"", ""100px !important"");
This does nothing; no width style whatsoever is applied. Is there a jQuery-ish way of applying such a style without having to overwrite cssText (which would mean I’d need to parse it first, etc.)?
Edit: I should add that I have a stylesheet with an !important style that I am trying to override with an !important style inline, so using .width() and the like does not work since it gets overridden by my external !important style.
Also, the value that will override the previous value is computed, so I cannot simply create another external style.
",https://stackoverflow.com/questions/2655925/how-to-apply-important-using-css,868,772484.0,31.0,,,2010-04-16 20:31:13,2023-05-10 19:29:04,2017-04-11 20:25:11,,,javascript;jquery;html;css,mkoryak,58092,26188,registered,true,59073080,,CC BY-SA 3.0,2014-04-21 16:14:40,885,667,7,0,0,4,true,false,false,true,true,true,37,6,true,0.04,0.0011,6063,2010,4,20,Friday,false,false,true,false,false,false,false
65034,Remove border from IFrame,"How would I remove the border from an iframe embedded in my web app? An example of the iframe is:
<iframe src=""myURL"" width=""300"" height=""300"">Browser not compatible.</iframe>
I would like the transition from the content on my page to the contents of the iframe to be seamless, assuming the background colors are consistent. The target browser is IE6 only and unfortunately solutions for others will not help.
",https://stackoverflow.com/questions/65034/remove-border-from-iframe,866,1174697.0,26.0,,,2008-09-15 17:43:53,2022-06-03 08:39:54,2019-10-02 16:03:02,,,html;css;iframe;internet-explorer-6;noborder,JoelB,349,2650,registered,true,65052,,CC BY-SA 4.0,2018-05-21 14:21:32,463,425,1,0,0,5,true,false,false,true,true,true,25,4,false,0.022,0.0007,6641,2008,9,17,Monday,false,false,false,false,false,false,false
484719,Should I make HTML Anchors with 'name' or 'id'?,"When one wants to refer to some part of a webpage with the ""http://example.com/#foo"" method, should one use
<h1><a name=""foo""/>Foo Title</h1>
or
<h1 id=""foo"">Foo Title</h1>
They both work, but are they equal, or do they have semantic differences?
",https://stackoverflow.com/questions/484719/should-i-make-html-anchors-with-name-or-id,857,702727.0,15.0,,,2009-01-27 18:57:18,2023-02-16 09:09:20,2018-08-02 14:38:12,,,html;hyperlink;fragment-identifier,Henrik Paul,67991,2238,registered,true,484781,,CC BY-SA 4.0,2013-06-23 10:11:42,365,283,3,0,0,3,true,false,false,true,true,true,63,9,true,0.021,0.0012,6507,2009,1,18,Tuesday,false,false,false,false,false,false,false
3357553,How do I store an array in localStorage?,"If I didn't need localStorage, my code would look like this:
var names=new Array();
names[0]=prompt(""New member name?"");
This works. However, I need to store this variable in localStorage and it's proving quite stubborn. I've tried:
var localStorage[names] = new Array();
localStorage.names[0] = prompt(""New member name?"");
Where am I going wrong?
",https://stackoverflow.com/questions/3357553/how-do-i-store-an-array-in-localstorage,856,942394.0,6.0,,,2010-07-28 21:14:27,2022-11-14 13:05:46,2017-02-17 15:02:39,2013-05-23 06:11:52,exact duplicate,javascript;arrays;html;local-storage,David,14119,385815,registered,true,3357615,,,,424,355,2,0,0,4,true,true,false,true,true,true,40,8,true,0.006,0.0009,5960,2010,7,21,Wednesday,false,false,true,false,false,false,false
4425198,Can I create links with 'target="_blank"' in Markdown?,"Is there a way to create a link in Markdown that opens in a new window? If not, what syntax do you recommend to do this? I'll add it to the markdown compiler I use. I think it should be an option.
",https://stackoverflow.com/questions/4425198/can-i-create-links-with-target-blank-in-markdown,847,557630.0,24.0,,,2010-12-13 01:33:05,2026-03-22 07:33:01,2021-10-07 11:14:16,,,html;hyperlink;markdown;target;new-window,ma11hew28,128159,242933,registered,true,4425223,,CC BY-SA 4.0,,204,197,0,0,0,5,true,false,false,true,true,true,72,8,true,0.043,0.0015,5822,2010,12,1,Monday,false,false,false,false,false,false,false
3296644,Hiding the scroll bar on an HTML page,"How to use CSS to hide the scroll bar?
",https://stackoverflow.com/questions/3296644/hiding-the-scroll-bar-on-an-html-page,845,1973058.0,22.0,,,2010-07-21 05:57:43,2025-09-24 16:32:16,2025-09-24 16:32:16,,,html;css;browser;scrollbar,ANP,15687,386263,registered,true,3296701,,CC BY-SA 4.0,2014-10-24 12:33:26,46,39,0,0,0,4,true,false,false,true,true,true,37,8,false,0.011,0.0004,5967,2010,7,5,Wednesday,false,false,false,false,false,false,false
923885,Capture HTML canvas as GIF/JPG/PNG/PDF?,"Is it possible to capture or print what's displayed in an HTML canvas as an image or PDF?
I'd like to generate an image via canvas and be able to generate a PNG from that image.
",https://stackoverflow.com/questions/923885/capture-html-canvas-as-gif-jpg-png-pdf,839,864333.0,16.0,,,2009-05-29 00:28:27,2023-03-06 10:17:37,2023-02-11 20:18:25,,,javascript;html;canvas;export;png,Parand,107148,13055,registered,true,3514404,,CC BY-SA 4.0,2012-02-19 10:35:48,192,178,0,0,0,5,true,false,false,true,true,true,39,5,true,0.019,0.001,6385,2009,5,0,Friday,false,false,true,false,false,false,false
48248832,Stylesheet not loaded because of MIME type,"I'm working on a website that uses Gulp.js to compile and browser sync to keep the browser synchronised with my changes.
The Gulp.js task compiles everything properly, but on the website, I'm unable to see any style, and the console shows this error message:
Refused to apply style from
'http://localhost:3000/assets/styles/custom-style.css' because its
MIME type ('text/html') is not a supported stylesheet MIME type, and
strict MIME checking is enabled.
Now, I don't really understand why this happens.
The HTML includes the file like this (which I am pretty sure is correct):
<link rel="stylesheet" type="text/css" href="assets/styles/custom-style.css"/>
And the style sheet is a merge between Bootstrap and Font Awesome styles for now (nothing custom yet).
The path is correct as well, as this is the folder structure:
index.html
assets
|-styles
|-custom-style.css
But I keep getting the error.
What could it be? Is this something (maybe a setting?) for gulp/browsersync maybe?
",https://stackoverflow.com/questions/48248832/stylesheet-not-loaded-because-of-mime-type,835,2325201.0,75.0,,,2018-01-14 10:52:40,2025-01-22 15:06:49,2022-09-29 00:04:07,,,html;css;gulp;mime-types;browser-sync,Nick,14383,3760661,registered,true,48270432,,CC BY-SA 4.0,2018-03-23 02:22:08,1478,1024,2,3,0,5,true,false,false,true,true,true,42,7,false,0.032,0.0004,3233,2018,1,10,Sunday,true,false,false,false,false,false,false
8988855,Include another HTML file in a HTML file,"I have 2 HTML files, suppose a.html and b.html. In a.html I want to include b.html.
In JSF I can do it like that:
<ui:include src=""b.xhtml"" />
It means that inside a.xhtml file, I can include b.xhtml.
How can we do it in *.html file?
",https://stackoverflow.com/questions/8988855/include-another-html-file-in-a-html-file,832,2236998.0,46.0,,,2012-01-24 14:51:16,2025-08-12 15:26:01,2020-06-15 21:33:32,,,javascript;html;dom;include,lolo,18074,1001224,registered,true,9003363,,CC BY-SA 4.0,2015-02-12 16:23:00,388,245,8,0,0,4,true,false,false,true,true,true,40,8,false,0.021,0.0004,5415,2012,1,14,Tuesday,false,false,true,false,false,false,false
19867599,"What is the difference between localStorage, sessionStorage, session and cookies?","What are the technical pros and cons of localStorage, sessionStorage, session and cookies, and when would I use one over the other?
",https://stackoverflow.com/questions/19867599/what-is-the-difference-between-localstorage-sessionstorage-session-and-cookies,829,521163.0,11.0,,,2013-11-08 20:02:04,2024-11-20 20:42:44,2021-12-06 19:19:48,,,html;cookies;local-storage;session-storage,Pank,14448,983624,registered,true,19869560,,CC BY-SA 4.0,2015-10-13 21:11:51,178,132,3,0,0,4,true,false,false,true,true,true,81,10,true,0.021,0.0016,4761,2013,11,20,Friday,false,false,false,false,false,false,false
19758598,What is sr-only in Bootstrap 3?,"What is the class sr-only used for? Is it important or can I remove it? Works fine without.
Here's my example:
<div class=""btn-group"">
<button type=""button"" class=""btn btn-info btn-md"">Departments</button>
<button type=""button"" class=""btn btn-info dropdown-toggle btn-md"" data-toggle=""dropdown"">
<span class=""caret""></span>
<span class=""sr-only"">Toggle Dropdown</span>
</button>
<ul class=""dropdown-menu"" role=""menu"">
<li><a href=""#"">Sales</a></li>
<li><a href=""#"">Technical</a></li>
<li class=""divider""></li>
<li><a href=""#"">Show all</a></li>
</ul>
</div>
",https://stackoverflow.com/questions/19758598/what-is-sr-only-in-bootstrap-3,818,607918.0,6.0,,,2013-11-03 21:51:16,2021-10-18 09:37:28,2016-08-16 09:01:44,,,html;css;twitter-bootstrap;twitter-bootstrap-3,kanarifugl,10027,2445075,registered,true,19758620,,CC BY-SA 3.0,2014-11-26 07:22:04,827,776,2,0,0,4,true,false,false,true,true,true,31,6,true,0.01,0.0013,4766,2013,11,21,Sunday,true,false,false,false,false,false,false
896777,How to remove close button on the jQuery UI dialog?,"How do I remove the close button (the X in the top-right corner) on a dialog box created by jQuery UI?
",https://stackoverflow.com/questions/896777/how-to-remove-close-button-on-the-jquery-ui-dialog,812,452861.0,25.0,,,2009-05-22 07:55:41,2021-07-11 20:57:11,2014-08-19 08:45:14,,,jquery;html;css;jquery-ui;jquery-ui-dialog,Robert MacLean,39385,53236,registered,true,897393,,CC BY-SA 3.0,2011-04-20 05:28:59,127,103,0,0,0,5,true,false,false,true,true,true,51,10,true,0.055,0.0018,6392,2009,5,7,Friday,false,false,false,false,false,false,false
10487292,Position absolute but relative to parent,"I have two divs inside another div, and I want to position one child div to the top right of the parent div, and the other child div to the bottom of the parent div using css. Ie, I want to use absolute positioning with the two child divs, but position them relative to the parent div rather than the page. How can I do this?
Sample html:
<div id="parent">
<div id="child1"></div>
<div id="child2"></div>
</div>
",https://stackoverflow.com/questions/10487292/position-absolute-but-relative-to-parent,806,711807.0,5.0,,,2012-05-07 18:41:54,2023-09-29 10:33:46,2023-09-22 08:43:11,,,html;css,BlaShadow,11773,1056852,registered,true,10487329,,CC BY-SA 4.0,2016-08-25 17:17:44,523,485,1,0,0,2,true,false,false,true,true,true,40,6,false,0.007,0.0011,5311,2012,5,18,Monday,false,false,false,false,false,false,false
9943771,Adding a favicon to a static HTML page,"I have a few static pages that are just pure HTML, that we display when the server goes down. How can I put a favicon that I made (it's 16x16px and it's sitting in the same directory as the HTML file; it's called favicon.ico) as the ""tab"" icon as it were? I have read up on Wikipedia and looked at a few tutorials and have implemented the following:
<link rel=""icon"" href=""favicon.ico"" type=""image/x-icon""/>
<link rel=""shortcut icon"" href=""favicon.ico"" type=""image/x-icon""/>
But it still doesn't want to work. I am using Chrome to test the sites. According to Wikipedia .ico is the best picture format that runs on all browser types.
Update
I could not get this to work locally although the code checks out it will only really work properly once the server started serving the site. Just try pushing it up to the server and refresh your cache and it should work fine.
",https://stackoverflow.com/questions/9943771/adding-a-favicon-to-a-static-html-page,800,1867520.0,18.0,,,2012-03-30 13:17:49,2025-03-04 17:16:32,2021-08-29 08:01:31,,,html;static;favicon,legendary_rob,13112,990940,registered,true,9943801,,CC BY-SA 4.0,2013-09-23 03:07:41,939,885,1,0,0,3,true,false,false,true,true,true,38,8,false,0.01,0.0004,5349,2012,3,13,Friday,false,false,false,false,false,false,false
210717,Using jQuery to center a DIV on the screen,"How do I go about setting a <div> in the center of the screen using jQuery?
",https://stackoverflow.com/questions/210717/using-jquery-to-center-a-div-on-the-screen,791,542760.0,29.0,,,2008-10-17 00:11:48,2022-07-28 16:11:04,2016-03-16 16:29:06,,,javascript;jquery;html;css;layout,Craig,36961,27294,registered,true,210733,,CC BY-SA 3.0,,102,82,1,0,0,5,true,false,false,true,true,true,42,9,false,0.053,0.0015,6609,2008,10,0,Friday,false,false,true,false,false,false,false
4476526,"Do I use <img>, <object>, or <embed> for SVG files?","Should I use <img>, <object>, or <embed> for loading SVG files into a page in a way similar to loading a jpg, gif or png?
What is the code for each to ensure it works as well as possible? (I'm seeing references to including the mimetype or pointing to fallback SVG renderers in my research and not seeing a good state of the art reference).
Assume I am checking for SVG support with Modernizr and falling back (probably doing a replacement with a plain <img> tag)for non SVG-capable browsers.
",https://stackoverflow.com/questions/4476526/do-i-use-img-object-or-embed-for-svg-files,791,979302.0,21.0,,,2010-12-18 03:50:45,2025-11-13 11:38:27,2018-09-10 16:05:46,,,html;svg;vector-graphics,artlung,33447,63094,registered,true,4482962,,CC BY-SA 4.0,2025-08-14 23:54:54,680,519,7,1,0,3,true,false,false,true,true,true,69,10,true,0.021,0.0008,5817,2010,12,3,Saturday,true,false,false,false,false,false,false
4888377,How to add a browser tab icon (favicon) for a website?,"I've been working on a website and I'd like to add a small icon to the browser tab.
How can I do this in HTML and where in the code would I need to place it (e.g. header)? I have a .png logo file that I'd like to convert to an icon.
Related: HTML set image on browser tab.
",https://stackoverflow.com/questions/4888377/how-to-add-a-browser-tab-icon-favicon-for-a-website,790,2319869.0,13.0,,,2011-02-03 15:55:10,2021-12-20 17:16:31,2021-08-29 08:01:44,,,html;icons;favicon,knookie,8281,184867,registered,true,35625707,,CC BY-SA 4.0,2013-07-20 20:24:43,397,275,1,1,0,3,true,false,false,true,true,true,54,11,true,0.006,0.0003,5770,2011,2,15,Thursday,false,false,false,false,false,false,false
14573223,Set cookie and get cookie with JavaScript,"I'm trying to set a cookie depending on which CSS file I choose in my HTML. I have a form with a list of options, and different CSS files as values. When I choose a file, it should be saved to a cookie for about a week. The next time you open your HTML file, it should be the previous file you've chosen.
JavaScript code:
function cssLayout() {
document.getElementById(""css"").href = this.value;
}
function setCookie(){
var date = new Date(""Februari 10, 2013"");
var dateString = date.toGMTString();
var cookieString = ""Css=document.getElementById(""css"").href"" + dateString;
document.cookie = cookieString;
}
function getCookie(){
alert(document.cookie);
}
HTML code:
<form>
Select your css layout:<br>
<select id=""myList"">
<option value=""style-1.css"">CSS1</option>
<option value=""style-2.css"">CSS2</option>
<option value=""style-3.css"">CSS3</option>
<option value=""style-4.css"">CSS4</option>
</select>
</form>
",https://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript,788,1803914.0,4.0,,,2013-01-28 23:34:38,2025-07-06 06:59:20,2018-03-01 21:53:39,2014-09-05 13:14:05,Duplicate,javascript;html;css;cookies,DrWooolie,8155,1420480,registered,true,,,,,1134,1065,2,0,0,4,false,true,false,true,true,true,41,7,false,0.002,0.0004,5045,2013,1,23,Monday,false,false,true,false,false,false,false
368813,HTML form readonly SELECT tag/input,"According to HTML specs, the select tag in HTML doesn't have a readonly attribute, only a disabled attribute. So if you want to keep the user from changing the dropdown, you have to use disabled.
The only problem is that disabled HTML form inputs don't get included in the POST / GET data.
What's the best way to emulate the readonly attribute for a select tag, and still get the POST data?
",https://stackoverflow.com/questions/368813/html-form-readonly-select-tag-input,788,1105400.0,50.0,,,2008-12-15 15:59:09,2025-09-23 13:54:05,2014-01-24 14:12:48,,,javascript;html,Jrgns,25337,6681,registered,true,368834,,CC BY-SA 3.0,2018-04-18 16:05:13,492,393,6,0,0,2,true,false,false,true,true,true,35,5,false,0.045,0.0007,6550,2008,12,15,Monday,false,false,true,false,false,false,false
442704,How do you handle multiple submit buttons in ASP.NET MVC Framework?,"Is there some easy way to handle multiple submit buttons from the same form? For example:
<% Html.BeginForm(""MyAction"", ""MyController"", FormMethod.Post); %>
<input type=""submit"" value=""Send"" />
<input type=""submit"" value=""Cancel"" />
<% Html.EndForm(); %>
Any idea how to do this in ASP.NET Framework Beta? All examples I've googled for have single buttons in them.
",https://stackoverflow.com/questions/442704/how-do-you-handle-multiple-submit-buttons-in-asp-net-mvc-framework,786,522954.0,36.0,,,2009-01-14 11:58:36,2024-06-12 19:52:04,2020-02-26 21:14:50,,,c#;html;asp.net-mvc;http-post;form-submit,Spoike,122358,3713,registered,true,7111222,,CC BY-SA 4.0,2015-02-10 17:12:56,430,392,1,0,0,5,true,false,false,true,true,true,67,11,true,0.069,0.0015,6520,2009,1,11,Wednesday,false,false,false,false,true,false,false
12829608,Text-align class for inside a table,"Is there a set of classes in Twitter's Bootstrap framework that aligns text?
For example, I have some tables with $ totals that I want aligned to the right...
<th class=""align-right"">Total</th>
and
<td class=""align-right"">$1,000,000.00</td>
",https://stackoverflow.com/questions/12829608/text-align-class-for-inside-a-table,785,1604894.0,23.0,,,2012-10-10 22:45:40,2024-11-30 06:01:00,2019-11-03 07:09:04,,,html;css;twitter-bootstrap;text-align,mylesthe.dev,9725,1128680,registered,true,15140080,,CC BY-SA 4.0,2015-10-08 08:31:27,353,271,3,0,0,4,true,false,false,true,true,true,35,6,false,0.014,0.0005,5155,2012,10,22,Wednesday,false,false,false,false,false,false,false
3558119,Are (non-void) self-closing tags valid in HTML5?,"The W3C validator (Wikipedia) shows a warning for self-closing tags (those that end with “/>”) on non-void elements. (Void elements are those that may not ever contain any content.) Are they still valid in HTML5?
Some examples of accepted void elements:
<br />
<img src="" />
<input type="text" name="username" />
Some examples of rejected non-void elements:
<div id="myDiv" />
<span id="mySpan" />
<textarea id="someTextMessage" />
Note:
The W3C validator actually accepts void self-closing tags: the author originally had a problem because of a simple typo (\> instead of />); however, self-closing tags are 100% not valid in HTML5 in general, and the answers elaborate on the issue of self-closing tags across various HTML flavors.
",https://stackoverflow.com/questions/3558119/are-non-void-self-closing-tags-valid-in-html5,779,335910.0,8.0,,,2010-08-24 15:28:40,2024-05-27 05:38:58,2024-05-27 05:38:58,,,html;syntax;w3c-validation,cdeszaq,31400,20770,registered,true,3558200,,CC BY-SA 4.0,2013-06-23 10:14:05,1401,839,5,4,0,3,true,false,false,true,true,true,48,7,true,0.024,0.0023,5933,2010,8,15,Tuesday,false,false,false,false,false,false,false
492809,When to use IMG vs. CSS background-image?,"In what situations is it more appropriate to use an HTML IMG tag to display an image, as opposed to a CSS background-image, and vice-versa?
Factors may include accessibility, browser support, dynamic content, or any kind of technical limits or usability principles.
",https://stackoverflow.com/questions/492809/when-to-use-img-vs-css-background-image,777,494107.0,31.0,,,2009-01-29 18:25:06,2021-09-04 21:04:03,2014-05-23 15:08:03,,,html;css;image;background-image,system PAUSE,39098,52963,registered,true,1469139,,CC BY-SA 3.0,2014-02-20 00:23:22,307,267,2,0,0,4,true,false,false,true,true,true,41,7,true,0.063,0.0016,6505,2009,1,18,Thursday,false,false,false,false,false,false,false
1219860,HTML-encoding lost when attribute read from input field,"I’m using JavaScript to pull a value out from a hidden field and display it in a textbox. The value in the hidden field is encoded.
For example,
<input id='hiddenId' type='hidden' value='chalk & cheese' />
gets pulled into
<input type='text' value='chalk & cheese' />
via some jQuery to get the value from the hidden field (it’s at this point that I lose the encoding):
$('#hiddenId').attr('value')
The problem is that when I read chalk & cheese from the hidden field, JavaScript seems to lose the encoding. I do not want the value to be chalk & cheese. I want the literal amp; to be retained.
Is there a JavaScript library or a jQuery method that will HTML-encode a string?
",https://stackoverflow.com/questions/1219860/html-encoding-lost-when-attribute-read-from-input-field,774,663926.0,26.0,,,2009-08-02 21:08:29,2021-10-12 15:09:49,2019-04-08 22:08:03,,,javascript;jquery;html;escaping;html-escape-characters,AJM,32600,64226,registered,true,1219983,,CC BY-SA 4.0,2011-08-15 11:25:53,994,726,6,0,0,5,true,false,false,true,true,true,55,8,false,0.039,0.0012,6320,2009,8,21,Sunday,true,false,true,false,false,false,false
774054,Should I put input elements inside a label element?,"Is there a best practice concerning the nesting of label and input HTML elements?
classic way:
<label for=""myinput"">My Text</label>
<input type=""text"" id=""myinput"" />
or
<label for=""myinput"">My Text
<input type=""text"" id=""myinput"" />
</label>
",https://stackoverflow.com/questions/774054/should-i-put-input-elements-inside-a-label-element,773,347119.0,16.0,,,2009-04-21 18:52:05,2025-05-24 15:46:34,2018-10-18 23:27:22,,,html;semantics,jpsimard-nyx,8965,47109,registered,true,774065,,CC BY-SA 4.0,2014-06-07 19:20:01,461,288,4,0,0,2,true,false,false,true,true,true,51,9,true,0.046,0.0022,6423,2009,4,18,Tuesday,false,false,false,false,false,false,false
6095530,Maximum call stack size exceeded error,"I am using a Direct Web Remoting (DWR) JavaScript library file and am getting an error only in Safari (desktop and iPad)
It says
Maximum call stack size exceeded.
What exactly does this error mean and does it stop processing completely?
Also any fix for Safari browser (Actually on the iPad Safari, it says
JS:execution exceeded timeout
which I am assuming is the same call stack issue)
",https://stackoverflow.com/questions/6095530/maximum-call-stack-size-exceeded-error,770,2511236.0,40.0,,,2011-05-23 09:49:48,2025-01-21 16:37:42,2017-05-03 18:22:15,,,javascript;html;webkit;callstack;dwr,copenndthagen,51192,485743,registered,true,6095695,,CC BY-SA 3.0,2014-10-30 16:35:05,528,403,2,0,0,5,true,false,false,true,true,true,38,6,false,0.016,0.0003,5661,2011,5,9,Monday,false,false,true,false,false,false,false
2155737,Remove CSS class from element with JavaScript (no jQuery),"Could anyone let me know how to remove a class on an element using JavaScript only?
Please do not give me an answer with jQuery as I can't use it, and I don't know anything about it.
",https://stackoverflow.com/questions/2155737/remove-css-class-from-element-with-javascript-no-jquery,769,1041992.0,11.0,,,2010-01-28 15:43:04,2022-06-17 20:25:24,2012-10-04 08:59:47,2014-08-12 16:58:50,Duplicate,javascript;html;css,Amra,25454,207847,registered,true,2156090,,,,190,183,0,0,0,3,true,true,false,true,true,true,57,9,false,0.011,0.0007,6141,2010,1,15,Thursday,false,false,true,false,false,false,false
7117949,How To Auto-Format / Indent XML/HTML in Notepad++,"Is there a way to re-indent a block of code? I'm looking for something similar to Ctrl+Shift+F in Eclipse (Auto-Format/Indent).
To be clear,
- I already know how to format XML outside of Notepad++ (Eclipse works fine, as mentioned) so I don't need a bunch of links to other XML-formatting tools.
- I'm specifically working with XML and HTML.
- Ideally, there's a keybinding as convenient as the one in Eclipse, so I don't have to break my workflow.
I already know about NppAutoIndent - it won't work, as I'm working with XML, HTML and CSS.
",https://stackoverflow.com/questions/7117949/how-to-auto-format-indent-xml-html-in-notepad,769,1514608.0,9.0,,,2011-08-19 06:50:52,2026-02-18 14:24:16,2017-11-24 15:54:03,,,html;xml;notepad++;auto-indent;autoformatting,SBoss,9325,767581,registered,true,8786249,,CC BY-SA 3.0,2017-01-21 00:41:59,640,541,0,0,0,5,true,false,false,true,true,true,49,8,false,0.006,0.0005,5573,2011,8,6,Friday,false,false,false,false,false,false,false
5523140,Are there any benefits to Session Storage over Local Storage?,"Apart from being non persistent and scoped only to the current window, are there any benefits (performance, data access, etc) to Session Storage over Local Storage?
",https://stackoverflow.com/questions/5523140/are-there-any-benefits-to-session-storage-over-local-storage,768,480545.0,11.0,,,2011-04-02 12:30:07,2024-11-17 13:26:56,2024-03-30 23:25:00,,,javascript;html;local-storage;session-storage,jpkeisala,9086,31425,registered,true,5523174,,CC BY-SA 4.0,,172,165,0,0,0,4,true,false,false,true,true,true,61,10,true,0.023,0.0016,5712,2011,4,12,Saturday,true,false,true,false,false,false,false
1122381,How to force child div to be 100% of parent div's height without specifying parent's height?,"I have a site with the following structure:
<div id=""header""></div>
<div id=""main"">
<div id=""navigation""></div>
<div id=""content""></div>
</div>
<div id=""footer""></div>
The navigation is on the left and the content div is on the right. The information for the content div is pulled in through PHP, so it's different every time.
How can I scale the navigation vertically so that its height is the same as the content div's height, no matter which page is loaded?
",https://stackoverflow.com/questions/1122381/how-to-force-child-div-to-be-100-of-parent-divs-height-without-specifying-pare,768,1447961.0,32.0,,,2009-07-13 22:14:05,2024-09-10 11:18:41,2019-01-03 20:20:39,,,html;css,user137726,,,does_not_exist,true,1122411,,CC BY-SA 4.0,2015-07-30 00:14:26,576,531,1,0,0,2,true,false,false,true,false,true,100,16,true,0.022,0.0005,6340,2009,7,22,Monday,false,false,false,false,false,false,false
5319754,Cross-reference (named anchor) in markdown,"Is there markdown syntax for the equivalent of:
Take me to <a href=""#pookie"">pookie</a>
...
<a name=""pookie"">this is pookie</a>
",https://stackoverflow.com/questions/5319754/cross-reference-named-anchor-in-markdown,767,477171.0,16.0,,,2011-03-16 00:41:44,2026-01-28 15:30:55,2021-11-30 21:42:06,,,html;syntax;markdown;anchor,Synesso,39478,45525,registered,true,7335259,,CC BY-SA 4.0,,244,157,1,0,0,4,true,false,false,true,true,true,42,5,false,0.034,0.0016,5729,2011,3,0,Wednesday,false,false,false,false,false,false,false
12374442,Chrome ignores autocomplete="off","I've created a web application which uses a tagbox drop down. This works great in all browsers except Chrome browser (Version 21.0.1180.89).
Despite both the input fields AND the form field having the autocomplete=""off"" attribute, Chrome insists on showing a drop down history of previous entries for the field, which is obliterating the tagbox list.
",https://stackoverflow.com/questions/12374442/chrome-ignores-autocomplete-off,764,737495.0,73.0,,,2012-09-11 16:54:31,2025-03-18 03:25:26,2019-01-03 20:14:31,,,html;google-chrome;autocomplete;forms,Mr Fett,8638,1663528,registered,true,,,CC BY-SA 4.0,2014-03-27 17:58:50,405,352,3,0,0,4,false,false,false,true,true,true,43,3,false,0.099,0.001,5184,2012,9,16,Tuesday,false,false,false,false,false,false,false
9707397,Making a div vertically scrollable using CSS,"This
<div id="""" style=""overflow:scroll; height:400px;"">
gives a div that the user can scroll in both in horizontally and vertically. How do I change it so that the div is only scrollable vertically?
",https://stackoverflow.com/questions/9707397/making-a-div-vertically-scrollable-using-css,764,1791443.0,10.0,,,2012-03-14 17:56:08,2022-06-17 13:44:41,2015-12-17 07:49:35,,,html;css,Saswat,12986,1170507,registered,true,9707674,,CC BY-SA 3.0,2016-01-07 19:30:25,433,217,2,0,0,2,true,false,false,true,true,true,44,7,false,0.006,0.0004,5365,2012,3,17,Wednesday,false,false,false,false,false,false,false
5804256,Why does my image inside a div have extra space below it?,"Why in the following code the height of the div is bigger than the height of the img ? There is a gap below the image, but it doesn't seems to be a padding/margin.
What is the gap or extra space below image?
#wrapper {
border: 1px solid red;
width:200px;
}
img {
width:200px;
}
<div id=""wrapper"">
<img src=""http://i.imgur.com/RECDV24.jpg"" />
</div>
![]()
",https://stackoverflow.com/questions/5804256/why-does-my-image-inside-a-div-have-extra-space-below-it,764,243811.0,11.0,,,2011-04-27 12:40:35,2025-06-07 11:56:02,2025-05-02 16:07:05,,,html;css;image,Misha Moroshko,172725,247243,registered,true,5804278,,CC BY-SA 4.0,2014-10-18 20:05:33,912,399,4,1,1,3,true,false,false,true,true,true,57,12,true,0.045,0.0031,5687,2011,4,12,Wednesday,false,false,false,false,false,false,false
1227286,Get class list for element with jQuery,"Is there a way in jQuery to loop through or assign to an array all of the classes that are assigned to an element?
ex.
<div class=""Lorem ipsum dolor_spec sit amet"">Hello World!</div>
I will be looking for a ""special"" class as in ""dolor_spec"" above. I know that I could use hasClass() but the actual class name may not necessarily be known at the time.
",https://stackoverflow.com/questions/1227286/get-class-list-for-element-with-jquery,760,887685.0,16.0,,,2009-08-04 12:41:04,2023-07-11 06:12:04,2014-12-17 23:11:40,,,javascript;jquery;html,Buggabill,14030,2106,registered,true,1227309,,CC BY-SA 3.0,2016-02-18 16:33:26,414,369,1,0,0,3,true,false,false,true,true,true,38,7,false,0.018,0.0009,6318,2009,8,12,Tuesday,false,false,true,false,false,false,false
7117073,Add a tooltip to a div,"I have a div tag like this:
<div>
<label>Name</label>
<input type=""text""/>
</div>
How can I displaying a tooltip on :hover of the div, preferably with a fade in/out effect.
",https://stackoverflow.com/questions/7117073/add-a-tooltip-to-a-div,757,1049953.0,25.0,,,2011-08-19 04:49:50,2023-03-14 09:11:46,2019-09-12 01:57:45,,,javascript;html;css;tooltip,user475685,8369,475685,registered,true,7117107,,CC BY-SA 4.0,2014-09-10 10:45:12,300,210,2,0,0,4,true,false,false,true,true,true,22,6,false,0.024,0.0007,5573,2011,8,4,Friday,false,false,true,false,false,false,false
787839,Resize image proportionally with CSS?,"Is there a way to resize (scale down) images proportionally using ONLY CSS?
I'm doing the JavaScript way, but just trying to see if this is possible with CSS.
",https://stackoverflow.com/questions/787839/resize-image-proportionally-with-css,756,1907553.0,18.0,,,2009-04-24 23:40:17,2020-09-23 15:02:26,2018-03-11 11:16:25,2019-01-02 15:36:02,Duplicate,html;css;image-resizing,codingbear,15173,191083,registered,true,,,,2014-10-23 11:48:13,174,160,0,0,0,3,false,true,false,true,true,true,37,5,true,0.009,0.0004,6420,2009,4,23,Friday,false,false,false,false,false,false,false
9601357,Placing border inside of div and not on its edge,"I have a <div> element and I want to put a border on it. I know I can write style=""border: 1px solid black"", but this adds 2px to either side of the div, which is not what I want.
I would rather have this border be -1px from the edge of the div. The div itself is 100px x 100px, and if I add a border, then I have to do some mathematics to make the border appear.
Is there any way that I can make the border appear, and ensure the box will still be 100px (including the border)?
",https://stackoverflow.com/questions/9601357/placing-border-inside-of-div-and-not-on-its-edge,751,1717842.0,15.0,,,2012-03-07 12:16:24,2024-06-30 18:13:16,2015-01-26 16:38:38,,,html;css;border,TheMonkeyMan,9272,701928,registered,true,9601431,,CC BY-SA 3.0,,537,490,2,0,0,3,true,false,false,true,true,true,48,10,false,0.009,0.0004,5372,2012,3,12,Wednesday,false,false,false,false,false,false,false
618097,How do you easily horizontally center a <div> using CSS?,"I'm trying to horizontally center a <div> block element on a page and have it set to a minimum width. What is the simplest way to do this? I want the <div> element to be inline with rest of my page. I'll try to draw an example:
page text page text page text page text
page text page text page text page text
-------
| div |
-------
page text page text page text page text
page text page text page text page text
",https://stackoverflow.com/questions/618097/how-do-you-easily-horizontally-center-a-div-using-css,751,1221310.0,21.0,,,2009-03-06 08:51:07,2019-10-09 08:52:07,,2018-09-28 00:53:54,Duplicate,css;html,cmcginty,118384,64313,registered,true,10797328,,,,528,471,3,0,0,2,true,true,false,true,true,false,62,10,true,0.017,0.0006,6469,2009,3,8,Friday,false,false,false,false,false,false,false
7415872,Change color of PNG image via CSS?,"Given a transparent PNG displaying a simple shape in white, is it possible to somehow change the color of this through CSS? Some kind of overlay or what not?
",https://stackoverflow.com/questions/7415872/change-color-of-png-image-via-css,751,1856631.0,30.0,,,2011-09-14 11:53:05,2025-11-17 19:23:47,2022-04-11 21:45:55,,,html;css;image;png;overlay,user429620,,,does_not_exist,true,20933311,,CC BY-SA 4.0,,165,158,0,0,0,5,true,false,false,true,false,true,34,7,true,0.016,0.0004,5547,2011,9,11,Wednesday,false,false,false,false,false,false,false
3828554,How can I allow <input type="file"> to accept only image files?,"I need to upload only an image file through the <input type="file"> tag.
Right now, it accepts all file types. But, I want to restrict it to only specific image file extensions, which include .jpg, .gif, etc.
How can I achieve this functionality?
",https://stackoverflow.com/questions/3828554/how-can-i-allow-input-type-file-to-accept-only-image-files,747,1184021.0,13.0,,,2010-09-30 07:14:46,2026-02-04 01:20:31,2026-02-03 22:34:05,,,html;image;input;file-upload,kbvishnu,15718,438624,registered,true,6225815,,CC BY-SA 4.0,2016-01-08 14:56:36,315,263,1,0,0,4,true,false,false,true,true,true,79,11,true,0.011,0.0006,5896,2010,9,7,Thursday,false,false,false,false,false,false,false
4502633,How to affect other elements when one element is hovered,"What I want to do is when a certain div is hovered, it'd affect the properties of another div.
For example, in this JSFiddle demo, when you hover over #cube it changes the background-color but what I want is that when I hover over #container, #cubeis affected.
div {
outline: 1px solid red;
}
#container {
width: 200px;
height: 30px;
}
#cube {
width: 30px;
height: 100%;
background-color: red;
}
#cube:hover {
width: 30px;
height: 100%;
background-color: blue;
}
<div id=""container"">
<div id=""cube"">
</div>
</div>
",https://stackoverflow.com/questions/4502633/how-to-affect-other-elements-when-one-element-is-hovered,746,911021.0,8.0,,,2010-12-21 18:29:18,2022-12-15 19:20:44,2020-07-06 09:21:43,,,html;css;hover,Trufa,40943,463065,registered,true,4502693,,CC BY-SA 4.0,2013-07-16 18:15:05,1031,574,8,1,0,3,true,false,false,true,true,true,56,10,false,0.009,0.0008,5814,2010,12,18,Tuesday,false,false,false,false,false,false,false
11832930,HTML Input="file" Accept Attribute File Type (CSV),"I have a file upload object on my page:
<input type="file" ID="fileSelect" />
with the following excel files on my desktop:
- file1.xlsx
- file1.xls
- file.csv
I want the file upload to ONLY show .xlsx, .xls, & .csv files.
Using the accept attribute, I found these content-types took care of .xlsx & .xls extensions...
accept= application/vnd.openxmlformats-officedocument.spreadsheetml.sheet (.XLSX)
accept= application/vnd.ms-excel (.XLS)
However, I cannot find the correct content-type for an Excel CSV file! Any suggestions?
EXAMPLE: http://jsfiddle.net/LzLcZ/
",https://stackoverflow.com/questions/11832930/html-input-file-accept-attribute-file-type-csv,745,936146.0,12.0,,,2012-08-06 17:18:50,2022-11-13 07:53:33,2020-06-20 09:12:55,,,html;csv;file-upload;input;content-type,Dom,40796,1558171,registered,true,,,CC BY-SA 4.0,2014-10-14 07:48:48,954,600,9,1,0,5,false,false,false,true,true,true,60,7,false,0.013,0.0008,5220,2012,8,17,Monday,false,false,false,false,false,false,false
6579844,How does Zalgo text work?,"I've seen weirdly formatted text called Zalgo like below written on various forums. It's kind of annoying to look at, but it really bothers me because it undermines my notion of what a character is supposed to be. My understanding is that a character is supposed to move horizontally across a line and stay within a certain ""container"". Obviously the Zalgo text is moving vertically and doesn't seem to be restricted to any space.
Is this a bug/flaw/exploit/hack in Unicode? Are these individual characters with weird properties? ""What"" is happening here?
H̡̫̤̤̣͉̤ͭ̓̓̇͗̎̀ơ̯̗̱̘̮͒̄̀̈ͤ̀͡w͓̲͙͖̥͉̹͋ͬ̊ͦ̂̀̚ ͎͉͖̌ͯͅͅd̳̘̿̃̔̏ͣ͂̉̕ŏ̖̙͋ͤ̊͗̓͟͜e͈͕̯̮̙̣͓͌ͭ̍̐̃͒s͙͔̺͇̗̱̿̊̇͞ ̸̤͓̞̱̫ͩͩ͑̋̀ͮͥͦ̊Z̆̊͊҉҉̠̱̦̩͕ą̟̹͈̺̹̋̅ͯĺ̡̘̹̻̩̩͋͘g̪͚͗ͬ͒o̢̖͇̬͍͇͓̔͋͊̓ ̢͈͙͂ͣ̏̿͐͂ͯ͠t̛͓̖̻̲ͤ̈ͣ͝e͋̄ͬ̽͜҉͚̭͇ͅx͎̬̠͇̌ͤ̓̂̓͐͐́͋͡ț̗̹̝̄̌̀ͧͩ̕͢ ̮̗̩̳̱̾w͎̭̤͍͇̰̄͗ͭ̃͗ͮ̐o̢̯̻̰̼͕̾ͣͬ̽̔̍͟ͅr̢̪͙͍̠̀ͅǩ̵̶̗̮̮ͪ́?̙͉̥̬͙̟̮͕ͤ̌͗ͩ̕͡
",https://stackoverflow.com/questions/6579844/how-does-zalgo-text-work,741,223140.0,2.0,,,2011-07-05 08:30:37,2018-11-16 05:23:26,2017-03-08 00:02:22,,,html;unicode;zalgo,Mike,61550,357024,registered,true,20310289,,CC BY-SA 3.0,2012-09-17 21:08:24,941,872,0,0,0,3,true,false,false,true,true,true,25,5,true,0.009,0.0033,5618,2011,7,8,Tuesday,false,false,false,false,false,false,false
13,Determine a user's timezone,"Is there a standard way for a web server to be able to determine a user's timezone within a web page?
Perhaps from an HTTP header or part of the user-agent string?
",https://stackoverflow.com/questions/13/determine-a-users-timezone,735,329686.0,28.0,,,2008-08-01 00:42:38,2025-03-12 10:54:11,2020-12-03 03:37:56,,,html;browser;timezone;user-agent;timezone-offset,Kevin Dente,25898,9,registered,true,,,CC BY-SA 4.0,2013-07-02 03:03:08,193,166,1,0,0,5,false,false,false,true,true,true,31,4,false,0.085,0.0022,6686,2008,8,0,Friday,false,false,false,false,false,false,false
5394116,Outline radius?,"Is there any way of getting rounded corners on the outline of a div element, similar to border-radius?
",https://stackoverflow.com/questions/5394116/outline-radius,734,614974.0,25.0,,,2011-03-22 16:01:35,2024-08-09 05:37:39,2021-09-25 17:27:14,,,html;css,Marc Guerin,7482,664602,registered,true,,,CC BY-SA 4.0,2018-12-18 09:13:14,136,103,2,0,0,2,false,false,false,true,true,true,15,2,true,0.041,0.0012,5723,2011,3,16,Tuesday,false,false,false,false,false,false,false
2834350,Get checkbox value in jQuery,"How can I get a checkbox's value in jQuery?
",https://stackoverflow.com/questions/2834350/get-checkbox-value-in-jquery,729,1789109.0,21.0,,,2010-05-14 13:08:46,2025-04-01 17:50:52,2025-04-01 17:50:24,,,javascript;html;jquery;forms;checkbox,maztt,12582,324831,registered,true,2834357,,CC BY-SA 4.0,2014-12-18 22:51:36,51,44,0,0,0,5,true,false,false,true,true,true,28,5,false,0.012,0.0004,6035,2010,5,13,Friday,false,false,true,false,false,false,false
4067469,Selecting all text in HTML text input when clicked,"I have the following code to display a textbox in a HTML webpage.
<input type=""text"" id=""userid"" name=""userid"" value=""Please enter the user ID"" />
When the page displays, the text contains the Please enter the user ID message. However, I found that the user needs to click 3 times in order to select all the text (in this case it is Please enter the user ID).
Is it possible to select the entire text with only one click?
Edit:
Sorry, I forgot to say: I must use the input type=""text""
",https://stackoverflow.com/questions/4067469/selecting-all-text-in-html-text-input-when-clicked,728,751481.0,30.0,,,2010-11-01 08:27:05,2026-03-16 10:56:36,2014-03-12 04:49:04,,,javascript;html;textinput,Questions,21155,387298,registered,true,4067488,,CC BY-SA 3.0,,605,498,2,0,0,3,true,false,false,true,true,true,50,9,false,0.04,0.001,5864,2010,11,8,Monday,false,false,true,false,false,false,false
2989284,What is the max size of localStorage values?,"Since localStorage (currently) only supports strings as values, and in order to do that the objects need to be stringified (stored as JSON-string) before they can be stored, is there a defined limitation regarding the length of the values.
Does anyone know if there is a definition which applies to all browsers?
",https://stackoverflow.com/questions/2989284/what-is-the-max-size-of-localstorage-values,728,634687.0,13.0,,,2010-06-07 12:09:15,2026-02-19 15:27:57,2015-07-16 02:13:39,,,javascript;html;local-storage,Codekie,7934,269386,registered,true,2989317,,CC BY-SA 3.0,2018-01-06 21:37:54,341,314,1,0,0,3,true,false,false,true,true,true,44,8,true,0.02,0.0011,6011,2010,6,12,Monday,false,false,true,false,false,false,false
5347357,jQuery: Get selected element tag name,"Is there an easy way to get a tag name?
For example, if I am given $('a') into a function, I want to get 'a'.
",https://stackoverflow.com/questions/5347357/jquery-get-selected-element-tag-name,724,695035.0,7.0,,,2011-03-18 02:20:23,2022-04-12 14:44:21,2022-04-12 14:44:21,,,javascript;html;jquery;css;htmlelements,configurator,41900,9536,registered,true,5347371,,CC BY-SA 4.0,2014-12-31 08:25:16,151,111,2,0,0,5,true,false,false,true,true,true,37,6,false,0.01,0.001,5727,2011,3,2,Friday,false,false,true,false,false,false,false
31000885,Align an element to bottom with flexbox,"I have a div with some children:
<div class=""content"">
<h1>heading 1</h1>
<h2>heading 2</h2>
<p>Some more or less text</p>
<a href=""/"" class=""button"">Click me</a>
</div>
and I want the following layout:
-------------------
|heading 1 |
|heading 2 |
|paragraph text |
|can have many |
|rows |
| |
| |
| |
|link-button |
-------------------
Regardless how much text is in the p I want to stick the .button always at the bottom without taking it out of the flow. I've heard this can be achievable with Flexbox but I can't get it to work.
",https://stackoverflow.com/questions/31000885/align-an-element-to-bottom-with-flexbox,721,1166716.0,12.0,,,2015-06-23 10:56:13,2024-03-11 14:01:34,2017-04-20 07:31:32,,,html;css;flexbox,supersize,15013,1778367,registered,true,31006659,,CC BY-SA 3.0,2024-06-05 18:25:52,823,715,5,0,0,3,true,false,false,true,true,true,39,7,false,0.01,0.0006,4169,2015,6,10,Tuesday,false,false,false,false,false,false,false
17711146,How to open link in a new tab in HTML?,"I'm working on an HTML project, and I can't find out how to open a link in a new tab without JavaScript.
I already know that <a href="http://www.WEBSITE_NAME.com"></a> opens the link in the same tab. Any ideas how to make it open in a new one?
",https://stackoverflow.com/questions/17711146/how-to-open-link-in-a-new-tab-in-html,721,1252720.0,11.0,,,2013-07-17 22:09:51,2026-09-15 12:49:47,2021-03-11 01:02:58,,,html;hyperlink;anchor;browser-tab,ZenthyxProgramming,7393,2581716,registered,true,17711167,,CC BY-SA 4.0,2019-03-14 14:58:02,293,266,1,0,0,4,true,false,false,true,true,true,38,10,true,0.009,0.0006,4875,2013,7,22,Wednesday,false,false,false,false,false,false,false
11620698,How to trigger a file download when clicking an HTML button or JavaScript,"This is crazy but I don't know how to do this, and because of how common the words are, it's hard to find what I need on search engines. I'm thinking this should be an easy one to answer.
I want a simple file download, that would do the same as this:
<a href=""file.doc"">Download!</a>
But I want to use an HTML button, e.g. either of these:
<input type=""button"" value=""Download!"">
<button>Download!</button>
Likewise, is it possible to trigger a simple download via JavaScript?
$(""#fileRequest"").click(function(){ /* code to download? */ });
I'm definitely not looking for a way to create an anchor that looks like a button, use any back-end scripts, or mess with server headers or mime types.
",https://stackoverflow.com/questions/11620698/how-to-trigger-a-file-download-when-clicking-an-html-button-or-javascript,719,1903814.0,25.0,,,2012-07-23 21:22:08,2025-07-26 18:36:21,2017-07-23 11:43:22,,,javascript;html;download,brentonstrine,23012,925897,registered,true,11620761,,CC BY-SA 3.0,2014-06-10 13:26:45,849,733,3,0,0,3,true,false,false,true,true,true,73,13,false,0.013,0.0004,5234,2012,7,21,Monday,false,false,true,false,false,false,false
183532,What is the difference between HTML div and span elements?,"I would like to ask for some simple examples showing the uses of <div> and <span>. I've seen them both used to mark a section of a page with an id or class, but I'm interested in knowing if there are times when one is preferred over the other.
",https://stackoverflow.com/questions/183532/what-is-the-difference-between-html-div-and-span-elements,717,551815.0,13.0,,,2008-10-08 16:01:44,2022-12-10 17:12:55,2021-11-05 13:07:36,,,html;tags,JSchaefer,7401,3676,registered,true,183536,,CC BY-SA 4.0,2013-11-04 15:26:28,315,256,4,0,0,2,true,false,false,true,true,true,58,10,true,0.024,0.0013,6618,2008,10,16,Wednesday,false,false,false,false,false,false,false
8605516,Set the select option as blank as default in HTML select element,"I am required to have no option selected by default in drop down menu in HTML. However, I cannot use:
<select>
<option></option>
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select>
Because for this I will have to validate to handle the first option.
Can anyone help me in achieving this target without actually including the first option as part of the select tag?
",https://stackoverflow.com/questions/8605516/set-the-select-option-as-blank-as-default-in-html-select-element,715,1101532.0,21.0,,,2011-12-22 14:48:08,2025-04-29 10:52:05,2023-03-02 05:45:44,,,html,Pankaj Parashar,10362,903446,registered,true,23638053,,CC BY-SA 4.0,2020-10-26 16:43:14,719,479,1,0,0,1,true,false,false,true,true,true,64,12,false,0.019,0.0006,5448,2011,12,14,Thursday,false,false,false,false,false,false,false
2182716,Is it possible to set a src attribute of an img tag in CSS?,"Is it possible to set the src attribute value in CSS?
In most cases, we use it like this:
<img src="pathTo/myImage.jpg" />
and I want it to be something like this
<img class="myClass" />
.myClass {
some-src-property: url("pathTo/myImage.jpg");
}
I want to know if there is a way doing it without using the background or background-image properties in CSS.
",https://stackoverflow.com/questions/2182716/is-it-possible-to-set-a-src-attribute-of-an-img-tag-in-css,714,783326.0,24.0,,,2010-02-02 08:33:16,2023-12-01 05:46:16,2023-06-08 22:16:19,,,html;css;image;src,Rakesh Juyal,37007,94813,registered,true,11484688,,CC BY-SA 4.0,,635,406,6,0,0,4,true,false,false,true,true,true,59,14,true,0.031,0.0009,6136,2010,2,8,Tuesday,false,false,false,false,false,false,false
121203,How to detect if JavaScript is disabled?,"There was a post this morning asking about how many people disable JavaScript. Then I began to wonder what techniques might be used to determine if the user has it disabled.
Does anyone know of some short/simple ways to detect if JavaScript is disabled? My intention is to give a warning that the site is not able to function properly without the browser having JS enabled.
Eventually I would want to redirect them to content that is able to work in the absence of JS, but I need this detection as a placeholder to start.
",https://stackoverflow.com/questions/121203/how-to-detect-if-javascript-is-disabled,714,536157.0,41.0,,,2008-09-23 14:07:12,2024-05-25 10:58:48,2024-01-05 07:02:06,,,javascript;html;css,MikeJ,14606,10676,registered,true,121259,,CC BY-SA 4.0,2011-09-13 05:10:30,547,526,0,0,0,3,true,false,false,true,true,true,40,7,true,0.076,0.0013,6633,2008,9,14,Tuesday,false,false,true,false,false,false,false
547821,Two submit buttons in one form,"I have two submit buttons in a form. How do I determine which one was hit serverside?
",https://stackoverflow.com/questions/547821/two-submit-buttons-in-one-form,713,908882.0,23.0,,,2009-02-13 21:47:04,2025-08-19 13:58:56,2009-02-13 21:52:31,,,html;forms;submit,Alex,45141,85185,registered,true,547824,,CC BY-SA 2.5,2020-05-12 07:24:32,102,86,0,0,0,3,true,false,false,true,true,true,30,6,false,0.025,0.0008,6490,2009,2,21,Friday,false,false,false,false,false,false,false
413439,How to dynamically change a web page's title?,"I have a webpage that implements a set of tabs each showing different content. The tab clicks do not refresh the page but hide/unhide contents at the client side.
Now there is a requirement to change the page title according to the tab selected on the page ( for SEO reasons ). Is this possible? Can someone suggest a solution to dynamically alter the page title via javascript without reloading the page?
",https://stackoverflow.com/questions/413439/how-to-dynamically-change-a-web-pages-title,706,838863.0,20.0,,,2009-01-05 15:25:13,2023-09-29 16:38:49,2017-08-09 13:47:00,,,javascript;html,user12129,7081,12129,registered,true,413455,,CC BY-SA 3.0,2013-07-17 14:06:52,421,407,0,0,0,2,true,false,false,true,true,true,49,8,true,0.024,0.0008,6529,2009,1,15,Monday,false,false,true,false,false,false,false
3314989,Can I make a <button> not submit a form?,"I've got a form, with 2 buttons
<a href=""index.html""><button>Cancel changes</button></a>
<button type=""submit"">Submit</button>
I use jQuery UI's button on them too, simply like this
$('button').button();
However, the first button also submits the form. I would have thought that if it didn't have the type=""submit"", it wouldn't.
Obviously I could do this
$('button[type!=submit]').click(function(event) { event.stopPropagation(); });
But is there a way I can stop that back button from submitting the form without JavaScript intervention?
To be honest, I used a button only so I could style it with jQuery UI. I tried calling button() on the link and it didn't work as expected (looked quite ugly!).
",https://stackoverflow.com/questions/3314989/can-i-make-a-button-not-submit-a-form,705,503410.0,8.0,,,2010-07-23 02:29:32,2022-04-06 08:20:12,2022-04-06 08:20:12,,,javascript;html;jquery;jquery-ui;button,alex,492880,31671,registered,true,3315016,,CC BY-SA 4.0,,888,748,5,0,0,5,true,false,false,true,true,true,46,9,true,0.016,0.0014,5965,2010,7,2,Friday,false,false,true,false,false,false,false
4457506,Set the table column width constant regardless of the amount of text in its cells?,"In my table I set the width of the first cell in a column to be 100px.
However, when the text in one of the cell in this column is too long, the width of the column becomes more than 100px. How could I disable this expansion?
",https://stackoverflow.com/questions/4457506/set-the-table-column-width-constant-regardless-of-the-amount-of-text-in-its-cell,705,1476191.0,19.0,,,2010-12-16 04:44:25,2025-01-22 16:11:15,2017-06-16 19:58:11,,,html;css;column-width,Misha Moroshko,172725,247243,registered,true,4457905,,CC BY-SA 3.0,2019-05-18 06:17:24,265,226,2,0,0,3,true,false,false,true,true,true,82,15,true,0.013,0.0005,5819,2010,12,4,Thursday,false,false,false,false,false,false,false
37112218,CSS3 100vh not constant in mobile browser,"I have a very odd issue... in every browser and mobile version I encountered this behavior:
- all the browsers have a top menu when you load the page (showing the address bar for example) which slide up when you start scrolling the page.
- 100vh sometimes is calculated only on the visible part of a viewport, so when the browser bar slide up 100vh increases (in terms of pixels)
- all layout re-paint and re-adjust since the dimensions have changed
- a bad jumpy effect for user experience
How can avoid this problem? When I first heard of viewport-height I was excited and I thought I could use it for fixed height blocks instead of using javascript, but now I think the only way to do that is in fact javascript with some resize event...
you can see the problem at: sample site
Can anyone help me with / suggest a CSS solution?
simple test code:
/* maybe i can track the issue whe it occours... */
$(function(){
var resized = -1;
$(window).resize(function(){
$('#currenth').val( $('.vhbox').eq(1).height() );
if (++resized) $('#currenth').css('background:#00c');
})
.resize();
})
*{ margin:0; padding:0; }
/*
this is the box which should keep constant the height...
min-height to allow content to be taller than viewport if too much text
*/
.vhbox{
min-height:100vh;
position:relative;
}
.vhbox .t{
display:table;
position:relative;
width:100%;
height:100vh;
}
.vhbox .c{
height:100%;
display:table-cell;
vertical-align:middle;
text-align:center;
}
<div class=""vhbox"" style=""background-color:#c00"">
<div class=""t""><div class=""c"">
this div height should be 100% of viewport and keep this height when scrolling page
<br>
<!-- this input highlight if resize event is fired -->
<input type=""text"" id=""currenth"">
</div></div>
</div>
<div class=""vhbox"" style=""background-color:#0c0"">
<div class=""t""><div class=""c"">
this div height should be 100% of viewport and keep this height when scrolling page
</div></div>
</div>
<script src=""https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js""></script>
",https://stackoverflow.com/questions/37112218/css3-100vh-not-constant-in-mobile-browser,704,560739.0,38.0,,,2016-05-09 09:32:40,2024-08-05 19:37:57,2019-03-25 01:28:28,,,html;css;viewport-units,Nereo Costacurta,8632,1779863,registered,true,37113430,,CC BY-SA 4.0,,2804,2237,3,1,0,3,true,false,false,true,true,true,41,7,false,0.068,0.0013,3848,2016,5,9,Monday,false,false,false,false,false,false,false
1360869,How to use HTML to print header and footer on every printed page of a document?,"Is it possible to print HTML pages with custom headers and footers on each printed page?
I'd like to add the word ""UNCLASSIFIED"" in Red, Arial, size 16pt to the top and bottom of every printed page, regardless of the content.
To clarify, if the document was printed onto 5 pages, each page should have the custom header and footer.
Does anybody know if this is possible using HTML/CSS?
",https://stackoverflow.com/questions/1360869/how-to-use-html-to-print-header-and-footer-on-every-printed-page-of-a-document,704,745545.0,23.0,,,2009-09-01 06:38:42,2026-06-29 19:27:33,2024-02-02 18:52:25,,,html;css;printing;header;footer,ben,,,does_not_exist,true,,,CC BY-SA 4.0,2014-05-23 17:36:03,426,389,0,0,0,5,false,false,false,true,false,true,79,16,true,0.031,0.0009,6290,2009,9,6,Tuesday,false,false,false,false,false,false,false
13499040,How do search engines deal with AngularJS applications?,"I see two issues with AngularJS application regarding search engines and SEO:
1) What happens with custom tags? Do search engines ignore the whole content within those tags? i.e. suppose I have
<custom>
<h1>Hey, this title is important</h1>
</custom>
would <h1> be indexed despite being inside custom tags?
2) Is there a way to avoid search engines of indexing {{}} binds literally? i.e.
<h2>{{title}}</h2>
I know I could do something like
<h2 ng-bind=""title""></h2>
but what if I want to actually let the crawler ""see"" the title? Is server-side rendering the only solution?
",https://stackoverflow.com/questions/13499040/how-do-search-engines-deal-with-angularjs-applications,703,209840.0,15.0,,,2012-11-21 17:44:48,2022-09-07 06:38:28,2013-08-03 20:39:00,,,html;angularjs;seo;search-engine;google-search,dariofarzati,8656,1206952,registered,true,13521668,,CC BY-SA 3.0,2014-08-25 01:02:22,781,643,4,0,0,5,true,false,false,true,true,true,55,8,true,0.071,0.0034,5113,2012,11,17,Wednesday,false,false,false,false,false,false,false
5041008,How to find elements by class,"I'm having trouble parsing HTML elements with ""class"" attribute using Beautifulsoup. The code looks like this
soup = BeautifulSoup(sdata)
mydivs = soup.findAll('div')
for div in mydivs:
if (div[""class""] == ""stylelistrow""):
print div
I get an error on the same line ""after"" the script finishes.
File ""./beautifulcoding.py"", line 130, in getlanguage
if (div[""class""] == ""stylelistrow""):
File ""/usr/local/lib/python2.6/dist-packages/BeautifulSoup.py"", line 599, in __getitem__
return self._getAttrMap()[key]
KeyError: 'class'
How do I get rid of this error?
",https://stackoverflow.com/questions/5041008/how-to-find-elements-by-class,698,1257273.0,21.0,,,2011-02-18 11:58:10,2024-11-09 01:00:26,2019-05-30 05:41:32,,,python;html;web-scraping;beautifulsoup,Neo,13941,1678010,registered,true,5041056,,CC BY-SA 4.0,,649,580,2,0,0,4,true,false,false,true,true,true,29,6,false,0.017,0.0006,5755,2011,2,11,Friday,false,true,false,false,false,false,false
5899337,Proper way to make HTML nested list?,"The W3 docs have a nested list example prefixed by DEPRECATED EXAMPLE:, but they never corrected it with a non-deprecated example, nor explained exactly what is wrong with the example.
So which of these ways is the correct way to write an HTML list?
Option 1: The nested <ul> is a child of the parent <ul>:
<ul>
<li>List item one</li>
<li>List item two with subitems:</li>
<ul>
<li>Subitem 1</li>
<li>Subitem 2</li>
</ul>
<li>Final list item</li>
</ul>
Option 2: The nested <ul> is a child of the <li> it belongs in:
<ul>
<li>List item one</li>
<li>List item two with subitems:
<ul>
<li>Subitem 1</li>
<li>Subitem 2</li>
</ul>
</li>
<li>Final list item</li>
</ul>
",https://stackoverflow.com/questions/5899337/proper-way-to-make-html-nested-list,698,553173.0,7.0,,,2011-05-05 14:25:42,2025-07-29 06:27:15,2023-09-08 23:08:37,,,html;html-lists;nested-lists,Ricket,34445,47493,registered,true,5899394,,CC BY-SA 4.0,2014-10-23 17:57:35,1211,950,7,1,0,3,true,false,false,true,true,true,36,7,true,0.013,0.0013,5679,2011,5,14,Thursday,false,false,false,false,false,false,false
6421966,CSS overflow-x: visible; and overflow-y: hidden; causing scrollbar issue,"Suppose you have some style and the markup:
ul
{
white-space: nowrap;
overflow-x: visible;
overflow-y: hidden;
/* added width so it would work in the snippet */
width: 100px;
}
li
{
display: inline-block;
}
<div>
<ul>
<li>1</li> <li>2</li> <li>3</li>
<li>4</li> <li>5</li> <li>6</li>
<li>7</li> <li>8</li> <li>9</li>
<li>1</li> <li>2</li> <li>3</li>
<li>4</li> <li>5</li> <li>6</li>
<li>7</li> <li>8</li> <li>9</li>
<li>1</li> <li>2</li> <li>3</li>
<li>4</li> <li>5</li> <li>6</li>
<li>7</li> <li>8</li> <li>9</li>
</ul>
</div>
When you view this. The <ul> has a scroll bar at the bottom even though I've specified visible and hidden values for overflow x/y.
(observed on Chrome 11 and Opera)
I'm guessing there must be some w3c spec or something telling this to happen but for the life of me I can't work out why.
UPDATE:
I found a way to achieve the same result by adding another element wrapped around the ul.
",https://stackoverflow.com/questions/6421966/css-overflow-x-visible-and-overflow-y-hidden-causing-scrollbar-issue,697,612920.0,11.0,,,2011-06-21 07:45:06,2024-08-18 12:37:52,2024-08-18 12:37:52,,,html;css;overflow,James Khoury,22635,684890,registered,true,6433475,,CC BY-SA 4.0,2023-05-31 03:09:29,1862,1347,4,2,0,3,true,false,false,true,true,true,72,9,false,0.018,0.0011,5632,2011,6,7,Tuesday,false,false,false,false,false,false,false
376253,Stretch and scale CSS background,"Is there a way to get a background in CSS to stretch or scale to fill its container?
",https://stackoverflow.com/questions/376253/stretch-and-scale-css-background,696,1000251.0,16.0,,,2008-12-17 22:21:25,2017-11-24 07:47:35,2012-09-30 15:08:49,,,html;css,Cornelius Dol,64249,8946,registered,true,4495748,,CC BY-SA 3.0,2012-01-24 17:04:17,92,85,0,0,0,2,true,false,false,true,true,true,32,5,false,0.016,0.0007,6548,2008,12,22,Wednesday,false,false,false,false,false,false,false
251420,Invoking JavaScript code in an iframe from the parent page,"Basically, I have an iframe embedded in a page and the iframe has some JavaScript routines I need to invoke from the parent page.
Now the opposite is quite simple as you only need to call parent.functionName(), but unfortunately, I need exactly the opposite of that.
Please note that my problem is not changing the source URL of the iframe, but invoking a function defined in the iframe.
",https://stackoverflow.com/questions/251420/invoking-javascript-code-in-an-iframe-from-the-parent-page,689,619128.0,17.0,,,2008-10-30 19:27:56,2022-07-05 11:27:29,2018-03-05 01:44:20,,,javascript;html;iframe,Mkkt Bkkt,122065,8954,registered,true,251453,,CC BY-SA 3.0,2014-03-30 17:57:06,632,390,5,2,0,3,true,false,false,true,true,true,58,10,false,0.027,0.0011,6596,2008,10,19,Thursday,false,false,true,false,false,false,false
7693224,How do I right align div elements?,"The body of my html document consists of 3 elements, a button, a form, and a canvas. I want the button and the form to be right aligned and the canvas to stay left aligned. The problem is when I try to align the first two elements, they no longer follow each other and instead are next to each other horizontally?
Here's the code I have so far, I want the form to follow directly after the button on the right with no space in between.
#cTask {
background-color: lightgreen;
}
#button {
position: relative;
float: right;
}
#addEventForm {
position: relative;
float: right;
border: 2px solid #003B62;
font-family: verdana;
background-color: #B5CFE0;
padding-left: 10px;
}
<!DOCTYPE html>
<html lang=""en"">
<head>
<script type=""text/javascript"" src=""http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js""></script>
<script type=""text/javascript"" src=""timeline.js""></script>
<link rel=""stylesheet"" href=""master.css"" type=""text/css"" media=""screen"" />
</head>
<body bgcolor=""000"" TEXT=""FFFFFF"">
<div id=""button"">
<button onclick=""showForm()"" type=""button"" id=""cTask"">
Create Task
</button>
</div>
<div id=""addEventForm"">
<form>
<p><label>Customer name: <input></label></p>
<p><label>Telephone: <input type=tel></label></p>
<p><label>E-mail address: <input type=email></label></p>
</form>
</div>
<div>
<canvas id=""myBoard"" width=""600"" height=""600"" style=""background:lightgray;"">
<p>Your browser doesn't support canvas.</p>
</canvas>
</div>
</body>
</html>
",https://stackoverflow.com/questions/7693224/how-do-i-right-align-div-elements,684,2273175.0,19.0,,,2011-10-07 21:54:04,2026-04-16 22:38:35,2024-07-07 15:10:42,,,css;html,MEURSAULT,8929,412556,registered,true,7693264,,CC BY-SA 4.0,2020-11-18 22:36:38,2119,1807,2,0,0,2,true,false,false,true,true,true,34,7,true,0.008,0.0003,5524,2011,10,21,Friday,false,false,false,false,false,false,false
1258416,Word-wrap in an HTML table,"I've been using word-wrap: break-word to wrap text in divs and spans. However, it doesn't seem to work in table cells. I have a table set to width:100%, with one row and two columns. Text in columns, although styled with the above word-wrap, doesn't wrap. It causes the text to go past the bounds of the cell. This happens on Firefox, Google Chrome and Internet Explorer.
Here's what the source looks like:
td {
border: 1px solid;
}
<table style=""width: 100%;"">
<tr>
<td>
<div style=""word-wrap: break-word;"">
Looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong word
</div>
</td>
<td><span style=""display: inline;"">Short word</span></td>
</tr>
</table>
The long word above is larger than the bounds of my page, but it doesn't break with the above HTML. I've tried the suggestions below of adding text-wrap:suppress and text-wrap:normal, but neither helped.
",https://stackoverflow.com/questions/1258416/word-wrap-in-an-html-table,679,1097803.0,29.0,,,2009-08-11 04:01:28,2024-08-26 10:59:05,2019-01-20 16:58:19,,,html;css;html-table,psychotik,39287,106095,registered,true,,,CC BY-SA 4.0,2011-12-01 17:35:34,1547,1136,9,0,0,3,false,false,false,true,true,true,26,5,false,0.026,0.0006,6311,2009,8,4,Tuesday,false,false,false,false,false,false,false
9975810,Make iframe automatically adjust height according to the contents without using scrollbar?,"For example:
<iframe name=""Stack"" src=""http://stackoverflow.com/"" width=""740""
frameborder=""0"" scrolling=""no"" id=""iframe""> ...
</iframe>
I want it to be able to adjust its height according to the contents inside it, without using scroll.
",https://stackoverflow.com/questions/9975810/make-iframe-automatically-adjust-height-according-to-the-contents-without-using,677,1586947.0,16.0,,,2012-04-02 11:45:38,2024-12-24 23:16:07,2020-10-03 13:45:53,2016-07-06 13:12:23,Duplicate,javascript;html;iframe;height;scrollbar,akashbc,6785,1307919,registered,true,9976309,,,2015-05-14 17:47:40,298,260,1,0,0,5,true,true,false,true,true,true,90,12,true,0.01,0.0004,5346,2012,4,11,Monday,false,false,true,false,false,false,false
25311541,How to vertically align text inside a flexbox?,"I would like to use flexbox to vertically align some content inside an <li> but not having great success.
I've checked online and many of the tutorials actually use a wrapper div which gets the align-items:center from the flex settings on the parent, but I'm wondering is it possible to cut out this additional element?
I've opted to use flexbox in this instance as the list item height will be a dynamic %.
* {
padding: 0;
margin: 0;
}
html,
body {
height: 100%;
}
ul {
height: 100%;
}
li {
display: flex;
justify-content: center;
align-self: center;
background: silver;
width: 100%;
height: 20%;
}
<ul>
<li>This is the text</li>
</ul>
",https://stackoverflow.com/questions/25311541/how-to-vertically-align-text-inside-a-flexbox,675,1126686.0,14.0,,,2014-08-14 15:11:24,2024-05-15 14:06:06,2019-09-18 02:55:27,,,html;css;flexbox,styler,16597,1977333,registered,true,,,CC BY-SA 4.0,,1089,731,5,0,0,3,false,false,false,true,true,true,46,8,true,0.012,0.0006,4482,2014,8,15,Thursday,false,false,false,false,false,false,false
18716863,CSS hide scroll bar if not needed,"I am trying to figure out how I can hide the overflow-y:scroll; if not needed. What I mean is that I am building a website and I have a main area which posts will be displayed and I want to hide the scroll bar if content does not exceed the current width.
Also, my second question. I want to make it so when the posts exceed the current width, the width will increase automatically and the content won't go out of the box.
Does anyone have a clue how to do this?
Posts area:
.content {
height: 600px;
border-left: 1px solid;
border-right: 1px solid;
border-bottom: 1px solid;
font-size: 15px;
text-align: justify;
line-height: 19px;
overflow-y:scroll;
}
Main website container:
.container {
margin: 0 auto;
width: 757px;
margin-top: 30px;
text-align: center;
}
",https://stackoverflow.com/questions/18716863/css-hide-scroll-bar-if-not-needed,673,468338.0,6.0,,,2013-09-10 10:46:43,2022-07-28 10:24:50,2015-09-29 11:23:35,,,html;css,Thanos Paravantis,7763,2672192,registered,true,18716885,,CC BY-SA 3.0,,913,817,3,0,0,2,true,false,false,true,true,true,33,7,false,0.013,0.0014,4820,2013,9,10,Tuesday,false,false,false,false,false,false,false
3076708,Can we have multiple <tbody> in same <table>?,"Can we have multiple <tbody> tags in same <table>? If yes then in what scenarios should we use multiple <tbody> tags?
",https://stackoverflow.com/questions/3076708/can-we-have-multiple-tbody-in-same-table,673,231737.0,7.0,,,2010-06-19 18:25:10,2025-08-18 07:27:57,2022-04-13 13:28:05,,,html;html-table;xhtml,Jitendra Vyas,154325,84201,registered,true,3076790,,CC BY-SA 4.0,2013-08-25 09:28:50,182,136,3,0,0,3,true,false,false,true,true,true,57,8,true,0.03,0.0029,5999,2010,6,18,Saturday,true,false,false,false,false,false,false
5068951,What do < and > stand for?,"I know that the entities < and > are used for < and >, but I am curious what these names stand for.
Does < stand for something like ""Left tag"" or is it just a code?
",https://stackoverflow.com/questions/5068951/what-do-lt-and-gt-stand-for,672,2175399.0,9.0,,,2011-02-21 17:09:42,2022-06-15 00:14:32,2017-10-31 15:25:20,,,html;terminology;html-entities;html-escape-characters,Michiel Pater,23243,248756,registered,true,5068965,,CC BY-SA 3.0,2015-05-18 10:04:34,281,193,5,0,0,4,true,false,false,true,true,true,40,7,true,0.004,0.0003,5752,2011,2,17,Monday,false,false,false,false,false,false,false
1260122,Expand a div to fill the remaining width,"I want a two-column div layout, where each one can have variable width e.g.
div {
float: left;
}
.second {
background: #ccc;
}
<div>Tree</div>
<div class=""second"">View</div>
I want the 'view' div to expand to the whole width available after 'tree' div has filled needed space.
Currently, my 'view' div is resized to content it contains
It will also be good if both divs take up the whole height.
Not duplicate disclaimer:
- Expand div to max width when float:left is set
because there the left one has a fixed width.
- Help with div - make div fit the remaining width
because I need two columns both aligned to left
",https://stackoverflow.com/questions/1260122/expand-a-div-to-fill-the-remaining-width,671,564573.0,21.0,,,2009-08-11 12:46:15,2026-06-29 07:22:47,2020-03-10 02:18:09,,,html;css;multiple-columns,Anurag Uniyal,89437,6946,registered,true,1767270,,CC BY-SA 4.0,2018-08-12 08:11:50,1251,668,2,2,0,3,true,false,false,true,true,true,40,8,false,0.037,0.0012,6311,2009,8,12,Tuesday,false,false,false,false,false,false,false
10281962,Is there a minlength validation attribute in HTML?,"It seems the minlength attribute for an <input> field doesn't work.
Is there any other attribute in HTML with the help of which I can set the minimal length of a value for fields?
",https://stackoverflow.com/questions/10281962/is-there-a-minlength-validation-attribute-in-html,668,721277.0,21.0,,,2012-04-23 13:56:22,2026-07-12 11:38:01,2023-01-04 15:58:42,,,html;validation,emilan,13175,613318,registered,true,10294291,,CC BY-SA 4.0,2023-01-04 16:00:07,226,186,2,0,0,2,true,false,false,true,true,true,50,8,true,0.029,0.0009,5325,2012,4,13,Monday,false,false,false,false,false,false,false
2400386,Get class name using jQuery,"I want to get the class name using jQuery
And if it has an id
<div class=""myclass""></div>
",https://stackoverflow.com/questions/2400386/get-class-name-using-jquery,666,1678392.0,19.0,,,2010-03-08 09:43:29,2020-06-26 18:12:13,2020-06-26 18:12:13,,,javascript;html;jquery,X10nD,22076,257705,registered,true,2400396,,CC BY-SA 4.0,,144,106,1,0,0,3,true,false,false,true,true,true,27,5,false,0.011,0.0004,6102,2010,3,9,Monday,false,false,true,false,false,false,false
7609130,Set the default value of an input field,"How would you set the default value of a form <input> text field in JavaScript?
",https://stackoverflow.com/questions/7609130/set-the-default-value-of-an-input-field,665,2216341.0,19.0,,,2011-09-30 10:32:00,2025-03-05 14:51:29,2023-03-15 06:15:40,,,javascript;html;forms;input;html-input,SebastianOpperman,7326,954325,registered,true,7609144,,CC BY-SA 4.0,2016-11-14 05:55:38,106,86,1,0,0,5,true,false,false,true,true,true,39,8,false,0.009,0.0003,5531,2011,9,10,Friday,false,false,true,false,false,false,false
83073,Why not use tables for layout in HTML?,"It seems to be the general opinion that tables should not be used for layout in HTML.
Why?
I have never (or rarely to be honest) seen good arguments for this. The usual answers are:
It's good to separate content from layout
But this is a fallacious argument; Cliche Thinking. I guess it's true that using the table element for layout has little to do with tabular data. So what? Does my boss care? Do my users care?
Perhaps me or my fellow developers who have to maintain a web page care... Is a table less maintainable? I think using a table is easier than using divs and CSS.
By the way... why is using a div or a span good separation of content from layout and a table not? Getting a good layout with only divs often requires a lot of nested divs.
Readability of the code
I think it's the other way around. Most people understand HTML, few understand CSS.
It's better for SEO not to use tables
Why? Can anybody show some evidence that it is? Or a statement from Google that tables are discouraged from an SEO perspective?
Tables are slower.
An extra tbody element has to be inserted. This is peanuts for modern web browsers. Show me some benchmarks where the use of a table significantly slows down a page.
A layout overhaul is easier without tables, see css Zen Garden.
Most web sites that need an upgrade need new content (HTML) as well. Scenarios where a new version of a web site only needs a new CSS file are not very likely. Zen Garden is a nice web site, but a bit theoretical. Not to mention its misuse of CSS.
I am really interested in good arguments to use divs + CSS instead of tables.
",https://stackoverflow.com/questions/83073/why-not-use-tables-for-layout-in-html,664,483710.0,66.0,,,2008-09-17 13:19:09,2018-11-06 00:07:39,2018-11-06 00:07:39,2011-12-02 15:21:56,not constructive,html;css,Benno Richters,15813,3565,registered,true,84986,,,2017-09-08 18:23:45,2319,1600,0,6,0,2,true,true,false,true,true,true,38,8,true,0.136,0.0014,6639,2008,9,13,Wednesday,false,false,false,false,false,false,false
11135261,What are the advantages/disadvantages of using the <i> tag for icons instead of <span>?,"Facebook's HTML and Twitter Bootstrap HTML (before v3) both use the <i> tag to display icons.
However, from the HTML5 spec:
The I element represents a span of text in an alternate voice or mood,
or otherwise offset from the normal prose, such as a taxonomic
designation, a technical term, an idiomatic phrase from another
language, a thought, a ship name, or some other prose whose typical
typographic presentation is italicized.
Why are they using <i> tag to display icons? Isn't it a bad practice? Or am I missing something here?
I am using span to display icons and it seems to be working for me until now.
Update:
Bootstrap 3 uses span for icons. Official Doc
Bootstrap 5 is back to i. Official doc
",https://stackoverflow.com/questions/11135261/what-are-the-advantages-disadvantages-of-using-the-i-tag-for-icons-instead-of,663,325758.0,7.0,,,2012-06-21 09:27:38,2023-08-03 18:45:29,2023-08-01 23:29:49,2026-05-01 10:03:50,Opinion-based,html;semantic-markup,Jashwant,29175,702469,registered,true,11135302,,,2016-06-28 17:26:08,1138,717,5,3,0,2,true,true,false,true,true,true,99,14,true,0.021,0.002,5266,2012,6,9,Thursday,false,false,false,false,false,false,false
846994,How to use HTML Agility pack,"How do I use the HTML Agility Pack?
My XHTML document is not completely valid. That's why I wanted to use it. How do I use it in my project? My project is in C#.
",https://stackoverflow.com/questions/846994/how-to-use-html-agility-pack,662,407003.0,7.0,,,2009-05-11 06:50:11,2019-05-29 10:11:16,2017-11-23 01:59:08,,,c#;html;html-agility-pack,chh,,,does_not_exist,true,,,CC BY-SA 3.0,2011-08-08 13:42:11,249,163,0,1,0,3,false,false,false,true,false,true,28,6,false,0.017,0.0016,6403,2009,5,6,Monday,false,false,false,false,true,false,false
6490252,Vertically centering a div inside another div,"I want to center a div which is inside another div.
<div id="outerDiv">
<div id="innerDiv">
</div>
</div>
This is the CSS I am currently using.
#outerDiv {
width: 500px;
height: 500px;
position: relative;
}
#innerDiv {
width: 284px;
height: 290px;
position: absolute;
top: 50%;
left: 50%;
margin-top: -147px;
margin-left: -144px;
}
As you can see, the approach I use now depends on the width and height of #innerDiv. If the width/height changes, I will have to modify the margin-top and margin-left values. Is there any generic solution that I can use to center the #innerDiv independently of its size?
I figured out that using margin: auto can horizontally align the #innerDiv to the middle. But what about vertical alignment?
",https://stackoverflow.com/questions/6490252/vertically-centering-a-div-inside-another-div,658,857942.0,24.0,,,2011-06-27 08:22:03,2021-12-01 07:03:49,2021-12-01 07:03:49,2019-04-09 12:47:39,Duplicate,html;css,user700284,13670,700284,registered,true,6490283,,,,1037,883,8,0,0,2,true,true,false,true,true,true,45,7,false,0.028,0.0008,5626,2011,6,8,Monday,false,false,false,false,false,false,false
39325414,Line break in HTML with '\n',"Is there a way to make HTML properly treat \n line breaks? Or do I have to replace them with <br/>?
<div class=""text"">
abc
def
ghi
</div>
",https://stackoverflow.com/questions/39325414/line-break-in-html-with-n,655,1818683.0,11.0,,,2016-09-05 07:08:27,2025-02-02 08:34:56,2023-07-19 05:15:57,,,html;css;line-breaks,stkvtflw,13881,4845952,registered,true,39325471,,CC BY-SA 4.0,,424,172,3,0,0,3,true,false,false,true,true,true,36,6,false,0.006,0.0004,3729,2016,9,7,Monday,false,false,false,false,false,false,false
4652654,How to turn off word wrapping in HTML?,"I feel silly for not being able to figure this out, but how do I turn off wordwrap? the css word-wrap property can be forced on with break-word, but cannot be forced off (only can be left alone with normal value).
How do I force word wrap off?
",https://stackoverflow.com/questions/4652654/how-to-turn-off-word-wrapping-in-html,653,507891.0,7.0,,,2011-01-10 23:19:32,2024-08-12 14:31:54,2011-01-10 23:39:53,,,html;css;word-wrap,Alexander Bird,41208,10608,registered,true,4652666,,CC BY-SA 2.5,,316,245,3,0,0,3,true,false,false,true,true,true,38,8,true,0.014,0.0013,5794,2011,1,23,Monday,false,false,false,false,false,false,false
2272507,Find out whether radio button is checked with JQuery?,"I can set a radio button to checked fine, but what I want to do is setup a sort of 'listener' that activates when a certain radio button is checked.
Take, for example the following code:
$(""#element"").click(function()
{
$('#radio_button').attr(""checked"", ""checked"");
});
it adds a checked attribute and all is well, but how would I go about
adding an alert. For example, that pops up when the radio button is checked
without the help of the click function?
",https://stackoverflow.com/questions/2272507/find-out-whether-radio-button-is-checked-with-jquery,651,1183765.0,18.0,,,2010-02-16 11:33:08,2021-01-16 04:43:44,2019-09-25 11:28:59,,,jquery;html;jquery-ui;checked,Keith,26569,37418,registered,true,2272532,,CC BY-SA 4.0,,530,468,1,0,0,4,true,false,false,true,true,true,53,9,true,0.015,0.0005,6122,2010,2,11,Tuesday,false,false,false,false,false,false,false
78932,How do I programmatically set the value of a select box element using JavaScript?,"I have the following HTML <select> element:
<select id=""leaveCode"" name=""leaveCode"">
<option value=""10"">Annual Leave</option>
<option value=""11"">Medical Leave</option>
<option value=""14"">Long Service</option>
<option value=""17"">Leave Without Pay</option>
</select>
Using a JavaScript function with the leaveCode number as a parameter, how do I select the appropriate option in the list?
",https://stackoverflow.com/questions/78932/how-do-i-programmatically-set-the-value-of-a-select-box-element-using-javascript,647,1502636.0,15.0,,,2008-09-17 01:28:04,2024-09-30 19:43:29,2017-07-23 11:41:15,,,javascript;html;dom,brasskazoo,79876,6340,registered,true,78945,,CC BY-SA 3.0,2013-04-23 09:15:02,528,464,3,0,0,3,true,false,false,true,true,true,81,14,true,0.01,0.0004,6639,2008,9,1,Wednesday,false,false,true,false,false,false,false
26960703,How can I change the color of header bar and address bar in the newest Chrome version on Lollipop?,"I haven't found anything on this topic yet. I really like the ability to change the color of address bar and header color on Overview. Is there an easy way to do this?
.
I think you need Android 5.0 (Lollipop) for this to work, and Chrome's Merge Tabs and Apps set to On.
",https://stackoverflow.com/questions/26960703/how-can-i-change-the-color-of-header-bar-and-address-bar-in-the-newest-chrome-ve,646,409520.0,5.0,,,2014-11-16 18:48:58,2022-11-27 01:57:19,2022-11-27 01:35:54,,,android;html;google-chrome,Arpad Gabor,15288,2654663,registered,true,26960753,,CC BY-SA 4.0,2016-03-25 12:45:27,542,273,0,1,2,3,true,false,false,true,true,true,98,19,true,0.012,0.0016,4388,2014,11,18,Sunday,true,false,false,false,false,false,false
19669786,Check if element is visible in DOM,"Is there any way that I can check if an element is visible in pure JS (no jQuery) ?
So, given a DOM element, how can I check if it is visible or not? I tried:
window.getComputedStyle(my_element)['display']);
but it doesn't seem to be working. I wonder which attributes should I check. It comes to my mind:
display !== 'none'
visibility !== 'hidden'
Any others that I might be missing?
",https://stackoverflow.com/questions/19669786/check-if-element-is-visible-in-dom,644,912845.0,31.0,,,2013-10-29 21:45:09,2025-09-20 05:01:53,2022-12-09 09:44:31,,,javascript;html;dom,Hommer Smith,28032,1196150,registered,true,21696585,,CC BY-SA 4.0,,464,388,2,0,0,3,true,false,false,true,true,true,34,7,false,0.034,0.0007,4771,2013,10,21,Tuesday,false,false,true,false,false,false,false
574941,How to track onchange as-you-type in input type="text"?,"In my experience, input type="text" onchange event usually occurs only after you leave (blur) the control.
Is there a way to force browser to trigger onchange every time textfield content changes? If not, what is the most elegant way to track this “manually”?
Using onkey* events is not reliable, since you can right-click the field and choose Paste, and this will change the field without any keyboard input.
Is setTimeout the only way?
",https://stackoverflow.com/questions/574941/how-to-track-onchange-as-you-type-in-input-type-text,642,857136.0,16.0,,,2009-02-22 13:43:48,2025-04-21 18:03:33,2024-11-12 21:06:52,,,javascript;html;forms,Ilya Birman,10142,65813,registered,true,574971,,CC BY-SA 4.0,2020-05-03 18:08:43,567,448,7,0,0,3,true,false,false,true,true,true,65,8,true,0.019,0.0007,6481,2009,2,13,Sunday,true,false,true,false,false,false,false
1383143,How to prevent line breaks in list items using CSS,"I'm trying to put a link called Submit resume in a menu using a li tag. Because of the whitespace between the two words it wraps to two lines. How to prevent this wrapping with CSS?
",https://stackoverflow.com/questions/1383143/how-to-prevent-line-breaks-in-list-items-using-css,641,550349.0,6.0,,,2009-09-05 11:47:30,2024-03-19 22:40:14,2013-08-29 09:21:04,,,html;css;word-wrap,Rajasekar,19146,148814,registered,true,1383147,,CC BY-SA 3.0,,211,182,1,0,0,3,true,false,false,true,true,true,50,10,false,0.011,0.0012,6286,2009,9,11,Saturday,true,false,false,false,false,false,false
356809,Best way to center a <div> on a page vertically and horizontally?,"Best way to center a <div> element on a page both vertically and horizontally?
I know that margin-left: auto; margin-right: auto; will center on the horizontal, but what is the best way to do it vertically, too?
",https://stackoverflow.com/questions/356809/best-way-to-center-a-div-on-a-page-vertically-and-horizontally,640,1291172.0,30.0,,,2008-12-10 17:11:33,2021-09-09 13:14:29,2018-05-01 10:41:11,2019-01-03 20:13:40,Duplicate,html;css;alignment;vertical-alignment;centering,J-Dog,,,does_not_exist,true,,,,2014-09-21 22:08:14,259,219,2,0,0,5,false,true,false,true,false,true,71,12,true,0.023,0.0005,6555,2008,12,17,Wednesday,false,false,false,false,false,false,false
5445491,Height equal to dynamic width (CSS fluid layout),"Is it possible to set same height as width (ratio 1:1)?
Example
+----------+
| body |
| 1:3 |
| |
| +------+ |
| | div | |
| | 1:1 | |
| +------+ |
| |
| |
| |
| |
| |
+----------+
CSS
div {
width: 80%;
height: same-as-width
}
",https://stackoverflow.com/questions/5445491/height-equal-to-dynamic-width-css-fluid-layout,638,821005.0,9.0,,,2011-03-26 21:35:42,2023-02-18 11:41:26,2016-05-10 09:05:00,2015-04-19 15:39:15,Duplicate,javascript;jquery;html;css;responsive-design,Thomas Norman,6383,678411,unregistered,true,5445536,,,,405,302,2,0,0,5,true,true,false,true,true,true,48,8,false,0.011,0.0008,5719,2011,3,21,Saturday,true,false,true,false,false,false,false
2076299,How to close current tab in a browser window?,"I want to create a link on a webpage that would close the currently active tab in a browser without closing other tabs in the browser.
When the user clicks the close link, an alert message should appear asking the user to confirm with two buttons, ""YES"" and ""NO"". If the user clicks ""YES"", close that page and If ""NO"", do nothing.
How can it be done? Any suggestions?
",https://stackoverflow.com/questions/2076299/how-to-close-current-tab-in-a-browser-window,635,1615737.0,24.0,,,2010-01-16 05:25:59,2025-10-10 00:58:22,2018-07-19 08:39:27,,,javascript;html;hyperlink,Naveed,42351,149206,registered,true,2076307,,CC BY-SA 4.0,2013-06-03 15:41:33,387,369,0,0,0,3,true,false,false,true,true,true,45,9,true,0.015,0.0004,6153,2010,1,5,Saturday,true,false,true,false,false,false,false
3245141,Using .otf fonts on web browsers,"I'm working on a website that requires font trials online, the fonts I have are all .otf
Is there a way to embed the fonts and get them working on all browsers?
If not, what other alternatives do I have ?
",https://stackoverflow.com/questions/3245141/using-otf-fonts-on-web-browsers,630,862739.0,2.0,,,2010-07-14 10:13:13,2025-08-22 19:46:21,2013-03-21 17:22:50,,,html;css;fonts;font-face,Naruto,6796,390269,registered,true,,,CC BY-SA 3.0,2025-08-23 03:46:11,229,208,0,0,0,4,false,false,false,true,true,true,32,6,false,0.002,0.0007,5974,2010,7,10,Wednesday,false,false,false,false,false,false,false
12627443,jQuery.click() vs onClick,"I have a huge jQuery application, and I'm using the below two methods for click events.
First method
HTML
<div id=""myDiv"">Some Content</div>
jQuery
$('#myDiv').click(function(){
//Some code
});
Second method
HTML
<div id=""myDiv"" onClick=""divFunction()"">Some Content</div>
JavaScript function call
function divFunction(){
//Some code
}
I use either the first or second method in my application. Which one is better? Better for performance? And standard?
",https://stackoverflow.com/questions/12627443/jquery-click-vs-onclick,623,1752427.0,18.0,,,2012-09-27 18:02:02,2022-04-05 04:59:11,2020-06-26 10:49:16,,,javascript;html;jquery;dom-events;jquery-events,Techie,45254,1263783,registered,true,12627478,,CC BY-SA 4.0,2020-10-09 11:44:18,694,500,4,0,0,5,true,false,false,true,true,true,25,3,false,0.01,0.0004,5168,2012,9,18,Thursday,false,false,true,false,false,false,false
6003819,What is the difference between properties and attributes in HTML?,"After the changes made in jQuery 1.6.1, I have been trying to define the difference between properties and attributes in HTML.
Looking at the list on the jQuery 1.6.1 release notes (near the bottom), it seems one can classify HTML properties and attributes as follows:
Properties: All which either has a boolean value or that is UA calculated such as selectedIndex.
Attributes: 'Attributes' that can be added to a HTML element which is neither boolean nor containing a UA generated value.
Thoughts?
",https://stackoverflow.com/questions/6003819/what-is-the-difference-between-properties-and-attributes-in-html,622,359654.0,8.0,,,2011-05-14 18:04:41,2024-04-09 04:22:43,2024-04-09 04:22:43,,,html;dom;properties,schalkneethling,6824,355766,registered,true,6004028,,CC BY-SA 4.0,,655,505,0,1,0,3,true,false,false,true,true,true,65,10,true,0.022,0.0017,5670,2011,5,18,Saturday,true,false,false,false,false,false,false
1827965,Is putting a div inside an anchor ever correct?,"I've heard that putting a block element inside a inline element is a HTML sin:
<a href="http://example.com">
<div>
What we have here is a problem.
You see, an anchor element is an inline element,
and the div element is a block level element.
</div>
</a>
But what about if you style the outer anchor as display:block in the stylesheet? Is it still wrong? The HTML 4.01 spec on block-level and inline elements seems to think so:
Style sheets provide the means to
specify the rendering of arbitrary
elements, including whether an element
is rendered as block or inline. In
some cases, such as an inline style
for list elements, this may be
appropriate, but generally speaking,
authors are discouraged from
overriding the conventional
interpretation of HTML elements in
this way.
Does anyone have any further tips about this issue?
",https://stackoverflow.com/questions/1827965/is-putting-a-div-inside-an-anchor-ever-correct,622,405045.0,16.0,,,2009-12-01 18:26:19,2023-09-06 06:07:34,2021-06-13 19:46:01,,,html,Tom,14280,42754,registered,true,1828032,,CC BY-SA 4.0,,1114,898,2,1,0,1,true,false,false,true,true,true,47,9,true,0.04,0.0015,6199,2009,12,18,Tuesday,false,false,false,false,false,false,false
796087,Make a div into a link,"I have a <div> block with some fancy visual content that I don't want to change. I want to make it a clickable link.
I'm looking for something like <a href=""…""><div> … </div></a>, but that is valid XHTML 1.1.
",https://stackoverflow.com/questions/796087/make-a-div-into-a-link,620,847794.0,33.0,,,2009-04-28 03:15:24,2024-02-28 09:30:22,2013-02-11 11:16:08,,,css;html;xhtml;anchor,EE.,6291,26351,registered,true,,,CC BY-SA 3.0,2012-10-28 21:29:49,280,240,2,0,0,4,false,false,false,true,true,true,22,6,false,0.039,0.0007,6416,2009,4,3,Tuesday,false,false,false,false,false,false,false
1328538,How do I escape ampersands in XML so they are rendered as entities in HTML?,"I have some XML text that I wish to render in an HTML page. This text contains an ampersand, which I want to render in its entity representation: &.
How do I escape this ampersand in the source XML? I tried &, but this is decoded as the actual ampersand character (&), which is invalid in HTML.
So I want to escape it in such a way that it will be rendered as & in the web page that uses the XML output.
",https://stackoverflow.com/questions/1328538/how-do-i-escape-ampersands-in-xml-so-they-are-rendered-as-entities-in-html,620,907372.0,10.0,,,2009-08-25 14:11:14,2021-11-10 20:18:59,2019-11-06 00:16:40,,,html;xml;escaping;ampersand,AJM,32600,64226,registered,true,1328720,,CC BY-SA 4.0,2011-10-14 20:08:16,600,435,4,1,0,4,true,false,false,true,true,true,75,15,true,0.011,0.0007,6297,2009,8,14,Tuesday,false,false,false,false,false,false,false
8287779,How to use the "required" attribute with a "radio" input field,"I am just wondering how to use the new HTML5 input attribute ""required"" in the right way on radio buttons. Does every radio button field need the attribute like below or is it sufficient if only one field gets it?
<input type=""radio"" name=""color"" value=""black"" required=""required"" />
<input type=""radio"" name=""color"" value=""white"" required=""required"" />
",https://stackoverflow.com/questions/8287779/how-to-use-the-required-attribute-with-a-radio-input-field,620,744040.0,4.0,,,2011-11-27 18:13:27,2021-12-22 08:43:18,2020-02-24 07:42:17,,,html;radio-button;required,nerdess,11070,393704,registered,true,8287947,,CC BY-SA 4.0,,402,371,1,0,0,3,true,false,false,true,true,true,82,11,false,0.005,0.0008,5473,2011,11,18,Sunday,true,false,false,false,false,false,false
15738259,Disabling Chrome Autofill,"I have been running into issues with the chrome autofill behavior on several forms.
The fields in the form all have very common and accurate names, such as ""email"", ""name"", or ""password"", and they also have autocomplete=""off"" set.
The autocomplete flag has successfully disabled the autocomplete behavior, where a dropdown of values appear as you start typing, but has not changed the values that Chrome auto-populates the fields as.
This behavior would be ok except that chrome is filling the inputs incorrectly, for example filling the phone input with an email address. Customers have complained about this, so it's verified to be happening in multiple cases, and not as some some sort of result to something that I've done locally on my machine.
The only current solution I can think of is to dynamically generate custom input names and then extract the values on the backend, but this seems like a pretty hacky way around this issue. Are there any tags or quirks that change the autofill behavior that could be used to fix this?
",https://stackoverflow.com/questions/15738259/disabling-chrome-autofill,617,1131776.0,68.0,,,2013-04-01 05:45:09,2023-06-26 12:18:27,2016-11-08 13:00:08,,,html;forms;google-chrome;autocomplete;autofill,templaedhel,6296,1552923,registered,true,,,CC BY-SA 3.0,2015-04-20 19:15:06,1090,1042,1,0,0,5,false,false,false,true,true,true,25,3,false,0.06,0.0005,4982,2013,4,5,Monday,false,false,false,false,false,false,false
491052,Minimum and maximum value of z-index?,"I have a div in my HTML page. I am showing this div based on some condition, but the div is displaying behind the HTML element where I pointed the mouse cursor.
I have tried all values for z-index from 0 - 999999. Can anyone tell me why this is happening?
Is there any minimum or maximum value of Z-INDEX property of CSS?
.divClass {
position: absolute;
left: 25px;
top: 25px;
width: 320px;
height: 300px;
z-index: 1000;
}
<table cellspacing=""0"" cellpadding=""0"" width=""100%"">
<tr>
<td>
<asp:HyperLink ID=""lnkProgram"" runat=""server""></asp:HyperLink>
</td>
</tr>
<tr>
<td>
<div class=""divClass"">
Some Data
</div>
</td>
</tr>
</table>
I am showing and hiding the div with .divClass onclick via the <asp:hyperlink> using jQuery.
",https://stackoverflow.com/questions/491052/minimum-and-maximum-value-of-z-index,614,501342.0,14.0,,,2009-01-29 09:50:20,2024-09-04 18:57:23,2019-05-11 00:15:02,,,html;css;z-index,Sachin Gaur,13139,2572740,registered,true,,,CC BY-SA 4.0,2014-04-30 12:42:21,1299,947,4,0,0,3,false,false,false,true,true,true,37,6,true,0.028,0.0012,6505,2009,1,9,Thursday,false,false,false,false,false,false,false
4781077,HTML5 best practices; section/header/aside/article elements,"There is enough information about HTML5 on the web (and also on stackoverflow), but now I'm curious about the ""best practices"". Tags like section/headers/article are new, and everyone has different opinions about when/where you should use these tags. So what do you guys think of the following layout and code?
![]()
1 <!doctype html>
2 <head>
3 <title>Website</title>
4 </head>
5
6 <body>
7 <section>
8 <header>
9 <div id=""logo""></div>
10 <div id=""language""></div>
11 </header>
12
13 <nav>
14 <ul>
15 <li>menu 1</li>
16 <li>menu 2</li>
17 <li>menu 3</li>
18 <li>menu 4</li>
19 <li>menu 5</li>
20 </ul>
21 </nav>
22
23 <div id=""main"">
24 <div id=""main-left"">
25 <article>
26 <header><h1>This is a title</h1></header>
27
28 <p>Lorem ipsum dolor sit amet, consectetur
29 adipiscing elit. Quisque semper, leo eget</p>
30
31 <p>Lorem ipsum dolor sit amet, consectetur
32 adipiscing elit. Quisque semper, leo eget</p>
33
34 <p>Lorem ipsum dolor sit amet, consectetur
35 adipiscing elit. Quisque semper, leo eget</p>
36
37 <p>Lorem ipsum dolor sit amet, consectetur
38 adipiscing elit. Quisque semper, leo eget</p>
39 </article>
40 </div>
41
42 <div id=""main-right"">
43 <section id=""main-right-hot"">
44 <h2>Hot items</h2>
45 <ul>
46 <li>Lorem ipsum</li>
47 <li>dolor sit</li>
48 <li>...</li>
49 </ul>
50 </section>
51
52 <section id=""main-right-new"">
53 <h2>New items</h2>
54 <ul>
55 <li>Lorem ipsum</li>
56 <li>dolor sit</li>
57 <li>...</li>
58 </ul>
59 </section>
60 </div>
61 </div>
62
63 <div id=""news-items"">
64 <header><h2>The latest news</h2></header>
65
66 <div id=""item_1"">
67 <article>
68 <header>
69 <img src=""#"" title=""titel artikel"" />
70 <h3>Lorem ipsum .....</h3>
71 </header>
72 <p>Lorem ipsum dolor sit amet,
73 adipiscing elit. Quisque semper, </p>
74 <a href=""#"">Read more</a>
75 </article>
76 </div>
77
78
79 <div id=""item_2"">
80 <article>
81 <header>
82 <img src=""#"" title=""titel artikel"" />
83 <h3>Lorem ipsum .....</h3>
84 </header>
85 <p>Lorem ipsum dolor sit amet,
86 adipiscing elit. Quisque semper, </p>
87 <a href=""#"">Read more</a>
88 </article>
89 </div>
90
91
92 <div id=""item_3"">
93 <article>
94 <header>
95 <img src=""#"" title=""titel artikel"" />
96 <h3>Lorem ipsum .....</h3>
97 </header>
98 <p>Lorem ipsum dolor sit amet,
99 adipiscing elit. Quisque semper, </p>
100 <a href=""#"">Read more</a>
101 </article>
102 </div>
103 </div>
104
105 <footer>
106 <ul>
107 <li>menu 1</li>
108 <li>menu 2</li>
109 <li>menu 3</li>
110 <li>menu 4</li>
111 <li>menu 5</li>
112 </ul>
113 </footer>
114 </section>
115 </body>
116 </html>
line 7. section around the whole website? Or only a div?
line 8. Each section start with a header?
line 23. Is this div right? or must this be a section?
line 24. Split left/right column with a div.
line 25. Right place for the article tag?
line 26. Is it required to put your h1-tag in the header-tag?
line 43. The content is not related to the main article, so I decided this is a section and not a aside.
line 44. H2 without header
line 53. section without header
line 63. Div with all (non-related) news items
line 64. header with h2
line 65. Hmm, div or section? Or remove this div and only use the article-tag
line 105. Footer :-)
",https://stackoverflow.com/questions/4781077/html5-best-practices-section-header-aside-article-elements,612,502057.0,16.0,,,2011-01-24 10:48:00,2022-03-09 23:18:44,2017-01-25 00:16:24,2021-10-30 00:52:26,Opinion-based,html;header;article,Bas van Dorst,6640,263621,registered,true,,,,2013-08-26 20:14:36,6651,6159,21,0,1,3,false,true,false,true,true,true,59,5,false,0.032,0.0012,5780,2011,1,10,Monday,false,false,false,false,false,false,false
1608548,How to trigger a phone call when clicking a link in a web page on mobile phone,"I need to build a web page for mobile devices. There's only one thing I still haven't figured out: how can I trigger a phone call through the click of text?
Is there a special URL I could enter like the mailto: tag for emails?
Device specific solution are not preferred.
I know iPhone automatically recognizes phone numbers and creates a link for this, but it would be great if this could be done for images too... and also for most mobile devices.
",https://stackoverflow.com/questions/1608548/how-to-trigger-a-phone-call-when-clicking-a-link-in-a-web-page-on-mobile-phone,608,1258430.0,7.0,,,2009-10-22 16:52:44,2022-07-12 18:33:26,2016-07-06 20:47:22,,,html;phone-call;mobile-phones;url-protocol,Frederic Morin,9125,4064,registered,true,1610066,,CC BY-SA 3.0,2014-04-02 07:36:11,493,452,1,0,0,4,true,false,false,true,true,true,78,17,false,0.006,0.0005,6239,2009,10,16,Thursday,false,false,false,false,false,false,false
6262472,Multiple lines of input in <input type="text" />,"I have this text input in a form:
<input type=""text""
cols=""40""
rows=""5""
style=""width:200px; height:50px;""
name=""Text1""
id=""Text1""
value="""" />
I am trying to get it to take multiple lines of input. The width and height make the box to be bigger, but the user can enter text all (s)he wants yet it fills one line only.
How do I make the input more like a textarea?
",https://stackoverflow.com/questions/6262472/multiple-lines-of-input-in-input-type-text,607,1805194.0,10.0,,,2011-06-07 08:23:54,2023-07-28 02:06:22,2014-05-01 13:15:27,,,html,Beginner,29811,569654,registered,true,6262536,,CC BY-SA 3.0,2016-12-07 08:17:02,466,421,1,0,0,1,true,false,false,true,true,true,64,8,false,0.006,0.0003,5646,2011,6,8,Tuesday,false,false,false,false,false,false,false
17147821,how to make a whole row in a table clickable as a link?,"I'm using Bootstrap and the following doesn't work:
<tbody>
<a href=""#"">
<tr>
<td>Blah Blah</td>
<td>1234567</td>
<td>£158,000</td>
</tr>
</a>
</tbody>
",https://stackoverflow.com/questions/17147821/how-to-make-a-whole-row-in-a-table-clickable-as-a-link,606,962206.0,33.0,,,2013-06-17 12:46:29,2026-07-10 09:11:02,2018-05-02 13:10:39,,,html;html-table;bootstrap-4,user1038814,9739,1038814,registered,true,17147973,,CC BY-SA 4.0,2016-01-25 22:56:17,317,286,1,0,0,3,true,false,false,true,true,true,55,13,true,0.034,0.0006,4905,2013,6,12,Monday,false,false,false,false,false,false,false
37745051,Fill the remaining height or width in a flex container,"I have 2 divs side-by-side in a flexbox. The right hand one should always be the same width, and I want the left hand one to just grab the remaining space. But it won't unless I specifically set its width.
So at the moment, it's set to 96% which looks OK until you really squash the screen - then the right hand div gets a bit starved of the space it needs.
I guess I could leave it as it is but it feels wrong - like there has to be a way to say:
the right one is always the same; you on the left - you get everything that's left
.ar-course-nav {
cursor: pointer;
padding: 8px 12px 8px 12px;
border-radius: 8px;
}
.ar-course-nav:hover {
background-color: rgba(0, 0, 0, 0.1);
}
<br/>
<br/>
<div class=""ar-course-nav"" style=""display:flex; justify-content:space-between;"">
<div style=""width:96%;"">
<div style=""overflow:hidden; white-space:nowrap; text-overflow:ellipsis;"">
<strong title=""Course Name Which is Really Quite Long And Does Go On a Bit But Then When You Think it's Stopped it Keeps on Going for even longer!"">
Course Name Which is Really Quite Long And Does Go On a Bit But Then When You Think it's Stopped it Keeps on Going for even longer!
</strong>
</div>
<div style=""width:100%; display:flex; justify-content:space-between;"">
<div style=""color:#555555; margin-right:8px; overflow:hidden; white-space:nowrap; text-overflow:ellipsis;"" title=""A really really really really really really really really really really really long department name"">
A really really really really really really really really really really really long department name
</div>
<div style=""color:#555555; text-align:right; white-space:nowrap;"">
Created: 21 September 2016
</div>
</div>
</div>
<div style=""margin-left:8px;"">
<strong>></strong>
</div>
</div>
",https://stackoverflow.com/questions/37745051/fill-the-remaining-height-or-width-in-a-flex-container,604,893527.0,4.0,,,2016-06-10 09:46:11,2024-08-06 10:20:17,2021-03-27 17:33:59,,,html;css;flexbox,Adam Benson,8862,5686593,registered,true,37751019,,CC BY-SA 4.0,,2386,2026,2,0,0,3,true,false,false,true,true,true,54,10,false,0.004,0.0007,3816,2016,6,9,Friday,false,false,false,false,false,false,false
16152073,Prevent Bootstrap Modal from disappearing when clicking outside or pressing escape?,"I'm using the Twitter Bootstrap modal as a wizard window, and would like to prevent the user from closing it when clicking outside of the modal or when pressing escape. Instead, I want it to be closed when the user presses the finish button. How could I achieve this scenario?
",https://stackoverflow.com/questions/16152073/prevent-bootstrap-modal-from-disappearing-when-clicking-outside-or-pressing-esca,601,830728.0,16.0,,,2013-04-22 16:29:58,2025-10-09 15:51:55,2014-02-06 20:07:50,2019-04-27 20:30:04,Duplicate,html;twitter-bootstrap;modal-dialog,Ehsan Zargar Ershadi,25043,404339,registered,true,16155852,,,,284,277,0,0,0,3,true,true,false,true,true,true,83,11,true,0.019,0.0007,4961,2013,4,16,Monday,false,false,false,false,false,false,false
5797014,Why do browsers match CSS selectors from right to left?,"CSS Selectors are matched by browser engines from right to left. So they first find the children and then check their parents to see if they match the rest of the parts of the rule.
- Why is this?
- Is it just because the spec says?
- Does it affect the eventual layout if it was evaluated from left to right?
To me the simplest way to do it would be use the selectors with the least number of elements. So IDs first (as they should only return 1 element). Then maybe classes or an element that has the fewest number of nodes — e.g. there may only be one span on the page so go directly to that node with any rule that references a span.
Here are some links backing up my claims
- http://code.google.com/speed/page-speed/docs/rendering.html
- https://developer.mozilla.org/en/Writing_Efficient_CSS
It sounds like that it is done this way to avoid having to look at all the children of parent (which could be many) rather than all the parents of a child which must be one. Even if the DOM is deep it would only look at one node per level rather than multiple in the RTL matching. Is it easier/faster to evaluate CSS selectors LTR or RTL?
",https://stackoverflow.com/questions/5797014/why-do-browsers-match-css-selectors-from-right-to-left,601,84749.0,3.0,,,2011-04-26 22:03:36,2019-10-17 20:19:51,2017-05-23 12:26:24,,,html;css;browser;css-selectors,tgandrews,12688,41709,registered,true,5813672,,CC BY-SA 3.0,2016-08-29 15:35:00,1522,1138,0,3,0,4,true,false,false,true,true,true,55,10,true,0.035,0.0071,5688,2011,4,22,Tuesday,false,false,false,false,false,false,false
306924,Can I change the checkbox size using CSS?,"Is it possible to set the size of a checkbox using CSS or HTML across browsers?
width and size work in IE6+, but not with Firefox, where the checkbox stays 16x16 even if I set a smaller size.
",https://stackoverflow.com/questions/306924/can-i-change-the-checkbox-size-using-css,600,876488.0,20.0,,,2008-11-20 21:34:14,2025-05-28 15:15:14,2019-05-30 13:30:19,,,html;css,RaGE,8307,39474,registered,true,,,CC BY-SA 4.0,2016-01-19 17:52:07,234,194,2,0,0,2,false,false,false,true,true,true,41,8,true,0.023,0.0007,6575,2008,11,21,Thursday,false,false,false,false,false,false,false
36247140,Why don't flex items shrink past content size?,"I have 4 flexbox columns and everything works fine, but when I add some text to a column and set it to a big font size, it is making the column wider than it should be due to the flex property.
I tried to use word-break: break-word and it helped, but still when I resize the column to a very small width, letters in the text are broken into multiple lines (one letter per line), and yet the column does not get smaller width than one letter size.
Watch this video
(at the start, the first column is the smallest, but when I resized the window, it is the widest column. I just want to respect flex settings always; flex sizes 1 : 3 : 4 : 4)
I know, setting font-size and column padding to smaller will help... but is there any other solution?
I can not use overflow-x: hidden.
.container {
display: flex;
width: 100%
}
.col {
min-height: 200px;
padding: 30px;
word-break: break-word
}
.col1 {
flex: 1;
background: orange;
font-size: 80px
}
.col2 {
flex: 3;
background: yellow
}
.col3 {
flex: 4;
background: skyblue
}
.col4 {
flex: 4;
background: red
}
<div class=""container"">
<div class=""col col1"">Lorem ipsum dolor</div>
<div class=""col col2"">Lorem ipsum dolor</div>
<div class=""col col3"">Lorem ipsum dolor</div>
<div class=""col col4"">Lorem ipsum dolor</div>
</div>
",https://stackoverflow.com/questions/36247140/why-dont-flex-items-shrink-past-content-size,600,209787.0,8.0,,,2016-03-27 12:08:53,2025-11-11 13:56:38,2019-02-26 12:28:23,,,html;css;flexbox,tomas657,6119,2443568,registered,true,36247448,,CC BY-SA 4.0,2021-11-16 19:15:40,1928,1419,4,2,0,3,true,false,false,true,true,true,50,8,true,0.038,0.0029,3891,2016,3,12,Sunday,true,false,false,false,false,false,false
107936,How to add some non-standard font to a website?,"Is there a way to add some custom font on a website without using images or other graphics?
For example, I was working on a wedding website, and I found a lot of nice fonts for that subject, but I can't find the right way to add that font on the server. And how do I include that font with CSS into the HTML?
",https://stackoverflow.com/questions/107936/how-to-add-some-non-standard-font-to-a-website,600,1072173.0,14.0,,,2008-09-20 11:26:52,2025-10-07 17:39:09,2025-10-07 17:39:09,,,html;css;fonts;font-face,vaske,9610,16039,registered,true,107951,,CC BY-SA 4.0,2011-06-29 14:54:36,323,309,0,0,0,4,true,false,false,true,true,true,47,9,true,0.013,0.0006,6636,2008,9,11,Saturday,true,false,false,false,false,false,false
985431,Max parallel HTTP connections in a browser?,"I am creating some suspended connections to an HTTP server (comet, reverse AJAX, etc). It works ok, but I see the browser only allows two suspended connections to a given domain simultaneously. So if a user is looking at my website in Tab1 of their browser, then also tries loading it in Tab2, they've used up the two allowed connections to my site.
I think I can do some wildcard domain thing, where I have my HTTP server resolve any address to my site like:
*.example.com/webapp -> 192.0.2.1 (the actual ip of my server)
so:
a.example.com/webapp
b.example.com/webapp
c.example.com/webapp
all still point to (www.example.com/webapp) but the browser considers them different domains, so I don't run into the 2 connection limit. Is this true?
Even if that is true - is there any limit to the number of active connections per browser, across all domains? Say I use the scheme above - does Firefox for example only allow 24 parallel connections at any given time? Something like:
1) a.example.com/webapp
2) www.download.example/hugefile.zip
3) b.example.com/webapp
4) c.example.com/webapp
...
24) x.example.com/webapp
25) // Error - all 24 possible connections currently in use!
I just picked 24 connections/Firefox as an example.
",https://stackoverflow.com/questions/985431/max-parallel-http-connections-in-a-browser,598,527130.0,11.0,,,2009-06-12 07:23:53,2026-11-16 19:36:07,2026-11-16 19:36:07,,,html;http;web-performance;persistent-connection,Mark,,,does_not_exist,true,,,CC BY-SA 4.0,,1371,1235,4,0,0,4,false,false,false,true,false,true,43,7,true,0.021,0.0011,6371,2009,6,7,Friday,false,false,false,false,false,false,false
5271782,How to disable the resize grabber of <textarea>?,"How to disable the grabber in the <textarea>?
I mean that triangle thing which appears in the right-bottom corner of the <textarea>.
",https://stackoverflow.com/questions/5271782/how-to-disable-the-resize-grabber-of-textarea,596,609628.0,3.0,,,2011-03-11 10:33:20,2019-06-24 20:27:06,2019-06-24 20:16:37,2014-09-04 08:05:23,Duplicate,html;css;forms,Jack Billy,7211,637378,registered,true,5271803,,,2014-06-24 09:43:37,186,146,2,0,0,3,true,true,false,true,true,true,54,8,true,0.005,0.001,5734,2011,3,10,Friday,false,false,false,false,false,false,false
6982692,How to set input type date's default value to today?,"Given an input element:
<input type="date" />
Is there any way to set the default value of the date field to today's date?
",https://stackoverflow.com/questions/6982692/how-to-set-input-type-dates-default-value-to-today,594,1515885.0,46.0,,,2011-08-08 13:14:13,2024-10-23 11:31:20,2021-05-16 05:47:47,,,html;date;input,Ian Brown,5941,884138,registered,true,,,CC BY-SA 4.0,2018-04-17 11:31:06,217,140,1,0,0,3,false,false,false,true,true,true,56,10,true,0.03,0.0004,5584,2011,8,13,Monday,false,false,false,false,false,false,false
92720,jQuery/JavaScript to replace broken images,"I have a web page that includes a bunch of images. Sometimes the image isn't available, so a broken image is displayed in the client's browser.
How do I use jQuery to get the set of images, filter it to broken images then replace the src?
--I thought it would be easier to do this with jQuery, but it turned out much easier to just use a pure JavaScript solution, that is, the one provided by Prestaul.
",https://stackoverflow.com/questions/92720/jquery-javascript-to-replace-broken-images,594,333315.0,32.0,,,2008-09-18 13:53:32,2021-10-01 04:49:44,2016-05-15 19:54:30,,,javascript;jquery;html;broken-image,Dan Lord,6211,17702,registered,true,92819,,CC BY-SA 3.0,2016-11-28 03:21:26,433,407,0,0,0,4,true,false,false,true,true,true,42,5,false,0.096,0.0018,6638,2008,9,13,Thursday,false,false,true,false,false,false,false
9293423,Can one AngularJS controller call another?,"Is it possible to have one controller use another?
For example:
This HTML document simply prints a message delivered by the MessageCtrl controller in the messageCtrl.js file.
<html xmlns:ng=""http://angularjs.org/"">
<head>
<meta charset=""utf-8"" />
<title>Inter Controller Communication</title>
</head>
<body>
<div ng:controller=""MessageCtrl"">
<p>{{message}}</p>
</div>
<!-- Angular Scripts -->
<script src=""http://code.angularjs.org/angular-0.9.19.js"" ng:autobind></script>
<script src=""js/messageCtrl.js"" type=""text/javascript""></script>
</body>
</html>
The controller file contains the following code:
function MessageCtrl()
{
this.message = function() {
return ""The current date is: "" + new Date().toString();
};
}
Which simply prints the current date;
If I were to add another controller, DateCtrl which handed the date in a specific format back to MessageCtrl, how would one go about doing this? The DI framework seems to be concerned with XmlHttpRequests and accessing services.
",https://stackoverflow.com/questions/9293423/can-one-angularjs-controller-call-another,594,400889.0,14.0,,,2012-02-15 12:31:20,2020-06-25 09:24:31,2018-06-20 21:19:56,,,javascript;html;angularjs,BanksySan,28806,442351,registered,true,9407953,,CC BY-SA 4.0,,1312,1157,7,0,0,3,true,false,false,true,true,true,42,6,true,0.035,0.0015,5393,2012,2,12,Wednesday,false,false,true,false,false,false,false
9184141,How do you get centered content using Twitter Bootstrap?,"I'm trying to follow a very basic example. Using the starter page and the grid system, I was hoping the following:
<div class=""row"">
<div class=""span12"">
<h1>Bootstrap starter template</h1>
<p>Example text.</p>
</div>
</div>
...would produce centered text.
However, it still appears on the far left. What am I doing wrong?
",https://stackoverflow.com/questions/9184141/how-do-you-get-centered-content-using-twitter-bootstrap,589,958108.0,24.0,,,2012-02-07 21:21:55,2022-07-24 15:57:32,2017-10-28 10:09:54,,,html;css;twitter-bootstrap,Hoa,20568,1011816,registered,true,9184443,,CC BY-SA 3.0,2014-04-20 18:37:35,708,402,1,1,0,3,true,false,false,true,true,true,56,9,true,0.025,0.0006,5401,2012,2,21,Tuesday,false,false,false,false,false,false,false
7470268,HTML input - name vs. id,"When using the HTML <input> tag, what is the difference between the use of the name and id attributes especially that I found that they are sometimes named the same?
",https://stackoverflow.com/questions/7470268/html-input-name-vs-id,588,456270.0,13.0,,,2011-09-19 11:33:35,2021-08-19 14:37:44,2018-02-20 11:43:10,2019-10-18 07:21:13,Duplicate,html;html-input,Simplicity,49466,588855,registered,true,,,,2015-07-30 09:04:16,218,172,3,0,0,2,false,true,false,true,true,true,24,6,false,0.028,0.0013,5542,2011,9,11,Monday,false,false,false,false,false,false,false
3084261,Alternate table row color using CSS?,"I am using a table with alternate row color with this.
tr.d0 td {
background-color: #CC9999;
color: black;
}
tr.d1 td {
background-color: #9999CC;
color: black;
}
<table>
<tr class=""d0"">
<td>One</td>
<td>one</td>
</tr>
<tr class=""d1"">
<td>Two</td>
<td>two</td>
</tr>
</table>
Here I am using class for tr, but I want to use only for table. When I use class for table than this apply on tr alternative.
Can I write my HTML like this using CSS?
<table class=""alternate_color"">
<tr><td>One</td><td>one</td></tr>
<tr><td>Two</td><td>two</td></tr>
</table>
How can I make the rows have ""zebra stripes"" using CSS?
",https://stackoverflow.com/questions/3084261/alternate-table-row-color-using-css,584,932097.0,11.0,,,2010-06-21 11:34:45,2026-08-11 07:32:33,2016-06-07 20:30:37,,,html;css;html-table,Kali Charan Rajput,12776,254806,registered,true,3084318,,CC BY-SA 3.0,2014-10-24 12:38:29,1243,853,6,0,0,3,true,false,false,true,true,true,36,6,true,0.012,0.0006,5997,2010,6,11,Monday,false,false,false,false,false,false,false
5324415,Select elements by attribute in CSS,"Is it possible to select elements in CSS by their HTML5 data attributes (for example, data-role)?
",https://stackoverflow.com/questions/5324415/select-elements-by-attribute-in-css,584,489659.0,7.0,,,2011-03-16 11:07:58,2023-12-03 11:32:18,2020-08-07 19:30:24,,,css;html;css-selectors;custom-data-attribute,Diogo Cardoso,22403,574419,registered,true,5324433,,CC BY-SA 4.0,2022-08-16 13:45:14,118,98,1,0,0,4,true,false,false,true,true,true,35,6,false,0.014,0.0012,5729,2011,3,11,Wednesday,false,false,false,false,false,false,false
1207190,Embedding Base64 Images,"Purely out of curiosity, which browsers does Base64 image embedding work in? What I'm referring to is this.
I realize it's not usually a good solution for most things, as it increases the page size quite a bit - I'm just curious.
Some examples:
HTML:
<img alt=""Embedded Image"" src=""data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA..."" />
CSS:
div.image {
width:100px;
height:100px;
background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA...);
}
",https://stackoverflow.com/questions/1207190/embedding-base64-images,582,696404.0,3.0,,,2009-07-30 15:01:01,2019-12-02 17:19:57,2019-12-02 17:19:57,,,html;base64;browser,S Pangborn,12779,38751,registered,true,1207373,,CC BY-SA 4.0,2014-05-26 16:26:20,678,483,2,1,0,3,true,false,false,true,true,true,23,3,false,0.004,0.0008,6323,2009,7,15,Thursday,false,false,false,false,false,false,false
22581345,Click button copy to clipboard,"How do I copy the text inside a div to the clipboard? I have a div and need to add a link which will add the text to the clipboard. Is there a solution for this?
<p class=""content"">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s</p>
<a class=""copy-text"">copy Text</a>
After I click copy text, then I press Ctrl + V, it must be pasted.
",https://stackoverflow.com/questions/22581345/click-button-copy-to-clipboard,578,1137084.0,33.0,,,2014-03-22 17:53:46,2024-02-13 16:56:46,2021-11-10 08:54:39,,,jquery;html;css,Dishan TD,8838,1215731,registered,true,22581382,,CC BY-SA 4.0,2016-01-17 07:23:32,528,468,1,0,0,3,true,false,false,true,true,true,30,5,false,0.029,0.0005,4627,2014,3,17,Saturday,true,false,false,false,false,false,false
13367868,How to modify the fill color of an SVG image when being served as background image?,"Placing the SVG output directly inline with the page code I am able to simply modify fill colors with CSS like so:
polygon.mystar {
fill: blue;
}
circle.mycircle {
fill: green;
}
This works great, however I'm looking for a way to modify the ""fill"" attribute of an SVG when it's being served as a BACKGROUND-IMAGE.
html {
background-image: url(../img/bg.svg);
}
How can I change the colors now? Is it even possible?
For reference, here are the contents of my external SVG file:
<svg version=""1.1"" id=""Layer_1"" xmlns=""http://www.w3.org/2000/svg"" xmlns:xlink=""http://www.w3.org/1999/xlink"" x=""0px"" y=""0px""
width=""320px"" height=""100px"" viewBox=""0 0 320 100"" enable-background=""new 0 0 320 100"" xml:space=""preserve"">
<polygon class=""mystar"" fill=""#3CB54A"" points=""134.973,14.204 143.295,31.066 161.903,33.77 148.438,46.896 151.617,65.43 134.973,56.679
118.329,65.43 121.507,46.896 108.042,33.77 126.65,31.066 ""/>
<circle class=""mycircle"" fill=""#ED1F24"" cx=""202.028"" cy=""58.342"" r=""12.26""/>
</svg>
",https://stackoverflow.com/questions/13367868/how-to-modify-the-fill-color-of-an-svg-image-when-being-served-as-background-ima,578,815295.0,28.0,,,2012-11-13 20:02:43,2026-01-05 17:18:44,2021-07-25 16:17:41,,,html;css;svg,Joe,6723,594646,registered,true,27827090,,CC BY-SA 4.0,2026-01-06 01:36:20,1272,1058,3,0,0,3,true,false,false,true,true,true,83,16,true,0.034,0.0007,5121,2012,11,20,Tuesday,false,false,false,false,false,false,false
8454510,Open URL in same window and in same tab,"I want to open a link in the same window and in the same tab that contains the page with the link.
When I try to open a link by using window.open, then it opens in new tab—not in the same tab in the same window.
",https://stackoverflow.com/questions/8454510/open-url-in-same-window-and-in-same-tab,577,1474668.0,16.0,,,2011-12-10 05:00:15,2024-01-27 21:48:06,2011-12-10 05:15:58,,,javascript;html;hyperlink;href,user1065055,5851,1065055,registered,true,,,CC BY-SA 3.0,2018-10-04 15:00:14,240,213,1,0,0,4,false,false,false,true,true,true,39,9,false,0.011,0.0004,5460,2011,12,5,Saturday,true,false,true,false,false,false,false
379610,Can you nest HTML forms?,"Is it possible to nest HTML forms like this
<form name="mainForm">
<form name="subForm">
</form>
</form>
so that both forms work? My friend is having problems with this, a part of the subForm works, while another part of it does not.
",https://stackoverflow.com/questions/379610/can-you-nest-html-forms,576,369265.0,20.0,,,2008-12-18 22:54:57,2025-05-29 11:24:49,2023-08-02 19:37:25,,,html,Levi,12532,27620,registered,true,379622,,CC BY-SA 4.0,2023-03-21 08:30:09,334,283,2,0,0,1,true,false,false,true,true,true,24,5,true,0.054,0.0016,6547,2008,12,22,Thursday,false,false,false,false,false,false,false
10040842,Add border-bottom to table row <tr>,"I have a table of 3 by 3. I need a way to add a border for the bottom of every row tr and give it a specific color.
First I tried the direct way, i.e.:
<tr style=""border-bottom:1pt solid black;"">
But that didn't work. So I added CSS like this:
tr {
border-bottom: 1pt solid black;
}
That still didn't work.
I would prefer to use CSS because then I don't need to add a style attribute to every row.
I haven't added a border attribute to the <table>. I hope that that is not affecting my CSS.
",https://stackoverflow.com/questions/10040842/add-border-bottom-to-table-row-tr,575,1167809.0,18.0,,,2012-04-06 08:09:47,2023-07-22 18:15:28,2019-01-01 22:50:48,,,html;css;html-table,Sangram Nandkhile,18250,443244,registered,true,10040976,,CC BY-SA 4.0,2019-08-31 12:05:51,684,511,6,0,0,3,true,false,false,true,true,true,41,6,false,0.015,0.0005,5342,2012,4,8,Friday,false,false,false,false,false,false,false
25066214,Flexbox not giving equal width to elements,"Attempting a flexbox nav that has up to 5 items and as little as 3, but it's not dividing the width equally between all the elements.
Fiddle
The tutorial I'm modeling this after is http://www.sitepoint.com/responsive-fluid-width-variable-item-navigation-css/
* {
font-size: 16px;
}
.tabs {
max-width: 1010px;
width: 100%;
height: 5rem;
border-bottom: solid 1px grey;
margin: 0 0 0 6.5rem;
display: table;
table-layout: fixed;
}
.tabs ul {
margin: 0;
display: flex;
flex-direction: row;
}
.tabs ul li {
flex-grow: 1;
list-style: none;
text-align: center;
font-size: 1.313rem;
background: blue;
color: white;
height: inherit;
left: auto;
vertical-align: top;
text-align: left;
padding: 20px 20px 20px 70px;
border-top-left-radius: 20px;
border: solid 1px blue;
cursor: pointer;
}
.tabs ul li.active {
background: white;
color: blue;
}
.tabs ul li:before {
content: """";
}
<div class=""tabs"">
<ul>
<li class=""active"" data-tab=""1"">Pizza</li>
<li data-tab=""2"">Chicken Noodle Soup</li>
<li data-tab=""3"">Peanut Butter</li>
<li data-tab=""4"">Fish</li>
</ul>
</div>
",https://stackoverflow.com/questions/25066214/flexbox-not-giving-equal-width-to-elements,575,572906.0,6.0,,,2014-07-31 18:19:59,2023-10-03 22:53:24,2023-04-14 22:09:22,,,html;css;flexbox,itsclarke,9042,2138024,registered,true,25066844,,CC BY-SA 4.0,,1704,1214,2,2,0,3,true,false,false,true,true,true,42,7,false,0.01,0.001,4496,2014,7,18,Thursday,false,false,false,false,false,false,false
6974684,How to send FormData objects with Ajax-requests in jQuery?,"The XMLHttpRequest Level 2 standard (still a working draft) defines the FormData interface. This interface enables appending File objects to XHR-requests (Ajax-requests).
Btw, this is a new feature - in the past, the ""hidden-iframe-trick"" was used (read about that in my other question).
This is how it works (example):
var xhr = new XMLHttpRequest(),
fd = new FormData();
fd.append( 'file', input.files[0] );
xhr.open( 'POST', 'http://example.com/script.php', true );
xhr.onreadystatechange = handler;
xhr.send( fd );
where input is a <input type=""file""> field, and handler is the success-handler for the Ajax-request.
This works beautifully in all browsers (again, except IE).
Now, I would like to make this functionality work with jQuery. I tried this:
var fd = new FormData();
fd.append( 'file', input.files[0] );
$.post( 'http://example.com/script.php', fd, handler );
Unfortunately, that won't work (an ""Illegal invocation"" error is thrown - screenshot is here). I assume jQuery expects a simple key-value object representing form-field-names / values, and the FormData instance that I'm passing in is apparently incompatible.
Now, since it is possible to pass a FormData instance into xhr.send(), I hope that it is also possible to make it work with jQuery.
Update:
I've created a ""feature ticket"" over at jQuery's Bug Tracker. It's here: http://bugs.jquery.com/ticket/9995
I was suggested to use an ""Ajax prefilter""...
Update:
First, let me give a demo demonstrating what behavior I would like to achieve.
HTML:
<form>
<input type=""file"" id=""file"" name=""file"">
<input type=""submit"">
</form>
JavaScript:
$( 'form' ).submit(function ( e ) {
var data, xhr;
data = new FormData();
data.append( 'file', $( '#file' )[0].files[0] );
xhr = new XMLHttpRequest();
xhr.open( 'POST', 'http://hacheck.tel.fer.hr/xml.pl', true );
xhr.onreadystatechange = function ( response ) {};
xhr.send( data );
e.preventDefault();
});
The above code results in this HTTP-request:
![]()
This is what I need - I want that ""multipart/form-data"" content-type!
The proposed solution would be like so:
$( 'form' ).submit(function ( e ) {
var data;
data = new FormData();
data.append( 'file', $( '#file' )[0].files[0] );
$.ajax({
url: 'http://hacheck.tel.fer.hr/xml.pl',
data: data,
processData: false,
type: 'POST',
success: function ( data ) {
alert( data );
}
});
e.preventDefault();
});
However, this results in:
![]()
As you can see, the content type is wrong...
",https://stackoverflow.com/questions/6974684/how-to-send-formdata-objects-with-ajax-requests-in-jquery,575,1133496.0,8.0,,,2011-08-07 18:06:39,2020-04-18 12:32:23,2017-05-23 12:34:44,2016-05-11 10:32:41,Duplicate,javascript;jquery;ajax;html;multipartform-data,Šime Vidas,186742,425275,registered,true,8244082,,,,3546,2642,13,4,2,5,true,true,false,true,true,true,58,9,true,0.007,0.0005,5585,2011,8,18,Sunday,true,false,true,false,false,false,false
7055393,Center image using text-align center?,"Is the property text-align: center; a good way to center an image using CSS?
img {
text-align: center;
}
",https://stackoverflow.com/questions/7055393/center-image-using-text-align-center,573,1422282.0,28.0,,,2011-08-14 06:21:52,2022-11-23 09:42:32,2013-08-15 01:44:50,,,html;css,Web_Designer,75143,552067,registered,true,7055404,,CC BY-SA 3.0,2014-03-01 20:05:50,155,111,2,0,0,2,true,false,false,true,true,true,37,5,true,0.02,0.0004,5578,2011,8,6,Sunday,true,false,false,false,false,false,false
8446218,"How to see an HTML page on Github as a normal rendered HTML page to see preview in browser, without downloading?","On http://github.com developer keep the HTML, CSS, JavaScript and images files of the project. How can I see the HTML output in browser?
For example this: https://github.com/necolas/css3-social-signin-buttons/blob/master/index.html
When I open this it doesn't show the rendered HTML of the code of author. It shows the page as a source code.
Is it possible to see it as rendered HTML directly? Otherwise I always need to download the whole ZIP just to see the result.
",https://stackoverflow.com/questions/8446218/how-to-see-an-html-page-on-github-as-a-normal-rendered-html-page-to-see-preview,573,517601.0,13.0,,,2011-12-09 13:34:02,2026-10-26 07:50:39,2019-12-16 12:38:22,,,html;css;git;github;github-pages,Jitendra Vyas,154325,84201,registered,true,12233684,,CC BY-SA 4.0,2019-05-28 11:34:56,656,471,0,2,0,5,true,false,false,true,true,true,112,21,true,0.025,0.0011,5461,2011,12,13,Friday,false,false,false,false,false,false,false
21064101,"Understanding offsetWidth, clientWidth, scrollWidth and -Height, respectively","There are several questions on StackOverflow regarding offsetWidth / clientWidth / scrollWidth (and -Height, respectively), but none give comprehensive explanation of what those values are.
Also, there are several sources on the web giving confusing or incorrect information.
Can you give a complete explanation including some visual hints?
Also, how can those values be used to calculate scroll bar widths?
",https://stackoverflow.com/questions/21064101/understanding-offsetwidth-clientwidth-scrollwidth-and-height-respectively,572,285113.0,7.0,,,2014-01-11 15:26:57,2025-01-14 17:16:52,2020-06-25 22:20:14,,,html;css;dom,user123444555621,154660,27862,registered,true,21064102,,CC BY-SA 4.0,,481,408,4,0,0,3,true,false,false,true,true,true,77,7,false,0.025,0.002,4697,2014,1,15,Saturday,true,false,false,false,false,false,false
19461521,How to center an element horizontally and vertically,"I am trying to center my tabs content vertically, but when I add the CSS style display:inline-flex, the horizontal text-align disappears.
How can I make both text alignments x and y for each of my tabs?
* { box-sizing: border-box; }
#leftFrame {
background-color: green;
position: absolute;
left: 0;
right: 60%;
top: 0;
bottom: 0;
}
#leftFrame #tabs {
background-color: red;
position: absolute;
top: 0;
left: 0;
right: 0;
height: 25%;
}
#leftFrame #tabs div {
border: 2px solid black;
position: static;
float: left;
width: 50%;
height: 100%;
text-align: center;
display: inline-flex;
align-items: center;
}
<div id=leftFrame>
<div id=tabs>
<div>first</div>
<div>second</div>
</div>
</div>
",https://stackoverflow.com/questions/19461521/how-to-center-an-element-horizontally-and-vertically,572,563440.0,30.0,,,2013-10-19 02:01:24,2025-04-08 12:14:49,2022-04-11 22:06:02,,,html;css;layout;alignment;centering,shuji,7577,1417926,registered,true,19461564,,CC BY-SA 4.0,2019-05-29 13:50:41,1158,833,3,0,0,5,true,false,false,true,true,true,52,8,false,0.053,0.001,4781,2013,10,2,Saturday,true,false,false,false,false,false,false
3058866,How to force a line break in a long word in a DIV?,"Okay, this is really confusing me. I have some content inside of a div like so:
<div style=""background-color: green; width: 200px; height: 300px;"">
Thisisatest.Thisisatest.Thisisatest.Thisisatest.Thisisatest.Thisisatest.
</div>
However, the content overflows the DIV (as expected) because the 'word' is too long.
How can I force the browser to 'break' the word where necessary to fit all of the content inside?
",https://stackoverflow.com/questions/3058866/how-to-force-a-line-break-in-a-long-word-in-a-div,568,677333.0,19.0,,,2010-06-17 04:26:59,2024-06-11 17:59:20,2019-10-29 13:52:50,,,html;css;line-breaks,Nathan Osman,73789,193619,registered,true,3059128,,CC BY-SA 4.0,2017-04-05 11:24:11,474,429,1,0,0,3,true,false,false,true,true,true,50,13,true,0.028,0.0008,6001,2010,6,4,Thursday,false,false,false,false,false,false,false
11799236,Should I use px or rem value units in my CSS?,"I am designing a new website and I want it to be compatible with as much browsers and browser settings as possible. I am trying to decide what unit of measurement I should use for the sizes of my fonts and elements, but am unable to find a conclusive answer.
My question is: should I use px or rem in my CSS?
- So far I know that using
px isn't compatible with users who adjust their base font size in their browser.
- I've disregarded
ems because they are more of a hassle to maintain, compared to rems, as they cascade.
- Some say that
rems are resolution independent and therefore more desirable. But others say that most modern browsers zoom all elements equally anyway, so using px is not a problem.
I'm asking this because there are a lot of different opinions as to what is the most desirable measure of distance in CSS, and I am not sure which is best.
",https://stackoverflow.com/questions/11799236/should-i-use-px-or-rem-value-units-in-my-css,567,364409.0,10.0,,,2012-08-03 15:59:25,2023-01-07 20:05:27,2021-10-04 13:57:34,2020-04-16 15:14:43,Opinion-based,html;css;distance;units-of-measurement,user1218247,,,does_not_exist,true,11803273,,,2015-11-20 02:59:19,1022,857,7,0,0,4,true,true,false,true,false,true,45,11,true,0.027,0.0016,5223,2012,8,15,Friday,false,false,false,false,false,false,false
1358810,How do I change the text of an element using JavaScript?,"If I have a span, say:
<span id="myspan"> hereismytext </span>
How do I use JavaScript to change "hereismytext" to "newtext"?
",https://stackoverflow.com/questions/1358810/how-do-i-change-the-text-of-an-element-using-javascript,567,1059736.0,18.0,,,2009-08-31 18:40:19,2024-07-05 14:22:29,2023-06-20 13:12:01,,,javascript;html,user105033,19768,105033,registered,true,1358815,,CC BY-SA 4.0,,216,169,1,0,0,2,true,false,false,true,true,true,56,11,true,0.017,0.0005,6291,2009,8,18,Monday,false,false,true,false,false,false,false
15381105,What is the motivation behind the introduction of preflight CORS requests?,"Cross-origin resource sharing is a mechanism that allows a web page to make XMLHttpRequests to another domain (from Wikipedia).
I've been fiddling with CORS for the last couple of days and I think I have a pretty good understanding of how everything works.
So my question is not about how CORS / preflight work, it's about the reason behind coming up with preflights as a new request type. I fail to see any reason why server A needs to send a preflight (PR) to server B just to find out if the real request (RR) will be accepted or not - it would certainly be possible for B to accept/reject RR without any prior PR.
After searching quite a bit I found this piece of information at www.w3.org (7.1.5):
To protect resources against cross-origin requests that could not originate from certain user agents before this specification existed, a
preflight request is made to ensure that the resource is aware of this
specification.
I find this is the hardest to understand sentence ever. My interpretation (should better call it 'best guess') is that it's about protecting server B against requests from server C that is not aware of the spec.
Can someone please explain a scenario / show a problem that PR + RR solves better than RR alone?
",https://stackoverflow.com/questions/15381105/what-is-the-motivation-behind-the-introduction-of-preflight-cors-requests,567,141137.0,9.0,,,2013-03-13 09:16:10,2026-07-11 11:09:17,2024-04-10 17:15:51,,,ajax;html;http;cors;preflight,Jan Groth,14846,512155,registered,true,16945321,,CC BY-SA 4.0,2017-04-13 18:19:27,1564,1238,0,3,0,5,true,false,false,true,true,true,74,11,true,0.064,0.004,5001,2013,3,9,Wednesday,false,false,false,false,false,false,false
2703601,"How to line-break from css, without using <br />?","How to achieve same output without <br>?
<p>hello <br> How are you </p>
output:
hello
How are you
",https://stackoverflow.com/questions/2703601/how-to-line-break-from-css-without-using-br,560,1617785.0,29.0,,,2010-04-24 07:22:37,2023-10-02 10:04:14,2022-05-13 01:03:49,,,html;css;line-breaks,Jitendra Vyas,154325,84201,registered,true,2703610,,CC BY-SA 4.0,,408,134,2,0,0,3,true,false,false,true,true,true,55,9,true,0.018,0.0003,6055,2010,4,7,Saturday,true,false,false,false,false,false,false
1043957,Clearing <input type='file' /> using jQuery,"Is it possible to clear an <input type='file' /> control value with jQuery? I've tried the following:
$('#control').attr({ value: '' });
But it's not working.
",https://stackoverflow.com/questions/1043957/clearing-input-type-file-using-jquery,560,477504.0,27.0,,,2009-06-25 13:32:15,2022-09-29 06:55:13,2017-09-26 14:14:34,,,javascript;jquery;html;file-io;forms,sagar,,,does_not_exist,true,,,CC BY-SA 3.0,2012-09-05 09:03:54,220,169,2,0,0,5,false,false,false,true,false,true,57,6,false,0.057,0.0012,6358,2009,6,13,Thursday,false,false,true,false,false,false,false
2997767,How do I keep two side-by-side div elements the same height?,"I have two div elements side by side. I'd like the height of them to be the same, and stay the same if one of them resizes. If one grows because text is placed into it, the other one should grow to match the height. I can't figure this one out though. Any ideas?
<div style=""overflow: hidden"">
<div style=""
border: 1px solid #cccccc;
float: left;
padding-bottom: 1000px;
margin-bottom: -1000px;
"">
Some content!<br />
Some content!<br />
Some content!<br />
Some content!<br />
Some content!<br />
</div>
<div style=""
border: 1px solid #cccccc;
float: left;
padding-bottom: 1000px;
margin-bottom: -1000px;
"">
Some content!
</div>
</div>
",https://stackoverflow.com/questions/2997767/how-do-i-keep-two-side-by-side-div-elements-the-same-height,560,932802.0,24.0,,,2010-06-08 13:39:54,2025-01-13 12:31:21,2022-07-09 00:26:04,,,html;css,NibblyPig,53430,174375,registered,true,20669539,,CC BY-SA 4.0,2014-12-19 13:54:20,1076,850,1,0,0,2,true,false,false,true,true,true,60,11,true,0.026,0.0006,6010,2010,6,13,Tuesday,false,false,false,false,false,false,false
398734,Colspan all columns,"How can I specify a td tag should span all columns (when the exact amount of columns in the table will be variable/difficult to determine when the HTML is being rendered)? w3schools mentions you can use colspan=""0"", but it doesn't say exactly what browsers support that value (IE 6 is in our list to support).
It appears that setting colspan to a value greater than the theoretical amount of columns you may have will work, but it will not work if you have table-layout set to fixed. Are there any disadvantages to using an automatic layout with a large number for colspan? Is there a more correct way of doing this?
",https://stackoverflow.com/questions/398734/colspan-all-columns,558,481139.0,17.0,,,2008-12-29 21:31:00,2024-04-12 12:23:56,2018-09-16 13:57:47,,,html;html-table;tablelayout,Bob,100451,45,registered,true,398778,,CC BY-SA 4.0,,791,619,6,1,0,3,true,false,false,true,true,true,19,3,false,0.035,0.0012,6536,2008,12,21,Monday,false,false,false,false,false,false,false
22039910,What is aria-label and how should I use it?,"A few hours ago I read about the aria-label attribute, which:
Defines a string value that labels the current element.
But in my opinion this is what the title attribute was supposed to do. I looked further in the Mozilla Developer Network to get some examples and explanations, but the only thing I found was
<button aria-label=""Close"" onclick=""myDialog.close()"">X</button>
Which does not provide me with any label (so I assume I misunderstood the idea). I tried it here in jsfiddle.
So my question is: why do I need aria-label and how should I use it?
",https://stackoverflow.com/questions/22039910/what-is-aria-label-and-how-should-i-use-it,557,534157.0,7.0,,,2014-02-26 11:25:59,2024-01-11 08:48:08,2019-08-06 04:03:03,,,html;accessibility,Salvador Dali,225001,1090562,registered,true,22040485,,CC BY-SA 4.0,2015-07-25 05:51:01,985,576,3,3,0,2,true,false,false,true,true,true,43,9,true,0.013,0.001,4651,2014,2,11,Wednesday,false,false,false,false,false,false,false
4964130,target="_blank" vs. target="_new","What's the difference between <a target=""_new""> and <a target=""_blank""> and which should I use if I just want to open a link in a new tab/window?
",https://stackoverflow.com/questions/4964130/target-blank-vs-target-new,556,638151.0,11.0,,,2011-02-10 23:54:23,2020-07-28 16:44:02,,,,html,grin,8281,182709,registered,true,4964223,,CC BY-SA 2.5,2016-08-01 22:10:43,191,158,2,0,0,1,true,false,false,true,true,false,53,3,false,0.017,0.0009,5763,2011,2,23,Thursday,false,false,false,false,false,false,false
6724515,What is the purpose of the HTML "no-js" class?,"I notice that in a lot of template engines, in the HTML5 Boilerplate, in various frameworks and in plain php sites there is the no-js class added onto the <HTML> tag.
Why is this done? Is there some sort of default browser behavior that reacts to this class? Why include it always? Does that not render the class itself obsolete, if there is no no-""no-js"" case and html can be addressed directly?
Here is an example from the HTML5 Boilerplate index.html:
<!--[if lt IE 7 ]> <html lang=""en"" class=""no-js ie6""> <![endif]-->
<!--[if IE 7 ]> <html lang=""en"" class=""no-js ie7""> <![endif]-->
<!--[if IE 8 ]> <html lang=""en"" class=""no-js ie8""> <![endif]-->
<!--[if IE 9 ]> <html lang=""en"" class=""no-js ie9""> <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--> <html lang=""en"" class=""no-js""> <!--<![endif]-->
As you can see, the <html> element will always have this class.
Can someone explain why this is done so often?
",https://stackoverflow.com/questions/6724515/what-is-the-purpose-of-the-html-no-js-class,555,274712.0,7.0,,,2011-07-17 14:35:30,2018-10-31 19:58:10,2013-08-10 10:07:07,,,javascript;html;modernizr;html5boilerplate,Swader,11617,504357,registered,true,6724530,,CC BY-SA 3.0,2015-09-23 15:22:30,1181,1030,4,1,0,4,true,false,false,true,true,true,56,9,true,0.025,0.002,5606,2011,7,14,Sunday,true,false,true,false,false,false,false
454202,Creating a textarea with auto-resize,"There was another thread about this, which I've tried. But there is one problem: the textarea doesn't shrink if you delete the content. I can't find any way to shrink it to the correct size - the clientHeight value comes back as the full size of the textarea, not its contents.
The code from that page is below:
function FitToContent(id, maxHeight)
{
var text = id && id.style ? id : document.getElementById(id);
if ( !text )
return;
var adjustedHeight = text.clientHeight;
if ( !maxHeight || maxHeight > adjustedHeight )
{
adjustedHeight = Math.max(text.scrollHeight, adjustedHeight);
if ( maxHeight )
adjustedHeight = Math.min(maxHeight, adjustedHeight);
if ( adjustedHeight > text.clientHeight )
text.style.height = adjustedHeight + ""px"";
}
}
window.onload = function() {
document.getElementById(""ta"").onkeyup = function() {
FitToContent( this, 500 )
};
}
",https://stackoverflow.com/questions/454202/creating-a-textarea-with-auto-resize,551,756015.0,56.0,,,2009-01-17 22:30:42,2026-03-07 02:40:14,2018-03-24 14:42:11,,,javascript;html;resize;height;textarea,DisgruntledGoat,73124,37947,registered,true,5346855,,CC BY-SA 3.0,2011-06-21 21:41:53,1104,952,4,1,0,5,true,false,false,true,true,true,36,5,false,0.074,0.0007,6517,2009,1,22,Saturday,true,false,true,false,false,false,false
7730695,What's the difference between disabled="disabled" and readonly="readonly" for HTML form input fields?,"I have read a bit on this, but I can't seem to find anything solid about how different browsers treat things.
",https://stackoverflow.com/questions/7730695/whats-the-difference-between-disabled-disabled-and-readonly-readonly-for-ht,551,324004.0,8.0,,,2011-10-11 18:28:42,2023-08-29 13:50:23,2018-12-11 14:42:57,,,html;cross-browser,Andy,8978,493807,registered,true,7730719,,CC BY-SA 4.0,2023-08-29 13:56:55,117,110,0,0,0,2,true,false,false,true,true,true,125,12,true,0.025,0.0017,5520,2011,10,18,Tuesday,false,false,false,false,false,false,false
7020659,Submit form using a button outside the <form> tag,"Say I have:
<form method=""get"" action=""something.php"">
<input type=""text"" name=""name"" />
</form>
<input type=""submit"" />
How do I go about submitting that form with that submit button outside of the form, I think in HTML5 theres an action attribute for the submit but I'm not sure if thats fully cross-browser and if it isn't is there anyway to do this?
",https://stackoverflow.com/questions/7020659/submit-form-using-a-button-outside-the-form-tag,550,564180.0,15.0,,,2011-08-11 03:55:02,2021-12-09 15:25:20,2017-09-19 14:59:06,,,html,daryl,15345,633424,registered,true,7020729,,CC BY-SA 3.0,,424,386,1,0,0,1,true,false,false,true,true,true,55,9,false,0.027,0.001,5581,2011,8,3,Thursday,false,false,false,false,false,false,false
35945001,Binding select element to object in Angular,"I'd like to bind a select element to a list of objects -- which is easy enough:
@Component({
selector: 'myApp',
template:
`<h1>My Application</h1>
<select [(ngModel)]="selectedValue">
<option *ngFor="#c of countries" value="c.id">{{c.name}}</option>
</select>`
})
export class AppComponent{
countries = [
{id: 1, name: "United States"},
{id: 2, name: "Australia"}
{id: 3, name: "Canada"},
{id: 4, name: "Brazil"},
{id: 5, name: "England"}
];
selectedValue = null;
}
In this case, it appears that selectedValue would be a number -- the id of the selected item.
However, I'd actually like to bind to the country object itself so that selectedValue is the object rather than just the id. I tried changing the value of the option like so:
<option *ngFor="#c of countries" value="c">{{c.name}}</option>
but this does not seem to work. It seems to place an object in my selectedValue -- but not the object that I'm expecting. You can see this in my Plunker example.
I also tried binding to the change event so that I could set the object myself based on the selected id; however, it appears that the change event fires before the bound ngModel is updated -- meaning I don't have access to the newly selected value at that point.
Is there a clean way to bind a select element to an object with Angular 2?
",https://stackoverflow.com/questions/35945001/binding-select-element-to-object-in-angular,549,736172.0,16.0,,,2016-03-11 16:15:53,2021-10-08 14:50:05,2021-08-17 02:42:08,,,html;angular,RHarris,11247,372296,registered,true,35945293,,CC BY-SA 4.0,2020-06-30 10:08:36,1780,1531,5,1,0,2,true,false,false,true,true,true,43,7,false,0.022,0.0007,3907,2016,3,16,Friday,false,false,false,false,false,false,false
7261619,jQuery Data vs Attr?,"What is the difference in usage between $.data and $.attr when using data-someAttribute?
My understanding is that $.data is stored within jQuery's $.cache, not the DOM. Therefore, if I want to use $.cache for data storage, I should use $.data. If I want to add HTML5 data-attributes, I should use $.attr(""data-attribute"", ""myCoolValue"").
",https://stackoverflow.com/questions/7261619/jquery-data-vs-attr,547,215211.0,3.0,,,2011-08-31 18:26:33,2019-03-28 09:25:41,2017-10-18 12:31:21,,,javascript;jquery;html;custom-data-attribute,John B,5495,918235,unregistered,true,,,CC BY-SA 3.0,2016-09-09 18:52:53,457,339,8,0,0,4,false,false,false,true,true,true,20,4,true,0.014,0.0025,5561,2011,8,18,Wednesday,false,false,true,false,false,false,false
34057595,Allow 2 decimal places in <input type="number">,"I have a <input type=""number""> and I want to restrict the input of the users to purely numbers or numbers with decimals up to 2 decimal places.
Basically, I am asking for a price input.
I wanted to avoid doing regex. Is there a way to do it?
<input type=""number"" required name=""price"" min=""0"" value=""0"" step=""any"">
",https://stackoverflow.com/questions/34057595/allow-2-decimal-places-in-input-type-number,546,1316013.0,18.0,,,2015-12-03 03:55:55,2023-07-21 13:07:52,2017-01-04 20:01:58,,,html;numbers,nubteens,6376,3433716,registered,true,34057860,,CC BY-SA 3.0,,389,331,2,0,0,2,true,false,false,true,true,true,63,7,false,0.014,0.0004,4006,2015,12,3,Thursday,false,false,false,false,false,false,false
5882716,HTML5 Canvas vs. SVG vs. div,"What is the best approach for creating elements on the fly and being able to move them around? For example, let's say I want to create a rectangle, circle and polygon and then select those objects and move them around.
I understand that HTML5 provides three elements that can make this possible: svg, canvas and div. For what I want to do, which one of those elements will provide the best performance?
To compare these approaches, I was thinking of creating three visually identical web pages that each have a header, footer, widget and text content in them. The widget in the first page would be created entirely with the canvas element, the second entirely with the svg element, and the third with the plain div element, HTML and CSS.
",https://stackoverflow.com/questions/5882716/html5-canvas-vs-svg-vs-div,546,173082.0,10.0,,,2011-05-04 11:36:18,2023-07-30 01:43:17,2016-09-17 10:19:55,,,javascript;html;svg;html5-canvas,Agustinus Verdy,7345,737888,registered,true,5883032,,CC BY-SA 3.0,2019-10-05 06:36:16,1130,740,3,3,0,4,true,false,false,true,true,true,28,6,false,0.058,0.0032,5680,2011,5,11,Wednesday,false,false,true,false,false,false,false
16529825,AngularJS ngClass conditional,"Is there any way to make an expression for something like ng-class to be a conditional?
For example, I have tried the following:
<span ng-class=""{test: 'obj.value1 == \'someothervalue\''}"">test</span>
The issue with this code is that no matter what obj.value1 is, the class test is always applied to the element. Doing this:
<span ng-class=""{test: obj.value2}"">test</span>
As long as obj.value2 does not equal a truthy value, the class in not applied. Now I can work around the issue in the first example by doing this:
<span ng-class=""{test: checkValue1()}"">test</span>
Where the checkValue1 function looks like this:
$scope.checkValue1 = function() {
return $scope.obj.value === 'somevalue';
}
I am just wondering if this is how ng-class is supposed to work. I am also building a custom directive where I would like to do something similar to this. However, I can't find a way to watch an expression (and maybe that is impossible and the reason why it works like this).
Here is a plnkr to show what I mean.
",https://stackoverflow.com/questions/16529825/angularjs-ngclass-conditional,543,995165.0,11.0,,,2013-05-13 19:38:38,2021-11-15 12:51:13,2019-03-29 19:18:17,,,html;css;angularjs,ryanzec,28246,384016,registered,true,16529903,,CC BY-SA 4.0,,1439,1063,9,2,0,3,true,false,false,true,true,true,29,3,false,0.011,0.0005,4940,2013,5,19,Monday,false,false,false,false,false,false,false
13630229,Can I have an onclick effect in CSS?,"I have an image element that I want to change on click.
<img id="btnLeft">
This works:
#btnLeft:hover {
width: 70px;
height: 74px;
}
But what I need is:
#btnLeft:onclick {
width: 70px;
height: 74px;
}
But, it doesn't work, obviously. Is it possible at all to have onclick behavior in CSS (i.e., without using JavaScript)?
",https://stackoverflow.com/questions/13630229/can-i-have-an-onclick-effect-in-css,542,1879570.0,15.0,,,2012-11-29 16:27:58,2026-11-06 10:11:45,2022-08-10 16:38:06,,,html;css;onclick,Alegro,8086,1491095,registered,true,13630259,,CC BY-SA 4.0,2013-07-23 06:19:18,546,357,4,0,0,3,true,false,false,true,true,true,36,8,true,0.008,0.0003,5105,2012,11,16,Thursday,false,false,false,false,false,false,false
4086107,Fixed page header overlaps in-page anchors,"If I have a non-scrolling header in an HTML page, fixed to the top, having a defined height:
Is there a way to use the URL anchor (the #fragment part) to have the browser scroll to a certain point in the page, but still respect the height of the fixed element without the help of JavaScript?
http://example.com/#bar
WRONG (but the common behavior): CORRECT:
+---------------------------------+ +---------------------------------+
| BAR///////////////////// header | | //////////////////////// header |
+---------------------------------+ +---------------------------------+
| Here is the rest of the Text | | BAR |
| ... | | |
| ... | | Here is the rest of the Text |
| ... | | ... |
+---------------------------------+ +---------------------------------+
",https://stackoverflow.com/questions/4086107/fixed-page-header-overlaps-in-page-anchors,540,274040.0,38.0,,,2010-11-03 10:31:11,2023-01-10 10:04:04,2021-02-16 16:23:47,,,html;url;anchor,Tomalak,339834,18771,registered,true,13117744,,CC BY-SA 4.0,2020-06-30 17:13:54,1103,985,2,0,0,3,true,false,false,true,true,true,42,6,false,0.139,0.002,5862,2010,11,10,Wednesday,false,false,false,false,false,false,false
6492683,How to detect DIV's dimension changed?,"I've the following sample html, there is a DIV which has 100% width. It contains some elements. While performing windows re-sizing, the inner elements may be re-positioned, and the dimension of the div may change. I'm asking if it is possible to hook the div's dimension change event? and How to do that? I currently bind the callback function to the jQuery resize event on the target DIV, however, no console log is outputted, see below:
![]()
<html>
<head>
<script type=""text/javascript"" language=""javascript"" src=""http://code.jquery.com/jquery-1.6.1.min.js""></script>
<script type=""text/javascript"" language=""javascript"">
$('#test_div').bind('resize', function(){
console.log('resized');
});
</script>
</head>
<body>
<div id=""test_div"" style=""width: 100%; min-height: 30px; border: 1px dashed pink;"">
<input type=""button"" value=""button 1"" />
<input type=""button"" value=""button 2"" />
<input type=""button"" value=""button 3"" />
</div>
</body>
</html>
",https://stackoverflow.com/questions/6492683/how-to-detect-divs-dimension-changed,539,650535.0,28.0,,,2011-06-27 12:13:50,2022-11-16 09:50:48,,,,javascript;jquery;html,William X,7041,440327,registered,true,19418065,,CC BY-SA 3.0,,1302,1123,1,0,2,3,true,false,false,true,true,false,42,6,true,0.043,0.0008,5626,2011,6,12,Monday,false,false,true,false,false,false,false
940451,"Using relative URL in CSS file, what location is it relative to?","When defining something like a background image URL in a CSS file, when using a relative URL, where is it relative to? For example:
Suppose the file /stylesheets/base-styles.css contains:
div#header {
background-image: url('images/header-background.jpg');
}
If I include this style-sheet into different documents via <link ... /> will the relative URL in the CSS file be relative to the stylesheet document in /stylesheets/ or relative to the current document it's included to? Possible paths like:
/item/details.html
/about/index.html
/about/extra/other.html
/index.html
",https://stackoverflow.com/questions/940451/using-relative-url-in-css-file-what-location-is-it-relative-to,539,457951.0,7.0,,,2009-06-02 16:21:00,2018-06-19 08:42:30,2014-04-05 12:02:28,,,html;css,anonymous coward,12904,26196,registered,true,940475,,CC BY-SA 3.0,2019-01-27 21:41:56,773,592,5,0,0,2,true,false,false,true,true,true,64,12,true,0.015,0.0012,6381,2009,6,16,Tuesday,false,false,false,false,false,false,false
29546550,Flexbox: 4 items per row,"I'm using a flex box to display 8 items that will dynamically resize with my page. How do I force it to split the items into two rows? (4 per row)?
Here is a relevant snip:
(Or if you prefer jsfiddle - http://jsfiddle.net/vivmaha/oq6prk1p/2/)
.parent-wrapper {
height: 100%;
width: 100%;
border: 1px solid black;
}
.parent {
display: flex;
font-size: 0;
flex-wrap: wrap;
margin: -10px 0 0 -10px;
}
.child {
display: inline-block;
background: blue;
margin: 10px 0 0 10px;
flex-grow: 1;
height: 100px;
}
<body>
<div class=""parent-wrapper"">
<div class=""parent"">
<div class=""child""></div>
<div class=""child""></div>
<div class=""child""></div>
<div class=""child""></div>
<div class=""child""></div>
<div class=""child""></div>
<div class=""child""></div>
<div class=""child""></div>
</div>
</div>
</body>
",https://stackoverflow.com/questions/29546550/flexbox-4-items-per-row,538,991176.0,10.0,,,2015-04-09 18:47:34,2021-12-27 09:33:23,2017-12-26 21:47:05,,,html;css;flexbox,V Maharajh,9799,1495198,registered,true,45384426,,CC BY-SA 3.0,,1383,1049,2,1,0,3,true,false,false,true,true,true,24,5,false,0.01,0.0005,4244,2015,4,18,Thursday,false,false,false,false,false,false,false
33454533,Can't scroll to top of flex item that is overflowing container,"In attempting to make a useful modal using flexbox, I found what seems to be a browser issue and am wondering if there is a known fix or workaround -- or ideas on how to resolve it.
The thing I'm trying to solve has two aspects. First, getting the modal window vertically centered, which works as expected. The second is to get the modal window to scroll -- externally, so the whole modal window scrolls, not the contents within it (this is so you can have dropdowns and other UI elements that can extend outside of the bounds of the modal -- like a custom date picker, etc.)
However, when combining the vertical centering with scroll bars, the top of the modal can become inaccessible as it begins to overflow. In the above example, you can resize to force the overflow, and in doing so it allows you to scroll to the bottom of the modal, but not to the top (first paragraph is cut off).
.modal-container {
position: fixed;
top: 0;
left: 0;
bottom: 0;
right: 0;
background: rgba(0, 0, 0, 0.5);
overflow-x: auto;
}
.modal-container .modal-window {
display: -ms-flexbox;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
/* Optional support to confirm scroll behavior makes sense in IE10
//-ms-flex-direction: column;
//-ms-flex-align: center;
//-ms-flex-pack: center; */
height: 100%;
}
.modal-container .modal-window .modal-content {
border: 1px solid #ccc;
border-radius: 4px;
background: #fff;
width: 100%;
max-width: 500px;
padding: 10px
}
<div class=""modal-container"">
<div class=""modal-window"">
<div class=""modal-content"">
<p class=""p3"">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p class=""p3"">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p class=""p3"">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
</div>
</div>
</div>
This affects (current) Firefox, Safari, Chrome, and Opera. It does interestingly behave correctly in IE10 if you comment in the IE10 vendor prefixed CSS -- I did not bother testing in IE11 yet, but assume the behavior matches that of IE10.
Here's the link to the example code (highly simplified)
https://jsfiddle.net/dh9k18k0/2/
",https://stackoverflow.com/questions/33454533/cant-scroll-to-top-of-flex-item-that-is-overflowing-container,537,134636.0,13.0,,,2015-10-31 17:35:22,2025-08-06 00:09:19,2022-06-01 17:08:35,,,html;css;flexbox,jejacks0n,6252,1931600,registered,true,33455342,,CC BY-SA 4.0,2022-06-01 17:15:22,4287,3882,2,1,0,3,true,false,false,true,true,true,66,11,false,0.097,0.004,4039,2015,10,17,Saturday,true,false,false,false,false,false,false
3341485,How to make a HTML Page in A4 paper size page(s)?,"Is it possible to make a HTML page behave, for example, like a A4-sized page in MS Word?
Essentially, I want to be able to show the HTML page in the browser, and outline the content in the dimensions of an A4 size page.
For the sake of simplicity, I'm assuming that the HTML page will only contain text (no images etc.) and there will be no <br> tags for example.
Also, when the HTML page is printed, it would come out as A4-sized paper pages.
",https://stackoverflow.com/questions/3341485/how-to-make-a-html-page-in-a4-paper-size-pages,537,1001087.0,16.0,,,2010-07-27 07:26:37,2026-01-21 20:07:23,2015-08-03 05:25:06,,,html;css;printing,Zabba,65607,382818,registered,true,21795173,,CC BY-SA 3.0,2013-07-29 07:11:00,495,454,1,0,0,3,true,false,false,true,true,true,49,11,true,0.016,0.0005,5961,2010,7,7,Tuesday,false,false,false,false,false,false,false
17067294,"HTML table with 100% width, with vertical scroll inside tbody","How can I set for <table> 100% width and put only inside <tbody> vertical scroll for some height?
![]()
table {
width: 100%;
display:block;
}
thead {
display: inline-block;
width: 100%;
height: 20px;
}
tbody {
height: 200px;
display: inline-block;
width: 100%;
overflow: auto;
}
<table>
<thead>
<tr>
<th>Head 1</th>
<th>Head 2</th>
<th>Head 3</th>
<th>Head 4</th>
<th>Head 5</th>
</tr>
</thead>
<tbody>
<tr>
<td>Content 1</td>
<td>Content 2</td>
<td>Content 3</td>
<td>Content 4</td>
<td>Content 5</td>
</tr>
</tbody>
</table>
I want to avoid adding some additional div, all I want is simple table like this and when I trying to change display, table-layout, position and much more things in CSS table not working good with 100% width only with fixed width in px.
",https://stackoverflow.com/questions/17067294/html-table-with-100-width-with-vertical-scroll-inside-tbody,530,1135887.0,14.0,,,2013-06-12 13:50:42,2024-09-05 07:51:01,2017-11-07 23:49:24,,,html;css;vertical-scrolling,Marko S,5357,2270632,registered,true,17380697,,CC BY-SA 3.0,2014-08-01 21:15:20,1561,1112,6,0,1,3,true,false,false,true,true,true,61,10,false,0.012,0.0005,4910,2013,6,13,Wednesday,false,false,false,false,false,false,false
1032914,How to make a div fill a remaining horizontal space?,"I have 2 divs: one in the left side and one in the right side of my page. The one in the left side has fixed width and I want the one of the right side to fill the remaining space.
#search {
width: 160px;
height: 25px;
float: left;
background-color: #ffffff;
}
#navigation {
width: 780px;
float: left;
background-color: #A53030;
}
<div id=""search"">Text</div>
<div id=""navigation"">Navigation</div>
",https://stackoverflow.com/questions/1032914/how-to-make-a-div-fill-a-remaining-horizontal-space,530,745321.0,26.0,,,2009-06-23 14:29:30,2021-07-27 14:34:19,2020-03-10 02:14:33,,,html;css;width;responsive,wyc,55767,122536,registered,true,1032952,,CC BY-SA 4.0,2019-11-11 20:08:10,782,460,2,0,0,4,true,false,false,true,true,true,52,10,true,0.035,0.0007,6360,2009,6,14,Tuesday,false,false,false,false,false,false,false
44840735,(change) vs (ngModelChange) in angular,"Angular 1 does not accept onchange() event, it's only accepts ng-change() event.
Angular 2, on the other hand, accepts both (change) and (ngModelChange) events, which both seems to be doing the same thing.
What's the difference?
which one is best for performance?
ngModelChange:
<input type=""text"" pInputText class=""ui-widget ui-text""
(ngModelChange)=""clearFilter()"" placeholder=""Find""/>
vs change:
<input type=""text"" pInputText class=""ui-widget ui-text""
(change)=""clearFilter()"" placeholder=""Find""/>
",https://stackoverflow.com/questions/44840735/change-vs-ngmodelchange-in-angular,529,1126013.0,6.0,,,2017-06-30 07:16:42,2023-09-12 11:01:55,2019-10-15 05:19:50,,,javascript;html;angular;typescript;angular-ngmodelchange,Ramesh Rajendran,38951,2218635,registered,true,45075106,,CC BY-SA 4.0,,710,534,6,0,0,5,true,false,false,true,true,true,38,5,false,0.005,0.0005,3431,2017,6,7,Friday,false,false,true,false,false,false,false
564650,Convert HTML to PDF in .NET,"I want to generate a PDF by passing HTML contents to a function. I have made use of iTextSharp for this but it does not perform well when it encounters tables and the layout just gets messy.
Is there a better way?
",https://stackoverflow.com/questions/564650/convert-html-to-pdf-in-net,529,964167.0,26.0,,,2009-02-19 10:21:22,2024-09-05 13:11:17,2015-12-09 16:10:48,2021-10-20 18:15:18,Needs details or clarity,c#;html;pdf;itext,SandHurst,,,does_not_exist,true,,,,2014-05-29 17:00:11,229,215,0,0,0,4,false,true,false,true,false,true,27,6,false,0.027,0.0005,6484,2009,2,10,Thursday,false,false,false,false,true,false,false
4804581,How can I expand floated child div's height to parent's height?,"I have the page structure as:
<div class=""parent"">
<div class=""child-left floatLeft"">
</div>
<div class=""child-right floatLeft"">
</div>
</div>
Now, the child-left DIV will have more content, so the parent DIV's height increases as per the child DIV.
But the problem is child-right height is not increasing. How can I make its height as equal to it's parent?
",https://stackoverflow.com/questions/4804581/how-can-i-expand-floated-child-divs-height-to-parents-height,527,1102244.0,13.0,,,2011-01-26 12:32:22,2021-06-30 13:15:30,2021-06-30 13:15:30,,,html;css;layout,Veera,33382,42372,registered,true,4804706,,CC BY-SA 4.0,,500,416,4,0,0,3,true,false,false,true,true,true,71,11,true,0.012,0.0005,5778,2011,1,12,Wednesday,false,false,false,false,false,false,false
6088409,SVG drop shadow using css3,"Is it possible to set drop shadow for an svg element using css3, something like
box-shadow: -5px -5px 5px #888;
-webkit-box-shadow: -5px -5px 5px #888;
I saw some remarks on creating shadow using filter effects. Is there an example of using CSS alone. Below is a working code where the cursor style is correctly applied, but no shadow effect. How can I get the shadow effect with the least bit of code?
svg .shadow {
cursor:crosshair;
-moz-box-shadow: -5px -5px 5px #888;
-webkit-box-shadow: -5px -5px 5px #888;
box-shadow: -5px -5px 5px #888;
}
<svg xmlns=""http://www.w3.org/2000/svg"" xmlns:xlink=""http://www.w3.org/1999/xlink"" version=""1.1"" baseProfile=""full"" viewBox=""0 0 120 70"">
<rect class=""shadow"" x=""10"" y=""10"" width=""100"" height=""50"" fill=""#c66"" />
</svg>
",https://stackoverflow.com/questions/6088409/svg-drop-shadow-using-css3,523,642767.0,9.0,,,2011-05-22 14:05:30,2024-08-14 19:09:29,2024-03-26 22:04:15,,,html;css;svg;svg-filters,bsr,59056,303477,registered,true,6094674,,CC BY-SA 4.0,,1152,816,3,0,0,4,true,false,false,true,true,true,26,5,false,0.014,0.0008,5662,2011,5,14,Sunday,true,false,false,false,false,false,false
260857,Changing website favicon dynamically,"I have a web application that's branded according to the user that's currently logged in. I'd like to change the favicon of the page to be the logo of the private label, but I'm unable to find any code or any examples of how to do this. Has anybody successfully done this before?
I'm picturing having a dozen icons in a folder, and the reference to which favicon.ico file to use is just generated dynamically along with the HTML page. Thoughts?
",https://stackoverflow.com/questions/260857/changing-website-favicon-dynamically,523,340072.0,18.0,,,2008-11-04 04:11:55,2024-12-10 14:30:37,2021-08-29 07:57:07,,,javascript;html;dom;favicon,SqlRyan,34090,8114,registered,true,260876,,CC BY-SA 4.0,2021-03-27 19:56:12,460,446,0,0,0,4,true,false,false,true,true,true,36,4,false,0.053,0.0015,6591,2008,11,4,Tuesday,false,false,true,false,false,false,false
43707076,How does the "position: sticky;" property work?,"I want to make the navigation bar stick to the top of the viewport once a user scrolls the page, but it's not working and I have no clue why. If you can please help, here is my HTML and CSS code:
.container {
min-height: 300vh;
}
.nav-selections {
text-transform: uppercase;
letter-spacing: 5px;
font: 18px ""lato"",sans-serif;
display: inline-block;
text-decoration: none;
color: white;
padding: 18px;
float: right;
margin-left: 50px;
transition: 1.5s;
}
.nav-selections:hover{
transition: 1.5s;
color: black;
}
ul {
background-color: #B79b58;
overflow: auto;
}
li {
list-style-type: none;
}
<main class=""container"">
<nav style=""position: sticky; position: -webkit-sticky;"">
<ul align=""left"">
<li><a href=""#/contact"" class=""nav-selections"" style=""margin-right:35px;"">Contact</a></li>
<li><a href=""#/about"" class=""nav-selections"">About</a></li>
<li><a href=""#/products"" class=""nav-selections"">Products</a></li>
<li><a href=""#"" class=""nav-selections"">Home</a></li>
</ul>
</nav>
</main>
",https://stackoverflow.com/questions/43707076/how-does-the-position-sticky-property-work,521,991331.0,32.0,,,2017-04-30 13:43:42,2025-07-11 09:16:14,2021-02-25 19:57:54,,,html;css;position;css-position;sticky,Harleyoc1,5211,6876001,registered,true,43707215,,CC BY-SA 4.0,2019-07-25 14:25:06,1502,1197,2,0,0,5,true,false,false,true,true,true,57,7,true,0.032,0.0005,3492,2017,4,13,Sunday,true,false,false,false,false,false,false
5219175,How to make an element width: 100% minus padding?,"I have an html input.
The input has padding: 5px 10px; I want it to be 100% of the parent div's width(which is fluid).
However using width: 100%; causes the input to be 100% + 20px how can I get around this?
",https://stackoverflow.com/questions/5219175/how-to-make-an-element-width-100-minus-padding,519,342727.0,15.0,,,2011-03-07 11:35:07,2025-09-25 14:13:41,2020-01-08 15:57:34,,,html;css;width;fluid-layout,Hailwood,93335,383759,registered,true,5219611,,CC BY-SA 4.0,,344,219,3,1,0,4,true,false,false,true,true,true,49,9,true,0.044,0.0015,5738,2011,3,11,Monday,false,false,false,false,false,false,false
6725890,location.host vs location.hostname and cross-browser compatibility?,"Which one of these is the most effective vs checking if the user agent is accessing via the correct domain.
We would like to show a small js based 'top bar' style warning if they are accessing the domain using some sort of web proxy (as it tends to break the js).
We were thinking about using the following:
var r = /.*domain\.com$/;
if (r.test(location.hostname)) {
// showMessage ...
}
That would take care of any subdomains we ever use.
Which should we use host or hostname?
In Firefox 5 and Chrome 12:
console.log(location.host);
console.log(location.hostname);
.. shows the same for both.
Is that because the port isn't actually in the address bar?
W3Schools says host contains the port.
Should location.host/hostname be validated or can we be pretty certain in IE6+ and all the others it will exist?
",https://stackoverflow.com/questions/6725890/location-host-vs-location-hostname-and-cross-browser-compatibility,518,316539.0,7.0,,,2011-07-17 18:34:18,2023-06-22 12:31:21,2016-10-18 16:28:13,,,javascript;html;window;location;host,anonymous-one,15232,815370,registered,true,11379802,,CC BY-SA 3.0,,1037,823,2,1,0,5,true,false,false,true,true,true,67,6,true,0.022,0.0016,5606,2011,7,18,Sunday,true,false,true,false,false,false,false
25351968,How can I display full (non-truncated) dataframe information in HTML when converting from Pandas dataframe to HTML?,"I converted a Pandas dataframe to an HTML output using the DataFrame.to_html function. When I save this to a separate HTML file, the file shows truncated output.
For example, in my TEXT column,
df.head(1) will show
The film was an excellent effort...
instead of
The film was an excellent effort in deconstructing the complex social sentiments that prevailed during this period.
This rendition is fine in the case of a screen-friendly format of a massive Pandas dataframe, but I need an HTML file that will show complete tabular data contained in the dataframe, that is, something that will show the latter text element rather than the former text snippet.
How would I be able to show the complete, non-truncated text data for each element in my TEXT column in the HTML version of the information? I would imagine that the HTML table would have to display long cells to show the complete data, but as far as I understand, only column-width parameters can be passed into the DataFrame.to_html function.
",https://stackoverflow.com/questions/25351968/how-can-i-display-full-non-truncated-dataframe-information-in-html-when-conver,518,816482.0,13.0,,,2014-08-17 17:52:52,2025-03-14 03:48:13,2021-05-24 21:02:23,,,python;html;pandas,Amy,5293,3950509,registered,true,25352191,,CC BY-SA 4.0,,1114,1001,3,0,0,3,true,false,false,true,true,true,115,17,true,0.016,0.0006,4479,2014,8,17,Sunday,true,true,false,false,false,false,false
2825856,HTML button to NOT submit form,"I have a form. Outside that form, I have a button. A simple button, like this:
<button>My Button</button>
Nevertheless, when I click it, it submits the form. Here's the code:
<form id="myform">
<label>Label
<input />
</label>
</form>
<button>My Button</button>
All this button should do is some JavaScript. But even when it looks just like in the code above, it submits the form. When I change the tag button to span, it works perfectly. But unfortunately, it needs to be a button. Is there any way to block that button from submitting the form? Like e. g.
<button onclick="document.getElementById('myform').doNotSubmit();">My Button</button>
",https://stackoverflow.com/questions/2825856/html-button-to-not-submit-form,518,286237.0,9.0,,,2010-05-13 10:01:12,2022-09-04 01:18:25,2022-07-13 13:15:26,,,javascript;html,arik,29620,299711,registered,true,2825867,,CC BY-SA 4.0,,840,747,3,0,0,2,true,false,false,true,true,true,30,6,false,0.031,0.0018,6036,2010,5,10,Thursday,false,false,true,false,false,false,false
826782,How to disable text selection highlighting,"For anchors that act like buttons (for example, the buttons on the sidebar of this Stack Overflow page titled Questions, Tags, and Users) or tabs, is there a CSS standard way to disable the highlighting effect if the user accidentally selects the text?
I realize that this could be done with JavaScript and a little googling yielded the Mozilla-only -moz-user-select option.
Is there a standard-compliant way to accomplish this with CSS, and if not, what is the "best practice" approach?
",https://stackoverflow.com/questions/826782/how-to-disable-text-selection-highlighting,6168,2843690.0,46.0,,,2009-05-05 20:29:18,2025-03-05 13:36:22,2022-07-24 23:50:34,,,css;cross-browser;highlight;textselection,anon,,,does_not_exist,true,,,CC BY-SA 4.0,2012-04-25 20:42:50,559,498,1,0,0,4,false,false,false,true,false,true,42,6,false,0.016,0.0022,6409,2009,5,20,Tuesday,false,false,false,false,false,false,false
1014861,Is there a CSS parent selector?,"How do I select the <li> element that is a direct parent of the anchor element?
As an example, my CSS would be something like this:
li < a.active {
property: value;
}
Obviously there are ways of doing this with JavaScript, but I'm hoping that there is some sort of workaround that exists native to CSS Level 2.
The menu that I am trying to style is being spewed out by a CMS, so I can't move the active element to the <li> element... (unless I theme the menu creation module which I'd rather not do).
",https://stackoverflow.com/questions/1014861/is-there-a-css-parent-selector,4335,3828688.0,33.0,,,2009-06-18 19:59:36,2026-10-09 10:46:15,2022-05-22 05:10:02,,,css;css-selectors,jcuenod,59085,123415,registered,true,1014958,,CC BY-SA 4.0,2013-09-05 00:39:11,599,521,3,0,0,2,true,false,false,true,true,true,31,6,true,0.009,0.0011,6365,2009,6,19,Thursday,false,false,false,false,false,false,false
3508605,How can I transition height: 0; to height: auto; using CSS?,"I am trying to make a <ul> slide down using CSS transitions.
The <ul> starts off at height: 0;. On hover, the height is set to height:auto;. However, this is causing it to simply appear, not transition,
If I do it from height: 40px; to height: auto;, then it will slide up to height: 0;, and then suddenly jump to the correct height.
How else could I do this without using JavaScript?
#child0 {
height: 0;
overflow: hidden;
background-color: #dedede;
-moz-transition: height 1s ease;
-webkit-transition: height 1s ease;
-o-transition: height 1s ease;
transition: height 1s ease;
}
#parent0:hover #child0 {
height: auto;
}
#child40 {
height: 40px;
overflow: hidden;
background-color: #dedede;
-moz-transition: height 1s ease;
-webkit-transition: height 1s ease;
-o-transition: height 1s ease;
transition: height 1s ease;
}
#parent40:hover #child40 {
height: auto;
}
h1 {
font-weight: bold;
}
The only difference between the two snippets of CSS is one has height: 0, the other height: 40.
<hr>
<div id=""parent0"">
<h1>Hover me (height: 0)</h1>
<div id=""child0"">Some content
<br>Some content
<br>Some content
<br>Some content
<br>Some content
<br>Some content
<br>
</div>
</div>
<hr>
<div id=""parent40"">
<h1>Hover me (height: 40)</h1>
<div id=""child40"">Some content
<br>Some content
<br>Some content
<br>Some content
<br>Some content
<br>Some content
<br>
</div>
</div>
",https://stackoverflow.com/questions/3508605/how-can-i-transition-height-0-to-height-auto-using-css,3018,1970591.0,47.0,,,2010-08-18 02:50:35,2026-06-12 18:29:43,2021-10-25 13:08:45,,,css;css-transitions,Hailwood,93335,383759,registered,true,8331169,,CC BY-SA 4.0,2014-10-22 20:50:30,2120,1693,9,0,0,2,true,false,false,true,true,true,59,11,true,0.024,0.0015,5939,2010,8,2,Wednesday,false,false,false,false,false,false,false
2189452,What is the difference between margin and padding in CSS?,"What is the difference between margin and padding in CSS? When should one or the other be used?
",https://stackoverflow.com/questions/2189452/what-is-the-difference-between-margin-and-padding-in-css,2643,1039870.0,14.0,,,2010-02-03 03:20:12,2024-06-15 17:18:27,2023-11-06 19:33:24,,,css;padding;margin,Alex Angas,60184,6651,registered,true,9183818,,CC BY-SA 4.0,2014-02-20 00:26:06,129,96,2,0,0,3,true,false,false,true,true,true,57,10,true,0.013,0.0025,6135,2010,2,3,Wednesday,false,false,false,false,false,false,false
5654447,What's the difference between SCSS and Sass?,"From what I've been reading, Sass is a language that makes CSS more powerful with variable and math support.
What's the difference with SCSS? Is it supposed to be the same language? Similar? Different?
",https://stackoverflow.com/questions/5654447/whats-the-difference-between-scss-and-sass,2519,1166594.0,16.0,,,2011-04-13 19:23:09,2025-08-03 09:35:42,2013-06-01 21:34:15,,,css;sass,bbonamin,30913,351901,registered,true,5654471,,CC BY-SA 3.0,2016-01-31 16:33:54,218,204,0,0,0,2,true,false,false,true,true,true,48,7,true,0.014,0.0022,5701,2011,4,19,Wednesday,false,false,false,false,false,false,false
3087975,How can I change the cursor into a hand when a user hovers over a list item?,"I've got a list, and I have a click handler for its items:
<ul>
<li>foo</li>
<li>goo</li>
</ul>
How can I change the mouse pointer into a hand pointer (like when hovering over a button)? Right now, the pointer turns into a text selection pointer when I hover over the list items.
",https://stackoverflow.com/questions/3087975/how-can-i-change-the-cursor-into-a-hand-when-a-user-hovers-over-a-list-item,2438,2853237.0,28.0,,,2010-06-21 19:45:44,2026-03-30 16:17:03,2026-03-30 14:22:41,,,css;hover;mouse-cursor,user246114,52041,246114,registered,true,3088012,,CC BY-SA 4.0,2014-01-23 21:22:12,398,321,1,0,0,3,true,false,false,true,true,true,76,17,true,0.01,0.0009,5997,2010,6,19,Monday,false,false,false,false,false,false,false
3680429,Click through div to underlying elements,"I have a div that has background:transparent, along with border. Underneath this div, I have more elements.
Currently, I'm able to click the underlying elements when I click outside of the overlay div. However, I'm unable to click the underlying elements when clicking directly on the overlay div.
I want to be able to click through this div so that I can click on the underlying elements.
![]()
",https://stackoverflow.com/questions/3680429/click-through-div-to-underlying-elements,2115,1147829.0,16.0,,,2010-09-09 20:42:54,2021-11-29 07:23:06,2021-11-29 07:23:06,,,css;click;mouseevent;layer,Ryan,22327,398434,registered,true,4839672,,CC BY-SA 4.0,2014-01-23 21:13:52,575,396,7,0,1,4,true,false,false,true,true,true,40,6,false,0.014,0.0018,5917,2010,9,20,Thursday,false,false,false,false,false,false,false
7073484,How do CSS triangles work?,"There're plenty of different CSS shapes over at CSS Tricks - Shapes of CSS and I'm particularly puzzled with a triangle:
![]()
#triangle-up {
width: 0;
height: 0;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 100px solid red;
}
<div id=""triangle-up""></div>
How and why does it work?
",https://stackoverflow.com/questions/7073484/how-do-css-triangles-work,2040,264008.0,23.0,,,2011-08-16 03:54:51,2024-10-19 04:15:56,2016-07-03 23:27:22,,,css;geometry;polygon;css-shapes,Stanislav Shabalin,19318,417810,registered,true,7073558,,CC BY-SA 3.0,2013-06-10 05:10:28,821,364,2,1,1,4,true,false,false,true,true,true,26,5,true,0.087,0.0077,5576,2011,8,3,Tuesday,false,false,false,false,false,false,false
3331353,Transitions on the CSS display property,"I'm currently designing a CSS 'mega dropdown' menu - basically a regular CSS-only dropdown menu, but one that contains different types of content.
At the moment, it appears that CSS 3 transitions don't apply to the 'display' property, i.e., you can't do any sort of transition from display: none to display: block (or any combination).
Is there a way for the second-tier menu from the above example to 'fade in' when someone hovers over one of the top level menu items?
I'm aware that you can use transitions on the visibility: property, but I can't think of a way to use that effectively.
I've also tried using height, but that just failed miserably.
I'm also aware that it's trivial to achieve this using JavaScript, but I wanted to challenge myself to use just CSS, and I think I'm coming up a little short.
",https://stackoverflow.com/questions/3331353/transitions-on-the-css-display-property,2016,2618444.0,44.0,,,2010-07-25 22:52:49,2026-08-25 22:31:43,2019-11-26 07:17:26,,,css;css-transitions,RichardTape,21823,308455,registered,true,6943704,,CC BY-SA 4.0,2014-10-11 23:23:15,919,821,3,0,0,2,true,false,false,true,true,true,39,6,false,0.017,0.0008,5963,2010,7,22,Sunday,true,false,false,false,false,false,false
1817792,Is there a "previous sibling" selector?,"The plus sign selector (+) is for selecting the next adjacent sibling.
Is there an equivalent for the previous sibling?
",https://stackoverflow.com/questions/1817792/is-there-a-previous-sibling-selector,1914,1215912.0,23.0,,,2009-11-30 04:06:36,2026-05-21 19:51:01,2022-11-01 13:53:12,,,css;css-selectors;siblings,Jourkey,35396,118547,registered,true,1817801,,CC BY-SA 4.0,2015-10-05 09:03:24,147,120,1,0,0,3,true,false,false,true,true,true,49,6,true,0.019,0.0016,6200,2009,11,4,Monday,false,false,false,false,false,false,false
17982111,Sass Variable in CSS calc() function,"I'm trying to use the calc() function in a Sass stylesheet, but I'm having some issues. Here's my code:
$body_padding: 50px
body
padding-top: $body_padding
height: calc(100% - $body_padding)
If I use the literal 50px instead of my body_padding variable, I get exactly what I want. However, when I switch to the variable, this is the output:
body {
padding-top: 50px;
height: calc(100% - $body_padding);
}
How can I get Sass to recognize that it needs to replace the variable within the calc function?
",https://stackoverflow.com/questions/17982111/sass-variable-in-css-calc-function,1868,720239.0,6.0,,,2013-07-31 22:30:09,2024-01-18 13:34:54,2020-08-23 00:04:48,,,css;sass;css-calc,GJK,37467,1277669,registered,true,20236515,,CC BY-SA 4.0,,641,520,6,0,0,3,true,false,false,true,true,true,36,6,false,0.008,0.0026,4861,2013,7,22,Wednesday,false,false,false,false,false,false,false
16056591,Font scaling based on size of container,"I'm having a hard time getting my head around font scaling.
I currently have a website with a body font-size of 100%. 100% of what though? This seems to compute out at 16 pixels.
I was under the impression that 100% would somehow refer to the size of the browser window, but apparently not because it's always 16 pixels whether the window is resized down to a mobile width or full-blown widescreen desktop.
How can I make the text on my site scale in relation to its container? I tried using em, but this doesn't scale either.
My reasoning is that things like my menu become squished when you resize, so I need to reduce the px font-size of .menuItem among other elements in relation to the width of the container. (For example, in the menu on a large desktop, 22px works perfectly. Move down to a tablet width and 16px is more appropriate.)
I'm aware I can add breakpoints, but I really want the text to scale as well as having extra breakpoints, otherwise, I'll end up with hundreds of breakpoints for every 100-pixels decrease in width to control the text.
",https://stackoverflow.com/questions/16056591/font-scaling-based-on-size-of-container,1865,2401381.0,43.0,,,2013-04-17 09:37:18,2025-07-04 18:26:23,2024-01-04 12:06:55,,,css;responsive-design;font-size,Francesca,28518,1178820,registered,true,19814948,,CC BY-SA 4.0,2018-08-02 13:42:53,1202,1060,7,0,0,3,true,false,false,true,true,true,39,7,false,0.018,0.0008,4966,2013,4,9,Wednesday,false,false,false,false,false,false,false
3397113,How to remove focus border (outline) around text/input boxes? (Chrome),"Can anyone explain how to remove the orange or blue border (outline) around text/input boxes? I think it only happens on Chrome to show that the input box is active. Here's the input CSS I'm using:
input {
background-color: transparent;
border: 0px solid;
height: 20px;
width: 160px;
color: #CCC;
}
![]()
",https://stackoverflow.com/questions/3397113/how-to-remove-focus-border-outline-around-text-input-boxes-chrome,1860,3076751.0,11.0,,,2010-08-03 13:49:03,2025-10-13 01:23:36,2020-04-19 10:35:24,2015-06-24 13:52:55,Duplicate,css;google-chrome;input;focus;border,Joey Morani,26771,303221,registered,true,3397158,,,2012-02-15 13:08:48,513,323,1,0,1,5,true,true,false,true,true,true,70,10,false,0.004,0.0006,5954,2010,8,13,Tuesday,false,false,false,false,false,false,false
7273338,How to vertically align an image inside a div,"How can you align an image inside of a containing div?
Example
In my example, I need to vertically center the <img> in the <div> with class ="frame":
<div class="frame" style="height: 25px;">
<img src="http://jsfiddle.net/img/logo.png" />
</div>
.frame's height is fixed and the image's height is unknown. I can add new elements in .frame if that's the only solution. I'm trying to do this on Internet Explorer 7 and later, WebKit, Gecko.
See the jsfiddle here.
.frame {
height: 25px; /* Equals maximum image height */
line-height: 25px;
width: 160px;
border: 1px solid red;
text-align: center;
margin: 1em 0;
}
img {
background: #3A6F9A;
vertical-align: middle;
max-height: 25px;
max-width: 160px;
}
<div class=frame>
<img src=""http://jsfiddle.net/img/logo.png"" height=250 />
</div>
<div class=frame>
<img src=""http://jsfiddle.net/img/logo.png"" height=25 />
</div>
<div class=frame>
<img src=""http://jsfiddle.net/img/logo.png"" height=23 />
</div>
<div class=frame>
<img src=""http://jsfiddle.net/img/logo.png"" height=21 />
</div>
<div class=frame>
<img src=""http://jsfiddle.net/img/logo.png"" height=19 />
</div>
<div class=frame>
<img src=""http://jsfiddle.net/img/logo.png"" height=17 />
</div>
<div class=frame>
<img src=""http://jsfiddle.net/img/logo.png"" height=15 />
</div>
<div class=frame>
<img src=""http://jsfiddle.net/img/logo.png"" height=13 />
</div>
<div class=frame>
<img src=""http://jsfiddle.net/img/logo.png"" height=11 />
</div>
<div class=frame>
<img src=""http://jsfiddle.net/img/logo.png"" height=9 />
</div>
<div class=frame>
<img src=""http://jsfiddle.net/img/logo.png"" height=7 />
</div>
<div class=frame>
<img src=""http://jsfiddle.net/img/logo.png"" height=5 />
</div>
<div class=frame>
<img src=""http://jsfiddle.net/img/logo.png"" height=3 />
</div>
",https://stackoverflow.com/questions/7273338/how-to-vertically-align-an-image-inside-a-div,1751,2134004.0,37.0,,,2011-09-01 16:25:51,2022-06-10 08:16:21,2020-06-20 09:12:55,,,css;image;vertical-alignment,Arnaud Le Blanc,100371,576875,registered,true,7310398,,CC BY-SA 4.0,2014-03-05 13:38:56,2684,2186,9,1,0,3,true,false,false,true,true,true,45,9,false,0.017,0.0008,5560,2011,9,16,Thursday,false,false,false,false,false,false,false
1776915,How can I center an absolutely positioned element in a div?,"I want to place a div (with position:absolute;) element in the center of the window. But I'm having problems doing so, because the width is unknown.
I tried the following CSS code, but it needs to be adjusted because the width is responsive.
.center {
left: 50%;
bottom: 5px;
}
How can I achieve this?
",https://stackoverflow.com/questions/1776915/how-can-i-center-an-absolutely-positioned-element-in-a-div,1615,2137004.0,39.0,,,2009-11-21 21:56:16,2024-11-23 12:16:11,2023-11-28 20:32:56,,,css;css-position;absolute,Ish,29836,69818,registered,true,1777282,,CC BY-SA 4.0,2014-08-07 13:22:13,412,307,3,0,0,3,true,false,false,true,true,true,59,11,true,0.018,0.0008,6209,2009,11,21,Saturday,true,false,false,false,false,false,false
20626685,How do I set distance between flexbox items?,"To set the minimal distance between flexbox items I'm using margin: 0 5px on .item and margin: 0 -5px on container. This seems like a hack. Is there another property or method intended to accomplish this goal?
#box {
display: flex;
width: 100px;
margin: 0 -5px;
}
.item {
background: gray;
width: 50px;
height: 50px;
margin: 0 5px;
}
<div id='box'>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
</div>
",https://stackoverflow.com/questions/20626685/how-do-i-set-distance-between-flexbox-items,1582,2808416.0,40.0,,,2013-12-17 05:35:30,2023-05-26 14:52:44,2023-05-26 14:52:44,,,css;flexbox;spacing,Sasha Koss,16626,75284,registered,true,20653092,,CC BY-SA 4.0,2019-02-21 15:27:34,895,550,5,0,0,3,true,false,false,true,true,true,44,8,true,0.014,0.0006,4722,2013,12,5,Tuesday,false,false,false,false,false,false,false
2504071,How do I combine a background-image and CSS3 gradient on the same element?,"How do I use CSS3 gradients for my background-color and then apply a background-image to apply some sort of light transparent texture?
",https://stackoverflow.com/questions/2504071/how-do-i-combine-a-background-image-and-css3-gradient-on-the-same-element,1437,1171261.0,23.0,,,2010-03-23 22:30:53,2025-11-12 12:25:28,2016-02-25 22:16:11,,,css;background-image;gradient,Ronald ,16458,90899,registered,true,2547064,,CC BY-SA 3.0,2012-10-21 22:57:02,168,135,2,0,0,3,true,false,false,true,true,true,74,13,true,0.02,0.0012,6087,2010,3,22,Tuesday,false,false,false,false,false,false,false
133051,What is the difference between visibility:hidden and display:none?,"The CSS rules visibility:hidden and display:none both result in the element not being visible. Are these synonyms?
",https://stackoverflow.com/questions/133051/what-is-the-difference-between-visibilityhidden-and-displaynone,1414,784243.0,21.0,,,2008-09-25 12:37:47,2021-10-11 23:09:34,2012-05-25 16:06:34,,,css;visibility,Chris Noe,37451,14749,registered,true,133064,,CC BY-SA 3.0,2012-05-25 16:08:17,148,115,2,0,0,2,true,false,false,true,true,true,66,8,true,0.027,0.0018,6631,2008,9,12,Thursday,false,false,false,false,false,false,false
22252472,How can I change the color of an 'svg' element?,"I want to use this technique and change the SVG color, but so far I haven't been able to do so. I use this in the CSS, but my image is always black, no matter what.
My code:
.change-my-color {
fill: green;
}
<svg>
<image class=""change-my-color"" xlink:href=""https://svgur.com/i/AFM.svg"" width=""96"" height=""96"" src=""ppngfallback.png"" />
</svg>
",https://stackoverflow.com/questions/22252472/how-can-i-change-the-color-of-an-svg-element,1366,3538312.0,50.0,,,2014-03-07 14:15:03,2025-02-07 18:15:31,2022-12-10 00:53:53,,,css;svg;colors,Barbara,15206,351320,registered,true,22253046,,CC BY-SA 4.0,2020-05-12 05:29:05,757,377,2,1,0,3,true,false,false,true,true,true,55,10,true,0.014,0.0004,4642,2014,3,14,Friday,false,false,false,false,false,false,false
448981,Which characters are valid in CSS class names/selectors?,"What characters/symbols are allowed within the CSS class selectors?
I know that the following characters are invalid, but what characters are valid?
~ ! @ $ % ^ & * ( ) + = , . / ' ; : " ? > < [ ] \ { } | ` #
",https://stackoverflow.com/questions/448981/which-characters-are-valid-in-css-class-names-selectors,1364,483489.0,11.0,,,2009-01-15 23:37:39,2025-04-06 19:04:08,2022-12-31 01:25:52,,,css;css-selectors,Darryl Hein,145615,5441,registered,true,449000,,CC BY-SA 4.0,,337,225,1,0,0,2,true,false,false,true,true,true,56,8,true,0.023,0.0028,6519,2009,1,23,Thursday,false,false,false,false,false,false,false
2717480,CSS selector for first element with class,"I have a bunch of elements with a class name red, but I can't seem to select the first element with the class="red" using the following CSS rule:
.home .red:first-child {
border: 1px solid red;
}
<div class=""home"">
<span>blah</span>
<p class=""red"">first</p>
<p class=""red"">second</p>
<p class=""red"">third</p>
<p class=""red"">fourth</p>
</div>
What is wrong in this selector and how do I correct it to target the first child with class red?
",https://stackoverflow.com/questions/2717480/css-selector-for-first-element-with-class,1362,1784868.0,26.0,,,2010-04-26 22:51:13,2025-02-18 10:52:33,2021-03-13 14:02:45,,,css;css-selectors,Rajat,34348,111683,registered,true,8539107,,CC BY-SA 4.0,2021-01-12 20:52:29,907,556,5,0,0,2,true,false,false,true,true,true,41,7,false,0.015,0.0008,6053,2010,4,22,Monday,false,false,false,false,false,false,false
8878033,How to make Twitter Bootstrap menu dropdown on hover rather than click,"I'd like to have my Bootstrap menu automatically drop down on hover, rather than having to click the menu title. I'd also like to lose the little arrows next to the menu titles.
",https://stackoverflow.com/questions/8878033/how-to-make-twitter-bootstrap-menu-dropdown-on-hover-rather-than-click,1252,853746.0,43.0,,,2012-01-16 09:36:40,2022-01-03 21:52:49,2017-07-29 18:17:26,,,css;drop-down-menu;twitter-bootstrap,falter,13664,787762,registered,true,10143018,,CC BY-SA 3.0,2012-04-14 19:04:35,185,178,0,0,0,3,true,false,false,true,true,true,70,12,false,0.05,0.0015,5423,2012,1,9,Monday,false,false,false,false,false,false,false
18153234,Center a column using Twitter Bootstrap,"How do I center a div of one column size within the container (12 columns) in Twitter Bootstrap 3?
.centered {
background-color: red;
}
<!-- Latest compiled and minified CSS -->
<link rel=""stylesheet"" href=""https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"" integrity=""sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"" crossorigin=""anonymous"">
<body class=""container"">
<div class=""col-lg-1 col-offset-6 centered"">
<img data-src=""holder.js/100x100"" alt="""" />
</div>
</body>
I want a div, with a class .centered to be centered within the container. I may use a row if there are multiple divs, but for now I just want a div with the size of one column centered within the container (12 columns).
I am also not sure the above approach is good enough as the intention is not to offset the div by half. I do not need free spaces outside the div and the contents of the div shrink in proportion. I want to empty space outside the div to be evenly distributed (shrink till the container width is equal to one column).
",https://stackoverflow.com/questions/18153234/center-a-column-using-twitter-bootstrap,1236,2305983.0,34.0,,,2013-08-09 18:24:37,2023-05-15 17:31:50,2023-05-15 17:25:12,,,css;twitter-bootstrap;twitter-bootstrap-3;bootstrap-5;centering,bsr,59056,303477,registered,true,18153551,,CC BY-SA 4.0,2014-09-05 14:05:51,1641,1117,9,1,0,5,true,false,false,true,true,true,39,6,false,0.015,0.0005,4852,2013,8,18,Friday,false,false,false,false,false,false,false
7792652,What is the best way to conditionally apply a class?,"Lets say you have an array that is rendered in a ul with an li for each element and a property on the controller called selectedIndex. What would be the best way to add a class to the li with the index selectedIndex in AngularJS?
I am currently duplicating (by hand) the li code and adding the class to one of the li tags and using ng-show and ng-hide to show only one li per index.
",https://stackoverflow.com/questions/7792652/what-is-the-best-way-to-conditionally-apply-a-class,1203,783014.0,23.0,,,2011-10-17 10:49:52,2024-02-06 10:48:58,2015-07-28 10:01:46,,,css;angularjs,respectTheCode,43236,109306,registered,true,8309832,,CC BY-SA 3.0,2015-06-11 18:43:36,528,384,10,0,0,2,true,false,false,true,true,true,52,10,true,0.029,0.0015,5514,2011,10,10,Monday,false,false,false,false,false,false,false
10782054,What does the "~" (tilde/squiggle/twiddle) CSS selector mean?,"Searching for the ~ character isn't easy. I was looking over some CSS and found this
.check:checked ~ .content {
}
What does it mean?
",https://stackoverflow.com/questions/10782054/what-does-the-tilde-squiggle-twiddle-css-selector-mean,1153,429544.0,4.0,,,2012-05-28 09:10:00,2025-09-10 19:47:39,2020-04-17 18:35:18,,,css;css-selectors,Tarang,76095,950147,registered,true,10782297,,CC BY-SA 4.0,2025-09-10 19:47:47,188,137,2,0,0,2,true,false,false,true,true,true,71,8,true,0.009,0.0027,5290,2012,5,9,Monday,false,false,false,false,false,false,false
12289853,How can I use a not:first-child selector?,"I have div tag containing several ul tags.
If I trying set CSS properties only for the first ul tag, and this code works:
div ul:first-child {
background-color: #900;
}
When I want set CSS properties for each ul tag except the first, I tried this:
div ul:not:first-child {
background-color: #900;
}
also this:
div ul:not(:first-child) {
background-color: #900;
}
and this:
div ul:first-child:after {
background-color: #900;
}
But to no effect. How must I write in CSS: "each element, except the first"?
",https://stackoverflow.com/questions/12289853/how-can-i-use-a-notfirst-child-selector,1146,1472844.0,13.0,,,2012-09-05 21:09:16,2023-11-13 16:17:21,2023-11-13 16:17:21,,,css;css-selectors,Oto Shavadze,43440,1609729,registered,true,12289888,,CC BY-SA 4.0,2023-11-13 16:17:07,875,533,8,0,0,2,true,false,false,true,true,true,41,7,true,0.009,0.0008,5190,2012,9,21,Wednesday,false,false,false,false,false,false,false
19695784,How can I make Bootstrap columns all the same height?,"I'm using Bootstrap. How can I make three columns all the same height?
Here is a screenshot of the problem. I would like the blue and red columns to be the same height as the yellow column.
![]()
Here is the code:
<link href=""https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"" rel=""stylesheet""/>
<div class=""container-fluid"">
<div class=""row"">
<div class=""col-xs-4 panel"" style=""background-color: red"">
some content
</div>
<div class=""col-xs-4 panel"" style=""background-color: yellow"">
catz
<img width=""100"" height=""100"" src=""https://lorempixel.com/100/100/cats/"">
</div>
<div class=""col-xs-4 panel"" style=""background-color: blue"">
some more content
</div>
</div>
</div>
",https://stackoverflow.com/questions/19695784/how-can-i-make-bootstrap-columns-all-the-same-height,1145,1329701.0,35.0,,,2013-10-30 23:31:37,2024-01-27 19:49:51,2017-06-23 21:36:07,,,css;twitter-bootstrap,Richard,66258,194000,registered,true,19695851,,CC BY-SA 3.0,2017-03-15 20:44:35,1220,843,1,0,1,2,true,false,false,true,true,true,53,10,true,0.026,0.0009,4770,2013,10,23,Wednesday,false,false,false,false,false,false,false
32551291,"In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?","Consider the main axis and cross axis of a flex container:
Source: W3C
To align flex items along the main axis there is one property:
To align flex items along the cross axis there are three properties:
In the image above, the main axis is horizontal and the cross axis is vertical. These are the default directions of a flex container.
However, these directions can be easily interchanged with the flex-direction property.
/* main axis is horizontal, cross axis is vertical */
flex-direction: row;
flex-direction: row-reverse;
/* main axis is vertical, cross axis is horizontal */
flex-direction: column;
flex-direction: column-reverse;
(The cross axis is always perpendicular to the main axis.)
My point in describing how the axes' work is that there doesn't seem to be anything special about either direction. Main axis, cross axis, they're both equal in terms of importance and flex-direction makes it easy to switch back and forth.
So why does the cross axis get two additional alignment properties?
Why are align-content and align-items consolidated into one property for the main axis?
Why does the main axis not get a justify-self property?
Scenarios where these properties would be useful:
placing a flex item in the corner of the flex container
#box3 { align-self: flex-end; justify-self: flex-end; }
making a group of flex items align-right (justify-content: flex-end) but have the first item align left (justify-self: flex-start)
Consider a header section with a group of nav items and a logo. With justify-self the logo could be aligned left while the nav items stay far right, and the whole thing adjusts smoothly ("flexes") to different screen sizes.
- in a row of three flex items, affix the middle item to the center of the container (
justify-content: center) and align the adjacent items to the container edges (justify-self: flex-start and justify-self: flex-end).
Note that values space-around and space-between on
justify-content property will not keep the middle item centered about the container if the adjacent items have different widths.
#container {
display: flex;
justify-content: space-between;
background-color: lightyellow;
}
.box {
height: 50px;
width: 75px;
background-color: springgreen;
}
.box1 {
width: 100px;
}
.box3 {
width: 200px;
}
#center {
text-align: center;
margin-bottom: 5px;
}
#center > span {
background-color: aqua;
padding: 2px;
}
<div id=""center"">
<span>TRUE CENTER</span>
</div>
<div id=""container"">
<div class=""box box1""></div>
<div class=""box box2""></div>
<div class=""box box3""></div>
</div>
<p>note that the middlebox will only be truly centered if adjacent boxes are equal width</p>
As of this writing, there is no mention of justify-self or justify-items in the flexbox spec.
However, in the CSS Box Alignment Module, which is the W3C's unfinished proposal to establish a common set of alignment properties for use across all box models, there is this:
Source: W3C
You'll notice that justify-self and justify-items are being considered... but not for flexbox.
",https://stackoverflow.com/questions/32551291/in-css-flexbox-why-are-there-no-justify-items-and-justify-self-properties,1136,463024.0,5.0,,,2015-09-13 15:30:27,2025-10-12 17:11:27,2025-10-12 17:11:27,,,css;flexbox;language-lawyer,Michael Benjamin,376909,3597276,registered,true,33856609,,CC BY-SA 4.0,,5588,3390,26,12,2,3,true,false,false,true,true,true,99,11,true,0.011,0.0025,4087,2015,9,15,Sunday,true,false,false,false,false,false,false
5135019,"CSS opacity only to background color, not the text on it?","Can I assign the opacity property to the background property of a div only and not to the text on it?
I've tried:
background: #CCC;
opacity: 0.6;
but this doesn't change the opacity.
",https://stackoverflow.com/questions/5135019/css-opacity-only-to-background-color-not-the-text-on-it,1021,2465210.0,11.0,,,2011-02-27 18:30:06,2021-06-16 02:49:50,2019-03-30 21:44:35,2014-12-21 07:42:29,Duplicate,css;opacity,Jay,11219,625072,registered,true,5135033,,,2014-10-24 11:22:00,271,187,4,0,0,2,true,true,false,true,true,true,57,11,true,0.004,0.0004,5746,2011,2,18,Sunday,true,false,false,false,false,false,false
3922739,Limit text length to n lines using CSS,"Is it possible to limit a text length to ""n"" lines using CSS (or cut it when overflows vertically).
text-overflow: ellipsis; only works for 1 line text.
original text:
Ultrices natoque mus mattis, aliquam, cras in pellentesque
tincidunt elit purus lectus, vel ut aliquet, elementum nunc
nunc rhoncus placerat urna! Sit est sed! Ut penatibus turpis
mus tincidunt! Dapibus sed aenean, magna sagittis, lorem velit
wanted output (2 lines):
Ultrices natoque mus mattis, aliquam, cras in pellentesque
tincidunt elit purus lectus, vel ut aliquet, elementum...
",https://stackoverflow.com/questions/3922739/limit-text-length-to-n-lines-using-css,1020,1422978.0,21.0,,,2010-10-13 10:32:35,2024-01-16 03:16:53,2014-04-28 18:53:28,,,css;text;overflow;ellipsis,Peter,5156,175975,registered,true,,,CC BY-SA 3.0,2014-07-03 06:01:28,697,576,1,0,0,4,false,false,false,true,true,true,38,8,false,0.015,0.0007,5883,2010,10,10,Wednesday,false,false,false,false,false,false,false
4515124,See :hover state in Chrome Developer Tools,"I want to see the :hover style for an anchor I'm hovering on in Chrome. In Firebug, there's a style dropdown that allows me to select different states for an element.
I can't seem to find anything similar in Chrome. Am I missing something?
",https://stackoverflow.com/questions/4515124/see-hover-state-in-chrome-developer-tools,988,423771.0,17.0,,,2010-12-23 01:16:54,2024-07-01 19:09:52,2023-09-14 14:55:17,,,css;google-chrome;browser;hover;google-chrome-devtools,Ben,13938,367641,registered,true,6778547,,CC BY-SA 4.0,,332,246,1,0,0,5,true,false,false,true,true,true,42,7,false,0.04,0.0023,5812,2010,12,1,Thursday,false,false,false,false,false,false,false
12991351,How to force image resize and keep aspect ratio?,"I am working with images, and I ran into a problem with aspect ratios.
<img src="big_image.jpg" width="900" height="600" alt="" />
As you can see, height and width are already specified. I added a CSS rule for images:
img {
max-width: 500px;
}
But for big_image.jpg, I receive width=500 and height=600. How do I set images to be re-sized, whilst keeping their aspect ratios.
",https://stackoverflow.com/questions/12991351/how-to-force-image-resize-and-keep-aspect-ratio,975,1900366.0,25.0,,,2012-10-20 18:20:13,2023-11-21 23:20:06,2023-11-21 23:20:06,,,css;image;aspect-ratio,moonvader,21301,1218405,registered,true,17183996,,CC BY-SA 4.0,2018-04-10 23:37:56,638,427,7,0,0,3,true,false,false,true,true,true,48,9,true,0.013,0.0005,5145,2012,10,18,Saturday,true,false,false,false,false,false,false
9271276,Should CSS always precede JavaScript?,"In countless places online I have seen the recommendation to include CSS prior to JavaScript. The reasoning is generally, of this form:
When it comes to ordering your CSS and JavaScript, you want your CSS
to come first. The reason is that the rendering thread has all the
style information it needs to render the page. If the JavaScript
includes come first, the JavaScript engine has to parse it all before
continuing on to the next set of resources. This means the rendering
thread can't completely show the page, since it doesn't have all the
styles it needs.
My actual testing reveals something quite different:
My test harness
I use the following Ruby script to generate specific delays for various resources:
require 'rubygems'
require 'eventmachine'
require 'evma_httpserver'
require 'date'
class Handler < EventMachine::Connection
include EventMachine::HttpServer
def process_http_request
resp = EventMachine::DelegatedHttpResponse.new( self )
return unless @http_query_string
path = @http_path_info
array = @http_query_string.split("&").map{|s| s.split("=")}.flatten
parsed = Hash[*array]
delay = parsed["delay"].to_i / 1000.0
jsdelay = parsed["jsdelay"].to_i
delay = 5 if (delay > 5)
jsdelay = 5000 if (jsdelay > 5000)
delay = 0 if (delay < 0)
jsdelay = 0 if (jsdelay < 0)
# Block which fulfills the request
operation = proc do
sleep delay
if path.match(/.js$/)
resp.status = 200
resp.headers["Content-Type"] = "text/javascript"
resp.content = "(function(){
var start = new Date();
while(new Date() - start < #{jsdelay}){}
})();"
end
if path.match(/.css$/)
resp.status = 200
resp.headers["Content-Type"] = "text/css"
resp.content = "body {font-size: 50px;}"
end
end
# Callback block to execute once the request is fulfilled
callback = proc do |res|
resp.send_response
end
# Let the thread pool (20 Ruby threads) handle request
EM.defer(operation, callback)
end
end
EventMachine::run {
EventMachine::start_server("0.0.0.0", 8081, Handler)
puts "Listening..."
}
The above mini server allows me to set arbitrary delays for JavaScript files (both server and client) and arbitrary CSS delays. For example, http://10.0.0.50:8081/test.css?delay=500 gives me a 500 ms delay transferring the CSS.
I use the following page to test.
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script type='text/javascript'>
var startTime = new Date();
</script>
<link href="http://10.0.0.50:8081/test.css?delay=500" type="text/css" rel="stylesheet">
<script type="text/javascript" src="http://10.0.0.50:8081/test2.js?delay=400&jsdelay=1000"></script>
</head>
<body>
<p>
Elapsed time is:
<script type='text/javascript'>
document.write(new Date() - startTime);
</script>
</p>
</body>
</html>
When I include the CSS first, the page takes 1.5 seconds to render:
![]()
When I include the JavaScript first, the page takes 1.4 seconds to render:
![]()
I get similar results in Chrome, Firefox and Internet Explorer. In Opera, however, the ordering simply does not matter.
What appears to be happening is that the JavaScript interpreter refuses to start until all the CSS is downloaded. So, it seems that having JavaScript includes first is more efficient as the JavaScript thread gets more run time.
Am I missing something? Is the recommendation to place CSS includes prior to JavaScript includes not correct?
It is clear that we could add async or use setTimeout to free up the render thread or put the JavaScript code in the footer, or use a JavaScript loader. The point here is about ordering of essential JavaScript bits and CSS bits in the head.
",https://stackoverflow.com/questions/9271276/should-css-always-precede-javascript,973,125930.0,14.0,,,2012-02-14 03:24:54,2022-09-03 19:31:57,2022-09-03 17:23:50,,,javascript;css;performance,Sam Saffron,131862,17174,registered,true,9272730,,CC BY-SA 4.0,2014-10-11 22:50:45,4772,4136,3,3,2,3,true,false,false,true,true,true,37,5,true,0.111,0.0077,5394,2012,2,3,Tuesday,false,false,true,false,false,false,false
20340138,Remove blue border from css custom-styled button in Chrome,"I'm working on a web page, and I want custom-styled <button> tags. So with CSS, I said: border: none. Now it works perfectly in safari, but in chrome, when I click one of the buttons, it puts an annoying blue border around it. I thought button:active { outline: none } or button:focus { outline:none } would work, but neither do. Any ideas?
This is what it looks like before being clicked (and how I want it to still look after being clicked):
![]()
And this is the border I'm talking about:
![]()
Here is my CSS:
button.launch {
background-color: #F9A300;
border: none;
height: 40px;
padding: 5px 15px;
color: #ffffff;
font-size: 16px;
font-weight: 300;
margin-top: 10px;
margin-right: 10px;
}
button.launch:hover {
cursor: pointer;
background-color: #FABD44;
}
button.change {
background-color: #F88F00;
border: none;
height: 40px;
padding: 5px 15px;
color: #ffffff;
font-size: 16px;
font-weight: 300;
margin-top: 10px;
margin-right: 10px;
}
button.change:hover {
cursor: pointer;
background-color: #F89900;
}
button:active {
outline: none;
border: none;
}
",https://stackoverflow.com/questions/20340138/remove-blue-border-from-css-custom-styled-button-in-chrome,963,1132784.0,25.0,,,2013-12-02 23:45:23,2023-05-25 00:07:04,2018-11-01 08:39:22,,,css;google-chrome,eshellborn,11291,1819891,registered,true,21758143,,CC BY-SA 4.0,,1409,1163,5,0,2,2,true,false,false,true,true,true,58,9,false,0.022,0.0009,4737,2013,12,23,Monday,false,false,false,false,false,false,false
4036857,How can I remove a style added with .css() function?,"I'm changing CSS with jQuery and I wish to remove the styling I'm adding based on the input value:
if(color != '000000') $(""body"").css(""background-color"", color); else // remove style ?
How can I do this?
Note that the line above runs whenever a color is selected using a color picker (ie. when the mouse moves over a color wheel).
2nd note: I can't do this with css(""background-color"", ""none"") because it will remove the default styling from the CSS files.
I just want to remove the background-color inline style added by jQuery.
",https://stackoverflow.com/questions/4036857/how-can-i-remove-a-style-added-with-css-function,962,1183128.0,21.0,,,2010-10-27 19:21:10,2020-08-24 20:57:26,2020-08-24 20:57:26,,,javascript;jquery;css,Alex,66826,376947,registered,true,4036868,,CC BY-SA 4.0,2013-12-17 17:25:02,713,541,3,0,0,3,true,false,false,true,true,true,52,10,true,0.018,0.0008,5869,2010,10,19,Wednesday,false,false,true,false,false,false,false
1065435,Can a CSS class inherit one or more other classes?,"Is it possible to make a CSS class that "inherits" from another CSS class (or more than one).
For example, say we had:
.something { display:inline }
.else { background:red }
What I'd like to do is something like this:
.composite
{
.something;
.else
}
where the ".composite" class would both display inline and have a red background
",https://stackoverflow.com/questions/1065435/can-a-css-class-inherit-one-or-more-other-classes,955,958477.0,29.0,,,2009-06-30 19:10:57,2023-10-27 02:33:13,2021-08-09 02:48:25,,,css,Joel Martinez,47844,5416,registered,true,1065476,,CC BY-SA 4.0,,518,366,2,0,0,1,true,false,false,true,true,true,50,10,true,0.03,0.001,6353,2009,6,19,Tuesday,false,false,false,false,false,false,false
1150163,Stretch and scale a CSS image in the background - with CSS only,"I want that my background image stretch and scale depending on the browser viewport size.
I've seen some questions on Stack Overflow that do the job, like Stretch and scale CSS background for example. It works well, but I want to place the image using background, not with an img tag.
In that one an img tag is placed, and then with CSS we tribute to the img tag.
width:100%; height:100%;
It works, but that question is a bit old, and states that in CSS 3 resizing a background image will work pretty well. I've tried this example the first one, but it didn't work out for me.
Is there a good method to do it with the background-image declaration?
",https://stackoverflow.com/questions/1150163/stretch-and-scale-a-css-image-in-the-background-with-css-only,945,1949620.0,23.0,,,2009-07-19 15:51:52,2026-04-05 20:42:00,2017-05-23 12:26:37,,,css;background,Fábio Antunes,17274,114298,registered,true,7372377,,CC BY-SA 3.0,2011-10-26 02:09:29,998,659,6,2,0,2,true,false,false,true,true,true,63,13,false,0.012,0.0005,6334,2009,7,15,Sunday,true,false,false,false,false,false,false
15381172,How can I make Flexbox children 100% height of their parent?,"I'm trying to fill the vertical space of a flex item inside a Flexbox.
.container {
height: 200px;
width: 500px;
display: flex;
flex-direction: row;
}
.flex-1 {
width: 100px;
background-color: blue;
}
.flex-2 {
position: relative;
flex: 1;
background-color: red;
}
.flex-2-child {
height: 100%;
width: 100%;
background-color: green;
}
<div class=""container"">
<div class=""flex-1""></div>
<div class=""flex-2"">
<div class=""flex-2-child""></div>
</div>
</div>
And here's the JSFiddle
flex-2-child doesn't fill the required height except in the two cases where:
flex-2 has a height of 100% (which is weird because a flex item has a 100% by default + it is buggy in Chrome)
flex-2-child has a position absolute which is also inconvenient
This doesn't work in Chrome or Firefox currently.
",https://stackoverflow.com/questions/15381172/how-can-i-make-flexbox-children-100-height-of-their-parent,941,1691209.0,15.0,,,2013-03-13 09:19:00,2026-08-10 10:23:11,2020-04-01 01:25:04,,,css;flexbox,Raz,9921,542642,registered,true,32466333,,CC BY-SA 4.0,2020-04-06 13:23:12,1355,904,5,1,0,2,true,false,false,true,true,true,60,11,true,0.009,0.0006,5001,2013,3,9,Wednesday,false,false,false,false,false,false,false
1520429,Is there a CSS selector for elements containing certain text?,"I am looking for a CSS selector for the following <table>:
Name
Identity
Age
Peter
male
34
Susanne
female
12
Is there any selector to match all <td>s containing the specific content "male"?
",https://stackoverflow.com/questions/1520429/is-there-a-css-selector-for-elements-containing-certain-text,940,1564090.0,22.0,,,2009-10-05 14:26:09,2024-12-21 03:49:57,2024-05-17 14:21:58,,,css;css-selectors,jantimon,38598,159319,registered,true,1520469,,CC BY-SA 4.0,2016-05-11 12:55:48,470,224,2,0,0,2,true,false,false,true,true,true,61,10,true,0.014,0.0006,6256,2009,10,14,Monday,false,false,false,false,false,false,false
485827,CSS 100% height with padding/margin,"With HTML/CSS, how can I make an element that has a width and/or height that is 100% of its parent element and still has proper padding or margins?
By "proper" I mean that if my parent element is 200px tall and I specify height = 100% with padding = 5px I would expect that I should get a 190px high element with border = 5px on all sides, nicely centered in the parent element.
Now, I know that that's not how the standard box model specifies it should work (although I'd like to know why, exactly...), so the obvious answer doesn't work:
#myDiv {
width: 100%
height: 100%;
padding: 5px;
}
But it would seem to me that there must be SOME way of reliably producing this effect for a parent of arbitrary size. Does anyone know of a way of accomplishing this (seemingly simple) task?
Oh, and for the record I'm not interested in IE compatibility so that should (hopefully) make things a bit easier.
EDIT: Since an example was asked for, here's the simplest one I can think of:
<html style="height: 100%">
<body style="height: 100%">
<div style="background-color: black; height: 100%; padding: 25px"></div>
</body>
</html>
The challenge is then to get the black box to show up with a 25-pixel padding on all edges without the page growing big enough to require scrollbars.
",https://stackoverflow.com/questions/485827/css-100-height-with-padding-margin,897,430360.0,15.0,,,2009-01-27 23:28:18,2024-03-25 09:55:57,2024-03-25 09:55:57,,,css,Toji,34628,25968,registered,true,485887,,CC BY-SA 4.0,2014-05-03 00:44:11,1632,1376,7,0,0,1,true,false,false,true,true,true,35,5,false,0.035,0.0021,6507,2009,1,23,Tuesday,false,false,false,false,false,false,false
211383,What methods of ‘clearfix’ can I use?,"I have the age-old problem of a div wrapping a two-column layout. My sidebar is floated, so my container div fails to wrap the content and sidebar.
<div id=""container"">
<div id=""content""></div>
<div id=""sidebar""></div>
</div>
There seem to be numerous methods of fixing the clear bug in Firefox:
<br clear=""all""/>
overflow:auto
overflow:hidden
In my situation, the only one that seems to work correctly is the <br clear=""all""/> solution, which is a little bit scruffy. overflow:auto gives me nasty scrollbars, and overflow:hidden must surely have side effects.
Also, IE7 apparently shouldn't suffer from this problem due to its incorrect behaviour, but in my situation it's suffering the same as Firefox.
Which method currently available to us is the most robust?
",https://stackoverflow.com/questions/211383/what-methods-of-clearfix-can-i-use,897,499627.0,29.0,,,2008-10-17 08:15:36,2021-12-19 10:29:55,2017-03-22 12:03:03,,,css;clearfix,Chris J Allen,19307,26107,registered,true,1633170,,CC BY-SA 3.0,2013-03-15 17:34:23,1055,824,9,0,0,2,true,false,false,true,true,true,37,7,true,0.058,0.0018,6609,2008,10,8,Friday,false,false,false,false,false,false,false
147500,Is it possible to include one CSS file in another?,"Is it possible to include one CSS file in another?
",https://stackoverflow.com/questions/147500/is-it-possible-to-include-one-css-file-in-another,895,610057.0,17.0,,,2008-09-29 04:23:10,2019-08-22 13:19:05,2013-10-20 19:26:05,,,css,Gaizka Allende,9487,460927,registered,true,147508,,CC BY-SA 3.0,2014-10-11 23:07:49,58,51,0,0,0,1,true,false,false,true,true,true,50,10,true,0.028,0.0015,6627,2008,9,4,Monday,false,false,false,false,false,false,false
609517,Why em instead of px?,"I heard you should define sizes and distances in your stylesheet with em instead of in pixels. So the question is why should I use em instead of px when defining styles in CSS? Is there a good example that illustrates this?
",https://stackoverflow.com/questions/609517/why-em-instead-of-px,871,480219.0,15.0,,,2009-03-04 07:08:11,2022-08-23 23:56:16,2022-08-09 21:07:39,,,css;font-size,Spoike,122358,3713,registered,true,657632,,CC BY-SA 4.0,2014-10-11 23:20:08,270,224,3,0,0,2,true,false,false,true,true,true,21,5,true,0.031,0.0018,6471,2009,3,7,Wednesday,false,false,false,false,false,false,false
5684160,Can the :not() pseudo-class have multiple arguments?,"I'm trying to select input elements of all types except radio and checkbox.
Many people have shown that you can put multiple arguments in :not, but using type doesn't seem to work anyway I try it.
form input:not([type=""radio""], [type=""checkbox""]) {
/* css here */
}
Any ideas?
",https://stackoverflow.com/questions/5684160/can-the-not-pseudo-class-have-multiple-arguments,868,357152.0,5.0,,,2011-04-16 02:43:33,2023-08-29 08:56:25,2017-08-26 10:35:39,,,css;css-selectors,delphi,11273,570489,registered,true,5684168,,CC BY-SA 3.0,,444,283,7,0,0,2,true,false,false,true,true,true,52,7,true,0.014,0.0024,5698,2011,4,2,Saturday,true,false,false,false,false,false,false
5110249,wildcard * in CSS for classes,"I have these divs that I'm styling with .tocolor, but I also need the unique identifier 1,2,3,4 etc. so I'm adding that it as another class tocolor-1.
<div class=""tocolor tocolor-1""> tocolor 1 </div>
<div class=""tocolor tocolor-2""> tocolor 2 </div>
<div class=""tocolor tocolor-3""> tocolor 3 </div>
<div class=""tocolor tocolor-4""> tocolor 4 </div>
.tocolor{
background: red;
}
Is there a way to have just 1 class tocolor-*. I tried using a wildcard * as in this css, but it didn't work.
.tocolor-*{
background: red;
}
",https://stackoverflow.com/questions/5110249/wildcard-in-css-for-classes,865,731390.0,4.0,,,2011-02-24 20:46:11,2020-11-30 12:54:46,2013-08-01 13:14:41,,,css;css-selectors;wildcard,twitter,9405,629665,registered,true,5110337,,CC BY-SA 3.0,2014-09-13 16:37:24,706,592,6,0,0,3,true,false,false,true,true,true,29,6,false,0.005,0.0012,5749,2011,2,20,Thursday,false,false,false,false,false,false,false
6794000,Fixed position but relative to container,"I am trying to fix a div so it always sticks to the top of the screen, using:
position: fixed;
top: 0px;
right: 0px;
However, the div is inside a centered container. When I use position:fixed it fixes the div relative to the browser window, such as it's up against the right side of the browser. Instead, it should be fixed relative to the container.
I know that position:absolute can be used to fix an element relative to the div, but when you scroll down the page the element vanishes and doesn't stick to the top as with position:fixed.
Is there a hack or workaround to achieve this?
",https://stackoverflow.com/questions/6794000/fixed-position-but-relative-to-container,863,1471838.0,33.0,,,2011-07-22 17:47:00,2026-11-16 19:35:36,2026-11-16 19:35:36,,,css;position;css-position,Zach Nicodemous,9597,628770,registered,true,6794097,,CC BY-SA 4.0,2014-02-04 13:56:43,735,592,8,0,0,3,true,false,false,true,true,true,40,6,false,0.022,0.0006,5601,2011,7,17,Friday,false,false,false,false,false,false,false
10765755,How to apply multiple transforms in CSS?,"Using CSS, how can I apply more than one transform?
Example: In the following, only the translation is applied, not the rotation.
li:nth-child(2) {
transform: rotate(15deg);
transform: translate(-20px,0px);
}
",https://stackoverflow.com/questions/10765755/how-to-apply-multiple-transforms-in-css,856,821143.0,9.0,,,2012-05-26 11:15:52,2024-01-15 09:33:35,2020-05-03 23:33:28,,,css;css-transforms,Ben,16843,795016,registered,true,10765771,,CC BY-SA 4.0,,279,228,2,0,0,2,true,false,false,true,true,true,40,7,true,0.011,0.001,5292,2012,5,11,Saturday,true,false,false,false,false,false,false
24933430,img src SVG changing the styles with CSS,"html
<img src=""logo.svg"" alt=""Logo"" class=""logo-img"">
css
.logo-img path {
fill: #000;
}
The above svg loads and is natively fill: #fff but when I use the above css to try change it to black it doesn't change, this is my first time playing with SVG and I am not sure why it's not working.
",https://stackoverflow.com/questions/24933430/img-src-svg-changing-the-styles-with-css,821,1384579.0,29.0,,,2014-07-24 12:15:31,2025-06-11 11:12:36,2019-10-17 17:46:28,,,css;image;svg,ngplayground,21845,1152045,registered,true,,,CC BY-SA 4.0,2020-08-28 23:59:25,432,303,4,0,0,3,false,false,false,true,true,true,40,8,false,0.021,0.0006,4503,2014,7,12,Thursday,false,false,false,false,false,false,false
1457849,How to remove the border highlight on an input text element,"When an HTML element is 'focused' (currently selected/tabbed into), many browsers (at least Safari and Chrome) will put a blue border around it.
For the layout I am working on, this is distracting and does not look right.
<input type=""text"" name=""user"" class=""middle"" id=""user"" tabindex=""1"" />
Firefox does not seem to do this, or at least, will let me control it with:
border: x;
If someone can tell me how IE performs, I would be curious.
Getting Safari to remove this little bit of flare would be nice.
",https://stackoverflow.com/questions/1457849/how-to-remove-the-border-highlight-on-an-input-text-element,817,974623.0,24.0,,,2009-09-22 02:22:23,2024-11-14 23:14:59,2019-03-08 23:16:48,,,css;input;safari;webkit;border,user170579,8580,170579,registered,true,1457976,,CC BY-SA 4.0,2016-02-08 17:20:28,604,521,2,0,0,5,true,false,false,true,true,true,59,11,false,0.025,0.0008,6269,2009,9,2,Tuesday,false,false,false,false,false,false,false
1139763,What does the "+" (plus sign) CSS selector mean?,"For example:
p + p {
/* Some declarations */
}
I don't know what the + means. What's the difference between this and just defining a style for p without + p?
",https://stackoverflow.com/questions/1139763/what-does-the-plus-sign-css-selector-mean,813,403971.0,9.0,,,2009-07-16 19:26:50,2026-06-26 06:58:41,2014-11-28 17:25:05,,,css;css-selectors,gday,8281,139093,registered,true,1139776,,CC BY-SA 3.0,2022-03-28 06:42:20,240,163,4,0,0,2,true,false,false,true,true,true,58,9,true,0.022,0.002,6337,2009,7,19,Thursday,false,false,false,false,false,false,false
9249359,Vertically align text within a div,"The code below (also available as a demo on JS Fiddle) does not position the text in the middle, as I ideally would like it to. I cannot find any way to vertically centre text in a div, even using the margin-top attribute. How can I do this?
<div id="column-content">
<img src="https://i.sstatic.net/12qzO.png">
<strong>1234</strong>
yet another text content that should be centered vertically
</div>
#column-content {
display: inline-block;
border: 1px solid red;
position:relative;
}
#column-content strong {
color: #592102;
font-size: 18px;
}
img {
margin-top:-7px;
vertical-align: middle;
}
",https://stackoverflow.com/questions/9249359/vertically-align-text-within-a-div,807,1835976.0,10.0,,,2012-02-12 14:00:48,2023-05-07 22:36:09,2020-06-26 09:16:59,2014-05-17 13:16:24,Duplicate,css;vertical-alignment,Cyclone,15429,989749,registered,true,14850381,,,2014-01-20 09:46:50,844,703,4,1,0,2,true,true,false,true,true,true,34,6,false,0.005,0.0004,5396,2012,2,14,Sunday,true,false,false,false,false,false,false
14007655,Remove IE10's "clear field" X button on certain inputs?,"It's a useful feature, to be sure, but is there any way to disable it?
For instance, if the form is a single text field and already has a ""clear"" button beside it, it's superfluous to also have the X. In this situation, it would be better to remove it.
Can it be done, and if so, how?
",https://stackoverflow.com/questions/14007655/remove-ie10s-clear-field-x-button-on-certain-inputs,775,329946.0,6.0,,,2012-12-23 00:07:48,2020-05-04 15:40:28,2020-04-19 17:48:13,,,css;internet-explorer-10,Niet the Dark Absol,325914,507674,registered,true,14007839,,CC BY-SA 4.0,2014-01-29 19:24:48,304,286,0,0,0,2,true,false,false,true,true,true,69,9,true,0.018,0.0023,5081,2012,12,0,Sunday,true,false,false,false,false,false,false
27539262,What's the difference between align-content and align-items?,"What is the difference between align-items and align-content?
",https://stackoverflow.com/questions/27539262/whats-the-difference-between-align-content-and-align-items,774,381847.0,15.0,,,2014-12-18 04:29:40,2025-07-03 02:00:25,2021-08-11 09:07:09,,,css;layout;flexbox;alignment,Dinh,7851,2652244,registered,true,,,CC BY-SA 4.0,2022-06-14 20:56:52,95,62,2,0,0,4,false,false,false,true,true,true,64,7,true,0.039,0.002,4356,2014,12,4,Thursday,false,false,false,false,false,false,false
17779293,CSS text-overflow: ellipsis; not working?,"I don't know why this simple CSS isn't working...
.app a {
height: 18px;
width: 140px;
padding: 0;
overflow: hidden;
position: relative;
margin: 0 5px 0 5px;
text-align: center;
text-decoration: none;
text-overflow: ellipsis;
white-space: nowrap;
color: #000;
}
<div class=""app"">
<a href="""">Test Test Test Test Test Test</a>
</div>
Should cut off around the 4th ""Test""
",https://stackoverflow.com/questions/17779293/css-text-overflow-ellipsis-not-working,773,998195.0,24.0,,,2013-07-22 03:01:43,2025-03-19 18:03:18,2019-01-07 21:26:58,,,overflow;ellipsis;css,ChristopherStrydom,8476,1850382,registered,true,17783233,,CC BY-SA 4.0,2022-12-30 14:51:34,756,444,2,0,0,3,true,false,false,true,true,true,41,5,true,0.024,0.0008,4870,2013,7,3,Monday,false,false,false,false,false,false,false
18529274,Change navbar color in Twitter Bootstrap,"How would I go about modifying the CSS to change the color of the navbar in Twitter Bootstrap?
",https://stackoverflow.com/questions/18529274/change-navbar-color-in-twitter-bootstrap,747,1260085.0,12.0,,,2013-08-30 09:19:10,2024-08-05 20:40:15,2021-07-08 19:37:12,,,css;twitter-bootstrap;bootstrap-4;navbar;bootstrap-5,Jamal Khan,9501,630267,registered,true,18529465,,CC BY-SA 4.0,2014-03-28 19:17:25,102,95,0,0,0,5,true,false,false,true,true,true,40,6,false,0.01,0.0006,4831,2013,8,9,Friday,false,false,false,false,false,false,false
952861,Targeting only Firefox with CSS,"Using conditional comments it is easy to target Internet Explorer with browser-specific CSS rules:
<!--[if IE 6]>
...include IE6-specific stylesheet here...
<![endif]-->
Sometimes it is the Gecko engine (Firefox) that misbehaves. What would be best way to target only Firefox with your CSS rules and not a single other browser? That is, not only should Internet Explorer ignore the Firefox-only rules, but also WebKit and Opera should.
Note: I'm looking for a 'clean' solution. Using a JavaScript browser sniffer to add a 'firefox' class to my HTML does not qualify as clean in my opinion. I would rather like to see something that depends on browser capabilities, much like conditional comments are only 'special' to IE…
",https://stackoverflow.com/questions/952861/targeting-only-firefox-with-css,745,708441.0,14.0,,,2009-06-04 20:19:09,2025-01-16 19:03:32,2022-10-03 15:43:23,,,css;firefox;browser-detection,avdgaag,42382,56430,registered,true,953491,,CC BY-SA 4.0,2013-12-10 19:43:31,817,738,1,0,0,3,true,false,false,true,true,true,31,5,false,0.02,0.0011,6379,2009,6,20,Thursday,false,false,false,false,false,false,false
6370690,"Media Queries: How to target desktop, tablet, and mobile?","I have been doing some research on media queries and I still don't quite understand how to target devices of certain sizes.
I want to be able to target desktop, tablet and mobile. I know that there will be some discrepancies but it would be nice to have a generic system that can be used to target these devices.
Some examples I have found:
# Mobile
only screen and (min-width: 480px)
# Tablet
only screen and (min-width: 768px)
# Desktop
only screen and (min-width: 992px)
# Huge
only screen and (min-width: 1280px)
Or:
# Phone
only screen and (max-width:320px)
# Tablet
only screen and (min-width:321px) and (max-width:768px)
# Desktop
only screen and (min-width:769px)
What should the breakpoints be for each device?
",https://stackoverflow.com/questions/6370690/media-queries-how-to-target-desktop-tablet-and-mobile,744,1821137.0,22.0,,,2011-06-16 10:57:10,2026-07-24 15:48:11,2020-03-30 15:48:05,,,css;mobile;media-queries;tablet,betamax,14141,239241,registered,true,7354648,,CC BY-SA 4.0,2015-03-27 14:48:54,820,737,2,0,0,4,true,false,false,true,true,true,57,9,true,0.012,0.0004,5637,2011,6,10,Thursday,false,false,false,false,false,false,false
10636667,Bootstrap modal appearing under background,"I have used the code for my modal straight from the Bootstrap example, and have included only the bootstrap.js (and not bootstrap-modal.js). However, my modal is appearing underneath the grey overlay (backdrop), making the modal not clickable.
Here's what it looks like:
![]()
See this fiddle for one way to reproduce this problem. The basic structure of that code is like this:
<body>
<p>Lorem ipsum dolor sit amet.</p>
<div class="my-module">
This container contains the modal code.
<div class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">Modal</div>
</div>
</div>
</div>
</div>
</body>
body {
padding-top: 50px;
}
.my-module {
position: fixed;
top: 0;
left: 0;
}
Any ideas why this is or what I can do to fix this?
",https://stackoverflow.com/questions/10636667/bootstrap-modal-appearing-under-background,737,614233.0,68.0,,,2012-05-17 13:27:00,2024-12-07 22:43:53,2024-12-06 14:27:47,,,javascript;css;twitter-bootstrap;modal-dialog,natlines,7766,1401092,registered,true,11788713,,CC BY-SA 4.0,2024-11-27 19:24:49,1348,1036,2,1,1,4,true,false,false,true,true,true,42,5,false,0.111,0.0012,5301,2012,5,13,Thursday,false,false,true,false,false,false,false
2789703,Remove blue underline from link,"I am attempting to have a link show up in white, without an underline. The text color shows up correctly as white, but the blue underline is stubbornly persisting. I tried text-decoration: none; and text-decoration: none !important; in the CSS to remove the link underline. Neither worked.
.boxhead .otherPage {
color: #FFFFFF;
text-decoration: none;
}
<div class=""boxhead"">
<h2>
<span class=""thisPage"">Current Page</span>
<a href=""myLink""><span class=""otherPage"">Different Page</span></a>
</h2>
</div>
How can I remove the blue underline from the link?
",https://stackoverflow.com/questions/2789703/remove-blue-underline-from-link,735,1489217.0,22.0,,,2010-05-07 15:29:21,2023-02-12 18:48:13,2021-06-20 22:15:04,,,css;hyperlink;underline,dmr,22531,174718,registered,true,2789864,,CC BY-SA 4.0,2014-05-18 06:38:13,990,652,4,0,0,3,true,false,false,true,true,true,31,5,false,0.015,0.0005,6042,2010,5,15,Friday,false,false,false,false,false,false,false
15901030,How to reset/remove CSS styles for a specific element or selector only,"Is there a CSS rule available that will remove any styles previously set in the stylesheet for a particular element?
A good use example might be in a mobile-first RWD site where much of the styling used for a particular element in the small-screen views needs 'resetting' or removing for the same element in the desktop view.
A CSS rule that could achieve something like:
.element {
all: none;
}
Example usage:
/* mobile first */
.element {
margin: 0 10;
transform: translate3d(0, 0, 0);
z-index: 50;
display: block;
etc..
etc..
}
@media only screen and (min-width: 980px) {
.element {
all: none;
}
}
So we could quickly remove or re-set styling without having to declare every property.
",https://stackoverflow.com/questions/15901030/how-to-reset-remove-css-styles-for-a-specific-element-or-selector-only,730,1558553.0,17.0,,,2013-04-09 11:49:16,2023-01-09 04:30:58,2023-01-06 14:44:01,,,css,matt_50,7685,841046,registered,true,15903168,,CC BY-SA 4.0,2023-01-06 14:42:22,802,719,2,0,0,1,true,false,false,true,true,true,70,12,false,0.011,0.0005,4974,2013,4,11,Tuesday,false,false,false,false,false,false,false
1485647,Removing multiple classes (jQuery),"Is there any better way to rewrite this:
$('element').removeClass('class1').removeClass('class2');
I cannot use removeClass(); as it would remove ALL classes, which I don't want.
",https://stackoverflow.com/questions/1485647/removing-multiple-classes-jquery,716,439651.0,8.0,,,2009-09-28 06:10:42,2022-12-20 13:44:00,2018-12-28 08:03:18,,,jquery;css,eozzy,69710,172637,registered,true,1485656,,CC BY-SA 4.0,,250,182,2,0,0,2,true,false,false,true,true,true,34,4,false,0.018,0.0016,6263,2009,9,6,Monday,false,false,false,false,false,false,false
643879,"CSS to make HTML page footer stay at bottom of the page with a minimum height, but not overlap the page","I have the following page (deadlink: http://www.workingstorage.com/Sample.htm ) that has a footer which I can't make sit at the bottom of the page.
I want the footer to
- stick to the window bottom when the page is short and the screen is not filled, and
- stay at the document end and move down as normal when there is more than a screenful of content (instead of overlapping the content).
The CSS is inherited and befuddles me. I can't seem to change it properly to put a minimum height on the content or make the footer go to the bottom.
",https://stackoverflow.com/questions/643879/css-to-make-html-page-footer-stay-at-bottom-of-the-page-with-a-minimum-height-b,708,1936120.0,37.0,,,2009-03-13 17:59:22,2024-04-16 10:08:59,2020-09-07 13:06:54,,,css;footer,Caveatrob,13465,335036,registered,true,689290,,CC BY-SA 4.0,2016-03-22 19:25:40,600,539,1,0,0,2,true,false,false,true,true,true,103,21,false,0.019,0.0004,6462,2009,3,17,Friday,false,false,false,false,false,false,false
40010597,How do I apply opacity to a CSS color variable?,"I have defined a color variable in vars.css:
:root {
--color: #f0f0f0;
}
I want to use this color in main.css, but with some opacity applied:
#element {
background: (somehow use var(--color) at some opacity);
}
How would I go about doing this?
I am not using any preprocessor, only CSS. I would prefer an all-CSS answer, but I will accept JavaScript/jQuery.
I cannot use opacity because I am using a background image that should not be transparent.
",https://stackoverflow.com/questions/40010597/how-do-i-apply-opacity-to-a-css-color-variable,708,505757.0,21.0,,,2016-10-13 00:51:12,2026-11-12 19:15:33,2025-08-19 14:32:27,,,css;colors;css-variables,jotch,7304,4730938,registered,true,41265350,,CC BY-SA 4.0,2023-07-11 06:04:11,652,456,5,0,0,3,true,false,false,true,true,true,47,10,true,0.042,0.0014,3691,2016,10,0,Thursday,false,false,false,false,false,false,false
9789723,CSS text-overflow in a table cell?,"I want to use CSS text-overflow in a table cell, such that if the text is too long to fit on one line, it will clip with an ellipsis instead of wrapping to multiple lines. Is this possible?
I tried this:
td {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
But the white-space: nowrap seems to make the text (and its cell) continually expand out to the right, pushing the total width of the table beyond the width of its container. Without it, however, the text continues to wrap to multiple lines when it hits the edge of the cell.
",https://stackoverflow.com/questions/9789723/css-text-overflow-in-a-table-cell,704,700323.0,15.0,,,2012-03-20 15:27:12,2024-01-08 21:11:32,2017-02-07 01:24:16,,,css;overflow,daGUY,29105,778581,registered,true,11877033,,CC BY-SA 3.0,2024-09-06 13:42:07,632,561,3,0,0,2,true,false,false,true,true,true,34,6,true,0.021,0.001,5359,2012,3,15,Tuesday,false,false,false,false,false,false,false
2253110,Managing CSS Explosion,"I have been heavily relying on CSS for a website that I am working on. Right now, all the CSS styles are being applied on a per tag basis, and so now I am trying to move it to more of an external styling to help with any future changes.
But now the problem is that I have noticed I am getting a ""CSS Explosion"". It is becoming difficult for me to decide how to best organize and abstract data within the CSS file.
I am using a large number of div tags within the website, moving from a heavily table-based website. So I'm getting a lot of CSS selectors that look like this:
div.title {
background-color: blue;
color: white;
text-align: center;
}
div.footer {
/* Styles Here */
}
div.body {
/* Styles Here */
}
/* And many more */
It's not too bad yet, but as I am a beginner, I was wondering if recommendations could be made on how best to organize the various parts of a CSS file. I don't want to have a separate CSS attribute for every element on my website, and I always want the CSS file to be fairly intuitive and easy to read.
My ultimate goal is to make it easy to use the CSS files and demonstrate their power to increase the speed of web development. This way, other individuals that may work on this site in the future will also get into the practice of using good coding practices, rather than having to pick it up the way I did.
",https://stackoverflow.com/questions/2253110/managing-css-explosion,696,50065.0,16.0,,,2010-02-12 16:03:34,2022-07-25 12:27:47,2017-01-10 00:14:42,2024-02-20 18:03:47,Opinion-based,css;organization,JasCav,34640,132528,registered,true,2253189,,,2013-07-31 21:17:29,1473,1363,2,0,0,2,true,true,false,true,true,true,22,3,false,0.32,0.0139,6126,2010,2,16,Friday,false,false,false,false,false,false,false
34521797,How to add multiple classes to a ReactJS Component?,"I am new to ReactJS and JSX and I am having a little problem with the code below.
I am trying to add multiple classes to the className attribute on each li:
<li key={index} className={activeClass, data.class, ""main-class""}></li>
My React component is:
var AccountMainMenu = React.createClass({
getInitialState: function() {
return { focused: 0 };
},
clicked: function(index) {
this.setState({ focused: index });
},
render: function() {
var self = this;
var accountMenuData = [
{
name: ""My Account"",
icon: ""icon-account""
},
{
name: ""Messages"",
icon: ""icon-message""
},
{
name: ""Settings"",
icon: ""icon-settings""
}
/*{
name:""Help & Support <span class='font-awesome icon-support'></span>(888) 664.6261"",
listClass:""no-mobile last help-support last""
}*/
];
return (
<div className=""acc-header-wrapper clearfix"">
<ul className=""acc-btns-container"">
{accountMenuData.map(function(data, index) {
var activeClass = """";
if (self.state.focused == index) {
activeClass = ""active"";
}
return (
<li
key={index}
className={activeClass}
onClick={self.clicked.bind(self, index)}
>
<a href=""#"" className={data.icon}>
{data.name}
</a>
</li>
);
})}
</ul>
</div>
);
}
});
ReactDOM.render(<AccountMainMenu />, document.getElementById(""app-container""));
",https://stackoverflow.com/questions/34521797/how-to-add-multiple-classes-to-a-reactjs-component,695,955398.0,40.0,,,2015-12-30 01:44:21,2023-11-30 02:57:11,2020-06-21 18:16:14,,,javascript;css;reactjs;ecmascript-6,Hector,7055,3953589,registered,true,34521945,,CC BY-SA 4.0,2021-02-07 20:41:34,1924,1752,4,0,0,4,true,false,false,true,true,true,51,9,true,0.042,0.0007,3979,2015,12,1,Wednesday,false,false,true,false,false,false,false
609273,Convert an image to grayscale in HTML/CSS,"Is there a simple way to display a color bitmap in grayscale with just HTML/CSS?
It doesn't need to be IE-compatible (and I imagine it won't be) -- if it works in FF3 and/or Sf3, that's good enough for me.
I know I can do it with both SVG and Canvas, but that seems like a lot of work right now.
Is there a truly lazy person's way to do this?
",https://stackoverflow.com/questions/609273/convert-an-image-to-grayscale-in-html-css,672,497602.0,25.0,,,2009-03-04 04:51:26,2021-04-19 12:48:14,2014-07-23 01:35:29,,,image;css;grayscale,Ken,7142,73105,unregistered,true,,,CC BY-SA 3.0,2013-03-31 12:16:59,402,348,2,0,0,3,false,false,false,true,true,true,41,7,false,0.05,0.0014,6471,2009,3,4,Wednesday,false,false,false,false,false,false,false
9670075,CSS transition shorthand with multiple properties?,"I can't seem to find the correct syntax for the CSS transition shorthand with multiple properties. This doesn't do anything:
.element {
-webkit-transition: height .5s, opacity .5s .5s;
-moz-transition: height .5s, opacity .5s .5s;
-ms-transition: height .5s, opacity .5s .5s;
transition: height .5s, opacity .5s .5s;
height: 0;
opacity: 0;
overflow: 0;
}
.element.show {
height: 200px;
opacity: 1;
}
I add the show class with javascript. The element becomes higher and visible, it just doesn't transition. Testing in latest Chrome, FF and Safari.
What am I doing wrong?
EDIT: Just to be clear, I'm looking for the shorthand version to scale my CSS down. It's bloated enough with all the vendor prefixes. Also expanded the example code.
",https://stackoverflow.com/questions/9670075/css-transition-shorthand-with-multiple-properties,671,594544.0,7.0,,,2012-03-12 15:37:40,2021-11-17 01:43:04,2013-10-01 04:30:55,,,css;webkit;css-transitions;shorthand,Gregory Bolkenstijn,10281,127550,registered,true,9670311,,CC BY-SA 3.0,,881,774,1,0,0,4,true,false,false,true,true,true,50,6,true,0.012,0.0011,5367,2012,3,15,Monday,false,false,false,false,false,false,false
12582624,What is a user agent stylesheet?,"I'm working on a web page in Google Chrome. It displays correctly with the following styles.
table {
display: table;
border-collapse: separate;
border-spacing: 2px;
border-color: gray;
}
It is important to note that I didn't define these styles. In Chrome developer tools, it says user agent stylesheet in place of the CSS file name.
Now if I submit a form and some validation error occurs, I get the following stylesheet:
table {
white-space: normal;
line-height: normal;
font-weight: normal;
font-size: medium;
font-variant: normal;
font-style: normal;
color: -webkit-text;
text-align: -webkit-auto;
}
table {
display: table;
border-collapse: separate;
border-spacing: 2px;
border-color: gray;
}
The font-size from these new styles is disturbing my design. Is there a way to force my stylesheets and if possible, completely overwrite Chrome's default stylesheet?
",https://stackoverflow.com/questions/12582624/what-is-a-user-agent-stylesheet,671,778884.0,10.0,,,2012-09-25 12:05:49,2026-07-04 19:48:05,2020-04-26 14:22:00,,,css;google-chrome,Kapil Sharma,10537,1295389,registered,true,55215684,,CC BY-SA 4.0,2024-05-29 19:18:05,1043,937,3,0,0,2,true,false,false,true,true,true,32,6,true,0.013,0.0009,5170,2012,9,12,Tuesday,false,false,false,false,false,false,false
8969381,What is the difference between display: inline and display: inline-block?,"What exactly is the difference between the inline and inline-block values of CSS display?
",https://stackoverflow.com/questions/8969381/what-is-the-difference-between-display-inline-and-display-inline-block,662,206346.0,7.0,,,2012-01-23 09:22:22,2022-01-28 20:44:09,2016-07-08 15:16:20,,,css;display,Logesh Paul,7700,148466,registered,true,14033814,,CC BY-SA 3.0,2016-06-22 12:15:53,136,90,3,0,0,2,true,false,false,true,true,true,73,10,true,0.034,0.0032,5416,2012,1,9,Monday,false,false,false,false,false,false,false
9189810,CSS display: inline vs inline-block,"In CSS, display can have values of inline and inline-block. Can anyone explain in detail the difference between inline and inline-block?
I searched everywhere, the most detailed explanation tells me inline-block is placed as inline, but behaves like block. But it does not explain what exactly ""behave as a block"" means. Is it any special feature?
An example would be an even better answer. Thanks.
",https://stackoverflow.com/questions/9189810/css-display-inline-vs-inline-block,659,607131.0,1.0,,,2012-02-08 08:24:15,2020-01-31 06:45:47,2017-05-23 12:34:51,2020-01-31 06:45:47,Duplicate,css,user926958,9675,926958,registered,true,9189873,,,,526,401,8,0,0,1,true,true,false,true,true,true,35,5,false,0.002,0.0011,5400,2012,2,8,Wednesday,false,false,false,false,false,false,false
26882177,React.js inline style best practices,"I'm aware that you can specify styles within React classes, like this:
const MyDiv = React.createClass({
render: function() {
const style = {
color: 'white',
fontSize: 200
};
return <div style={style}> Have a good and productive day! </div>;
}
});
Should I be aiming to do all styling this way, and have no styles at all specified in my CSS file?
Or should I avoid inline styles completely?
It seems odd and messy to do a little bit of both - two places would need to be checked when tweaking styling.
",https://stackoverflow.com/questions/26882177/react-js-inline-style-best-practices,659,1139893.0,20.0,,,2014-11-12 08:16:24,2026-09-18 18:25:59,2026-09-16 09:27:03,,,best-practices;css;reactjs;inline-styles,eye_mew,9193,1920325,registered,true,31638988,,CC BY-SA 4.0,2017-03-19 10:29:18,600,548,1,0,0,4,true,false,false,true,true,true,36,5,false,0.018,0.0006,4392,2014,11,8,Wednesday,false,false,false,false,false,false,false
15115052,How to set up fixed width for <td>?,"Simple scheme:
<tr class=""something"">
<td>A</td>
<td>B</td>
<td>C</td>
<td>D</td>
</tr>
I need to set up a fixed width for <td>. I've tried:
tr.something {
td {
width: 90px;
}
}
Also
td.something {
width: 90px;
}
for
<td class=""something"">B</td>
And even
<td style=""width: 90px;"">B</td>
But the width of <td> is still the same.
",https://stackoverflow.com/questions/15115052/how-to-set-up-fixed-width-for-td,654,1353528.0,25.0,,,2013-02-27 14:50:11,2025-07-21 13:18:42,2019-01-03 20:05:18,,,css;twitter-bootstrap;width;html-table,user984621,48903,984621,registered,true,18498071,,CC BY-SA 4.0,,658,470,7,0,0,4,true,false,false,true,true,true,41,8,true,0.018,0.0005,5015,2013,2,14,Wednesday,false,false,false,false,false,false,false
3772290,CSS Selector that applies to elements with two classes,"Is there a way to select an element with CSS based on the value of the class attribute being set to two specific classes. For example, let's say I have 3 divs:
<div class=""foo"">Hello Foo</div>
<div class=""foo bar"">Hello World</div>
<div class=""bar"">Hello Bar</div>
What CSS could I write to select ONLY the second element in the list, based on the fact that it is a member of both the foo AND bar classes?
",https://stackoverflow.com/questions/3772290/css-selector-that-applies-to-elements-with-two-classes,652,464890.0,3.0,,,2010-09-22 18:06:16,2024-11-08 17:03:44,2011-06-11 05:36:38,,,css;css-selectors,Adam,12750,362871,registered,true,3772305,,CC BY-SA 3.0,,522,445,1,0,0,2,true,false,false,true,true,true,54,9,false,0.006,0.0014,5904,2010,9,18,Wednesday,false,false,false,false,false,false,false
2922909,Should I use `border: none` or `border: 0`?,"Which of the two methods conforms to W3C standards? Do they both behave as expected across browsers?
border: none;
border: 0;
",https://stackoverflow.com/questions/2922909/should-i-use-border-none-or-border-0,650,572083.0,12.0,,,2010-05-27 16:25:24,2024-01-14 00:54:17,2024-01-14 00:53:37,,,css;border,John Himmelman,22100,194676,registered,true,2922923,,CC BY-SA 4.0,2020-05-16 14:16:51,198,129,1,0,0,2,true,false,false,true,true,true,43,8,true,0.021,0.0011,6022,2010,5,16,Thursday,false,false,false,false,false,false,false
17931571,Freeze screen in chrome debugger / DevTools panel for popover inspection?,"I'm using the chrome inspector to try and analyze the z-index of a twitter bootstrap popover, and finding it extremely frustrating...
Is there a way to freeze the popover (while shown) so that I can assess and modify the associated CSS?
Placing a fixed 'hover' on the associated link does not cause the popover to appear.
",https://stackoverflow.com/questions/17931571/freeze-screen-in-chrome-debugger-devtools-panel-for-popover-inspection,648,456698.0,16.0,,,2013-07-29 18:32:24,2025-07-23 15:56:37,2017-03-26 04:25:24,,,css;google-chrome;google-chrome-devtools,Abram,42605,881559,registered,true,17932238,,CC BY-SA 3.0,,360,326,1,0,0,3,true,false,false,true,true,true,73,11,true,0.035,0.0014,4863,2013,7,18,Monday,false,false,false,false,false,false,false
6887336,What is the difference between Normalize.css and Reset CSS?,"I know what CSS Reset is, but recently I heard about this new thing called Normalize.css
What is the difference between the Normalize.css and Reset CSS?
What is the difference between normalizing CSS and resetting CSS?
Is it just a new buzz word for the CSS Reset?
",https://stackoverflow.com/questions/6887336/what-is-the-difference-between-normalize-css-and-reset-css,635,262805.0,10.0,,,2011-07-31 03:17:53,2021-05-25 09:15:50,2021-05-19 02:39:25,,,css;normalize-css,Jitendra Vyas,154325,84201,registered,true,8357635,,CC BY-SA 4.0,,438,265,0,2,0,2,true,false,false,true,true,true,59,9,true,0.038,0.0024,5592,2011,7,3,Sunday,true,false,false,false,false,false,false
2005954,Center a position:fixed element,"I would like to make a position: fixed; popup box centered to the screen with a dynamic width and height. I used margin: 5% auto; for this. Without position: fixed; it centers fine horizontally, but not vertically. After adding position: fixed;, it's even not centering horizontally.
Here's the complete set:
.jqbox_innerhtml {
position: fixed;
width: 500px;
height: 200px;
margin: 5% auto;
padding: 10px;
border: 5px solid #ccc;
background-color: #fff;
}
<div class=""jqbox_innerhtml"">
This should be inside a horizontally
and vertically centered box.
</div>
How do I center this box in screen with CSS?
",https://stackoverflow.com/questions/2005954/center-a-positionfixed-element,630,945275.0,25.0,,,2010-01-05 12:29:00,2025-02-04 20:34:53,2015-12-29 18:54:04,,,css;css-position;centering,saturngod,25049,215939,registered,true,2006008,,CC BY-SA 3.0,2019-07-31 17:07:04,1049,677,6,0,0,3,true,false,false,true,true,true,31,4,false,0.026,0.0007,6164,2010,1,12,Tuesday,false,false,false,false,false,false,false
8549529,What is the difference between "screen" and "only screen" in media queries?,"What is the difference between screen and only screen in media queries?
<link media=""screen and (max-device-width: 480px)"" rel=""stylesheet"" href=""m.css"" />
<link media=""only screen and (max-device-width: 480px)"" rel=""stylesheet"" href=""m.css"" />
Why are we required to use only screen? Does screen not itself provide enough information to be rendered only for screen?
I've seen many responsive websites using any of these three different ways:
@media screen and (max-width:632px)
@media (max-width:632px)
@media only screen and (max-width:632px)
",https://stackoverflow.com/questions/8549529/what-is-the-difference-between-screen-and-only-screen-in-media-queries,629,509256.0,6.0,,,2011-12-18 02:56:33,2025-06-08 21:16:21,2019-04-16 22:39:13,,,css;media-queries,Jitendra Vyas,154325,84201,registered,true,,,CC BY-SA 4.0,,868,568,8,0,0,2,false,false,false,true,true,true,95,12,true,0.012,0.0012,5452,2011,12,2,Sunday,true,false,false,false,false,false,false
1625681,Dynamically change color to lighter or darker by percentage CSS,"We have a big application on the site and we have a few links which are, let's say blue color like the blue links on this site. Now I want to make some other links, but with lighter color. Obviously I can just do simply by the hex code adding in the CSS file, but our site lets user decide what colors they want for their customized profile/site (like Twitter).
So, my question is: can we reduce the color by percentage?
Let's say the following code is CSS:
a {
color: blue;
}
a.lighter {
color: -50%; /* obviously not correct way, but just an idea */
}
OR
a.lighter {
color: blue -50%; /* again not correct, but another example of setting color and then reducing it */
}
Is there a way to reduce a color by a percentage?
",https://stackoverflow.com/questions/1625681/dynamically-change-color-to-lighter-or-darker-by-percentage-css,628,1124178.0,31.0,,,2009-10-26 16:12:24,2025-08-20 17:46:33,2023-05-23 08:47:02,,,css;colors,Basit,17344,75799,registered,true,3280990,,CC BY-SA 4.0,,895,736,2,0,0,2,true,false,false,true,true,true,63,10,false,0.028,0.0006,6235,2009,10,16,Monday,false,false,false,false,false,false,false
19733447,"Bootstrap NavBar with left, center or right aligned items","In Bootstrap, what is the most platform-friendly way to create a navigation bar that has Logo A on the left, menu items in the center, and Logo B on the right?
Here is what I've tried so far, and it ends up being aligned so that Logo A is on the left, menu items next to the logo on the left and Logo B on the right.
<div class=""navbar navbar-fixed-top navbar-custom "">
<div class=""container"" >
<div class=""navbar-header"">
<button type=""button"" class=""navbar-toggle"" data-toggle=""collapse"" data-target="".navbar-collapse"">
<span class=""icon-bar""></span>
<span class=""icon-bar""></span>
<span class=""icon-bar""></span>
</button>
<a class=""navbar-brand"" href=""#""><span class=""navbar-logo"">Logo_A</span></a>
</div>
<div class=""collapse navbar-collapse"">
<ul class=""nav navbar-nav"">
<li class=""active""><a href=""#"">Home</a></li>
<li><a href=""#about"">Menu Item 1</a></li>
<li><a href=""#contact"">Menu Item 2</a></li>
<li><a href=""#about"">Menu Item 3</a></li>
</ul>
<ul class=""nav navbar-nav navbar-right"">
<li><a href=""#""><img src=""images/Logo_B.png"" class=""img-responsive""></a></li>
</ul>
</div>
</div>
</div>
",https://stackoverflow.com/questions/19733447/bootstrap-navbar-with-left-center-or-right-aligned-items,624,1605934.0,15.0,,,2013-11-01 18:54:20,2024-02-27 16:14:57,2022-03-01 20:11:51,,,css;twitter-bootstrap;navbar;web-frontend,Aliv,6265,2934431,registered,true,,,CC BY-SA 4.0,2019-11-06 17:09:03,1556,1501,1,0,0,4,false,false,false,true,true,true,57,9,false,0.009,0.0004,4768,2013,11,18,Friday,false,false,false,false,false,false,false
2570972,CSS Font Border?,"With all the new CSS3 border stuff going on (-webkit, ...) is it now possible to add a border to your font? (Like the solid white border around the blue Twitter logo). If not, are there any not-too-ugly hacks that will accomplish this in CSS/XHTML or do I still need to fire up Photoshop?
",https://stackoverflow.com/questions/2570972/css-font-border,614,1221621.0,13.0,,,2010-04-03 10:35:02,2024-08-05 18:47:17,2016-10-24 16:18:37,,,css;fonts,Lars Tackmann,21085,231211,registered,true,4269821,,CC BY-SA 3.0,2016-05-28 02:01:19,309,289,1,0,0,2,true,false,false,true,true,true,16,3,true,0.011,0.0005,6076,2010,4,10,Saturday,true,false,false,false,false,false,false
4459821,CSS '>' selector; what is it?,"I've seen the ""greater than"" (>) used in CSS code a few times, but I can't work out what it does. What does it do?
",https://stackoverflow.com/questions/4459821/css-selector-what-is-it,613,360859.0,7.0,,,2010-12-16 10:39:47,2020-02-02 13:36:11,2020-02-02 13:36:11,2020-02-02 13:32:29,Duplicate,css;css-selectors,Bojangles,101941,383609,registered,true,4459872,,,,138,118,1,0,0,2,true,true,false,true,true,true,40,6,true,0.019,0.0017,5819,2010,12,10,Thursday,false,false,false,false,false,false,false
11235206,Twitter Bootstrap Form File Element Upload Button,"Why isn't there a fancy file element upload button for twitter bootstrap? It would be sweet if the blue primary button was implemented for the upload button. Is it even possible to finesse the upload button using CSS? (seems like a native browser element that can't be manipulated)
",https://stackoverflow.com/questions/11235206/twitter-bootstrap-form-file-element-upload-button,612,885226.0,27.0,,,2012-06-27 21:41:56,2023-11-08 16:06:39,2018-03-02 17:28:59,,,css;forms;twitter-bootstrap;input-type-file,somejkuser,9062,135605,registered,true,18164555,,CC BY-SA 3.0,2015-11-05 08:00:38,290,283,0,0,0,4,true,false,false,true,true,true,49,7,false,0.031,0.0007,5260,2012,6,21,Wednesday,false,false,false,false,false,false,false
22207377,Disable click outside of bootstrap modal area to close modal,"I am making a bootstrap website, with a couple of Bootstrap 'Modals'.
I'm trying to customize some of the default features.
Problem is this;
You can close the modal by clicking on the background.
Is there anyway to disable this feature?
On specifc modals only?
",https://stackoverflow.com/questions/22207377/disable-click-outside-of-bootstrap-modal-area-to-close-modal,609,1105605.0,24.0,,,2014-03-05 19:31:12,2022-08-15 11:24:57,2017-08-01 13:33:04,2021-04-07 12:12:12,Duplicate,javascript;css;twitter-bootstrap;modal-dialog,Egghead,7075,2853734,registered,true,22208662,,,2021-04-07 11:56:20,379,284,0,1,0,4,true,true,false,true,true,true,60,10,false,0.022,0.0006,4644,2014,3,19,Wednesday,false,false,true,false,false,false,false
9280258,Prevent body scrolling but allow overlay scrolling,"I've been searching for a ""lightbox"" type solution that allows this but haven't found one yet (please, suggest if you know of any).
The behavior I'm trying to recreate is just like what you'd see at Pinterest when clicking on an image. The overlay is scrollable (as in the whole overlay moves up like a page on top of a page) but the body behind the overlay is fixed.
I attempted to create this with just CSS (i.e. a div overlay on top of the whole page and body with overflow: hidden), but it doesn't prevent div from being scrollable.
How to keep the body/page from scrolling but keep scrolling inside the fullscreen container?
",https://stackoverflow.com/questions/9280258/prevent-body-scrolling-but-allow-overlay-scrolling,609,1163225.0,24.0,,,2012-02-14 16:13:47,2024-10-12 09:25:55,2016-10-25 17:56:12,,,css;overlay;lightbox,PotatoFro,6638,1118481,registered,true,9280412,,CC BY-SA 3.0,2016-06-21 13:30:14,774,633,3,1,0,3,true,false,false,true,true,true,50,7,false,0.021,0.0005,5394,2012,2,16,Tuesday,false,false,false,false,false,false,false
11404744,CSS media queries: max-width OR max-height,"When writing a CSS media query, is there any way you can specify multiple conditions with ""OR"" logic?
I'm attempting to do something like this:
/* This doesn't work */
@media screen and (max-width: 995px OR max-height: 700px) {
...
}
",https://stackoverflow.com/questions/11404744/css-media-queries-max-width-or-max-height,608,701060.0,4.0,,,2012-07-09 23:37:01,2024-02-16 20:58:54,2016-10-07 01:59:13,,,css;media-queries,Fraser,14334,993588,registered,true,11404776,,CC BY-SA 3.0,2022-11-18 16:04:44,315,239,1,0,0,2,true,false,false,true,true,true,42,6,false,0.006,0.0009,5248,2012,7,23,Monday,false,false,false,false,false,false,false
27418104,What's the difference between display:inline-flex and display:flex?,"I am trying to vertically align elements within an ID wrapper. I gave the property display:inline-flex; to this ID as the ID wrapper is the flex container.
But there is no difference in presentation. I expected that everything in the wrapper ID would be displayed inline. Why isn't it?
#wrapper {
display: inline-flex;
/*no difference to display:flex; */
}
<body>
<div id=""wrapper"">
<header>header</header>
<nav>nav</nav>
<aside>aside</aside>
<main>main</main>
<footer>footer</footer>
</div>
</body>
",https://stackoverflow.com/questions/27418104/whats-the-difference-between-displayinline-flex-and-displayflex,608,789538.0,11.0,,,2014-12-11 08:12:46,2026-06-24 15:50:42,2020-03-18 13:39:41,,,css;flexbox,astridx,7431,4260616,registered,true,27459133,,CC BY-SA 4.0,,1003,664,4,0,0,2,true,false,false,true,true,true,71,7,true,0.014,0.0008,4363,2014,12,8,Thursday,false,false,false,false,false,false,false
8739665,Is background-color:none valid CSS?,"Can anyone tell me if the following CSS is valid?
.class {
background-color:none;
}
",https://stackoverflow.com/questions/8739665/is-background-colornone-valid-css,606,913516.0,5.0,,,2012-01-05 08:38:28,2024-07-31 19:56:06,2020-04-20 18:08:42,,,css;background-color,NarfkX,6236,1039226,registered,true,8739704,,CC BY-SA 4.0,2024-07-31 14:03:59,159,90,1,0,0,2,true,false,false,true,true,true,35,4,true,0.005,0.0007,5434,2012,1,8,Thursday,false,false,false,false,false,false,false
2573544,How can I select all children of an element except the last child?,"How would I select all but the last child using CSS3 selectors?
For example, to get only the last child would be div:nth-last-child(1).
",https://stackoverflow.com/questions/2573544/how-can-i-select-all-children-of-an-element-except-the-last-child,602,424240.0,11.0,,,2010-04-04 04:17:54,2023-08-21 19:20:24,2017-01-11 21:43:40,,,css-selectors;css,RyanScottLewis,14164,139089,registered,true,2573566,,CC BY-SA 3.0,2021-07-22 15:15:25,164,137,1,0,0,2,true,false,false,true,true,true,66,13,true,0.026,0.0014,6075,2010,4,4,Sunday,true,false,false,false,false,false,false
19865158,"What is the difference among col-lg-*, col-md-* and col-sm-* in Bootstrap?","What is the difference among col-lg-* , col-md-* and col-sm-* in Twitter Bootstrap?
",https://stackoverflow.com/questions/19865158/what-is-the-difference-among-col-lg-col-md-and-col-sm-in-bootstrap,602,421598.0,10.0,,,2013-11-08 17:34:06,2020-07-16 12:05:01,2018-02-22 12:43:28,,,css;twitter-bootstrap;twitter-bootstrap-3;responsive-design;bootstrap-4,StreetCoder,10053,2834501,registered,true,19865627,,CC BY-SA 3.0,,130,84,3,0,0,5,true,false,false,true,true,true,74,11,true,0.024,0.0014,4761,2013,11,17,Friday,false,false,false,false,false,false,false
7111610,Import regular CSS file in SCSS file?,"Is there anyway to import a regular CSS file with Sass's @import command? While I'm not using all of the SCSS syntax from sass, I do still enjoy it's combining/compressing features, and would like to be able to use it without renaming all of my files to *.scss
",https://stackoverflow.com/questions/7111610/import-regular-css-file-in-scss-file,601,479129.0,15.0,,,2011-08-18 17:32:23,2022-07-31 13:02:41,2020-01-07 07:31:20,,,css;sass,GSto,42574,89761,registered,true,9144570,,CC BY-SA 4.0,,281,261,1,0,0,2,true,false,false,true,true,true,37,7,true,0.031,0.0013,5574,2011,8,17,Thursday,false,false,false,false,false,false,false
29503227,How to make Flexbox items the same size,"I want to use Flexbox that has some number of items that are all the same width. I've noticed that Flexbox distributes the space around evenly, rather than the space itself.
For example:
.header {
display: flex;
}
.item {
flex-grow: 1;
text-align: center;
border: 1px solid black;
}
<div class=""header"">
<div class=""item"">asdfasdfasdfasdfasdfasdf</div>
<div class=""item"">z</div>
</div>
The first item is a lot bigger than the second. If I have three items, four items, or n items, I want them all to appear on the same line with an equal amount of space per item.
Any ideas?
http://codepen.io/anon/pen/gbJBqM
",https://stackoverflow.com/questions/29503227/how-to-make-flexbox-items-the-same-size,594,839641.0,16.0,,,2015-04-07 23:33:02,2026-01-18 08:35:23,2022-11-21 22:52:38,,,css;flexbox,Chet,20139,1191551,registered,true,29503264,,CC BY-SA 4.0,,1068,669,2,1,0,2,true,false,false,true,true,true,39,8,false,0.019,0.0007,4246,2015,4,23,Tuesday,false,false,false,false,false,false,false
2434602,Setting width/height as percentage minus pixels,"I'm trying to create some re-usable CSS classes for more consistency and less clutter on my site, and I'm stuck on trying to standardize one thing I use frequently.
I have a container <div> that I don't want to set the height for (because it will vary depending on where on the site it is), and inside it is a header <div>, and then an unordered list of items, all with CSS applied to them.
It looks a lot like this:
![]()
I want the unordered list to take up the remaining room in the container <div>, knowing that the header <div> is 18px tall. I just don't know how to specify the list's height as ""the result of 100% minus 18px"".
I've seen this question asked in a couple other contexts on SO, but I thought it would be worth asking again for my particular case. Does anyone have any advice in this situation?
",https://stackoverflow.com/questions/2434602/setting-width-height-as-percentage-minus-pixels,593,555356.0,11.0,,,2010-03-12 17:34:54,2020-12-28 21:05:58,2020-12-28 20:41:16,,,css;height;pixel,MegaMatt,23923,209113,registered,true,14101451,,CC BY-SA 4.0,,1061,838,7,0,1,3,true,false,false,true,true,true,47,6,false,0.02,0.0011,6098,2010,3,17,Friday,false,false,false,false,false,false,false
3225891,What does the ">" (greater-than sign) CSS selector mean?,"For example:
div > p.some_class {
/* Some declarations */
}
What exactly does the > sign mean?
",https://stackoverflow.com/questions/3225891/what-does-the-greater-than-sign-css-selector-mean,593,306680.0,8.0,,,2010-07-12 04:33:08,2024-06-12 02:59:40,2015-02-26 10:32:48,,,css;css-selectors,Misha Moroshko,172725,247243,registered,true,3225905,,CC BY-SA 3.0,,157,106,2,0,0,2,true,false,false,true,true,true,69,9,true,0.026,0.0019,5976,2010,7,4,Monday,false,false,false,false,false,false,false
18744164,Flex-box: Align last row to grid,"I have a simple flex-box layout with a container like:
.grid {
display: flex;
flex-flow: row wrap;
justify-content: space-between;
}
Now I want the items in the last row to be aligned with the other. justify-content: space-between; should be used because the width and height of the grid can be adjusted.
Currently it looks like
![]()
Here, I want the item in the bottom right to be in the ""middle column"". What is the simplest way to accomplish that? Here is a small jsfiddle that shows this behaviour.
.exposegrid {
display: flex;
flex-flow: row wrap;
justify-content: space-between;
}
.exposetab {
width: 100px;
height: 66px;
background-color: rgba(255, 255, 255, 0.2);
border: 1px solid rgba(0, 0, 0, 0.4);
border-radius: 5px;
box-shadow: 1px 1px 2px rgba(0, 0, 0, 0.2);
margin-bottom: 10px;
}
<div class=""exposegrid"">
<div class=""exposetab""></div>
<div class=""exposetab""></div>
<div class=""exposetab""></div>
<div class=""exposetab""></div>
<div class=""exposetab""></div>
<div class=""exposetab""></div>
<div class=""exposetab""></div>
<div class=""exposetab""></div>
<div class=""exposetab""></div>
<div class=""exposetab""></div>
<div class=""exposetab""></div>
<div class=""exposetab""></div>
<div class=""exposetab""></div>
<div class=""exposetab""></div>
</div>
",https://stackoverflow.com/questions/18744164/flex-box-align-last-row-to-grid,591,351848.0,39.0,,,2013-09-11 14:37:25,2026-03-13 10:50:26,2018-12-13 15:07:37,,,css;flexbox;grid-layout,Thorben Croisé,12934,196489,registered,true,34816625,,CC BY-SA 4.0,2016-03-09 11:08:33,2068,1529,4,1,1,3,true,false,false,true,true,true,32,6,false,0.111,0.0017,4819,2013,9,14,Wednesday,false,false,false,false,false,false,false
11757537,"CSS Image size, how to fill, but not stretch?","I have an image, and I want to set it a specific width and height (in pixels)
But If I set width and height using css (width:150px; height:100px), image will be stretched, and It may be ugly.
How to Fill images to a specific size using CSS, and not stretching it?
Example of fill and stretching image:
Original Image:
![]()
Stretched Image:
![]()
Filled Image:
![]()
Please note that in the Filled image example above: first, image is resized to 150x255 (maintained aspect ratio), and then, it cropped to 150x100.
",https://stackoverflow.com/questions/11757537/css-image-size-how-to-fill-but-not-stretch,578,1269022.0,18.0,,,2012-08-01 10:43:22,2022-07-26 13:30:10,2020-10-10 21:00:59,,,css;image,Mahdi Ghiasi,15401,942659,registered,true,29103071,,CC BY-SA 4.0,,832,509,1,0,3,2,true,false,false,true,true,true,45,9,true,0.014,0.0005,5225,2012,8,10,Wednesday,false,false,false,false,false,false,false
355313,How do I hide an element when printing a web page?,"I have a link on my webpage to print the webpage. However, the link is also visible in the printout itself.
Is there javascript or HTML code which would hide the link button when I click the print link?
Example:
""Good Evening""
Print (click Here To Print)
I want to hide this ""Print"" label when it prints the text ""Good Evening"". The ""Print"" label should not show on the printout itself.
",https://stackoverflow.com/questions/355313/how-do-i-hide-an-element-when-printing-a-web-page,578,630168.0,11.0,,,2008-12-10 07:11:24,2022-07-19 13:36:26,2015-10-14 11:14:29,,,css;printing,sourav,,,does_not_exist,true,,,CC BY-SA 3.0,2014-01-25 05:26:24,485,394,1,0,0,2,false,false,false,true,false,true,50,11,true,0.017,0.0009,6555,2008,12,7,Wednesday,false,false,false,false,false,false,false
20039765,How to apply a CSS filter to a background image,"I have a JPEG file that I'm using as a background image for a search page, and I'm using CSS to set it because I'm working within Backbone.js contexts:
background-image: url("whatever.jpg");
I want to apply a CSS 3 blur filter only to the background, but I'm not sure how to style just that one element. If I try:
filter: blur(5px);
just underneath background-image in my CSS, it styles the whole page, rather than just the background. Is there a way to select just the image and apply the filter to that? Alternatively, is there a way to just turn the blur off for every other element on the page?
",https://stackoverflow.com/questions/20039765/how-to-apply-a-css-filter-to-a-background-image,574,1888422.0,22.0,,,2013-11-18 03:49:20,2025-04-09 07:26:40,2025-04-09 07:26:40,,,css;background-image;css-filters,fox,5899,2659819,registered,true,20039965,,CC BY-SA 4.0,2025-09-23 21:34:01,775,611,3,1,0,3,true,false,false,true,true,true,47,10,false,0.012,0.0003,4751,2013,11,3,Monday,false,false,false,false,false,false,false
468881,Print <div id="printarea"></div> only?,"How do I print the indicated div (without manually disabling all other content on the page)?
I want to avoid a new preview dialog, so creating a new window with this content is not useful.
The page contains a couple of tables, one of them contains the div I want to print - the table is styled with visual styles for the web, that should not show in print.
",https://stackoverflow.com/questions/468881/print-div-id-printarea-div-only,569,1027609.0,37.0,,,2009-01-22 12:09:36,2024-12-22 09:15:58,2017-08-22 21:56:55,,,javascript;css;printing;dhtml,noesgard,6215,42108,registered,true,2618980,,CC BY-SA 3.0,2011-07-30 03:14:34,380,359,0,0,0,4,true,false,false,true,true,true,60,4,true,0.036,0.0006,6512,2009,1,12,Thursday,false,false,true,false,false,false,false
447197,How to define multiple CSS attributes in jQuery?,"Is there any syntactical way in jQuery to define multiple CSS attributes without stringing everything out to the right like this:
$(""#message"").css(""width"", ""550px"").css(""height"", ""300px"").css(""font-size"", ""8pt"");
If you have, say, 20 of these your code will become hard to read, any solutions?
From jQuery API, for example, jQuery understands and returns the correct value for both
.css({ ""background-color"": ""#ffe"", ""border-left"": ""5px solid #ccc"" })
and
.css({backgroundColor: ""#ffe"", borderLeft: ""5px solid #ccc"" }).
Notice that with the DOM notation, quotation marks around the property names are optional, but with CSS notation they're required due to the hyphen in the name.
",https://stackoverflow.com/questions/447197/how-to-define-multiple-css-attributes-in-jquery,566,728156.0,14.0,,,2009-01-15 15:35:29,2020-07-21 17:42:41,2018-09-14 17:41:31,,,jquery;css,Edward Tanguay,194372,4639,registered,true,447207,,CC BY-SA 4.0,2014-03-03 19:23:06,820,695,3,0,0,2,true,false,false,true,true,true,48,8,true,0.019,0.0008,6519,2009,1,15,Thursday,false,false,false,false,false,false,false
2436749,How to add multiple font files for the same font?,"I'm looking at the MDC page for the @font-face CSS rule, but I don't get one thing. I have separate files for bold, italic and bold + italic. How can I embed all three files in one @font-face rule? For example, if I have:
@font-face {
font-family: ""DejaVu Sans"";
src: url(""./fonts/DejaVuSans.ttf"") format(""ttf"");
}
strong {
font-family: ""DejaVu Sans"";
font-weight: bold;
}
The browser will not know which font to be used for bold (because that file is DejaVuSansBold.ttf), so it will default to something I probably don't want. How can I tell the browser all the different variants I have for a certain font?
",https://stackoverflow.com/questions/2436749/how-to-add-multiple-font-files-for-the-same-font,559,299475.0,10.0,,,2010-03-13 00:34:35,2025-01-24 01:00:55,2018-05-10 18:06:39,,,fonts;css;font-face,Felix,89736,180784,registered,true,2436830,,CC BY-SA 4.0,2011-07-10 02:18:32,810,628,2,1,0,3,true,false,false,true,true,true,49,10,true,0.033,0.0019,6097,2010,3,0,Saturday,true,false,false,false,false,false,false
5115427,How can I add a box-shadow on one side of an element?,"I need to create a box-shadow on some block element, but only (for example) on its right side. The way I do it is to wrap the inner element with box-shadow into an outer one with padding-right and overflow:hidden; so the three other sides of the shadow are not visible.
Is there some better way to achieve this? Like box-shadow-right?
EDIT: My intentions are to create only the vertical part of the shadow. Exactly the same as what repeat-y of the rule background:url(shadow.png) 100% 0% repeat-y would do.
",https://stackoverflow.com/questions/5115427/how-can-i-add-a-box-shadow-on-one-side-of-an-element,557,605780.0,13.0,,,2011-02-25 09:11:45,2024-10-05 12:43:31,2015-04-24 04:51:52,,,css;shadow;box-shadow,tillda,18790,437523,registered,true,5115490,,CC BY-SA 3.0,2014-10-23 11:46:47,647,509,7,0,0,3,true,false,false,true,true,true,53,12,true,0.021,0.0009,5748,2011,2,9,Friday,false,false,false,false,false,false,false
5306640,How to set Bullet colors in UL/LI html lists via CSS without using any images or span tags,"Imagine a simple unsorted list with some <li> items. Now, I have defined the bullets to be square shaped via list-style:square; However, if I set the color of the <li> items with color: #F00; then everything becomes red!
While I only want to set the color of the square bullets. Is there an elegant way to define the color of the bullets in CSS...
...without using any sprite images nor span tags!
HTML
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<ul>
CSS
li{
list-style:square;
}
",https://stackoverflow.com/questions/5306640/how-to-set-bullet-colors-in-ul-li-html-lists-via-css-without-using-any-images-or,550,952485.0,16.0,,,2011-03-15 01:50:29,2024-05-28 19:46:28,2020-06-20 09:12:55,2015-11-20 08:07:24,Duplicate,css;layout;colors;html-lists,Sam,15597,509670,registered,true,5308785,,,2014-10-24 12:52:20,762,556,6,0,0,4,true,true,false,true,true,true,90,18,false,0.017,0.0006,5730,2011,3,1,Tuesday,false,false,false,false,false,false,false
12991164,Maintaining the final state at end of a CSS animation,"I'm running an animation on some elements that are set to opacity: 0; in the CSS. The animation class is applied onClick, and, using keyframes, it changes the opacity from 0 to 1 (among other things).
Unfortunately, when the animation is over, the elements go back to opacity: 0 (in both Firefox and Chrome). My natural thinking would be that animated elements maintain the final state, overriding their original properties. Is this not true? And if not, how can I get the element to do so?
The code (prefixed versions not included):
@keyframes bubble {
0% { transform:scale(0.5); opacity:0.0; }
50% { transform:scale(1.2); opacity:0.5; }
100% { transform:scale(1.0); opacity:1.0; }
}
",https://stackoverflow.com/questions/12991164/maintaining-the-final-state-at-end-of-a-css-animation,547,404283.0,6.0,,,2012-10-20 17:58:48,2026-07-02 18:53:02,2023-01-30 19:54:40,,,css;css-animations,Dan,6584,389765,registered,true,12991203,,CC BY-SA 4.0,,801,704,5,0,0,2,true,false,false,true,true,true,53,10,false,0.015,0.0014,5145,2012,10,17,Saturday,true,false,false,false,false,false,false
11679567,Using CSS for a fade-in effect on page load,"Can CSS transitions be used to allow a text paragraph to fade-in on page load?
I really like how it looked on http://dotmailapp.com/ and would love to use a similar effect using CSS. The domain has since been purchased and no longer has the effect mentioned. An archived copy can be viewed on the Wayback Machine.
Illustration
Having this markup:
<div id=""test"">
<p>This is a test</p>
</div>
With the following CSS rule:
#test p {
opacity: 0;
margin-top: 25px;
font-size: 21px;
text-align: center;
-webkit-transition: opacity 2s ease-in;
-moz-transition: opacity 2s ease-in;
-o-transition: opacity 2s ease-in;
-ms-transition: opacity 2s ease-in;
transition: opacity 2s ease-in;
}
How can the transition be triggered on load?
",https://stackoverflow.com/questions/11679567/using-css-for-a-fade-in-effect-on-page-load,544,1560408.0,4.0,,,2012-07-26 23:36:49,2022-08-26 16:32:08,2019-09-25 17:20:42,,,css;css-transitions;opacity,user1556266,5443,1556266,registered,true,11681331,,CC BY-SA 4.0,2016-03-21 12:20:29,1223,854,2,2,0,3,true,false,false,true,true,true,43,9,false,0.003,0.0003,5231,2012,7,23,Thursday,false,false,false,false,false,false,false
19255296,Is there a way to use SVG as content in a pseudo element ::before or ::after,"I would like to use ::before to place SVG images before some selected elements:
#mydiv::before {
content: '<svg ... code here</svg>';
display: block;
width: 22px;
height: 10px;
margin: 10px 5px 0 10px;
}
Above code just displays the plaintext.
I checked the spec and there seem to be some restrictions on what content can be. CSS content property solution is preferable.
",https://stackoverflow.com/questions/19255296/is-there-a-way-to-use-svg-as-content-in-a-pseudo-element-before-or-after,542,793977.0,11.0,,,2013-10-08 18:17:26,2024-01-29 23:06:37,2022-05-09 12:45:32,,,css;svg;pseudo-element,Sunny,10335,2633817,registered,true,19255455,,CC BY-SA 4.0,,512,391,4,0,0,3,true,false,false,true,true,true,76,16,false,0.014,0.0007,4792,2013,10,18,Tuesday,false,false,false,false,false,false,false
4561097,CSS Box Shadow Bottom Only,"How can I do this? I want my element to look as though it has a shadow underline. I don't want the shadow for the other 3 sides.
",https://stackoverflow.com/questions/4561097/css-box-shadow-bottom-only,542,988954.0,4.0,,,2010-12-30 08:25:49,2019-06-24 15:00:33,2019-06-24 15:00:33,2013-06-28 00:50:12,Duplicate,css;underline;box-shadow,WillingLearner,7366,544140,registered,true,6245879,,,,136,129,0,0,0,3,true,true,false,true,true,true,26,5,false,0.004,0.0005,5805,2010,12,8,Thursday,false,false,false,false,false,false,false
4062001,Can you set a border opacity in CSS?,"Is there a straight forward CSS way to make the border of an element semi-transparent with something like this?
border-opacity: 0.7;
If not, does anyone have an idea how I could do so without using images?
",https://stackoverflow.com/questions/4062001/can-you-set-a-border-opacity-in-css,538,1018791.0,11.0,,,2010-10-31 05:48:53,2026-02-11 22:13:11,2019-08-29 11:08:33,,,css;opacity,mcbeav,12237,476412,registered,true,4062032,,CC BY-SA 4.0,2016-11-04 06:29:58,247,209,1,0,0,2,true,false,false,true,true,true,36,8,true,0.011,0.0005,5865,2010,10,5,Sunday,true,false,false,false,false,false,false
5218927,z-index not working with fixed positioning,"I have a div with default positioning (i.e. position:static) and a div with a fixed position.
If I set the z-indexes of the elements, it seems impossible to make the fixed element go behind the static element.
#over {
width: 600px;
z-index: 10;
}
#under {
position: fixed;
top: 5px;
width: 420px;
left: 20px;
border: 1px solid;
height: 10%;
background: #fff;
z-index: 1;
}
<div id=""over"">
Hello Hello HelloHelloHelloHelloHello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello
</div>
<div id=""under""></div>
Or on jsfiddle here: http://jsfiddle.net/mhFxf/
I can work around this by using
position:absolute
on the static element, but can anyone tell me why this is happening?
(There seems to be a similar question to this one, (Fixed Positioning breaking z-index) but it doesn't have a satisfactory answer, hence I am asking this here with my example code)
",https://stackoverflow.com/questions/5218927/z-index-not-working-with-fixed-positioning,535,715883.0,8.0,,,2011-03-07 11:09:36,2023-01-30 01:21:41,2023-01-30 01:18:24,,,css;z-index,DanSingerman,36610,43965,registered,true,42076701,,CC BY-SA 4.0,2012-10-31 16:53:22,1483,924,7,2,0,2,true,false,false,true,true,true,42,6,false,0.011,0.0007,5738,2011,3,11,Monday,false,false,false,false,false,false,false
4910077,Select all child elements recursively in CSS,"How can you select all child elements recursively?
div.dropdown, div.dropdown > * {
color: red;
}
This class only throws a class on the defined className and all immediate children. How can you, in a simple way, pick all childNodes like this:
div.dropdown,
div.dropdown > *,
div.dropdown > * > *,
div.dropdown > * > * > *,
div.dropdown > * > * > * > * {
color: red;
}
",https://stackoverflow.com/questions/4910077/select-all-child-elements-recursively-in-css,534,816670.0,3.0,,,2011-02-05 22:19:10,2023-01-27 20:16:19,2020-04-20 18:19:40,,,css;css-selectors,clarkk,28036,555222,registered,true,4910083,,CC BY-SA 4.0,,556,418,2,0,0,2,true,false,false,true,true,true,44,7,false,0.004,0.0007,5768,2011,2,22,Saturday,true,false,false,false,false,false,false
12251750,Can media queries resize based on a div element instead of the screen?,"I would like to use media queries to resize elements based on the size of a div element they are in. I cannot use the screen size as the div is just used like a widget within the webpage, and its size can vary.
",https://stackoverflow.com/questions/12251750/can-media-queries-resize-based-on-a-div-element-instead-of-the-screen,528,321376.0,12.0,,,2012-09-03 17:02:59,2025-10-08 13:31:52,2025-10-08 13:31:52,,,css;media-queries;container-queries,yazz.com,59156,190822,registered,true,12319280,,CC BY-SA 4.0,,244,211,2,0,0,3,true,false,false,true,true,true,70,13,true,0.037,0.0016,5192,2012,9,17,Monday,false,false,false,false,false,false,false
1762539,Margin on child element moves parent element,"I have a div (parent) that contains another div (child). Parent is the first element in body with no particular CSS style. When I set
.child
{
margin-top: 10px;
}
The end result is that top of my child is still aligned with parent. Instead of child being shifted for 10px downwards, my parent moves 10px down.
My DOCTYPE is set to XHTML Transitional.
What am I missing here?
edit 1
My parent needs to have strictly defined dimensions because it has a background that has to be displayed under it from top to bottom (pixel perfect). So setting vertical margins on it is a no go.
edit 2
This behaviour is the same on FF, IE as well as CR.
",https://stackoverflow.com/questions/1762539/margin-on-child-element-moves-parent-element,526,248903.0,18.0,,,2009-11-19 11:02:47,2024-09-02 08:52:05,2009-11-19 11:23:13,2025-03-13 13:30:53,Duplicate,css;xhtml;margin;nested,Robert Koritnik,105451,75642,registered,true,1939980,,,2020-01-18 06:45:31,873,648,6,0,0,4,true,true,false,true,true,true,44,7,false,0.072,0.0021,6211,2009,11,11,Thursday,false,false,false,false,false,false,false
71074,How to remove Firefox's dotted outline on BUTTONS as well as links?,"I can make Firefox not display the ugly dotted focus outlines on links with this:
a:focus {
outline: none;
}
But how can I do this for <button> tags as well? When I do this:
button:focus {
outline: none;
}
the buttons still have the dotted focus outline when I click on them.
(and yes, I know this is a usability issue, but I would like to provide my own focus hints which are appropriate to the design instead of ugly grey dots)
",https://stackoverflow.com/questions/71074/how-to-remove-firefoxs-dotted-outline-on-buttons-as-well-as-links,523,324322.0,25.0,,,2008-09-16 10:35:13,2021-10-31 05:50:50,2016-01-14 20:14:54,,,css;firefox,Edward Tanguay,194372,4639,registered,true,199319,,CC BY-SA 3.0,2011-10-11 19:09:27,627,455,3,0,0,2,true,false,false,true,true,true,71,12,true,0.077,0.0016,6640,2008,9,10,Tuesday,false,false,false,false,false,false,false
4919076,Outline effect to text,"Are there any ways in CSS to give outlines to text with different colors ? I want to highlight some parts of my text to make it more intuitive - like the names, links, etc. Changing the link colors etc. are common nowadays, so I want something new.
",https://stackoverflow.com/questions/4919076/outline-effect-to-text,523,1048092.0,19.0,,,2011-02-07 07:54:06,2026-02-06 14:05:43,2016-05-31 10:17:02,,,css,Mac,7713,333382,registered,true,4919231,,CC BY-SA 3.0,2014-09-23 09:54:23,256,249,0,0,0,1,true,false,false,true,true,true,22,4,false,0.018,0.0005,5766,2011,2,7,Monday,false,false,false,false,false,false,false
2099252,How can I apply styles to multiple classes at once?,"I want two classes with different names to have the same property in CSS. I don't want to repeat the code.
.abc {
margin-left:20px;
}
.xyz {
margin-left:20px;
}
<a class=""abc"">Lorem</a>
<a class=""xyz"">Ipsum</a>
Since both classes are doing the same thing, I should be able to merge it into one. How can I do that?
",https://stackoverflow.com/questions/2099252/how-can-i-apply-styles-to-multiple-classes-at-once,523,629614.0,8.0,,,2010-01-20 05:35:34,2025-12-15 00:04:35,2017-01-16 16:18:51,,,css;css-selectors,sat,41246,207646,registered,true,2099263,,CC BY-SA 3.0,,677,365,2,0,0,2,true,false,false,true,true,true,51,10,true,0.013,0.0008,6149,2010,1,5,Wednesday,false,false,false,false,false,false,false
1734618,How to increase the gap between text and underlining in CSS,"Using CSS, when text has text-decoration:underline applied, is it possible to increase the distance between the text and the underline?
",https://stackoverflow.com/questions/1734618/how-to-increase-the-gap-between-text-and-underlining-in-css,523,682660.0,18.0,,,2009-11-14 15:48:54,2024-08-01 20:14:26,2015-04-08 23:17:17,,,css;underline,maxp,25301,35026,registered,true,1734623,,CC BY-SA 3.0,2021-07-30 03:12:04,157,137,1,0,0,2,true,false,false,true,true,true,59,11,false,0.026,0.0008,6216,2009,11,15,Saturday,true,false,false,false,false,false,false
24175998,"Meaning of numbers in "col-md-4"," col-xs-1", "col-lg-2" in Bootstrap","I am confused with the grid system in the new Bootstrap, particularly these classes:
col-lg-*
col-md-*
col-xs-*
(where * represents some number).
Can anyone please explain the following:
- How that number is aligning the grids?
- How to use these numbers?
- What they actually represent?
",https://stackoverflow.com/questions/24175998/meaning-of-numbers-in-col-md-4-col-xs-1-col-lg-2-in-bootstrap,521,733553.0,6.0,,,2014-06-12 03:27:17,2023-02-14 00:48:29,2018-01-26 13:39:51,,,css;twitter-bootstrap;twitter-bootstrap-3;grid,Bravo,9185,3551773,registered,true,24177022,,CC BY-SA 3.0,2017-11-09 05:45:30,448,289,1,0,0,4,true,false,false,true,true,true,99,9,false,0.008,0.0007,4545,2014,6,3,Thursday,false,false,false,false,false,false,false
10085723,Twitter Bootstrap - add top space between rows,"How to add margin top to class=""row"" elements using twitter bootstrap framework?
",https://stackoverflow.com/questions/10085723/twitter-bootstrap-add-top-space-between-rows,519,839352.0,21.0,,,2012-04-10 08:53:46,2022-08-28 12:05:11,2013-11-20 12:43:39,,,css;twitter-bootstrap,Filippo oretti,50013,895174,registered,true,14429880,,CC BY-SA 3.0,2018-12-20 04:42:50,101,81,1,0,0,2,true,false,false,true,true,true,46,8,false,0.025,0.0006,5338,2012,4,8,Tuesday,false,false,false,false,false,false,false
5770341,I do not want to inherit the child opacity from the parent in CSS,"I do not want to inherit the child opacity from the parent in CSS.
I have one div which is the parent, and I have another div inside the first div which is the child.
I want to set the opacity property in the parent div, but I don't want the child div to inherit the opacity property.
How can I do that?
",https://stackoverflow.com/questions/5770341/i-do-not-want-to-inherit-the-child-opacity-from-the-parent-in-css,517,303186.0,18.0,,,2011-04-24 11:55:02,2022-09-17 23:46:43,2015-02-02 14:31:27,,,css,Lion King,34152,459943,registered,true,,,CC BY-SA 3.0,,335,307,0,0,0,1,false,false,false,true,true,true,65,14,false,0.059,0.0017,5690,2011,4,11,Sunday,true,false,false,false,false,false,false
8722163,How to assign multiple classes to an HTML container?,"Is it possible to assign multiple classes to a single HTML container?
Something like:
<article class="column, wrapper">
",https://stackoverflow.com/questions/8722163/how-to-assign-multiple-classes-to-an-html-container,515,963048.0,4.0,,,2012-01-04 04:51:14,2026-09-07 04:13:13,2023-01-13 07:11:01,,,html;css,ARGO,5321,1129142,registered,true,,,CC BY-SA 4.0,,189,138,2,0,0,2,false,false,false,true,true,true,52,9,true,0.004,0.0005,5435,2012,1,4,Wednesday,false,false,false,false,false,false,false
2869212,CSS3 gradient background set on body doesn't stretch but instead repeats?,"ok say the content inside the <body> totals 300px high.
If I set the background of my <body> using -webkit-gradient or -moz-linear-gradient
Then I maximize my window (or just make it taller than 300px) the gradient will be exactly 300px tall (the height of the content) and just repeat to fill the rest of the window.
I am assuming this is not a bug since it is the same in both webkit and gecko.
But is there a way to make the gradient stretch to fill the window instead of repeat?
",https://stackoverflow.com/questions/2869212/css3-gradient-background-set-on-body-doesnt-stretch-but-instead-repeats,514,468243.0,13.0,,,2010-05-19 20:40:23,2024-02-05 07:00:09,2012-09-29 23:20:55,,,css;gradient,JD Isaacks,57820,46011,registered,true,2870024,,CC BY-SA 3.0,2011-08-11 21:12:40,586,499,4,0,0,2,true,false,false,true,true,true,77,11,true,0.028,0.0011,6030,2010,5,20,Wednesday,false,false,false,false,false,false,false
10989238,How to center image horizontally within a div element?,"How can I center align (horizontally) an image inside its container div?
Here's the HTML and CSS. I have also included the CSS for the other elements of the thumbnail. It runs in descending order so the highest element is the container of everything and the lowest is inside everything.
#thumbnailwrapper {
color: #2A2A2A;
margin-right: 5px;
border-radius: 0.2em;
margin-bottom: 5px;
background-color: #E9F7FE;
padding: 5px;
border: thin solid #DADADA;
font-size: 15px
}
#artiststhumbnail {
width: 120px;
height: 108px;
overflow: hidden;
border: thin solid #DADADA;
background-color: white;
}
#artiststhumbnail:hover {
left: 50px
}
<!--link here-->
<a href=""NotByDesign"">
<div id=""thumbnailwrapper"">
<a href=""NotByDesign"">
<!--name here-->
<b>Not By Design</b>
<br>
<div id=""artiststhumbnail"">
<a href=""NotByDesign"">
<!--image here-->
<img src=""../files/noprofile.jpg"" height=""100%"" alt=""Not By Design"" border=""1"" />
</a>
</div>
<div id=""genre"">Punk</div>
</div>
Okay, I have added the markup without the PHP in so should be easier to see. Neither solution seems to work in practice. The text at top and bottom cannot be centered and the image should be centered within its container div. The container has overflow hidden so I want to see the center of the image as that's normally where the focus is.
",https://stackoverflow.com/questions/10989238/how-to-center-image-horizontally-within-a-div-element,513,1038462.0,24.0,,,2012-06-12 00:40:57,2025-02-18 00:32:29,2022-09-10 13:06:28,,,html;css,Jacob Windsor,7010,1420724,registered,true,10989261,,CC BY-SA 4.0,2021-02-12 15:03:38,1917,1598,2,0,0,2,true,false,false,true,true,true,54,9,true,0.023,0.0005,5275,2012,6,0,Tuesday,false,false,false,false,false,false,false
8200204,Fit background image to div,"I have a background image in the following div, but the image gets cut off:
<div style='text-align:center;background-image: url(/media/img_1_bg.jpg);background-repeat:no-repeat;width:450px;height:900px;' id=""mainpage"" align=""center"">
Is there a way to show the background image without cutting it off?
",https://stackoverflow.com/questions/8200204/fit-background-image-to-div,513,915000.0,8.0,,,2011-11-20 07:59:30,2024-12-06 08:29:59,2011-11-20 08:25:39,,,html;css;background-image,Rajeev,47417,277603,registered,true,8200264,,CC BY-SA 3.0,,350,312,1,0,0,3,true,false,false,true,true,true,27,5,false,0.009,0.0006,5480,2011,11,7,Sunday,true,false,false,false,false,false,false
30533171,Conditionally applying class attributes in React,"I want to conditionally show and hide this button group depending on what is passed in from the parent component which looks like this:
<TopicNav showBulkActions={this.__hasMultipleSelected} />
__hasMultipleSelected: function() {
return false; //return true or false depending on data
}
var TopicNav = React.createClass({
render: function() {
return (
<div className="row">
<div className="col-lg-6">
<div className="btn-group pull-right {this.props.showBulkActions ? 'show' : 'hidden'}">
<button type="button" className="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
Bulk Actions <span className="caret"></span>
</button>
<ul className="dropdown-menu" role="menu">
<li><a href="#">Merge into New Session</a></li>
<li><a href="#">Add to Existing Session</a></li>
<li className="divider"></li>
<li><a href="#">Delete</a></li>
</ul>
</div>
</div>
</div>
);
}
});
Nothing is happening however, with the {this.props.showBulkActions ? 'show' : 'hidden'}. Am I doing anything wrong here?
",https://stackoverflow.com/questions/30533171/conditionally-applying-class-attributes-in-react,509,676188.0,25.0,,,2015-05-29 15:14:38,2025-06-02 07:54:59,2023-12-19 17:13:18,,,javascript;css;twitter-bootstrap-3;reactjs;class-attributes,apexdodge,7047,400646,registered,true,30533260,,CC BY-SA 4.0,2018-01-20 03:23:44,1730,1631,4,0,0,5,true,false,false,true,true,true,48,6,false,0.037,0.0008,4194,2015,5,15,Friday,false,false,true,false,false,false,false
42252443,Vertical Align Center in Bootstrap 4,"I am trying to center my Container in the middle of the page using Bootstrap 4. I have been unsuccessful thus far.
I have built it at Codepen.io so it can be played with.
var currentAuthor = """";
var currentQuote = """";
function randomQuote() {
$.ajax({
url: ""https://api.forismatic.com/api/1.0/?"",
dataType: ""jsonp"",
data: ""method=getQuote&format=jsonp&lang=en&jsonp=?"",
success: function( response ) {
$(""#quote-content"").html('<h2 id=""quote-content"" class=""display-5""><i class=""fa fa-quote-left"" aria-hidden=""true""> ' + response.quoteText + ' <i class=""fa fa-quote-right"" aria-hidden=""true""></i></h2>');
$(""#quote-author"").html('<p id=""quote-author"" class=""lead""><em>' + response.quoteAuthor + '</em></p>');
currentAuthor = response.quoteAuthor;
currentQuote = response.quoteText
}
});
}
function openURL(url){
window.open(url,'Share', 'width=550, height=400, toolbar=0, scrollbars=1 ,location=0 ,statusbar=0,menubar=0, resizable=0');
}
function tweetQuote(){
openURL('https://twitter.com/intent/tweet?hashtags=quotes,freecodecamp&related=freecodecamp&text=' + encodeURIComponent('""' + currentQuote + '"" - ' + currentAuthor));
}
$(document).ready(function () {
randomQuote();
$(""#get-another-quote-button"").click(function(){
randomQuote();
});
$('#tweet').on('click', function() {
tweetQuote();
});
});
html, body {
background-image: url(""https://www.mylinea.com/wp-content/uploads/beautiful-trees-stock-photo-055.jpg"");
background-color: #17234E;
margin-bottom: 0;
min-height: 30%;
background-repeat: no-repeat;
background-position: center;
-webkit-background-size: cover;
background-size: cover;
}
.btn-new-quote {
color: #0C0C0D;
background-color: transparent;
border-color: #414147;
}
.btn-new-quote:hover {
color: #0C0C0D;
background-color: #9A989E;
border-color: #0C0C0D;
}
#tweet {
color: RGB(100, 100, 100);
}
#tweet:hover {
color: RGB(50, 50, 50);
}
.jumbotron {
position: relative;
top: 50%;
transform: translateY(-50%);
opacity: .85;
border-color: RGB(50, 50, 50);
padding-bottom: 8px;
}
<script src=""https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js""></script>
<link rel=""stylesheet"" href=""https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css"">
<div class=""container"">
<div class=""row justify-content-center align-self-center"">
<div class=""col-sm-6"">
<div class=""jumbotron vertical-center text-center"">
<h2 id=""quote-content"" class=""display-5""><i class=""fa fa-quote-left"" aria-hidden=""true""></i><i class=""fa fa-quote-right"" aria-hidden=""true""></i></h2>
<p id=""quote-author"" class=""lead""><em></em></p>
<hr class=""my-2"">
<div class=""row align-items-center justify-content-between"">
<div class=""col-sm-1-4 text-left"">
<a id=""tweet"" href=""#"">
<h2 class=""display-4""><i class=""fa fa-twitter"" aria-hidden=""true""></i></h2>
</a>
</div>
<div class=""col-sm-1-4 text-right"">
<button id=""get-another-quote-button"" type=""button"" class=""btn btn-outline-secondary btn-new-quote"">Don't Quote Me on This...</button>
</div>
</div>
</div>
</div>
</div>
</div>
",https://stackoverflow.com/questions/42252443/vertical-align-center-in-bootstrap-4,498,1023999.0,20.0,,,2017-02-15 14:42:13,2025-06-14 15:20:30,2025-06-14 15:20:30,2022-01-26 14:27:07,Duplicate,css;twitter-bootstrap;bootstrap-4;flexbox,canaan seaton,6868,7496355,registered,true,42252877,,,2019-09-28 12:08:19,4385,3831,3,1,0,4,true,true,false,true,true,true,36,6,false,0.02,0.0005,3566,2017,2,14,Wednesday,false,false,false,false,false,false,false
7896402,How can I replace text with CSS?,"How can I replace text with CSS using a method like this:
.pvw-title img[src*=""IKON.img""] { visibility:hidden; }
Instead of ( img[src*=""IKON.img""] ), I need to use something that can replace text instead.
I have to use [ ] to get it to work.
<div class=""pvw-title"">Facts</div>
I need to replace ""Facts"".
",https://stackoverflow.com/questions/7896402/how-can-i-replace-text-with-css,495,1446778.0,26.0,,,2011-10-25 21:58:46,2023-11-30 08:40:00,2020-02-22 15:16:23,,,css;text;replace,MokiTa,5150,1013586,registered,true,,,CC BY-SA 4.0,2019-05-09 10:47:23,454,326,5,0,0,3,false,false,false,true,true,true,32,7,true,0.018,0.0003,5506,2011,10,21,Tuesday,false,false,false,false,false,false,false
5142405,Offset a background image from the right using CSS,"Is there a way to position a background image a certain number of pixels from the right of its element?
For example, to position something a certain number of pixels (say, 10) from the left, this is how I'd do it:
#myElement {
background-position: 10px 0;
}
",https://stackoverflow.com/questions/5142405/offset-a-background-image-from-the-right-using-css,492,358527.0,17.0,,,2011-02-28 13:10:24,2024-12-09 04:19:03,,,,css,nickf,548426,9021,registered,true,16528840,,CC BY-SA 2.5,,312,265,1,0,0,1,true,false,false,true,true,false,50,9,false,0.047,0.0014,5745,2011,2,13,Monday,false,false,false,false,false,false,false
41513463,Bootstrap align navbar items to the right,"How do I align a navbar item to the right?
I want to have the login and register on the right.
However, nothing I try seems to work.
This is what I have tried so far:
<div> around the <ul> with the attribute: style="float: right"
<div> around the <ul> with the attribute: style="text-align: right"
- tried those two things on the
<li> tags
- tried all those things again with
!important added to the end
- changed
nav-item to nav-right in the <li>
- added a
pull-sm-right class to the <li>
- added a
align-content-end class to the <li>
This is my code:
<div id="app" class="container">
<nav class="navbar navbar-toggleable-md navbar-light bg-faded">
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<a class="navbar-brand" href="#">Navbar</a>
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Features</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Pricingg</a>
</li>
</ul>
<ul class="navbar-nav " >
<li class="nav-item">
<a class="nav-link" href="{{ url('/login') }}">Login</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ url('/register') }}">Register</a>
</li>
</ul>
</nav>
@yield('content')
</div>
",https://stackoverflow.com/questions/41513463/bootstrap-align-navbar-items-to-the-right,491,907415.0,24.0,,,2017-01-06 20:02:38,2025-12-22 13:36:45,2025-12-22 13:36:45,,,css;twitter-bootstrap;bootstrap-4;flexbox;bootstrap-5,Luuk Wuijster,6939,7267640,registered,true,41513784,,CC BY-SA 4.0,2018-03-06 13:46:49,2718,2208,16,1,1,5,true,false,false,true,true,true,41,7,false,0.026,0.0005,3606,2017,1,20,Friday,false,false,false,false,false,false,false
5214127,CSS technique for a horizontal line with words in the middle,"I'm trying to make a horizontal rule with some text in the middle.
For example:
----------------------------------- my title here -----------------------------
Is there a way to do that in CSS? Without all the ""-"" dashes obviously.
",https://stackoverflow.com/questions/5214127/css-technique-for-a-horizontal-line-with-words-in-the-middle,486,714871.0,36.0,,,2011-03-06 23:05:03,2024-05-09 09:54:12,2015-08-26 19:35:03,,,html;css;cross-browser,Jason,15421,311465,registered,true,5214204,,CC BY-SA 3.0,2017-05-24 11:54:38,255,234,0,0,0,3,true,false,false,true,true,true,60,11,false,0.05,0.0007,5739,2011,3,23,Sunday,true,false,false,false,false,false,false
271067,How can I make a TextArea 100% width without overflowing when padding is present in CSS?,"I have the following CSS and HTML snippet being rendered.
textarea
{
border:1px solid #999999;
width:100%;
margin:5px 0;
padding:3px;
}
<div style=""display: block;"" id=""rulesformitem"" class=""formitem"">
<label for=""rules"" id=""ruleslabel"">Rules:</label>
<textarea cols=""2"" rows=""10"" id=""rules""></textarea>
</div>
Is the problem is that the text area ends up being 8px wider (2px for border + 6px for padding) than the parent. Is there a way to continue to use border and padding but constrain the total size of the textarea to the width of the parent?
",https://stackoverflow.com/questions/271067/how-can-i-make-a-textarea-100-width-without-overflowing-when-padding-is-present,486,549074.0,15.0,,,2008-11-07 02:35:23,2023-01-15 13:39:14,2022-12-14 19:10:36,,,html;css,Eric Schoonover,48638,3957,registered,true,4156343,,CC BY-SA 4.0,2014-10-11 23:32:04,936,610,3,0,0,2,true,false,false,true,true,true,88,16,true,0.027,0.0009,6588,2008,11,2,Friday,false,false,false,false,false,false,false
16344354,How to make blinking/flashing text with CSS 3,"Currently, I have this code:
@-webkit-keyframes blinker {
from { opacity: 1.0; }
to { opacity: 0.0; }
}
.waitingForConnection {
-webkit-animation-name: blinker;
-webkit-animation-iteration-count: infinite;
-webkit-animation-timing-function: cubic-bezier(.5, 0, 1, 1);
-webkit-animation-duration: 1.7s;
}
It blinks, but it only blinks in ""one direction"". I mean, it only fades out, and then it appears back with opacity: 1.0, then again fades out, appears again, and so on...
I would like it to fade out, and then ""raise"" from this fade back again to opacity: 1.0. Is that possible?
",https://stackoverflow.com/questions/16344354/how-to-make-blinking-flashing-text-with-css-3,484,1044826.0,14.0,,,2013-05-02 17:39:06,2022-10-19 13:32:51,2019-09-25 17:20:59,,,html;css;css-animations;opacity,ojek,10146,1593783,registered,true,16344389,,CC BY-SA 4.0,2019-09-12 04:21:35,670,599,3,0,0,4,true,false,false,true,true,true,45,8,false,0.013,0.0005,4951,2013,5,17,Thursday,false,false,false,false,false,false,false
1124149,Is embedding background image data into CSS as Base64 good or bad practice?,"I was looking at the source of a greasemonkey userscript and noticed the following in their css:
.even { background: #fff url(data:image/gif;base64,R0lGODlhBgASALMAAOfn5+rq6uvr6+zs7O7u7vHx8fPz8/b29vj4+P39/f///wAAAAAAAAAAAAAAAAAAACwAAAAABgASAAAIMAAVCBxIsKDBgwgTDkzAsKGAhxARSJx4oKJFAxgzFtjIkYDHjwNCigxAsiSAkygDAgA7) repeat-x bottom}
I can appreciate that a greasemonkey script would want to bundle anything it can within the source as opposed to host it on a server, that's obvious enough. But since I had not seen this technique previously, I considered its use and it seems appealing for a number of reasons:
- It will reduce the amount of HTTP requests on page load, thus enhancing performance
- If no CDN, then it will reduce the amount of traffic generated through cookies being sent alongside of images
- CSS files can be cached
- CSS files can be GZIPPED
Considering that IE6 (for instance) has problems with cache for background images, this seems like it's not the worst idea...
So, is this a good or bad practice, why WOULDN'T you use it and what tools would you use to base64 encode the images?
update - results of testing
testing with image: http://fragged.org/dev/map-shot.jpg - 133.6Kb
test URL: http://fragged.org/dev/base64.html
dedicated CSS file:
http://fragged.org/dev/base64.css -
178.1Kb
GZIP encoding server side
resulting size sent to client (YSLOW
components test): 59.3Kb
Saving of data sent to client browser of: 74.3Kb
Nice, but it will be slightly less useful for smaller images, I guess.
UPDATE: Bryan McQuade, a software engineer at Google, working on PageSpeed, expressed at ChromeDevSummit 2013 that data:uris in CSS is considered a render-blocking anti-pattern for delivering critical/minimal CSS during his talk #perfmatters: Instant mobile web apps. See http://developer.chrome.com/devsummit/sessions and keep that in mind - actual slide
",https://stackoverflow.com/questions/1124149/is-embedding-background-image-data-into-css-as-base64-good-or-bad-practice,484,181398.0,8.0,,,2009-07-14 08:25:35,2018-07-25 13:31:41,2013-11-29 12:21:35,2025-04-27 16:22:45,Opinion-based,css;base64;background-image;data-uri,Dimitar Christoff,26083,126998,registered,true,1124180,,,2014-01-23 12:23:37,2653,1886,2,5,0,4,true,true,false,true,true,true,75,13,true,0.044,0.0027,6339,2009,7,8,Tuesday,false,false,false,false,false,false,false
12340737,Specify multiple attribute selectors in CSS,"What is the syntax for doing something like:
input[name=""Sex"" AND value=""M""]
Basically, I want to select the input element that has the attribute name=""Sex"" as well as the attribute value=""M"":
<input type=""radio"" name=""Sex"" value=""M"" />
Elements such as the following should not be selected:
<input type=""radio"" name=""Sex"" value=""F"" />
",https://stackoverflow.com/questions/12340737/specify-multiple-attribute-selectors-in-css,482,322025.0,5.0,,,2012-09-09 16:20:30,2024-07-20 04:32:44,2017-08-22 17:28:44,,,css;attributes;css-selectors,learningtech,33993,27305,registered,true,12340746,,CC BY-SA 3.0,2022-05-12 22:34:08,536,356,6,0,0,3,true,false,false,true,true,true,43,6,false,0.016,0.0015,5186,2012,9,16,Sunday,true,false,false,false,false,false,false
9262861,"CSS background image to fit width, height should auto-scale in proportion","I have
body {
background: url(images/background.svg);
}
The desired effect is that this background image will have width equal to that of the page, height changing to maintain the proportion. e.g. if the original image happens to be 100*200 (any units) and the body is 600px wide, the background image should end up being 1200px high. The height should change automatically if the window is resized. Is this possible?
At the moment, Firefox looks like it's making the height fit and then adjusting the width. Is this perhaps because the height is the longest dimension and it's trying to avoid cropping? I want to crop vertically, then scroll: no horizontal repeat.
Also, Chrome is placing the image in the centre, no repeat, even when background-repeat:repeat is given explicitly, which is the default anyway.
",https://stackoverflow.com/questions/9262861/css-background-image-to-fit-width-height-should-auto-scale-in-proportion,477,1178290.0,13.0,,,2012-02-13 15:14:33,2023-09-04 16:43:09,,,,html;css,spraff,33821,458742,registered,true,9265035,,CC BY-SA 3.0,,895,821,2,0,0,2,true,false,false,true,true,false,73,11,false,0.011,0.0004,5395,2012,2,15,Monday,false,false,false,false,false,false,false
7048313,How to have multiple CSS transitions on an element?,"It's a pretty straightforward question but I can't find very good documentation on the CSS transition properties. Here is the CSS snippet:
.nav a
{
text-transform:uppercase;
text-decoration:none;
color:#d3d3d3;
line-height:1.5 em;
font-size:.8em;
display:block;
text-align:center;
text-shadow: 0 -1.5em 0 rgba(255, 255, 255, 0.15);
-webkit-transition: color .2s linear;
-moz-transition: color .2s linear;
-o-transition: color .2s linear;
transition: color .2s linear;
-webkit-transition: text-shadow .2s linear;
-moz-transition: text-shadow .2s linear;
-o-transition: text-shadow .2s linear;
transition: text-shadow .2s linear;
}
.nav a:hover
{
color:#F7931E;
text-shadow: 0 1.5em 0 rgba(247, 147, 30, 0.15);
}
As you can see, the transition properties are overwriting eachother. As it stands, the text-shadow will animate, but not the color. How do I get them both to simultaneously animate? Thanks for any answers.
",https://stackoverflow.com/questions/7048313/how-to-have-multiple-css-transitions-on-an-element,477,487465.0,8.0,,,2011-08-13 03:06:58,2021-06-30 07:05:48,2011-08-13 13:48:09,,,animation;css;css-transitions,Eric Thoma,6195,862773,registered,true,7048326,,CC BY-SA 3.0,,1035,997,1,0,0,3,true,false,false,true,true,true,51,9,true,0.016,0.001,5579,2011,8,3,Saturday,true,false,false,false,false,false,false
18614301,Keep overflow div scrolled to bottom unless user scrolls up,"I have a div that is only 300 pixels big and I want it to when the page loads scroll to the bottom of the content. This div has content dynamically added to it and needs to stay scrolled all the way down. Now if the user decides to scroll up I don't want it to jump back to the bottom until the user scrolls all the way down again.
Is it possible to have a div that will stay scrolled to the bottom unless the user scrolls up and when the user scrolls back to the bottom it needs to keep itself at the bottom even when new dynamic content is added. How would I go about creating this?
",https://stackoverflow.com/questions/18614301/keep-overflow-div-scrolled-to-bottom-unless-user-scrolls-up,473,597452.0,25.0,,,2013-09-04 12:49:42,2025-11-11 02:25:39,2023-04-06 18:39:22,,,javascript;html;css;scroll,Robert E. McIntosh,6265,1842227,registered,true,44051405,,CC BY-SA 4.0,,599,585,0,0,0,4,true,false,false,true,true,true,59,10,false,0.042,0.0008,4826,2013,9,12,Wednesday,false,false,true,false,false,false,false
21168521,Table fixed header and scrollable body,"I am trying to make a table with fixed header and a scrollable content using the bootstrap 3 table.
Unfortunately the solutions I have found does not work with bootstrap or mess up the style.
Here there is a simple bootstrap table, but for some reason to me unknown the height of the tbody is not 10px.
height: 10px !important; overflow: scroll;
Example:
<link rel=""stylesheet"" type=""text/css"" href=""//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css"">
<table class=""table table-striped"">
<thead>
<tr>
<th>Make</th>
<th>Model</th>
<th>Color</th>
<th>Year</th>
</tr>
</thead>
<tbody style=""height: 10px !important; overflow: scroll; "">
<tr>
<td class=""filterable-cell"">111 Ford</td>
<td class=""filterable-cell"">Escort</td>
<td class=""filterable-cell"">Blue</td>
<td class=""filterable-cell"">2000</td>
</tr>
<tr>
<td class=""filterable-cell"">Ford</td>
<td class=""filterable-cell"">Escort</td>
<td class=""filterable-cell"">Blue</td>
<td class=""filterable-cell"">2000</td>
</tr>
<tr>
<td class=""filterable-cell"">Ford</td>
<td class=""filterable-cell"">Escort</td>
<td class=""filterable-cell"">Blue</td>
<td class=""filterable-cell"">2000</td>
</tr>
<tr>
<td class=""filterable-cell"">Ford</td>
<td class=""filterable-cell"">Escort</td>
<td class=""filterable-cell"">Blue</td>
<td class=""filterable-cell"">2000</td>
</tr>
</tbody>
</table>
",https://stackoverflow.com/questions/21168521/table-fixed-header-and-scrollable-body,473,1242680.0,29.0,,,2014-01-16 17:18:13,2023-01-11 11:01:50,2018-08-19 18:10:30,,,html;css;twitter-bootstrap;html-table,giulio,6215,1008538,registered,true,21175120,,CC BY-SA 4.0,,2220,1956,2,0,0,4,true,false,false,true,true,true,38,6,false,0.023,0.0004,4692,2014,1,17,Thursday,false,false,false,false,false,false,false
524696,How to create a <style> tag with Javascript?,"I'm looking for a way to insert a <style> tag into an HTML page with JavaScript.
The best way I found so far:
var divNode = document.createElement(""div"");
divNode.innerHTML = ""<br><style>h1 { background: red; }</style>"";
document.body.appendChild(divNode);
This works in Firefox, Opera and Internet Explorer but not in Google Chrome. Also it's a bit ugly with the <br> in front for IE.
Does anyone know of a way to create a <style> tag that
Is nicer
Works with Chrome?
Or maybe
This is a non-standard thing I should avoid
Three working browsers are great and who uses Chrome anyway?
",https://stackoverflow.com/questions/524696/how-to-create-a-style-tag-with-javascript,472,518227.0,19.0,,,2009-02-07 22:12:30,2023-05-15 04:26:28,2019-01-02 10:40:48,,,javascript;html;css,Arend,,,does_not_exist,true,524721,,CC BY-SA 4.0,,811,631,4,0,0,3,true,false,false,true,false,true,50,8,true,0.037,0.0009,6496,2009,2,22,Saturday,true,false,true,false,false,false,false
17904088,Disable LESS-CSS Overwriting calc(),"Right Now I'm trying to do this in CSS3 in my LESS code:
width: calc(100% - 200px);
However, when LESS compiles it is outputting this:
width: calc(-100%);
Is there a way to tell LESS not to compile it in that manner and to output it normally?
",https://stackoverflow.com/questions/17904088/disable-less-css-overwriting-calc,471,118665.0,5.0,,,2013-07-28 01:20:52,2016-09-23 00:46:19,2016-09-23 00:25:33,2016-09-23 13:45:38,Duplicate,css;less;css-calc,AJStacy,5233,1698890,registered,true,17904128,,,2016-09-23 01:28:45,318,249,2,0,0,3,true,true,false,true,true,true,35,4,false,0.042,0.004,4864,2013,7,1,Sunday,true,false,false,false,false,false,false
5803023,How to place two divs next to each other?,"Consider the following code:
#wrapper {
width: 500px;
border: 1px solid black;
}
#first {
width: 300px;
border: 1px solid red;
}
#second {
border: 1px solid green;
}
<div id=""wrapper"">
<div id=""first"">Stack Overflow is for professional and enthusiast programmers, people who write code because they love it.</div>
<div id=""second"">When you post a new question, other users will almost immediately see it and try to provide good answers. This often happens in a matter of minutes, so be sure to check back frequently when your question is still new for the best response.</div>
</div>
I would like the two divs to be next to each other inside the wrapper div. In this case, the height of the green div should determine the height of the wrapper.
How could I achieve this via CSS ?
",https://stackoverflow.com/questions/5803023/how-to-place-two-divs-next-to-each-other,471,1376711.0,13.0,,,2011-04-27 11:04:29,2021-12-30 14:50:44,2015-08-23 20:53:32,2022-09-01 14:54:36,Duplicate,css;html,Misha Moroshko,172725,247243,registered,true,5803055,,,,1249,871,2,1,0,2,true,true,false,true,true,true,41,9,true,0.009,0.0003,5687,2011,4,11,Wednesday,false,false,false,false,false,false,false
11978995,How to change color of SVG image using CSS (jQuery SVG image replacement)?,"This is a self Q&A of a handy piece of code I came up with.
Currently, there isn't an easy way to embed an SVG image and then have access to the SVG elements via CSS. There are various methods of using JS SVG frameworks, but they are overly complicated if all you are doing is making a simple icon with a rollover state.
So here is what I came up with, which I think is by far the easiest way to use SVG files on a website. It takes its concept from the early text-to-image replacement methods, but as far as I am aware has never been done for SVGs.
This is the question:
How do I embed an SVG and change its color in CSS without using a JS-SVG framework?
",https://stackoverflow.com/questions/11978995/how-to-change-color-of-svg-image-using-css-jquery-svg-image-replacement,471,782620.0,21.0,,,2012-08-16 00:05:27,2025-11-14 09:39:43,2015-09-14 01:26:23,,,jquery;css;svg,Drew Baker,14505,503546,registered,true,11978996,,CC BY-SA 3.0,2013-05-15 14:07:43,718,664,0,0,0,3,true,false,false,true,true,true,74,13,true,0.027,0.0006,5210,2012,8,0,Thursday,false,false,false,false,false,false,false
9245353,What does !important mean in CSS?,"What does !important mean in CSS?
Is it available in CSS 2? CSS 3?
Where is it supported? All modern browsers?
",https://stackoverflow.com/questions/9245353/what-does-important-mean-in-css,470,705020.0,6.0,,,2012-02-12 00:32:51,2025-11-17 18:15:15,2018-09-25 00:44:21,,,css,Hakim Iben Isa AL Burage Al Mk,53846,67153,registered,true,9245360,,CC BY-SA 4.0,,147,113,1,0,0,1,true,false,false,true,true,true,33,6,true,0.009,0.0007,5396,2012,2,0,Sunday,true,false,false,false,false,false,false
1604471,How can I find an element by CSS class with XPath?,"In my webpage, there's a div with a class named Test.
How can I find it with XPath?
",https://stackoverflow.com/questions/1604471/how-can-i-find-an-element-by-css-class-with-xpath,468,621082.0,8.0,,,2009-10-22 00:57:20,2023-05-10 15:54:59,2018-05-01 10:40:32,,,html;css;xml;xpath,Strawberry,68422,170365,registered,true,1604480,,CC BY-SA 3.0,2018-05-04 05:01:38,152,86,4,0,0,4,true,false,false,true,true,true,50,11,true,0.013,0.0008,6239,2009,10,0,Thursday,false,false,false,false,false,false,false
628301,The border-radius property and border-collapse:collapse don't mix. How can I use border-radius to create a collapsed table with rounded corners?,"I am trying to make a table with rounded corners using the CSS border-radius property. The table styles I'm using look something like this:
table {
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
border-radius: 10px;
}
Here's the problem. I also want to set the border-collapse:collapse property, and when that is set border-radius no longer works. Is there a CSS-based way I can get the same effect as border-collapse:collapse without actually using it?
It seems that a large part of the problem is that setting the table to have rounded corners does not affect the corners of the corner td elements. If the table was all one color, this wouldn't be a problem since I could just make the top and bottom td corners rounded for the first and last row respectively. However, I am using different background colors for the table to differentiate the headings and for striping, so the inner td elements would show their rounded corners as well.
Surrounding the table with another element with round corners doesn't work because the table's square corners "bleed through."
Specifying border width to 0 doesn't collapse the table.
Bottom td corners still square after setting cellspacing to zero.
The tables are generated in PHP, so I could just apply a different class to each of the outer th/tds and style each corner separately. I'd rather not do this, since it's not very elegant and a bit of a pain to apply to multiple tables, so please keep suggestions coming.
I'd like to do this without JavaScript.
",https://stackoverflow.com/questions/628301/the-border-radius-property-and-border-collapsecollapse-dont-mix-how-can-i-use,468,607316.0,31.0,,,2009-03-09 22:35:07,2025-04-25 14:17:35,2025-04-25 14:17:35,,,html;css;rounded-corners;html-table,vamin,2238,66703,registered,true,635863,,CC BY-SA 4.0,2014-03-03 23:59:48,1754,1532,9,0,0,4,true,false,false,true,true,true,148,20,true,0.051,0.0008,6466,2009,3,22,Monday,false,false,false,false,false,false,false
7049875,Why doesn't height: 100% work to expand divs to the screen height?,"I want the carousel DIV (s7) to expand to the height of the entire screen. I haven't an idea as to why it's not succeeding. To see the page you can go here.
body {
height: 100%;
color: #FFF;
font: normal 28px/28px'HelveticaWorldRegular', Helvetica, Arial, Sans-Serif;
background: #222 url('') no-repeat center center fixed;
overflow: hidden;
background-size: cover;
margin: 0;
padding: 0;
}
.holder {
height: 100%;
margin: auto;
}
#s7 {
width: 100%;
height: 100%: margin: auto;
overflow: hidden;
z-index: 1;
}
#s7 #posts {
width: 100%;
min-height: 100%;
color: #FFF;
font-size: 13px;
text-align: left;
line-height: 16px;
margin: auto;
background: #AAA;
}
<div class=""nav"">
<a class=""prev2"" id=""prev2"" href=""#"">
<img src=""http://static.tumblr.com/ux4v5bf/ASslogxz4/left.png"">
</a>
<a class=""next2"" id=""next2"" href=""#"">
<img src=""http://static.tumblr.com/ux4v5bf/swslogxmg/right.png"">
</a>
</div>
<div class=""holder"">
<tr>
<td>
<div id=""s7"">
{block:Posts}
<div id=""posts"">
",https://stackoverflow.com/questions/7049875/why-doesnt-height-100-work-to-expand-divs-to-the-screen-height,467,759034.0,12.0,,,2011-08-13 10:23:50,2022-10-06 04:50:49,2018-11-07 19:36:14,2024-01-03 14:49:39,Duplicate,html;css;height,Earl Larson,5329,557944,registered,true,7049918,,,2018-01-23 15:08:01,1560,1193,2,1,0,3,true,true,false,true,true,true,70,12,true,0.016,0.0006,5579,2011,8,10,Saturday,true,false,false,false,false,false,false
4151743,How can I change the thickness of my <hr> tag,"I want to change the thickness of my horizontal rule (<hr>)in CSS. I know it can be done in HTML like so -
<hr size=""10"">
But I hear that this is deprecated as mentioned on MDN here. In CSS I tried using height:1px but it does not change the thickness. I want the <hr> line to be 0.5px thick.
I am using Firefox 3.6.11 on Ubuntu
",https://stackoverflow.com/questions/4151743/how-can-i-change-the-thickness-of-my-hr-tag,466,740553.0,12.0,,,2010-11-11 05:57:18,2023-03-13 15:04:11,2019-07-15 06:18:10,,,html;css;user-interface,Srikar Appalaraju,74134,147019,registered,true,4151770,,CC BY-SA 4.0,2015-03-12 14:06:31,633,354,5,2,0,3,true,false,false,true,true,true,51,10,false,0.016,0.0006,5854,2010,11,5,Thursday,false,false,false,false,false,false,false
4472891,How can I "disable" zoom on a mobile web page?,"I am creating a mobile web page that is basically a big form with several text inputs.
However (at least on my Android cellphone), every time I click on some input the whole page zooms there, obscuring the rest of the page. Is there some HTML or CSS command to disable this kind of zoom on moble web pages?
",https://stackoverflow.com/questions/4472891/how-can-i-disable-zoom-on-a-mobile-web-page,464,658862.0,15.0,,,2010-12-17 17:00:24,2025-02-05 06:14:16,2015-07-10 12:20:37,,,html;css;mobile,Martín Fixman,9765,305597,registered,true,,,CC BY-SA 3.0,2012-06-29 01:33:10,322,308,0,0,0,3,false,false,false,true,true,true,56,10,true,0.023,0.0007,5818,2010,12,17,Friday,false,false,false,false,false,false,false
2554839,Select element based on multiple classes,"I have a style rule I want to apply to a tag when it has two classes. Is there any way to perform this without JavaScript? In other words:
<li class="left ui-class-selector">
I want to apply my style rule only if the li has both .left and .ui-class-selector classes applied.
",https://stackoverflow.com/questions/2554839/select-element-based-on-multiple-classes,461,391021.0,3.0,,,2010-03-31 16:50:35,2022-01-30 01:22:07,2021-01-07 09:12:14,,,css;css-selectors,Ciel,17890,84685,registered,true,2554853,,CC BY-SA 4.0,,434,292,4,0,0,2,true,false,false,true,true,true,40,6,false,0.008,0.0012,6079,2010,3,16,Wednesday,false,false,false,false,false,false,false
820412,Downloading jQuery UI CSS from Google's CDN,"I am planning on using Google to download the jQuery lib for both UI and Core. My question is, do they allow me to download the CSS for it or should I have to host it myself?
Also if I use Google to load how should I load other plugins? Can I compress all plugins together or should it be its own separate file?
",https://stackoverflow.com/questions/820412/downloading-jquery-ui-css-from-googles-cdn,461,261761.0,7.0,,,2009-05-04 14:45:22,2022-10-29 18:43:00,2013-10-31 19:40:36,,,jquery;css;jquery-ui;cdn;google-ajax-libraries,coool,8387,100008,registered,true,820444,,CC BY-SA 3.0,2014-08-27 14:39:06,328,314,0,0,0,5,true,false,false,true,true,true,47,7,false,0.027,0.0018,6410,2009,5,14,Monday,false,false,false,false,false,false,false
35269947,How can I align one item right with flexbox?,"https://jsfiddle.net/vhem8scs/
Is it possible to have two items align left and one item align right with flexbox? The link shows it more clearly. The last example is what I want to achieve.
In flexbox I have one block of code. With float I have four blocks of code. That is one reason why I prefer flexbox.
HTML
<div class=""wrap"">
<div>One</div>
<div>Two</div>
<div>Three</div>
</div>
<!-- DESIRED RESULT -->
<div class=""result"">
<div>One</div>
<div>Two</div>
<div>Three</div>
</div>
CSS
.wrap {
display: flex;
background: #ccc;
width: 100%;
justify-content: space-between;
}
.result {
background: #ccc;
margin-top: 20px;
}
.result:after {
content: '';
display: table;
clear: both;
}
.result div {
float: left;
}
.result div:last-child {
float: right;
}
",https://stackoverflow.com/questions/35269947/how-can-i-align-one-item-right-with-flexbox,460,471747.0,7.0,,,2016-02-08 12:41:31,2025-10-25 05:50:47,2021-03-02 14:57:44,,,css;alignment;flexbox,Jens Törnell,25088,148496,registered,true,35270047,,CC BY-SA 4.0,,1082,903,2,1,0,3,true,false,false,true,true,true,44,9,true,0.015,0.001,3939,2016,2,12,Monday,false,false,false,false,false,false,false
572298,How to stop text from taking up more than 1 line?,"Is there a word-wrap or any other attribute that stops text from wrapping? I have a height, and overflow:hidden, and the text still breaks.
Needs to work in all browsers, before CSS3.
",https://stackoverflow.com/questions/572298/how-to-stop-text-from-taking-up-more-than-1-line,460,414096.0,7.0,,,2009-02-21 04:58:20,2024-03-25 22:01:51,2019-07-17 16:50:06,,,html;css;text;word-wrap,Franky,,,does_not_exist,true,572302,,CC BY-SA 4.0,,213,186,1,0,0,4,true,false,false,true,false,true,49,11,true,0.017,0.0011,6482,2009,2,4,Saturday,true,false,false,false,false,false,false
2094508,Is there a CSS selector for the first direct child only?,"I have the following html
<div class=""section"">
<div>header</div>
<div>
contents
<div>sub contents 1</div>
<div>sub contents 2</div>
</div>
</div>
And the following style:
DIV.section DIV:first-child
{
...
}
For some reason that I don't understand the style is getting applied to the ""sub contents 1"" <div> as well as the ""header"" <div>.
I thought that the selector on the style would only apply to the first direct child of a div with a class called ""section"". How can I change the selector to get what I want?
",https://stackoverflow.com/questions/2094508/is-there-a-css-selector-for-the-first-direct-child-only,459,644269.0,8.0,,,2010-01-19 15:20:43,2022-11-16 14:38:46,2017-02-10 15:27:17,,,html;css;css-selectors,Jeremy,46930,9266,registered,true,2094512,,CC BY-SA 3.0,,770,650,4,0,0,3,true,false,false,true,true,true,56,11,true,0.012,0.0007,6150,2010,1,15,Tuesday,false,false,false,false,false,false,false
15649244,Responsive font size in CSS,"I've created a site using the Zurb Foundation 3 grid. Each page has a large h1:
body {
font-size: 100%
}
/* Headers */
h1 {
font-size: 6.2em;
font-weight: 500;
}
<div class=""row"">
<div class=""twelve columns text-center"">
<h1> LARGE HEADER TAGLINE </h1>
</div>
<!-- End Tagline -->
</div>
<!-- End Row -->
When I resize the browser to mobile size the large font doesn't adjust and causes the browser to include a horizontal scroll to accommodate for the large text.
I've noticed that on the Zurb Foundation 3 Typography example page, the headers adapt to the browser as it is compressed and expanded.
Am I missing something really obvious? How do I achieve this?
",https://stackoverflow.com/questions/15649244/responsive-font-size-in-css,457,1435933.0,34.0,,,2013-03-26 23:23:13,2024-03-16 07:08:36,2021-11-15 15:52:23,,,css;responsive-design;zurb-foundation;font-size,user2213682,4575,2213682,registered,true,15649277,,CC BY-SA 4.0,2021-08-30 15:36:44,1224,759,3,1,0,4,true,false,false,true,true,true,27,5,false,0.024,0.0003,4988,2013,3,23,Tuesday,false,false,false,false,false,false,false
45536537,Centering in CSS Grid,"I'm trying to create a simple page with CSS Grid.
What I'm failing to do is center the text from the HTML to the respective grid cells.
I've tried placing content in separate divs both inside and outside of the left_bg and right_bg selectors and playing with some of the CSS properties to no avail.
How do I do this?
html,
body {
margin: 0;
padding: 0;
}
.container {
display: grid;
grid-template-columns: 1fr 1fr;
grid-template-rows: 100vh;
grid-gap: 0px 0px;
}
.left_bg {
display: subgrid;
background-color: #3498db;
grid-column: 1 / 1;
grid-row: 1 / 1;
z-index: 0;
}
.right_bg {
display: subgrid;
background-color: #ecf0f1;
grid-column: 2 / 2;
grid_row: 1 / 1;
z-index: 0;
}
.left_text {
grid-column: 1 / 1;
grid-row: 1 / 1;
position: relative;
z-index: 1;
justify-self: center;
font-family: Raleway;
font-size: large;
}
.right_text {
grid-column: 2 / 2;
grid_row: 1 / 1;
position: relative;
z-index: 1;
justify-self: center;
font-family: Raleway;
font-size: large;
}
<div class=""container"">
<!--everything on the page-->
<div class=""left_bg"">
<!--left background color of the page-->
</div>
</div>
<div class=""right_bg"">
<!--right background color of the page-->
</div>
<div class=""left_text"">
<!--left side text content-->
<p>Review my stuff</p>
<div class=""right_text"">
<!--right side text content-->
<p>Hire me!</p>
</div>
</div>
",https://stackoverflow.com/questions/45536537/centering-in-css-grid,457,997012.0,10.0,,,2017-08-06 20:52:59,2025-06-06 16:00:27,2017-08-09 19:34:16,,,html;css;centering;css-grid,beetroot,4689,2957496,registered,true,45599428,,CC BY-SA 3.0,,1995,1630,5,0,0,4,true,false,false,true,true,true,21,4,false,0.01,0.0005,3394,2017,8,20,Sunday,true,false,false,false,false,false,false
8720931,Can CSS detect the number of children an element has?,"I'm probably answering my own question, but I'm extremely curious.
I know that CSS can select individual children of a parent, but is there support to style the children of a container, if its parent has a certain amount of children.
for example
container:children(8) .child {
//style the children this way if there are 8 children
}
I know it sounds weird, but my manager asked me to check it out, haven't found anything on my own so I decided to turn to SO before ending the search.
",https://stackoverflow.com/questions/8720931/can-css-detect-the-number-of-children-an-element-has,457,357412.0,14.0,,,2012-01-04 01:20:25,2026-01-27 10:51:53,2023-06-23 07:36:03,,,css;css-selectors,Brodie,8797,985138,registered,true,12198561,,CC BY-SA 4.0,2023-10-04 08:56:19,539,487,1,0,0,2,true,false,false,true,true,true,53,10,true,0.039,0.0013,5435,2012,1,1,Wednesday,false,false,false,false,false,false,false
1055581,How do I add a tool tip to a span element?,"In the following code, I want a tool-tip to come up when the user hovers the span, how do I do that? I don't want to use any links.
<span> text </span>
",https://stackoverflow.com/questions/1055581/how-do-i-add-a-tool-tip-to-a-span-element,457,483947.0,5.0,,,2009-06-28 19:35:58,2021-04-22 12:20:41,2016-01-06 09:49:50,,,html;css,Kladskull,10846,68452,registered,true,1055583,,CC BY-SA 3.0,,198,167,1,0,0,2,true,false,false,true,true,true,42,11,true,0.01,0.0009,6355,2009,6,19,Sunday,true,false,false,false,false,false,false
526347,jQuery get the rendered height of an element?,"How do you get the rendered height of an element?
Let's say you have a <div> element with some content inside. This content inside is going to stretch the height of the <div>. How do you get the ""rendered"" height when you haven't explicitly set the height. Obviously, I tried:
var h = document.getElementById('someDiv').style.height;
Is there a trick for doing this? I am using jQuery if that helps.
",https://stackoverflow.com/questions/526347/jquery-get-the-rendered-height-of-an-element,456,656501.0,18.0,,,2009-02-08 20:49:55,2024-10-07 07:49:00,2023-08-25 20:00:44,,,javascript;jquery;css;height,BuddyJoe,71523,36590,registered,true,526354,,CC BY-SA 4.0,,489,418,3,0,0,4,true,false,false,true,true,true,45,8,true,0.027,0.0007,6495,2009,2,20,Sunday,true,false,true,false,false,false,false
2603700,How to align 3 divs (left/center/right) inside another div?,"I want to have 3 divs aligned inside a container div, something like this:
[[LEFT] [CENTER] [RIGHT]]
Container div is 100% wide (no set width), and center div should remain in center after resizing the container.
So I set:
#container{width:100%;}
#left{float:left;width:100px;}
#right{float:right;width:100px;}
#center{margin:0 auto;width:100px;}
But it becomes:
[[LEFT] [CENTER] ]
[RIGHT]
Any tips?
",https://stackoverflow.com/questions/2603700/how-to-align-3-divs-left-center-right-inside-another-div,456,1050441.0,21.0,,,2010-04-08 21:49:54,2022-05-13 22:22:43,2021-07-03 11:36:36,,,html;css;alignment;css-float,serg,111593,20128,registered,true,2603709,,CC BY-SA 4.0,2017-10-18 23:36:39,617,472,3,0,0,4,true,false,false,true,true,true,59,9,true,0.02,0.0004,6071,2010,4,21,Thursday,false,false,false,false,false,false,false
1795109,What is the difference between "word-break: break-all" versus "word-wrap: break-word" in CSS?,"What is the difference between "word-break: break-all" and "word-wrap: break-word"?
When I used both, they seemed to break the word if it was not fitting the container. But why did W3C make two ways to do it?
",https://stackoverflow.com/questions/1795109/what-is-the-difference-between-word-break-break-all-versus-word-wrap-break,454,268087.0,13.0,,,2009-11-25 06:56:24,2023-02-08 21:31:53,2023-02-08 20:38:17,,,css;word-wrap,Nap,8390,121859,registered,true,1795878,,CC BY-SA 4.0,,330,229,0,1,0,2,true,false,false,true,true,true,113,12,true,0.048,0.0017,6205,2009,11,6,Wednesday,false,false,false,false,false,false,false
1709442,make div's height expand with its content,"I have these nested divs and I need the main container to expand (in height) to accommodate the DIVs inside
<!-- head -->
...
<!-- /head -->
<body class=""main"">
<div id=""container"">
<div id=""header"">
<!--series of divs in here, graphic banner etc. -->
</div>
<div id=""main_content""> <!-- this DIV _should_ stretch to accommodate inner divs -->
<div id=""items_list"" class=""items_list ui-sortable"">
<div id=""item_35"" class=""item_details"">
</div>
<div id=""item_36"" class=""item_details"">
</div>
<div id=""item_37"" class=""item_details"">
</div>
<!-- this list of DIVs ""item_xx"" goes on for a while
each one representing a photo with name, caption etcetc -->
</div>
</div>
<br class=""clear""/>
<div id=""footer"">
</div>
</body>
</html>
CSS is this:
* {
padding: 0;
margin: 0;
}
.main {
font: 100% Verdana, Arial, Helvetica, sans-serif;
background: #4c5462;
margin: 0;
padding: 0;
text-align: center;
color: #000000;
}
.main #container {
height: auto;
width: 46em;
background: #4c5462;
margin: 0 auto;
border: 0px solid #000000;
text-align: left;
}
.main #main_content {
padding: 5px;
margin: 0px;
}
#items_list {
width: 400px;
float: left;
}
.items_list {
width: 400px;
float: left;
}
.item_details {
margin-top: 3px;
margin-bottom: 3px;
padding: 3px;
float: left;
border-bottom: 0.5px solid blue;
}
The problem I have is that #main_content doesn't stretch to accommodate all the inner divs, with the result that they keep going against the background.
How can I solve this problem considering the above scenario?
",https://stackoverflow.com/questions/1709442/make-divs-height-expand-with-its-content,452,934550.0,27.0,,,2009-11-10 16:51:46,2023-04-24 04:46:41,2021-04-24 10:52:44,,,html;css;height,patrick,7599,185795,registered,true,1709580,,CC BY-SA 4.0,2017-05-02 17:12:40,2096,1930,3,0,0,3,true,false,false,true,true,true,45,7,false,0.029,0.0005,6220,2009,11,16,Tuesday,false,false,false,false,false,false,false
257505,CSS fixed width in a span,"Within an unordered list:
<li><span></span> The lazy dog.</li>
<li><span>AND</span> The lazy cat.</li>
<li><span>OR</span> The active goldfish.</li>
Adding a class or style attribute is permitted but padding the text and adding or changing tags is not allowed.
The page is rendering with Courier New.
Goal is to have text after span lined up.
The lazy dog.
AND The lazy cat.
OR The active goldfish.
Justification of the ""OR"" is unimportant.
The lazy animal text may be wrapped in an additional element but I'll have to double check.
",https://stackoverflow.com/questions/257505/css-fixed-width-in-a-span,451,942956.0,11.0,,,2008-11-02 22:36:31,2021-08-20 10:40:42,2015-03-19 11:27:51,,,html;css,jason saldo,10040,1293,registered,true,257524,,CC BY-SA 3.0,,709,619,2,0,0,2,true,false,false,true,true,true,25,6,false,0.012,0.0005,6593,2008,11,22,Sunday,true,false,false,false,false,false,false
9538868,Prevent BODY from scrolling when a modal is opened,"I want my body to stop scrolling when using the mousewheel while the Modal (from http://twitter.github.com/bootstrap) on my website is opened.
I've tried to call the piece of javascript below when the modal is opened but without success
$(window).scroll(function() { return false; });
AND
$(window).live('scroll', function() { return false; });
Please note our website dropped support for IE6, IE7+ needs to be compatible though.
",https://stackoverflow.com/questions/9538868/prevent-body-from-scrolling-when-a-modal-is-opened,451,772225.0,58.0,,,2012-03-02 19:00:08,2025-04-23 09:38:13,2020-02-22 14:16:47,,,javascript;jquery;css;scroll,xorinzor,6510,1024322,registered,true,11013994,,CC BY-SA 4.0,2017-07-29 01:35:18,580,437,2,1,0,4,true,false,false,true,true,true,50,9,false,0.075,0.0006,5377,2012,3,19,Friday,false,false,true,false,false,false,false
4113965,CSS selector for text input fields?,"How can I target input fields of type 'text' using CSS selectors?
",https://stackoverflow.com/questions/4113965/css-selector-for-text-input-fields,449,590073.0,8.0,,,2010-11-06 16:27:07,2023-01-03 05:35:26,2016-10-20 01:25:02,,,html;css;forms;css-selectors;html-input,Yarin,186649,165673,registered,true,4113981,,CC BY-SA 3.0,,74,67,0,0,0,5,true,false,false,true,true,true,35,6,true,0.014,0.0008,5859,2010,11,16,Saturday,true,false,false,false,false,false,false
69692842,Error message "error:0308010C:digital envelope routines::unsupported","I created the default IntelliJ IDEA React project and got this:
Error: error:0308010C:digital envelope routines::unsupported
at new Hash (node:internal/crypto/hash:67:19)
at Object.createHash (node:crypto:130:10)
at module.exports (/Users/user/Programming Documents/WebServer/untitled/node_modules/webpack/lib/util/createHash.js:135:53)
at NormalModule._initBuildHash (/Users/user/Programming Documents/WebServer/untitled/node_modules/webpack/lib/NormalModule.js:417:16)
at handleParseError (/Users/user/Programming Documents/WebServer/untitled/node_modules/webpack/lib/NormalModule.js:471:10)
at /Users/user/Programming Documents/WebServer/untitled/node_modules/webpack/lib/NormalModule.js:503:5
at /Users/user/Programming Documents/WebServer/untitled/node_modules/webpack/lib/NormalModule.js:358:12
at /Users/user/Programming Documents/WebServer/untitled/node_modules/loader-runner/lib/LoaderRunner.js:373:3
at iterateNormalLoaders (/Users/user/Programming Documents/WebServer/untitled/node_modules/loader-runner/lib/LoaderRunner.js:214:10)
at iterateNormalLoaders (/Users/user/Programming Documents/WebServer/untitled/node_modules/loader-runner/lib/LoaderRunner.js:221:10)
/Users/user/Programming Documents/WebServer/untitled/node_modules/react-scripts/scripts/start.js:19
throw err;
^
It seems to be a recent issue - webpack ran into this 4 days ago and is still working on it.
",https://stackoverflow.com/questions/69692842/error-message-error0308010cdigital-envelope-routinesunsupported,2573,3533761.0,71.0,,,2021-10-23 23:39:57,2025-07-21 03:07:17,2023-05-10 21:49:04,,,node.js;reactjs;webpack,a1cd,25816,14994086,registered,true,69699772,,CC BY-SA 4.0,2021-12-13 12:11:03,1592,1427,1,1,0,3,true,false,false,true,true,true,79,5,false,0.02,0.0007,1855,2021,10,23,Saturday,true,false,false,false,false,false,false
30626030,Can you force a React component to rerender without calling setState?,"I have an external (to the component), observable object that I want to listen for changes on. When the object is updated it emits change events, and then I want to rerender the component when any change is detected.
With a top-level React.render this has been possible, but within a component it doesn't work (which makes some sense since the render method just returns an object).
Here's a code example:
export default class MyComponent extends React.Component {
handleButtonClick() {
this.render();
}
render() {
return (
<div>
{Math.random()}
<button onClick={this.handleButtonClick.bind(this)}>
Click me
</button>
</div>
)
}
}
Clicking the button internally calls this.render(), but that's not what actually causes the rendering to happen (you can see this in action because the text created by {Math.random()} doesn't change). However, if I simply call this.setState() instead of this.render(), it works fine.
So I guess my question is: do React components need to have state in order to rerender? Is there a way to force the component to update on demand without changing the state?
",https://stackoverflow.com/questions/30626030/can-you-force-a-react-component-to-rerender-without-calling-setstate,1137,1705251.0,24.0,,,2015-06-03 16:44:58,2025-03-19 14:55:46,2016-01-30 11:19:15,,,reactjs,Philip Walton,30551,478460,registered,true,30626072,,CC BY-SA 3.0,,1387,1187,7,0,0,1,true,false,false,true,true,true,69,11,true,0.014,0.0007,4189,2015,6,16,Wednesday,false,false,false,false,false,false,false
28889826,How to set focus on an input field after rendering?,"What's the react way of setting focus on a particular text field after the component is rendered?
Documentation seems to suggest using refs, e.g:
Set ref=""nameInput"" on my input field in the render function, and then call:
this.refs.nameInput.getInputDOMNode().focus();
But where should I call this? I've tried a few places but I cannot get it to work.
",https://stackoverflow.com/questions/28889826/how-to-set-focus-on-an-input-field-after-rendering,995,1155719.0,28.0,,,2015-03-05 23:28:22,2023-12-02 03:58:53,2020-04-21 15:11:06,,,javascript;reactjs,Dave,11932,164431,registered,true,28890330,,CC BY-SA 4.0,2018-04-17 07:18:18,424,359,2,0,0,2,true,false,false,true,true,true,51,10,true,0.024,0.0009,4279,2015,3,23,Thursday,false,false,true,false,false,false,false
37949981,Call child method from parent,"I have two components:
- Parent component
- Child component
I was trying to call Child's method from Parent, I tried this way but couldn't get a result:
class Parent extends Component {
render() {
return (
<Child>
<button onClick={Child.getAlert()}>Click</button>
</Child>
);
}
}
class Child extends Component {
getAlert() {
alert('clicked');
}
render() {
return (
<h1 ref="hello">Hello</h1>
);
}
}
Is there a way to call Child's method from Parent?
Note: Child and Parent components are in two different files.
",https://stackoverflow.com/questions/37949981/call-child-method-from-parent,977,895324.0,24.0,,,2016-06-21 16:34:48,2026-11-17 18:22:18,2020-12-17 17:50:18,,,javascript;reactjs,N8FURY,10110,2299167,registered,true,37950970,,CC BY-SA 4.0,2019-01-18 02:05:07,703,624,1,0,0,2,true,false,false,true,true,true,29,5,false,0.027,0.0011,3805,2016,6,16,Tuesday,false,false,true,false,false,false,false
32553158,Detect click outside React component,"I'm looking for a way to detect if a click event happened outside of a component, as described in this article. jQuery closest() is used to see if the target from a click event has the dom element as one of its parents. If there is a match the click event belongs to one of the children and is thus not considered to be outside of the component.
So in my component, I want to attach a click handler to the window. When the handler fires I need to compare the target with the dom children of my component.
The click event contains properties like "path" which seems to hold the dom path that the event has traveled. I'm not sure what to compare or how to best traverse it, and I'm thinking someone must have already put that in a clever utility function... No?
",https://stackoverflow.com/questions/32553158/detect-click-outside-react-component,936,1018042.0,57.0,,,2015-09-13 18:34:00,2024-12-10 18:51:47,2022-08-21 23:36:36,,,javascript;dom;reactjs,Thijs Koerselman,23467,294632,registered,true,42234988,,CC BY-SA 4.0,,894,770,1,1,0,3,true,false,false,true,true,true,36,5,false,0.056,0.0009,4087,2015,9,18,Sunday,true,false,true,false,false,false,false
29810914,React js onClick can't pass value to method,"I want to read the onClick event value properties. But when I click on it, I see something like this on the console:
SyntheticMouseEvent {dispatchConfig: Object, dispatchMarker: "".1.1.0.2.0.0:1"", nativeEvent: MouseEvent, type: ""click"", target
My code is working correctly. When I run I can see {column} but can't get it in the onClick event.
My Code:
var HeaderRows = React.createClass({
handleSort: function(value) {
console.log(value);
},
render: function () {
var that = this;
return(
<tr>
{this.props.defaultColumns.map(function (column) {
return (
<th value={column} onClick={that.handleSort} >{column}</th>
);
})}
{this.props.externalColumns.map(function (column) {
// Multi dimension array - 0 is column name
var externalColumnName = column[0];
return ( <th>{externalColumnName}</th>);
})}
</tr>
);
}
});
How can I pass a value to the onClick event in React js?
",https://stackoverflow.com/questions/29810914/react-js-onclick-cant-pass-value-to-method,927,918002.0,38.0,,,2015-04-22 23:40:14,2024-04-12 23:56:49,2019-10-16 20:25:51,,,javascript;reactjs,user1924375,10931,1924375,registered,true,29810951,,CC BY-SA 4.0,,1146,1044,4,0,0,2,true,false,false,true,true,true,47,8,false,0.041,0.001,4231,2015,4,23,Wednesday,false,false,true,false,false,false,false
34641582,What is the difference between React Native and React?,"I have started to learn React out of curiosity and wanted to know the difference between React and React Native - though could not find a satisfactory answer using Google. React and React Native seems to have the same format. Do they have completely different syntax?
",https://stackoverflow.com/questions/34641582/what-is-the-difference-between-react-native-and-react,925,442695.0,45.0,,,2016-01-06 19:51:57,2026-03-14 04:48:25,2019-01-21 12:36:27,,,javascript;reactjs;react-native;javascript-framework,shiva kumar,11444,2400485,registered,true,34641772,,CC BY-SA 4.0,2017-10-11 12:09:36,284,268,0,0,0,4,true,false,false,true,true,true,54,9,true,0.102,0.0021,3972,2016,1,19,Wednesday,false,false,true,false,false,false,false
58123398,When to use JSX.Element vs ReactNode vs ReactElement?,"I am currently migrating a React application to TypeScript. So far, this works pretty well, but I have a problem with the return types of my render functions, specifically in my functional components.
I have always used JSX.Element as the return type, now this doesn't work any more if a component decides to not render anything, i.e. returns null, since null is not a valid value for JSX.Element. This was the beginning of my journey. I searched the web and found that you should use ReactNode instead, which includes null and a few other things that can happen.
However, when creating a functional component, TypeScript complains about the ReactNode type. Again, after some searching I found, that for functional components you should use ReactElement instead. However, if I do so, the compatibility issue is gone, but now TypeScript again complains about null not being a valid value.
To cut a long story short, I have three questions:
- What is the difference between
JSX.Element, ReactNode, and ReactElement?
- Why do the
render methods of class components return ReactNode but functional components return ReactElement?
- How do I solve this with respect to
null?
",https://stackoverflow.com/questions/58123398/when-to-use-jsx-element-vs-reactnode-vs-reactelement,913,549081.0,5.0,,,2019-09-26 19:18:45,2024-04-19 10:59:47,2024-04-19 10:59:47,,,javascript;reactjs;typescript,Golo Roden,153081,1333873,registered,true,58123882,,CC BY-SA 4.0,,1460,1166,17,0,0,3,true,false,false,true,true,true,53,8,true,0.009,0.0017,2613,2019,9,19,Thursday,false,false,true,false,false,false,false
34570758,Why do we need middleware for async flow in Redux?,"According to the docs, ""Without middleware, Redux store only supports synchronous data flow"". I don't understand why this is the case. Why can't the container component call the async API, and then dispatch the actions?
For example, imagine a simple UI: a field and a button. When user pushes the button, the field gets populated with data from a remote server.
import * as React from 'react';
import * as Redux from 'redux';
import { Provider, connect } from 'react-redux';
const ActionTypes = {
STARTED_UPDATING: 'STARTED_UPDATING',
UPDATED: 'UPDATED'
};
class AsyncApi {
static getFieldValue() {
const promise = new Promise((resolve) => {
setTimeout(() => {
resolve(Math.floor(Math.random() * 100));
}, 1000);
});
return promise;
}
}
class App extends React.Component {
render() {
return (
<div>
<input value={this.props.field}/>
<button disabled={this.props.isWaiting} onClick={this.props.update}>Fetch</button>
{this.props.isWaiting && <div>Waiting...</div>}
</div>
);
}
}
App.propTypes = {
dispatch: React.PropTypes.func,
field: React.PropTypes.any,
isWaiting: React.PropTypes.bool
};
const reducer = (state = { field: 'No data', isWaiting: false }, action) => {
switch (action.type) {
case ActionTypes.STARTED_UPDATING:
return { ...state, isWaiting: true };
case ActionTypes.UPDATED:
return { ...state, isWaiting: false, field: action.payload };
default:
return state;
}
};
const store = Redux.createStore(reducer);
const ConnectedApp = connect(
(state) => {
return { ...state };
},
(dispatch) => {
return {
update: () => {
dispatch({
type: ActionTypes.STARTED_UPDATING
});
AsyncApi.getFieldValue()
.then(result => dispatch({
type: ActionTypes.UPDATED,
payload: result
}));
}
};
})(App);
export default class extends React.Component {
render() {
return <Provider store={store}><ConnectedApp/></Provider>;
}
}
When the exported component is rendered, I can click the button and the input is updated correctly.
Note the update function in the connect call. It dispatches an action that tells the App that it is updating, and then performs an async call. After the call finishes, the provided value is dispatched as a payload of another action.
What is wrong with this approach? Why would I want to use Redux Thunk or Redux Promise, as the documentation suggests?
EDIT: I searched the Redux repo for clues, and found that Action Creators were required to be pure functions in the past. For example, here's a user trying to provide a better explanation for async data flow:
The action creator itself is still a pure function, but the thunk function it returns doesn't need to be, and it can do our async calls
Action creators are no longer required to be pure. So, thunk/promise middleware was definitely required in the past, but it seems that this is no longer the case?
",https://stackoverflow.com/questions/34570758/why-do-we-need-middleware-for-async-flow-in-redux,912,227485.0,13.0,,,2016-01-02 21:09:48,2023-07-21 09:13:06,2017-10-20 08:53:16,,,javascript;asynchronous;reactjs;redux;redux-thunk,Stas Bichenko,13293,710356,registered,true,34599594,,CC BY-SA 3.0,,3910,3378,4,4,1,5,true,false,false,true,true,true,50,10,true,0.057,0.004,3976,2016,1,21,Saturday,true,false,true,false,false,false,false
35352638,How to get parameter value from query string?,"How can I define a route in my routes.jsx file to capture the __firebase_request_key parameter value from a URL generated by Twitter's single sign on process after the redirect from their servers?
http://localhost:8000/#/signin?_k=v9ifuf&__firebase_request_key=blablabla
I tried with the following routes configuration, but the :redirectParam is not catching the mentioned param:
<Router>
<Route path=""/"" component={Main}>
<Route path=""signin"" component={SignIn}>
<Route path="":redirectParam"" component={TwitterSsoButton} />
</Route>
</Route>
</Router>
",https://stackoverflow.com/questions/35352638/how-to-get-parameter-value-from-query-string,909,2114180.0,47.0,,,2016-02-12 00:19:13,2025-01-08 04:15:12,2025-01-07 09:04:11,,,reactjs;react-router;query-string;url-parameters,Franco,12685,1865075,registered,true,37568368,,CC BY-SA 4.0,2021-01-04 22:16:20,710,622,4,0,0,4,true,false,false,true,true,true,45,8,true,0.022,0.0004,3935,2016,2,0,Friday,false,false,false,false,false,false,false
54069253,The useState set method is not reflecting a change immediately,"I am trying to learn hooks and the useState method has made me confused. I am assigning an initial value to a state in the form of an array. The set method in useState is not working for me, both with and without the spread syntax.
I have made an API on another PC that I am calling and fetching the data which I want to set into the state.
Here is my code:
<div id=""root""></div>
<script type=""text/babel"" defer>
// import React, { useState, useEffect } from ""react"";
// import ReactDOM from ""react-dom"";
const { useState, useEffect } = React; // web-browser variant
const StateSelector = () => {
const initialValue = [
{
category: """",
photo: """",
description: """",
id: 0,
name: """",
rating: 0
}
];
const [movies, setMovies] = useState(initialValue);
useEffect(() => {
(async function() {
try {
// const response = await fetch(""http://192.168.1.164:5000/movies/display"");
// const json = await response.json();
// const result = json.data.result;
const result = [
{
category: ""cat1"",
description: ""desc1"",
id: ""1546514491119"",
name: ""randomname2"",
photo: null,
rating: ""3""
},
{
category: ""cat2"",
description: ""desc1"",
id: ""1546837819818"",
name: ""randomname1"",
rating: ""5""
}
];
console.log(""result ="", result);
setMovies(result);
console.log(""movies ="", movies);
} catch (e) {
console.error(e);
}
})();
}, []);
return <p>hello</p>;
};
const rootElement = document.getElementById(""root"");
ReactDOM.render(<StateSelector />, rootElement);
</script>
<script src=""https://unpkg.com/@babel/standalone@7/babel.min.js""></script>
<script src=""https://unpkg.com/react@17/umd/react.production.min.js""></script>
<script src=""https://unpkg.com/react-dom@17/umd/react-dom.production.min.js""></script>
Neither setMovies(result) nor setMovies(...result) works.
I expect the result variable to be pushed into the movies array.
",https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately,908,931248.0,21.0,,,2019-01-07 06:05:32,2025-12-17 02:53:21,2022-04-07 12:49:15,,,javascript;reactjs;react-hooks,Pranjal,9203,9832240,registered,true,54069332,,CC BY-SA 4.0,2021-09-18 08:45:09,2566,2234,7,0,0,3,true,false,false,true,true,true,62,10,false,0.023,0.001,2875,2019,1,6,Monday,false,false,true,false,false,false,false
47012169,A component is changing an uncontrolled input of type text to be controlled error in ReactJS,"
Warning: A component is changing an uncontrolled input of type text to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.*
Following is my code:
constructor(props) {
super(props);
this.state = {
fields: {},
errors: {}
}
this.onSubmit = this.onSubmit.bind(this);
}
....
onChange(field, e){
let fields = this.state.fields;
fields[field] = e.target.value;
this.setState({fields});
}
....
render() {
return(
<div className=""form-group"">
<input
value={this.state.fields[""name""]}
onChange={this.onChange.bind(this, ""name"")}
className=""form-control""
type=""text""
refs=""name""
placeholder=""Name *""
/>
<span style={{color: ""red""}}>{this.state.errors[""name""]}</span>
</div>
)
}
",https://stackoverflow.com/questions/47012169/a-component-is-changing-an-uncontrolled-input-of-type-text-to-be-controlled-erro,905,753114.0,28.0,,,2017-10-30 09:47:10,2025-04-22 07:48:18,2019-10-22 18:59:04,,,javascript;reactjs,Riya Kapuria,9938,8724053,registered,true,47012342,,CC BY-SA 4.0,,1015,952,1,0,0,2,true,false,false,true,true,true,92,16,false,0.037,0.0012,3309,2017,10,9,Monday,false,false,true,false,false,false,false
55840294,How to fix missing dependency warning when using useEffect React Hook,"With React 16.8.6 (it was good on previous version 16.8.3), I get this error when I attempt to prevent an infinite loop on a fetch request:
./src/components/BusinessesList.js
Line 51: React Hook useEffect has a missing dependency: 'fetchBusinesses'.
Either include it or remove the dependency array react-hooks/exhaustive-deps
I've been unable to find a solution that stops the infinite loop. I want to stay away from using useReducer(). I did find this discussion [ESLint] Feedback for 'exhaustive-deps' lint rule #14920 where a possible solution is You can always // eslint-disable-next-line react-hooks/exhaustive-deps if you think you know what you're doing. I'm not confident in what I'm doing, so I haven't tried implementing it just yet.
I have this current setup, React hook useEffect runs continuously forever/infinite loop and the only comment is about useCallback() which I'm not familiar with.
How I'm currently using useEffect() (which I only want to run once in the beginning similar to componentDidMount()):
useEffect(() => {
fetchBusinesses();
}, []);
const fetchBusinesses = () => {
return fetch("theURL", {method: "GET"}
)
.then(res => normalizeResponseErrors(res))
.then(res => {
return res.json();
})
.then(rcvdBusinesses => {
// some stuff
})
.catch(err => {
// some error handling
});
};
",https://stackoverflow.com/questions/55840294/how-to-fix-missing-dependency-warning-when-using-useeffect-react-hook,890,1255481.0,26.0,,,2019-04-25 00:35:14,2026-01-14 01:50:36,2022-05-17 00:17:17,,,reactjs;react-hooks;eslint;create-react-app;use-effect,russ,8933,11407978,registered,true,55854902,,CC BY-SA 4.0,2021-06-11 06:11:28,1817,1436,8,2,0,5,true,false,false,true,true,true,69,11,false,0.021,0.0007,2767,2019,4,0,Thursday,false,false,false,false,false,false,false
34130539,Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object,"I am getting this error:
Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
This is my code:
var React = require('react')
var ReactDOM = require('react-dom')
var Router = require('react-router')
var Route = Router.Route
var Link = Router.Link
var App = React.createClass({
render() {
return (
<div>
<h1>App</h1>
<ul>
<li><Link to="/about">About</Link></li>
</ul>
</div>
)
}
})
var About = require('./components/Home')
ReactDOM.render((
<Router>
<Route path="/" component={App}>
<Route path="about" component={About} />
</Route>
</Router>
), document.body)
My Home.jsx file:
var React = require('react');
var RaisedButton = require('material-ui/lib/raised-button');
var Home = React.createClass({
render:function() {
return (
<RaisedButton label="Default" />
);
},
});
module.exports = Home;
",https://stackoverflow.com/questions/34130539/uncaught-error-invariant-violation-element-type-is-invalid-expected-a-string,856,1179539.0,55.0,,,2015-12-07 09:46:00,2025-04-03 05:55:24,2024-04-02 15:31:35,,,javascript;node.js;reactjs;react-router;jsx,Pankaj Thakur,9971,5439331,registered,true,36265067,,CC BY-SA 4.0,2020-06-05 16:05:10,1265,1151,3,0,0,5,true,false,false,true,true,true,141,20,false,0.047,0.0007,4002,2015,12,9,Monday,false,false,true,false,false,false,false
24502898,Show or hide element in React,"I am messing around with React.js for the first time and cannot find a way to show or hide something on a page via click event. I am not loading any other library to the page, so I am looking for some native way to use the React library. This is what I have so far. I would like to show the results div when the click event fires.
var Search= React.createClass({
handleClick: function (event) {
console.log(this.prop);
},
render: function () {
return (
<div className="date-range">
<input type="submit" value="Search" onClick={this.handleClick} />
</div>
);
}
});
var Results = React.createClass({
render: function () {
return (
<div id="results" className="search-results">
Some Results
</div>
);
}
});
React.renderComponent(<Search /> , document.body);
",https://stackoverflow.com/questions/24502898/show-or-hide-element-in-react,838,1506658.0,34.0,,,2014-07-01 05:17:00,2024-03-01 07:18:18,2024-03-01 07:18:18,,,javascript;reactjs,user1725382,8582,1725382,registered,true,24534492,,CC BY-SA 4.0,2020-01-18 06:45:48,1060,992,1,0,0,2,true,false,false,true,true,true,29,6,false,0.023,0.0006,4526,2014,7,5,Tuesday,false,false,true,false,false,false,false
40714583,How to specify a port to run a create-react-app based project?,"My project is based on create-react-app. npm start or yarn start by default will run the application on port 3000 and there is no option of specifying a port in the package.json.
How can I specify a port of my choice in this case? I want to run two of this project simultaneously (for testing), one in port 3005 and other is 3006
",https://stackoverflow.com/questions/40714583/how-to-specify-a-port-to-run-a-create-react-app-based-project,814,1055649.0,32.0,,,2016-11-21 07:07:24,2024-10-23 15:32:50,2021-11-17 05:36:04,,,reactjs;npm;create-react-app;react-server,letthefireflieslive,12812,7215872,registered,true,41770848,,CC BY-SA 4.0,2022-10-04 10:40:30,571,332,4,1,0,4,true,false,false,true,true,true,62,11,true,0.03,0.0008,3652,2016,11,7,Monday,false,false,false,false,false,false,false
60618844,useEffect() is called twice even if an empty array is used as an argument,"I am writing code so that before the data is loaded from DB, it will show loading message, and then after it is loaded, render components with the loaded data. To do this, I am using both useState hook and useEffect hook. Here is the code:
The problem is, useEffect is triggered twice when I check with console.log. The code is thus querying the same data twice, which should be avoided.
Below is the code that I wrote:
import React from 'react';
import './App.css';
import {useState,useEffect} from 'react';
import Postspreview from '../components/Postspreview'
const indexarray=[]; //The array to which the fetched data will be pushed
function Home() {
const [isLoading,setLoad]=useState(true);
useEffect(()=>{
/*
Query logic to query from DB and push to indexarray
*/
setLoad(false); // To indicate that the loading is complete
})
},[]);
if (isLoading===true){
console.log("Loading");
return <div>This is loading...</div>
}
else {
console.log("Loaded!"); //This is actually logged twice.
return (
<div>
<div className="posts_preview_columns">
{indexarray.map(indexarray=>
<Postspreview
username={indexarray.username}
idThumbnail={indexarray.profile_thumbnail}
nickname={indexarray.nickname}
postThumbnail={indexarray.photolink}
/>
)}
</div>
</div>
);
}
}
export default Home;
Why it is called twice, and how to fix the code properly?
",https://stackoverflow.com/questions/60618844/useeffect-is-called-twice-even-if-an-empty-array-is-used-as-an-argument,808,600552.0,26.0,,,2020-03-10 13:40:57,2025-10-26 14:56:01,2025-10-26 14:56:01,,,reactjs;react-hooks,J.Ko,9051,12662242,registered,true,60619061,,CC BY-SA 4.0,2022-12-13 11:53:05,1725,1673,1,0,0,2,true,false,false,true,true,true,73,14,false,0.043,0.0013,2447,2020,3,13,Tuesday,false,false,false,false,false,false,false
53688899,What is the type of the 'children' prop?,"I have a very simple functional component as follows:
import * as React from 'react';
export interface AuxProps {
children: React.ReactNode
}
const aux = (props: AuxProps) => props.children;
export default aux;
And another component:
import * as React from ""react"";
export interface LayoutProps {
children: React.ReactNode
}
const layout = (props: LayoutProps) => (
<Aux>
<div>Toolbar, SideDrawer, Backdrop</div>
<main>
{props.children}
</main>
<Aux/>
);
export default layout;
I keep on getting the following error:
[ts]
JSX element type 'ReactNode' is not a constructor function for JSX elements.
Type 'undefined' is not assignable to type 'ElementClass'. [2605]
How do I type this correctly?
",https://stackoverflow.com/questions/53688899/what-is-the-type-of-the-children-prop,805,710247.0,29.0,,,2018-12-09 02:38:33,2024-08-13 16:37:57,2022-10-13 08:51:11,,,reactjs;typescript;jsx;typescript2.0,Asool,14369,4873380,registered,true,,,CC BY-SA 4.0,,926,818,2,0,0,4,false,false,false,true,true,true,48,8,true,0.041,0.0011,2904,2018,12,2,Sunday,true,false,false,false,false,false,false
27991366,What is the difference between state and props in React?,"I was watching a Pluralsight course on React and the instructor stated that props should not be changed. I'm now reading an article (uberVU/react-guide) on props vs. state and it says
Both props and state changes trigger a render update.
Later in the article it says:
Props (short for properties) are a Component's configuration, its options if you may. They are received from above and immutable.
- So props can change but they should be immutable?
- When should you use props and when should you use state?
- If you have data that a React component needs, should it be passed through props or setup in the React component via
getInitialState?
",https://stackoverflow.com/questions/27991366/what-is-the-difference-between-state-and-props-in-react,797,348128.0,50.0,,,2015-01-16 19:28:27,2023-05-24 14:31:09,2016-04-05 10:21:04,,,javascript;reactjs,Animal Rights,9427,385834,registered,true,27992380,,CC BY-SA 3.0,2023-01-10 01:17:23,864,655,1,1,0,2,true,false,false,true,true,true,56,10,true,0.144,0.0023,4327,2015,1,19,Friday,false,false,true,false,false,false,false
63124161,Attempted import error: 'Switch' is not exported from 'react-router-dom',"I don't know why I am getting this error and I can't find an answer for it anywhere. I have uninstalled the react-router-dom package and reinstalled it, but it continues to tell me that the switch module is not exported from react-router-dom. Here's my code.
The error I'm getting:
Attempted import error: 'Switch' is not exported from 'react-router-dom'.
Code
import React from 'react';
import './App.css';
import NavBar from './components/navbar.js';
import Footer from './components/footer.js';
import Home from './components/pages/homepage/home.js';
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
function App() {
return (
<Router>
<div className="app-container">
<NavBar />
<Switch>
<Route path="/home" component={Home} />
</Switch>
<Footer />
</div>
</Router>
);
}
export default App;
",https://stackoverflow.com/questions/63124161/attempted-import-error-switch-is-not-exported-from-react-router-dom,774,1106366.0,44.0,,,2020-07-27 21:54:58,2025-01-13 10:23:01,2022-02-03 22:12:09,,,reactjs,ajesamann,7820,12384756,registered,true,,,CC BY-SA 4.0,2021-11-06 11:52:25,1099,970,2,0,0,1,false,false,false,true,true,true,88,9,false,0.04,0.0007,2308,2020,7,21,Monday,false,false,false,false,false,false,false
32782922,What do multiple arrow functions mean in JavaScript?,"I have been reading a bunch of React code and I see stuff like this that I don't understand:
handleChange = field => e => {
e.preventDefault();
/// Do something here
}
",https://stackoverflow.com/questions/32782922/what-do-multiple-arrow-functions-mean-in-javascript,749,188306.0,7.0,,,2015-09-25 13:06:31,2023-04-06 14:45:33,2022-02-16 14:25:38,,,javascript;reactjs;ecmascript-6;arrow-functions,jhamm,25192,968801,registered,true,,,CC BY-SA 4.0,2019-07-13 20:58:37,293,179,1,1,0,4,false,false,false,true,true,true,52,8,true,0.037,0.004,4075,2015,9,13,Friday,false,false,true,false,false,false,false
29685421,Hide keyboard in react-native,"If I tap onto a textinput, I want to be able to tap somewhere else in order to dismiss the keyboard again (not the return key though). I haven't found the slightest piece of information concerning this in all the tutorials and blog posts that I read.
This basic example is still not working for me with react-native 0.4.2 in the Simulator. Couldn't try it on my iPhone yet.
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit index.ios.js
</Text>
<Text style={styles.instructions}>
Press Cmd+R to reload,{'\n'}
Cmd+D or shake for dev menu
</Text>
<TextInput
style={{height: 40, borderColor: 'gray', borderWidth: 1}}
onEndEditing={this.clearFocus}
/>
</View>
",https://stackoverflow.com/questions/29685421/hide-keyboard-in-react-native,729,487586.0,38.0,,,2015-04-16 20:33:33,2023-06-07 07:53:24,2020-10-12 10:33:56,,,reactjs;react-native,TurboFish,8299,1714527,registered,true,34779467,,CC BY-SA 4.0,2018-04-13 21:19:36,928,853,1,0,0,2,true,false,false,true,true,true,29,4,false,0.078,0.0015,4237,2015,4,20,Thursday,false,false,false,false,false,false,false
30668326,What is the difference between using constructor vs getInitialState in React / React Native?,"I've seen both used interchangeably.
What are the main use cases for both? Are there advantages / disadvantages? Is one a better practice?
",https://stackoverflow.com/questions/30668326/what-is-the-difference-between-using-constructor-vs-getinitialstate-in-react-r,719,233465.0,9.0,,,2015-06-05 13:53:36,2025-02-12 10:24:42,2017-09-22 04:57:28,,,reactjs;react-native;constructor,Nader Dabit,53861,2864119,registered,true,30668609,,CC BY-SA 3.0,,164,150,0,0,0,3,true,false,false,true,true,true,92,14,true,0.039,0.0031,4187,2015,6,13,Friday,false,false,false,false,false,false,false
23123138,How can I perform a debounce?,"How do you perform debounce in React?
I want to debounce the handleOnChange function.
I tried with debounce(this.handleOnChange, 200), but it doesn't work.
function debounce(fn, delay) {
var timer = null;
return function() {
var context = this,
args = arguments;
clearTimeout(timer);
timer = setTimeout(function() {
fn.apply(context, args);
}, delay);
};
}
var SearchBox = React.createClass({
render: function() {
return <input type="search" name="p" onChange={this.handleOnChange} />;
},
handleOnChange: function(event) {
// Make Ajax call
}
});
",https://stackoverflow.com/questions/23123138/how-can-i-perform-a-debounce,701,528532.0,49.0,,,2014-04-17 01:41:50,2025-08-19 06:54:03,2025-08-19 06:54:03,,,javascript;reactjs;debouncing,Chetan Ankola,7085,1307200,registered,true,,,CC BY-SA 4.0,2021-05-11 14:47:14,684,626,2,0,0,3,false,false,false,true,true,true,29,6,true,0.093,0.0013,4601,2014,4,1,Thursday,false,false,true,false,false,false,false
24718709,ReactJS - Does render get called any time "setState" is called?,"Does React re-render all components and sub components every time setState() is called?
If so, why? I thought the idea was that React only rendered as little as needed - when state changed.
In the following simple example, both classes render again when the text is clicked, despite the fact that the state doesn't change on subsequent clicks, as the onClick handler always sets the state to the same value:
this.setState({'test':'me'});
I would've expected that renders would only happen if state data had changed.
Here's the code of the example, as a JS Fiddle, and embedded snippet:
var TimeInChild = React.createClass({
render: function() {
var t = new Date().getTime();
return (
<p>Time in child:{t}</p>
);
}
});
var Main = React.createClass({
onTest: function() {
this.setState({'test':'me'});
},
render: function() {
var currentTime = new Date().getTime();
return (
<div onClick={this.onTest}>
<p>Time in main:{currentTime}</p>
<p>Click me to update time</p>
<TimeInChild/>
</div>
);
}
});
ReactDOM.render(<Main/>, document.body);
<script src=""https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react.min.js""></script>
<script src=""https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react-dom.min.js""></script>
",https://stackoverflow.com/questions/24718709/reactjs-does-render-get-called-any-time-setstate-is-called,678,397060.0,10.0,,,2014-07-13 01:11:07,2025-08-03 01:23:21,2020-08-27 15:09:02,,,javascript;reactjs,Brad Parks,73800,26510,registered,true,24719289,,CC BY-SA 4.0,,1929,1473,6,1,0,2,true,false,false,true,true,true,73,11,true,0.025,0.0017,4514,2014,7,1,Sunday,true,false,true,false,false,false,false
30571875,What's the difference between "super()" and "super(props)" in React when using es6 classes?,"When is it important to pass props to super(), and why?
class MyComponent extends React.Component {
constructor(props) {
super(); // or super(props) ?
}
}
",https://stackoverflow.com/questions/30571875/whats-the-difference-between-super-and-superprops-in-react-when-using-e,664,270049.0,10.0,,,2015-06-01 11:04:52,2019-08-08 21:55:02,,,,reactjs;ecmascript-6,Misha Moroshko,172725,247243,registered,true,34995257,,CC BY-SA 3.0,,222,165,3,0,0,2,true,false,false,true,true,false,115,13,true,0.037,0.0025,4191,2015,6,11,Monday,false,false,false,false,false,false,false
64625050,Error: 'node-sass' version 5.0.0 is incompatible with ^4.0.0,"I've created a blank React project, using the command: npx create-react-app on npm v7.0.7 and Node.js v15.0.1
Installed:
- React v17.0.1,
- node-sass v5.0.0,
Then I tried to import a blank .scss file to the App component:
File App.js
import './App.scss'
function App() {
return (
<div className="App">
App
</div>
);
}
export default App;
It throws an error:
Failed to compile.
./src/App.scss (./node_modules/css-loader/dist/cjs.js??ref--5-oneOf-6-1!./node_modules/postcss-loader/src??postcss!./node_modules/resolve-url-loader??ref--5-oneOf-6-3!./node_modules/s
ass-loader/dist/cjs.js??ref--5-oneOf-6-4!./src/App.scss)
Error: Node Sass version 5.0.0 is incompatible with ^4.0.0.
File package.json
{
"name": "react-17-node-sass-5",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.11.5",
"@testing-library/react": "^11.1.0",
"@testing-library/user-event": "^12.1.10",
"node-sass": "^5.0.0",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-scripts": "4.0.0",
"web-vitals": "^0.2.4"
},
...
}
}
",https://stackoverflow.com/questions/64625050/error-node-sass-version-5-0-0-is-incompatible-with-4-0-0,662,496954.0,23.0,,,2020-10-31 18:19:20,2023-03-07 03:58:03,2021-09-05 13:38:51,,,reactjs;webpack;sass;create-react-app;node-sass,JDKot,6781,5552577,registered,true,64626556,,CC BY-SA 4.0,2020-11-07 00:46:15,1544,1342,4,0,0,5,true,false,false,true,true,true,68,8,false,0.046,0.0013,2212,2020,10,18,Saturday,true,false,false,false,false,false,false
43040721,How to update nested state properties in React,"I'm trying to organize my state by using nested property like this:
this.state = {
someProperty: {
flag:true
}
}
But updating state like this,
this.setState({ someProperty.flag: false });
doesn't work. How can this be done correctly?
",https://stackoverflow.com/questions/43040721/how-to-update-nested-state-properties-in-react,642,504086.0,36.0,,,2017-03-27 07:51:38,2023-05-30 19:28:43,2019-04-22 03:49:44,,,javascript;reactjs;ecmascript-6;setstate,Alex Yong,7675,7588803,registered,true,43041334,,CC BY-SA 4.0,,321,252,2,0,0,4,true,false,false,true,true,true,46,8,false,0.071,0.0013,3526,2017,3,7,Monday,false,false,true,false,false,false,false
46169472,What is the difference between using .js vs .jsx files in React?,"There is something I find very confusing when working in React.
There are plenty of examples available on internet which use .js files with react but many others use .jsx files.
I have read about .jsx files and my understanding is that they just let you write HTML tags within JavaScript. But the same thing can be written in .js files as well.
So what is the actual difference between using these two file types in React?
",https://stackoverflow.com/questions/46169472/what-is-the-difference-between-using-js-vs-jsx-files-in-react,636,434542.0,12.0,,,2017-09-12 06:34:28,2024-10-11 15:44:09,2024-10-11 15:44:09,,,reactjs;jsx,ConfusedDeveloper,7091,2988458,registered,true,46169521,,CC BY-SA 4.0,2019-12-23 21:44:19,451,423,0,0,0,2,true,false,false,true,true,true,64,12,true,0.028,0.0015,3357,2017,9,6,Tuesday,false,false,false,false,false,false,false
21733847,React JSX: selecting "selected" on selected <select> option,"In a React component for a <select> menu, I need to set the selected attribute on the option that reflects the application state.
In render(), the optionState is passed from the state owner to the SortMenu component. The option values are passed in as props from JSON.
render: function() {
var options = [],
optionState = this.props.optionState;
this.props.options.forEach(function(option) {
var selected = (optionState === option.value) ? ' selected' : '';
options.push(
<option value={option.value}{selected}>{option.label}</option>
);
});
// pass {options} to the select menu jsx
However that triggers a syntax error on JSX compilation.
Doing this gets rid of the syntax error but obviously doesn't solve the problem:
var selected = (optionState === option.value) ? 'selected' : 'false';
<option value={option.value} selected={selected}>{option.label}</option>
I also tried this:
var selected = (optionState === option.value) ? true : false;
<option value={option.value} {selected ? 'selected' : ''}>{option.label}</option>
Is there a recommended way of solving this?
",https://stackoverflow.com/questions/21733847/react-jsx-selecting-selected-on-selected-select-option,626,851825.0,17.0,,,2014-02-12 16:34:00,2023-07-10 07:54:42,2018-12-05 00:12:28,,,javascript;reactjs,cantera,25145,723007,registered,true,21736116,,CC BY-SA 4.0,,1338,1159,8,0,0,2,true,false,false,true,true,true,75,8,false,0.02,0.0007,4665,2014,2,16,Wednesday,false,false,true,false,false,false,false
26253351,Correct modification of state arrays in React.js,"I want to add an element to the end of a state array, is this the correct way to do it?
this.state.arrayvar.push(newelement);
this.setState({ arrayvar:this.state.arrayvar });
I'm concerned that modifying the array in-place with push might cause trouble - is it safe?
The alternative of making a copy of the array, and setStateing that seems wasteful.
",https://stackoverflow.com/questions/26253351/correct-modification-of-state-arrays-in-react-js,625,942762.0,19.0,,,2014-10-08 09:20:37,2024-09-16 17:53:29,2021-01-05 18:39:19,,,javascript;reactjs,fadedbee,45405,129805,registered,true,26254086,,CC BY-SA 4.0,,436,352,4,0,0,2,true,false,false,true,true,true,48,7,false,0.02,0.0007,4427,2014,10,9,Wednesday,false,false,true,false,false,false,false
35537229,How can I update the parent's state in React?,"My structure looks as follows:
Component 1
- |- Component 2
- - |- Component 4
- - - |- Component 5
Component 3
Component 3 should display some data depending on state of Component 5.
Since props are immutable, I can't simply save its state in Component 1 and forward it, right? And yes, I've read about Redux, but I don't want to use it. I hope that it's possible to solve it just with react. Am I wrong?
",https://stackoverflow.com/questions/35537229/how-can-i-update-the-parents-state-in-react,601,667182.0,26.0,,,2016-02-21 14:17:52,2023-10-08 14:19:58,2021-05-21 14:56:18,,,javascript;reactjs;web-deployment,Wojciech Kulma,6466,3510205,registered,true,35537718,,CC BY-SA 4.0,,550,417,1,1,0,3,true,false,false,true,true,true,49,9,true,0.039,0.0009,3926,2016,2,14,Sunday,true,false,true,false,false,false,false
66239691,What does npm install --legacy-peer-deps do exactly? When is it recommended / What's a potential use case?,"Just ran into this error:
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: nexttwin@0.1.0
npm ERR! Found: react@17.0.1
npm ERR! node_modules/react
npm ERR! react@"17.0.1" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@"^16.8.0" from react-hook-mousetrap@2.0.4
npm ERR! node_modules/react-hook-mousetrap
npm ERR! react-hook-mousetrap@"*" from the root project
npm ERR!
The module I am trying to install seems to have a different peer dependency from what I have installed. It seems like npm changed its behaviour in this regard and now lets the install fail.
What can I do now to fix this? I don't want to downgrade my React version for this.
I know there is a flag called --legacy-peer-deps but I am not sure what exactly this does and whether it's recommended to use it / what the potential disadvantages are? I assume there is a reason npm did let the install fail.
It's just strange because I was using yarn up until very recently and everything was fine.
",https://stackoverflow.com/questions/66239691/what-does-npm-install-legacy-peer-deps-do-exactly-when-is-it-recommended-wh,600,820377.0,8.0,,,2021-02-17 10:03:55,2023-12-27 18:10:30,,,,javascript;node.js;reactjs;npm;npm-install,antonwilhelm,7965,15093141,registered,true,66346921,,CC BY-SA 4.0,,1186,1101,3,0,0,5,true,false,false,true,true,false,110,17,true,0.01,0.0007,2103,2021,2,10,Wednesday,false,false,true,false,false,false,false
31284169,Parse Error: Adjacent JSX elements must be wrapped in an enclosing tag,"I am trying to set up my React.js app so that it only renders if a variable I have set is true.
The way my render function is set up looks like:
render: function() {
var text = this.state.submitted ? 'Thank you! Expect a follow up at '+email+' soon!' : 'Enter your email to request early access:';
var style = this.state.submitted ? {""backgroundColor"": ""rgba(26, 188, 156, 0.4)""} : {};
return (
<div>
if(this.state.submitted==false)
{
<input type=""email"" className=""input_field"" onChange={this._updateInputValue} ref=""email"" value={this.state.email} />
<ReactCSSTransitionGroup transitionName=""example"" transitionAppear={true}>
<div className=""button-row"">
<a href=""#"" className=""button"" onClick={this.saveAndContinue}>Request Invite</a>
</div>
</ReactCSSTransitionGroup>
}
</div>
)
},
Basically, the important portion here is the if(this.state.submitted==false) portion (I want these div elements to show up when the submitted variable is set to false).
But when running this, I get the error in the question:
Uncaught Error: Parse Error: Line 38: Adjacent JSX elements must be wrapped in an enclosing tag
What is the issue here? And what can I use to make this work?
",https://stackoverflow.com/questions/31284169/parse-error-adjacent-jsx-elements-must-be-wrapped-in-an-enclosing-tag,598,617986.0,17.0,,,2015-07-08 05:28:28,2024-02-12 07:18:29,2019-10-29 13:43:10,,,javascript;reactjs;render,user1072337,12967,1072337,registered,true,,,CC BY-SA 4.0,2021-02-04 05:59:21,1462,1306,6,0,0,3,false,false,false,true,true,true,70,12,false,0.028,0.001,4154,2015,7,5,Wednesday,false,false,true,false,false,false,false
53332321,React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing,"I was trying the useEffect example something like below:
useEffect(async () => {
try {
const response = await fetch(`https://www.reddit.com/r/${subreddit}.json`);
const json = await response.json();
setPosts(json.data.children.map(it => it.data));
} catch (e) {
console.error(e);
}
}, []);
and I get this warning in my console. But the cleanup is optional for async calls I think. I am not sure why I get this warning. Linking sandbox for examples. https://codesandbox.io/s/24rj871r0p
![]()
",https://stackoverflow.com/questions/53332321/react-hook-warnings-for-async-function-in-useeffect-useeffect-function-must-ret,595,927463.0,20.0,,,2018-11-16 06:07:12,2025-01-12 03:05:56,2020-09-30 23:05:47,,,javascript;reactjs;react-hooks,RedPandaz,6376,6790622,registered,true,53572588,,CC BY-SA 4.0,,836,538,2,2,1,3,true,false,false,true,true,true,113,17,false,0.022,0.0006,2927,2018,11,6,Friday,false,false,true,false,false,false,false
53120972,How to call loading function with React useEffect only once,"The useEffect React hook will run the passed-in function on every change. This can be optimized to let it call only when the desired properties change.
What if I want to call an initialization function from componentDidMount and not call it again on changes? Let's say I want to load an entity, but the loading function doesn't need any data from the component. How can we make this using the useEffect hook?
class MyComponent extends React.PureComponent {
componentDidMount() {
loadDataOnlyOnce();
}
render() { ... }
}
With hooks this could look like this:
function MyComponent() {
useEffect(() => {
loadDataOnlyOnce(); // this will fire on every change :(
}, [...???]);
return (...);
}
",https://stackoverflow.com/questions/53120972/how-to-call-loading-function-with-react-useeffect-only-once,594,772356.0,18.0,,,2018-11-02 14:58:55,2025-07-01 10:52:06,2022-05-17 00:37:50,,,javascript;reactjs;react-hooks;use-effect,Dávid Molnár,11773,1093508,registered,true,53121021,,CC BY-SA 4.0,,902,733,4,1,0,4,true,false,false,true,true,true,59,10,false,0.023,0.0008,2941,2018,11,14,Friday,false,false,true,false,false,false,false
37427508,React - changing an uncontrolled input,"I have a simple react component with the form which I believe to have one controlled input:
import React from 'react';
export default class MyForm extends React.Component {
constructor(props) {
super(props);
this.state = {}
}
render() {
return (
<form className=""add-support-staff-form"">
<input name=""name"" type=""text"" value={this.state.name} onChange={this.onFieldChange('name').bind(this)}/>
</form>
)
}
onFieldChange(fieldName) {
return function (event) {
this.setState({[fieldName]: event.target.value});
}
}
}
export default MyForm;
When I run my application I get the following warning:
Warning: MyForm is changing an uncontrolled input of type text to be
controlled. Input elements should not switch from uncontrolled to
controlled (or vice versa). Decide between using a controlled or
uncontrolled input element for the lifetime of the component
I believe my input is controlled since it has a value. I am wondering what am I doing wrong?
I am using React 15.1.0
",https://stackoverflow.com/questions/37427508/react-changing-an-uncontrolled-input,590,637963.0,25.0,,,2016-05-25 03:50:59,2024-06-15 09:28:46,2019-02-07 22:05:41,,,javascript;node.js;reactjs;react-state,alexs333,12683,872514,registered,true,37427579,,CC BY-SA 4.0,2021-09-10 17:39:49,1235,1134,1,0,0,4,true,false,false,true,true,true,38,6,false,0.039,0.0009,3832,2016,5,3,Wednesday,false,false,true,false,false,false,false
34930735,Pros/cons of using redux-saga with ES6 generators vs redux-thunk with ES2017 async/await,"There is a lot of talk about the latest kid in redux town right now, redux-saga/redux-saga. It uses generator functions for listening to/dispatching actions.
Before I wrap my head around it, I would like to know the pros/cons of using redux-saga instead of the approach below where I'm using redux-thunk with async/await.
A component might look like this, dispatch actions like usual.
import { login } from 'redux/auth';
class LoginForm extends Component {
onClick(e) {
e.preventDefault();
const { user, pass } = this.refs;
this.props.dispatch(login(user.value, pass.value));
}
render() {
return (<div>
<input type=""text"" ref=""user"" />
<input type=""password"" ref=""pass"" />
<button onClick={::this.onClick}>Sign In</button>
</div>);
}
}
export default connect((state) => ({}))(LoginForm);
Then my actions look something like this:
// auth.js
import request from 'axios';
import { loadUserData } from './user';
// define constants
// define initial state
// export default reducer
export const login = (user, pass) => async (dispatch) => {
try {
dispatch({ type: LOGIN_REQUEST });
let { data } = await request.post('/login', { user, pass });
await dispatch(loadUserData(data.uid));
dispatch({ type: LOGIN_SUCCESS, data });
} catch(error) {
dispatch({ type: LOGIN_ERROR, error });
}
}
// more actions...
// user.js
import request from 'axios';
// define constants
// define initial state
// export default reducer
export const loadUserData = (uid) => async (dispatch) => {
try {
dispatch({ type: USERDATA_REQUEST });
let { data } = await request.get(`/users/${uid}`);
dispatch({ type: USERDATA_SUCCESS, data });
} catch(error) {
dispatch({ type: USERDATA_ERROR, error });
}
}
// more actions...
",https://stackoverflow.com/questions/34930735/pros-cons-of-using-redux-saga-with-es6-generators-vs-redux-thunk-with-es2017-asy,581,137388.0,11.0,,,2016-01-21 17:45:12,2025-05-22 21:18:56,2018-02-17 09:04:09,,,javascript;reactjs;redux;redux-thunk;redux-saga,hampusohlsson,10239,980929,registered,true,34933395,,CC BY-SA 3.0,2025-05-22 22:09:41,2117,1915,5,1,0,5,true,false,false,true,true,true,88,12,false,0.08,0.0042,3957,2016,1,17,Thursday,false,false,true,false,false,false,false
50432556,Cannot use JSX unless the '--jsx' flag is provided,"I have looked around a bit for a solution to this problem. All of them suggest adding ""jsx"": ""react"" to your tsconfig.json file. Which I have done. Another one was to add ""include: []"", which I have also done. However, I am still getting the error when I am trying to edit .tsxfiles. Below is my tsconfig file.
{
""compilerOptions"": {
""module"": ""commonjs"",
""target"": ""es5"",
""allowJs"": true,
""checkJs"": false,
""jsx"": ""react"",
""outDir"": ""./build"",
""rootDir"": ""./lib"",
""removeComments"": true,
""noEmit"": true,
""pretty"": true,
""skipLibCheck"": true,
""strict"": true,
""moduleResolution"": ""node"",
""esModuleInterop"": true
},
""include"": [
""./lib/**/*""
],
""exclude"": [
""node_modules""
]
}
Any suggestions would be helpful. I am using babel 7 to compile all the code with the env, react and typescript presets. If you guys need more files to help debug this, let me know.
",https://stackoverflow.com/questions/50432556/cannot-use-jsx-unless-the-jsx-flag-is-provided,569,628562.0,36.0,,,2018-05-20 07:17:28,2025-07-23 05:09:46,,,,reactjs;typescript;jsx;tsx,AJDEV,5950,3584674,registered,true,50440909,,CC BY-SA 4.0,2022-05-22 19:42:42,1089,1012,4,0,0,4,true,false,false,true,true,false,58,9,false,0.057,0.0009,3107,2018,5,7,Sunday,true,false,false,false,false,false,false
34424845,Adding script tag to React/JSX,"I have a relatively straightforward issue of trying to add inline scripting to a React component. What I have so far:
'use strict';
import '../../styles/pages/people.scss';
import React, { Component } from 'react';
import DocumentTitle from 'react-document-title';
import { prefix } from '../../core/util';
export default class extends Component {
render() {
return (
<DocumentTitle title="People">
<article className={[prefix('people'), prefix('people', 'index')].join(' ')}>
<h1 className="tk-brandon-grotesque">People</h1>
<script src="https://use.typekit.net/foobar.js"></script>
<script dangerouslySetInnerHTML={{__html: 'try{Typekit.load({ async: true });}catch(e){}'}}></script>
</article>
</DocumentTitle>
);
}
};
I have also tried:
<script src="https://use.typekit.net/foobar.js"></script>
<script>try{Typekit.load({ async: true });}catch(e){}</script>
Neither approach seems to execute the desired script. I'm guessing it's a simple thing I'm missing. Can anybody help out?
PS: Ignore the foobar, I have a real id actually in use that I didn't feel like sharing.
",https://stackoverflow.com/questions/34424845/adding-script-tag-to-react-jsx,559,1026627.0,26.0,,,2015-12-22 21:38:29,2025-02-19 19:19:35,2021-01-03 09:19:42,,,javascript;reactjs;ecmascript-6,ArrayKnight,7426,2069860,registered,true,34425083,,CC BY-SA 4.0,2024-04-04 04:05:59,1479,1364,2,0,0,3,true,false,false,true,true,true,30,5,false,0.025,0.0005,3987,2015,12,21,Tuesday,false,false,true,false,false,false,false
43262121,Trying to use fetch and pass in mode: no-cors,"I can hit this endpoint, http://catfacts-api.appspot.com/api/facts?number=99 via Postman and it returns JSON
Additionally I am using create-react-app and would like to avoid setting up any server config.
In my client code I am trying to use fetch to do the same thing, but I get the error:
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:3000' is therefore not allowed
access. If an opaque response serves your needs, set the request's
mode to 'no-cors' to fetch the resource with CORS disabled.
So I am trying to pass in an object, to my Fetch which will disable CORS, like so:
fetch('http://catfacts-api.appspot.com/api/facts?number=99', { mode: 'no-cors'})
.then(blob => blob.json())
.then(data => {
console.table(data);
return data;
})
.catch(e => {
console.log(e);
return e;
});
Interestingly enough the error I get is actually a syntax error with this function. I am not sure my actual fetch is broken, because when I remove the { mode: 'no-cors' } object, and supply it with a different URL it works just fine.
I have also tried to pass in the object { mode: 'opaque'} , but this returns the original error from above.
I belive all I need to do is disable CORS.. What am I missing?
",https://stackoverflow.com/questions/43262121/trying-to-use-fetch-and-pass-in-mode-no-cors,547,1344792.0,13.0,,,2017-04-06 17:36:05,2025-01-28 11:27:39,2019-06-22 08:59:07,,,javascript;reactjs;cors;create-react-app;fetch-api,dwww,5728,6211000,registered,true,,,CC BY-SA 4.0,2025-01-28 15:14:49,1521,1298,6,1,0,5,false,false,false,true,true,true,45,9,false,0.01,0.0004,3516,2017,4,17,Thursday,false,false,true,false,false,false,false
40676343,Typescript input onchange event.target.value,"In my react and typescript app, I use:
onChange={(e) => data.motto = (e.target as any).value}
How do I correctly define the typings for the class, so I wouldn't have to hack my way around the type system with any?
export interface InputProps extends React.HTMLProps<Input> {
...
}
export class Input extends React.Component<InputProps, {}> {
}
If I put target: { value: string }; I get :
ERROR in [default] /react-onsenui.d.ts:87:18
Interface 'InputProps' incorrectly extends interface 'HTMLProps<Input>'.
Types of property 'target' are incompatible.
Type '{ value: string; }' is not assignable to type 'string'.
",https://stackoverflow.com/questions/40676343/typescript-input-onchange-event-target-value,545,1062681.0,25.0,,,2016-11-18 11:46:02,2025-09-25 11:13:52,2022-04-11 15:31:14,,,reactjs;typescript;types;typescript-typings,wildeyes,7708,2903329,registered,true,42645711,,CC BY-SA 4.0,,764,645,5,0,0,4,true,false,false,true,true,true,44,4,false,0.024,0.0005,3655,2016,11,11,Friday,false,false,false,false,false,false,false
39195687,Setting a backgroundImage With React Inline Styles,"I'm trying to access a static image to use within an inline backgroundImage property within React. Unfortunately, I've run up dry on how to do this.
Generally, I thought you just did as follows:
import Background from '../images/background_image.png';
var sectionStyle = {
width: "100%",
height: "400px",
backgroundImage: "url(" + { Background } + ")"
};
class Section extends Component {
render() {
return (
<section style={ sectionStyle }>
</section>
);
}
}
This works for <img> tags. Can someone explain the difference between the two?
Example:
<img src={ Background } /> works just fine.
Thank you!
",https://stackoverflow.com/questions/39195687/setting-a-backgroundimage-with-react-inline-styles,532,900802.0,23.0,,,2016-08-28 20:54:15,2024-05-19 04:24:43,2020-08-10 20:45:28,,,javascript;reactjs,Kris,10373,3783770,registered,true,39196525,,CC BY-SA 4.0,,805,700,4,0,0,2,true,false,false,true,true,true,50,7,false,0.026,0.0006,3737,2016,8,20,Sunday,true,false,true,false,false,false,false
33117449,Invariant Violation: Objects are not valid as a React child,"In my component's render function I have:
render() {
const items = ['EN', 'IT', 'FR', 'GR', 'RU'].map((item) => {
return (<li onClick={this.onItemClick.bind(this, item)} key={item}>{item}</li>);
});
return (
<div>
...
<ul>
{items}
</ul>
...
</div>
);
}
everything renders fine, however when clicking the <li> element I receive the following error:
Uncaught Error: Invariant Violation: Objects are not valid as a React
child (found: object with keys {dispatchConfig, dispatchMarker,
nativeEvent, target, currentTarget, type, eventPhase, bubbles,
cancelable, timeStamp, defaultPrevented, isTrusted, view, detail,
screenX, screenY, clientX, clientY, ctrlKey, shiftKey, altKey,
metaKey, getModifierState, button, buttons, relatedTarget, pageX,
pageY, isDefaultPrevented, isPropagationStopped, _dispatchListeners,
_dispatchIDs}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from
the React add-ons. Check the render method of Welcome.
If I change to this.onItemClick.bind(this, item) to (e) => onItemClick(e, item) inside the map function everything works as expected.
If someone could explain what I am doing wrong and explain why do I get this error, would be great
UPDATE 1:
onItemClick function is as follows and removing this.setState results in error disappearing.
onItemClick(e, item) {
this.setState({
lang: item,
});
}
But I cannot remove this line as I need to update state of this component
",https://stackoverflow.com/questions/33117449/invariant-violation-objects-are-not-valid-as-a-react-child,532,976462.0,54.0,,,2015-10-14 05:43:56,2024-07-04 01:18:21,2015-11-16 15:55:01,,,javascript;reactjs,a9a4k,7588,3194545,registered,true,,,CC BY-SA 3.0,2024-07-04 18:08:46,1843,1665,6,0,0,2,false,false,false,true,true,true,59,10,false,0.055,0.0005,4056,2015,10,5,Wednesday,false,false,true,false,false,false,false
19014250,Rerender view on browser resize with React,"How can I get React to re-render the view when the browser window is resized?
Background
I have some blocks that I want to layout individually on the page, however I also want them to update when the browser window changes. The very end result will be something like Ben Holland's Pinterest layout, but written using React not just jQuery. I’m still a way off.
Code
Here’s my app:
var MyApp = React.createClass({
//does the http get from the server
loadBlocksFromServer: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
mimeType: 'textPlain',
success: function(data) {
this.setState({data: data.events});
}.bind(this)
});
},
getInitialState: function() {
return {data: []};
},
componentWillMount: function() {
this.loadBlocksFromServer();
},
render: function() {
return (
<div>
<Blocks data={this.state.data}/>
</div>
);
}
});
React.renderComponent(
<MyApp url=""url_here""/>,
document.getElementById('view')
)
Then I have the Block component (equivalent to a Pin in the above Pinterest example):
var Block = React.createClass({
render: function() {
return (
<div class=""dp-block"" style={{left: this.props.top, top: this.props.left}}>
<h2>{this.props.title}</h2>
<p>{this.props.children}</p>
</div>
);
}
});
and the list/collection of Blocks:
var Blocks = React.createClass({
render: function() {
//I've temporarily got code that assigns a random position
//See inside the function below...
var blockNodes = this.props.data.map(function (block) {
//temporary random position
var topOffset = Math.random() * $(window).width() + 'px';
var leftOffset = Math.random() * $(window).height() + 'px';
return <Block order={block.id} title={block.summary} left={leftOffset} top={topOffset}>{block.description}</Block>;
});
return (
<div>{blockNodes}</div>
);
}
});
Question
Should I add jQuery’s window resize? If so, where?
$( window ).resize(function() {
// re-render the component
});
Is there a more “React” way of doing this?
",https://stackoverflow.com/questions/19014250/rerender-view-on-browser-resize-with-react,524,563704.0,25.0,,,2013-09-25 20:06:06,2025-11-09 07:35:19,2018-04-26 16:32:13,,,javascript;reactjs;resize,digibake,5251,2816731,registered,true,19014495,,CC BY-SA 3.0,,2578,2257,7,1,0,3,true,false,false,true,true,true,42,7,false,0.044,0.0009,4805,2013,9,20,Wednesday,false,false,true,false,false,false,false
39501289,"In reactJS, how to copy text to clipboard?","I'm using ReactJS and when a user clicks a link I want to copy some text to the clipboard.
I am using Chrome 52 and I do not need to support any other browsers.
I can't see why this code does not result in the data being copied to the clipboard. (the origin of the code snippet is from a Reddit post).
Am I doing this wrong? Can anyone suggest is there a ""correct"" way to implement copy to clipboard using reactjs?
copyToClipboard = (text) => {
console.log('text', text)
var textField = document.createElement('textarea')
textField.innerText = text
document.body.appendChild(textField)
textField.select()
document.execCommand('copy')
textField.remove()
}
",https://stackoverflow.com/questions/39501289/in-reactjs-how-to-copy-text-to-clipboard,514,698056.0,31.0,,,2016-09-14 23:52:18,2024-02-02 02:40:33,2016-09-15 00:49:47,,,javascript;reactjs;clipboard,Duke Dougal,26796,627492,registered,true,,,CC BY-SA 3.0,,729,677,1,0,0,3,false,false,false,true,true,true,42,8,true,0.044,0.0007,3720,2016,9,23,Wednesday,false,false,true,false,false,false,false
41004631,Trace why a React component is re-rendering,"Is there a systematic approach to debug what is causing a component to re-render in React? I put a simple console.log() to see how many time it renders, but am having trouble figuring out what is causing the component to render multiple times i.e (4 times) in my case. Is there a tool that exists that shows a timeline and/or all components tree renders and order?
",https://stackoverflow.com/questions/41004631/trace-why-a-react-component-is-re-rendering,510,285457.0,8.0,,,2016-12-06 20:50:16,2025-05-14 14:42:21,2019-03-28 17:29:59,,,reactjs;redux,jasan,13267,3818829,registered,true,65425731,,CC BY-SA 4.0,,373,366,0,0,0,2,true,false,false,true,true,true,43,7,false,0.028,0.0018,3637,2016,12,20,Tuesday,false,false,false,false,false,false,false
42701129,How to push to History in React Router v4?,"In the current version of React Router (v3) I can accept a server response and use browserHistory.push to go to the appropriate response page. However, this isn't available in v4, and I'm not sure what the appropriate way to handle this is.
In this example, using Redux, components/app-product-form.js calls this.props.addProduct(props) when a user submits the form. When the server returns a success, the user is taken to the Cart page.
// actions/index.js
export function addProduct(props) {
return dispatch =>
axios.post(`${ROOT_URL}/cart`, props, config)
.then(response => {
dispatch({ type: types.AUTH_USER });
localStorage.setItem('token', response.data.token);
browserHistory.push('/cart'); // no longer in React Router V4
});
}
How can I make a redirect to the Cart page from function for React Router v4?
",https://stackoverflow.com/questions/42701129/how-to-push-to-history-in-react-router-v4,495,1021304.0,24.0,,,2017-03-09 16:56:11,2021-11-08 13:24:45,2019-10-01 07:02:13,,,reactjs;react-router;react-router-v4,Chris,6204,420722,registered,true,45849608,,CC BY-SA 4.0,,946,866,3,0,0,3,true,false,false,true,true,true,42,9,true,0.023,0.0005,3544,2017,3,16,Thursday,false,false,false,false,false,false,false
43638938,Updating an object with setState in React,"Is it at all possible to update object's properties with setState?
Something like:
this.state = {
jasper: { name: 'jasper', age: 28 },
}
I have tried:
this.setState({jasper.name: 'someOtherName'});
and this:
this.setState({jasper: {name: 'someothername'}})
The first results in a syntax error and the second just does nothing. Any ideas?
",https://stackoverflow.com/questions/43638938/updating-an-object-with-setstate-in-react,494,793884.0,23.0,,,2017-04-26 15:47:09,2024-12-18 00:41:55,2020-03-22 11:37:32,,,reactjs;state,JohnSnow,7161,7391937,registered,true,43639228,,CC BY-SA 4.0,2019-03-14 18:31:05,472,352,4,0,0,2,true,false,false,true,true,true,41,7,false,0.029,0.0006,3496,2017,4,15,Wednesday,false,false,false,false,false,false,false
52783144,How do you test for the non-existence of an element using jest and react-testing-library?,"I have a component library that I'm writing unit tests for using Jest and react-testing-library. Based on certain props or events I want to verify that certain elements aren't being rendered.
getByText, getByTestId, etc throw and error in react-testing-library if the element isn't found causing the test to fail before the expect function fires.
How do you test for something not existing in jest using react-testing-library?
",https://stackoverflow.com/questions/52783144/how-do-you-test-for-the-non-existence-of-an-element-using-jest-and-react-testing,492,437750.0,14.0,,,2018-10-12 15:59:25,2024-03-04 03:14:18,2023-03-28 00:35:15,,,javascript;reactjs;jestjs;react-testing-library;testing-library,SomethingOn,11131,596979,registered,true,52783201,,CC BY-SA 4.0,,502,429,4,0,0,5,true,false,false,true,true,true,89,14,true,0.032,0.0011,2962,2018,10,15,Friday,false,false,true,false,false,false,false
26556436,React "after render" code?,"I have an app where I need to set the height of an element (lets say ""app-content"") dynamically. It takes the height of the ""chrome"" of the app and subtracts it and then sets the height of the ""app-content"" to fit 100% within those constraints. This is super simple with vanilla JS, jQuery, or Backbone views, but I'm struggling to figure out what the right process would be for doing this in React?
Below is an example component. I want to be able to set app-content's height to be 100% of the window minus the size of the ActionBar and BalanceBar, but how do I know when everything is rendered and where would I put the calculation stuff in this React Class?
/** @jsx React.DOM */
var List = require('../list');
var ActionBar = require('../action-bar');
var BalanceBar = require('../balance-bar');
var Sidebar = require('../sidebar');
var AppBase = React.createClass({
render: function () {
return (
<div className=""wrapper"">
<Sidebar />
<div className=""inner-wrapper"">
<ActionBar title=""Title Here"" />
<BalanceBar balance={balance} />
<div className=""app-content"">
<List items={items} />
</div>
</div>
</div>
);
}
});
module.exports = AppBase;
",https://stackoverflow.com/questions/26556436/react-after-render-code,492,518656.0,20.0,,,2014-10-24 21:19:36,2024-11-05 07:58:59,2014-10-24 21:41:06,,,javascript;reactjs,Oscar Godson,33014,144833,registered,true,26559473,,CC BY-SA 3.0,,1388,1311,4,0,0,2,true,false,false,true,true,true,36,4,true,0.039,0.0009,4411,2014,10,21,Friday,false,false,true,false,false,false,false
35604617,React Router with optional path parameter,"I want to declare a path with an optional path parameter, hence when I add it the page to do something extra (e.g. fill some data):
http://localhost/app/path/to/page <= render the page
http://localhost/app/path/to/page/pathParam <= render the page with
some data according to the pathParam
In my react router I have the following paths, in order to support the two options (this is a simplified example):
<Router history={history}>
<Route path=""/path"" component={IndexPage}>
<Route path=""to/page"" component={MyPage}/>
<Route path=""to/page/:pathParam"" component={MyPage}/>
</Route>
</Router>
My question is, can we declare it in one route? If I add only the second row then the route without the parameter is not found.
EDIT#1:
The solution mentioned here about the following syntax did not work for me, is it a proper one? Does it exist in the documentation?
<Route path=""/product/:productName/?:urlID?"" handler={SomeHandler} />
My react-router version is: 1.0.3
",https://stackoverflow.com/questions/35604617/react-router-with-optional-path-parameter,487,349928.0,8.0,,,2016-02-24 14:18:14,2024-05-28 11:48:52,2017-05-23 12:02:58,,,javascript;reactjs;react-router;react-router-v4,tbo,9922,2422807,registered,true,35604855,,CC BY-SA 3.0,2022-12-16 20:58:02,1442,1055,2,3,0,4,true,false,false,true,true,true,41,6,false,0.023,0.0014,3923,2016,2,14,Wednesday,false,false,true,false,false,false,false
39778607,Error Running React Native App From Terminal (iOS),"I am following the tutorial on the official React Native website.
Using the following to build my project:
react-native run-ios
I get the error:
Found Xcode project TestProject.xcodeproj
xcrun: error: unable to find utility ""instruments"", not a developer
tool or in PATH
Command failed: xcrun instruments -s
xcrun: error: unable to find utility ""instruments"", not a developer
tool or in PATH
Although, when I run the app from the .xcodeproj, everything works fine.
Any suggestions?
",https://stackoverflow.com/questions/39778607/error-running-react-native-app-from-terminal-ios,475,143385.0,18.0,,,2016-09-29 19:35:12,2025-01-04 05:46:07,2018-05-27 05:07:43,,,javascript;ios;reactjs;react-native;ios-simulator,JacobSiegel,5391,5943218,registered,true,39779171,,CC BY-SA 4.0,,578,495,2,0,0,5,true,false,false,true,true,true,50,8,false,0.126,0.0033,3705,2016,9,19,Thursday,false,false,true,false,false,false,false
43441856,How to scroll to an element?,"I have a chat widget that pulls up an array of messages every time I scroll up. The problem I am facing now is the slider stays fixed at the top when messages load. I want it to focus on the last index element from the previous array. I figured out that I can make dynamic refs by passing index, but I would also need to know what kind of scroll function to use to achieve that
handleScrollToElement(event) {
const tesNode = ReactDOM.findDOMNode(this.refs.test)
if (some_logic){
//scroll to testNode
}
}
render() {
return (
<div>
<div ref=""test""></div>
</div>)
}
",https://stackoverflow.com/questions/43441856/how-to-scroll-to-an-element,471,938484.0,30.0,,,2017-04-16 20:33:59,2025-07-02 17:48:01,2020-05-17 05:14:23,,,javascript;reactjs;ecmascript-6,edmamerto,8245,3709060,registered,true,71610903,,CC BY-SA 4.0,,678,647,1,0,0,3,true,false,false,true,true,true,28,6,true,0.032,0.0005,3506,2017,4,20,Sunday,true,false,true,false,false,false,false
47630163,axios post request to send form data,"axios POST request is hitting the url on the controller but setting null values to my POJO class, when I go through developer tools in chrome, the payload contains data. What am I doing wrong?
Axios POST Request:
var body = {
userName: 'Fred',
userEmail: 'Flintstone@gmail.com'
}
axios({
method: 'post',
url: '/addUser',
data: body
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Browser Response:
If I set headers as:
headers:{
Content-Type:'multipart/form-data'
}
The request throws the error
Error in posting multipart/form-data. Content-Type header is missing boundary
If I make the same request in postman it's working fine and sets values to my POJO class.
Can anyone explain how to set boundary or how can I send form data using axios.
",https://stackoverflow.com/questions/47630163/axios-post-request-to-send-form-data,470,1212701.0,22.0,,,2017-12-04 09:29:57,2024-12-20 06:46:39,2018-12-10 20:41:59,,,reactjs;react-redux;axios;ajaxform;axios-cookiejar-support,Srikanth Gowda,6561,7007693,registered,true,47630754,,CC BY-SA 4.0,2018-08-02 08:25:20,1174,850,3,1,1,5,true,false,false,true,true,true,36,7,false,0.018,0.0004,3274,2017,12,9,Monday,false,false,false,false,false,false,false
29537299,How can I update state.item[1] in state using setState?,"I'm creating an app where the user can design his own form. E.g. specify name of the field and details of which other columns that should be included.
The component is available as a JSFiddle.
My initial state looks like this:
var DynamicForm = React.createClass({
getInitialState: function() {
var items = {};
items[1] = { name: 'field 1', populate_at: 'web_start',
same_as: 'customer_name',
autocomplete_from: 'customer_name', title: '' };
items[2] = { name: 'field 2', populate_at: 'web_end',
same_as: 'user_name',
autocomplete_from: 'user_name', title: '' };
return { items };
},
render: function() {
var _this = this;
return (
<div>
{ Object.keys(this.state.items).map(function (key) {
var item = _this.state.items[key];
return (
<div>
<PopulateAtCheckboxes this={this}
checked={item.populate_at} id={key}
populate_at={data.populate_at} />
</div>
);
}, this)}
<button onClick={this.newFieldEntry}>Create a new field</button>
<button onClick={this.saveAndContinue}>Save and Continue</button>
</div>
);
}
I want to update the state when the user changes any of the values, but I'm having a hard time to target the correct object:
var PopulateAtCheckboxes = React.createClass({
handleChange: function (e) {
item = this.state.items[1];
item.name = 'newName';
items[1] = item;
this.setState({items: items});
},
render: function() {
var populateAtCheckbox = this.props.populate_at.map(function(value) {
return (
<label for={value}>
<input type="radio" name={'populate_at'+this.props.id} value={value}
onChange={this.handleChange} checked={this.props.checked == value}
ref="populate-at"/>
{value}
</label>
);
}, this);
return (
<div className="populate-at-checkboxes">
{populateAtCheckbox}
</div>
);
}
});
How should I craft this.setState to get it to update items[1].name ?
",https://stackoverflow.com/questions/29537299/how-can-i-update-state-item1-in-state-using-setstate,462,673481.0,27.0,,,2015-04-09 11:28:44,2023-10-14 04:57:18,2022-12-13 14:21:15,,,javascript;reactjs;state,martins,10137,375721,registered,true,49502115,,CC BY-SA 4.0,,2473,2290,4,1,0,3,true,false,false,true,true,true,55,9,true,0.04,0.0007,4244,2015,4,11,Thursday,false,false,true,false,false,false,false
32317154,React - uncaught TypeError: Cannot read property 'setState' of undefined,"I am getting the following error
Uncaught TypeError: Cannot read property 'setState' of undefined
even after binding delta in the constructor.
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
count : 1
};
this.delta.bind(this);
}
delta() {
this.setState({
count : this.state.count++
});
}
render() {
return (
<div>
<h1>{this.state.count}</h1>
<button onClick={this.delta}>+</button>
</div>
);
}
}
",https://stackoverflow.com/questions/32317154/react-uncaught-typeerror-cannot-read-property-setstate-of-undefined,454,442301.0,21.0,,,2015-08-31 18:00:06,2025-01-25 23:45:47,2018-01-20 17:11:02,,,javascript;reactjs,Dangling_pointer,4753,3016220,registered,true,32317459,,CC BY-SA 3.0,2019-04-16 13:00:48,724,654,1,0,0,2,true,false,false,true,true,true,80,10,false,0.047,0.001,4100,2015,8,18,Monday,false,false,true,false,false,false,false
64656055,"'React' refers to a UMD global, but the current file is a module","I updated my project to create react app 4.0, and I'm slowing moving over my files to TypeScript. I know with this new version you don't have to repetitively import React from 'react'. However, within all of my TS files where I'm not importing React I receive this error:
'React' refers to a UMD global, but the current file is a module.
Consider adding an import instead.ts(2686)`
I know I can fix it by importing React, but I thought this was no longer needed. Also, could someone explain the meaning of this error?
My basic TSX file
const Users = () => {
return <>Teachers aka Users</>;
};
export default Users;
",https://stackoverflow.com/questions/64656055/react-refers-to-a-umd-global-but-the-current-file-is-a-module,453,451429.0,33.0,,,2020-11-03 02:37:44,2025-04-17 08:07:22,2022-06-21 19:51:18,,,javascript;reactjs;typescript;create-react-app,Rafael,5409,4021213,registered,true,64677253,,CC BY-SA 4.0,2024-05-30 08:38:21,715,638,1,0,0,4,true,false,false,true,true,true,72,13,false,0.073,0.001,2209,2020,11,2,Tuesday,false,false,true,false,false,false,false
42640636,'React' must be in scope when using JSX react/react-in-jsx-scope?,"I am an Angular Developer and new to React , This is simple react Component but not working
import react , { Component} from 'react';
import { render } from 'react-dom';
class TechView extends Component {
constructor(props){
super(props);
this.state = {
name:'Gopinath'
}
}
render(){
return(
<span>hello Tech View</span>
);
}
}
export default TechView;
Error :
'React' must be in scope when using JSX react/react-in-jsx-scope
",https://stackoverflow.com/questions/42640636/react-must-be-in-scope-when-using-jsx-react-react-in-jsx-scope,450,764273.0,25.0,,,2017-03-07 05:06:52,2026-01-10 08:41:46,2024-04-16 12:31:54,,,javascript;reactjs;jsx;eslintrc,Gopinath Kaliappan,7429,5444836,registered,true,42641010,,CC BY-SA 4.0,2018-04-02 07:23:54,590,535,1,0,0,4,true,false,false,true,true,true,73,9,true,0.033,0.0006,3546,2017,3,5,Tuesday,false,false,true,false,false,false,false
22752116,React ignores 'for' attribute of the label element,"In React (Facebook's framework), I need to render a label element bound to a text input using the standard for attribute.
e.g. the following JSX is used:
<label for=""test"">Test</label>
<input type=""text"" id=""test"" />
However, this produces HTML missing the required (and standard) for attribute:
<label>Test</label>
<input type=""text"" id=""test"">
What am I doing wrong?
",https://stackoverflow.com/questions/22752116/react-ignores-for-attribute-of-the-label-element,449,307638.0,6.0,,,2014-03-31 01:07:38,2023-01-15 06:24:56,2020-03-21 06:29:54,,,reactjs;label,goofballLogic,41229,275501,registered,true,22752418,,CC BY-SA 4.0,,514,412,4,0,0,2,true,false,false,true,true,true,58,8,false,0.02,0.0015,4618,2014,3,1,Monday,false,false,false,false,false,false,false
38394015,How to pass data from child component to its parent in ReactJS?,"I'm trying to send data from a child component to its parent as follow:
const ParentComponent = React.createClass({
getInitialState() {
return {
language: '',
};
},
handleLanguageCode: function(langValue) {
this.setState({language: langValue});
},
render() {
return (
<div className="col-sm-9" >
<SelectLanguage onSelectLanguage={this.handleLanguage}/>
</div>
);
});
and here is the child component:
export const SelectLanguage = React.createClass({
getInitialState: function(){
return{
selectedCode: '',
selectedLanguage: '',
};
},
handleLangChange: function (e) {
var lang = this.state.selectedLanguage;
var code = this.state.selectedCode;
this.props.onSelectLanguage({selectedLanguage: lang});
this.props.onSelectLanguage({selectedCode: code});
},
render() {
var json = require("json!../languages.json");
var jsonArray = json.languages;
return (
<div >
<DropdownList ref='dropdown'
data={jsonArray}
value={this.state.selectedLanguage}
caseSensitive={false}
minLength={3}
filter='contains'
onChange={this.handleLangChange} />
</div>
);
}
});
What I need is to get the selected value by user in the parent component. I'm getting this error:
Uncaught TypeError: this.props.onSelectLanguage is not a function
Can anyone help me to find the problem?
P.S. The child component is creating a dropdown from a json file, and I need the dropdown list to show both elements of the json array next to each other(like: "aaa,english" as the first choice!)
{
"languages":[
[
"aaa",
"english"
],
[
"aab",
"swedish"
],
}
",https://stackoverflow.com/questions/38394015/how-to-pass-data-from-child-component-to-its-parent-in-reactjs,443,764645.0,21.0,,,2016-07-15 10:37:32,2024-07-23 14:33:18,2023-03-25 22:54:11,,,reactjs,Birish,5842,3711985,registered,true,38397755,,CC BY-SA 4.0,,2273,2142,4,0,0,1,true,false,false,true,true,true,63,12,true,0.027,0.0006,3781,2016,7,10,Friday,false,false,false,false,false,false,false
53464595,How to use componentWillMount() in React Hooks?,"In the official docs of React it mentions -
If you’re familiar with React class lifecycle methods, you can think
of useEffect Hook as componentDidMount, componentDidUpdate, and
componentWillUnmount combined.
My question is - how can we use the componentWillMount() lifecyle method in a hook?
",https://stackoverflow.com/questions/53464595/how-to-use-componentwillmount-in-react-hooks,440,480502.0,21.0,,,2018-11-25 04:13:08,2025-11-03 21:26:41,,,,javascript;reactjs;jsx;react-hooks,Abrar,7262,4397077,registered,true,53465182,,CC BY-SA 4.0,2023-11-21 06:49:16,363,304,1,0,0,4,true,false,false,true,true,false,47,7,true,0.044,0.0009,2918,2018,11,4,Sunday,true,false,true,false,false,false,false
39999367,How do I reference a local image in React?,"How can I load image from local directory and include it in reactjs img src tag?
I have an image called one.jpeg inside the same folder as my component and I tried both <img src=""one.jpeg"" /> and <img src={""one.jpeg""} /> inside my renderfunction but the image does not show up. Also, I do not have access to webpack config file since the project is created with the official create-react-app command line util.
Update: This works if I first import the image with import img from './one.jpeg' and use it inside img src={img}, but I have so many image files to import and therefore, I want to use them in the form, img src={'image_name.jpeg'}.
",https://stackoverflow.com/questions/39999367/how-do-i-reference-a-local-image-in-react,436,1245763.0,29.0,,,2016-10-12 13:05:16,2024-03-12 11:40:37,2018-07-04 15:58:00,,,reactjs,Zip,5672,3301668,registered,true,39999421,,CC BY-SA 4.0,2023-03-23 06:44:58,808,657,10,0,0,1,true,false,false,true,true,true,42,9,true,0.023,0.0003,3692,2016,10,13,Wednesday,false,false,false,false,false,false,false
53949393,Can't perform a React state update on an unmounted component,"Problem
I am writing an application in React and was unable to avoid a super common pitfall, which is calling setState(...) after componentWillUnmount(...).
I looked very carefully at my code and tried to put some guarding clauses in place, but the problem persisted and I am still observing the warning.
Therefore, I've got two questions:
- How do I figure out from the stack trace, which particular component and event handler or lifecycle hook is responsible for the rule violation?
- Well, how to fix the problem itself, because my code was written with this pitfall in mind and is already trying to prevent it, but some underlying component's still generating the warning.
Browser console
Warning: Can't perform a React state update on an unmounted component.
This is a no-op, but it indicates a memory leak in your application.
To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount
method.
in TextLayerInternal (created by Context.Consumer)
in TextLayer (created by PageInternal) index.js:1446
d/console[e]
index.js:1446
warningWithoutStack
react-dom.development.js:520
warnAboutUpdateOnUnmounted
react-dom.development.js:18238
scheduleWork
react-dom.development.js:19684
enqueueSetState
react-dom.development.js:12936
./node_modules/react/cjs/react.development.js/Component.prototype.setState
react.development.js:356
_callee$
TextLayer.js:97
tryCatch
runtime.js:63
invoke
runtime.js:282
defineIteratorMethods/</prototype[method]
runtime.js:116
asyncGeneratorStep
asyncToGenerator.js:3
_throw
asyncToGenerator.js:29
Code
Book.tsx
import { throttle } from 'lodash';
import * as React from 'react';
import { AutoWidthPdf } from '../shared/AutoWidthPdf';
import BookCommandPanel from '../shared/BookCommandPanel';
import BookTextPath from '../static/pdf/sde.pdf';
import './Book.css';
const DEFAULT_WIDTH = 140;
class Book extends React.Component {
setDivSizeThrottleable: () => void;
pdfWrapper: HTMLDivElement | null = null;
isComponentMounted: boolean = false;
state = {
hidden: true,
pdfWidth: DEFAULT_WIDTH,
};
constructor(props: any) {
super(props);
this.setDivSizeThrottleable = throttle(
() => {
if (this.isComponentMounted) {
this.setState({
pdfWidth: this.pdfWrapper!.getBoundingClientRect().width - 5,
});
}
},
500,
);
}
componentDidMount = () => {
this.isComponentMounted = true;
this.setDivSizeThrottleable();
window.addEventListener(""resize"", this.setDivSizeThrottleable);
};
componentWillUnmount = () => {
this.isComponentMounted = false;
window.removeEventListener(""resize"", this.setDivSizeThrottleable);
};
render = () => (
<div className=""Book"">
{ this.state.hidden && <div className=""Book__LoadNotification centered"">Book is being loaded...</div> }
<div className={this.getPdfContentContainerClassName()}>
<BookCommandPanel
bookTextPath={BookTextPath}
/>
<div className=""Book__PdfContent"" ref={ref => this.pdfWrapper = ref}>
<AutoWidthPdf
file={BookTextPath}
width={this.state.pdfWidth}
onLoadSuccess={(_: any) => this.onDocumentComplete()}
/>
</div>
<BookCommandPanel
bookTextPath={BookTextPath}
/>
</div>
</div>
);
getPdfContentContainerClassName = () => this.state.hidden ? 'hidden' : '';
onDocumentComplete = () => {
try {
this.setState({ hidden: false });
this.setDivSizeThrottleable();
} catch (caughtError) {
console.warn({ caughtError });
}
};
}
export default Book;
AutoWidthPdf.tsx
import * as React from 'react';
import { Document, Page, pdfjs } from 'react-pdf';
pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;
interface IProps {
file: string;
width: number;
onLoadSuccess: (pdf: any) => void;
}
export class AutoWidthPdf extends React.Component<IProps> {
render = () => (
<Document
file={this.props.file}
onLoadSuccess={(_: any) => this.props.onLoadSuccess(_)}
>
<Page
pageNumber={1}
width={this.props.width}
/>
</Document>
);
}
Update 1: Cancel throttleable function (still no luck)
const DEFAULT_WIDTH = 140;
class Book extends React.Component {
setDivSizeThrottleable: ((() => void) & Cancelable) | undefined;
pdfWrapper: HTMLDivElement | null = null;
state = {
hidden: true,
pdfWidth: DEFAULT_WIDTH,
};
componentDidMount = () => {
this.setDivSizeThrottleable = throttle(
() => {
this.setState({
pdfWidth: this.pdfWrapper!.getBoundingClientRect().width - 5,
});
},
500,
);
this.setDivSizeThrottleable();
window.addEventListener(""resize"", this.setDivSizeThrottleable);
};
componentWillUnmount = () => {
window.removeEventListener(""resize"", this.setDivSizeThrottleable!);
this.setDivSizeThrottleable!.cancel();
this.setDivSizeThrottleable = undefined;
};
render = () => (
<div className=""Book"">
{ this.state.hidden && <div className=""Book__LoadNotification centered"">Book is being loaded...</div> }
<div className={this.getPdfContentContainerClassName()}>
<BookCommandPanel
BookTextPath={BookTextPath}
/>
<div className=""Book__PdfContent"" ref={ref => this.pdfWrapper = ref}>
<AutoWidthPdf
file={BookTextPath}
width={this.state.pdfWidth}
onLoadSuccess={(_: any) => this.onDocumentComplete()}
/>
</div>
<BookCommandPanel
BookTextPath={BookTextPath}
/>
</div>
</div>
);
getPdfContentContainerClassName = () => this.state.hidden ? 'hidden' : '';
onDocumentComplete = () => {
try {
this.setState({ hidden: false });
this.setDivSizeThrottleable!();
} catch (caughtError) {
console.warn({ caughtError });
}
};
}
export default Book;
",https://stackoverflow.com/questions/53949393/cant-perform-a-react-state-update-on-an-unmounted-component,436,774584.0,33.0,,,2018-12-27 18:33:41,2024-01-17 21:26:34,2018-12-28 01:11:39,,,javascript;reactjs;typescript;lodash;setstate,Igor Soloydenko,11953,482868,registered,true,60907638,,CC BY-SA 4.0,,6756,6333,6,1,1,5,true,false,false,true,true,true,64,10,false,0.043,0.0006,2886,2018,12,18,Thursday,false,false,true,false,false,false,false
58613492,How to resolve "Cannot use import statement outside a module" from Jest when running tests?,"I have a React application (not using Create React App) built using TypeScript, Jest, Webpack, and Babel. When trying to run yarn jest, I get the following error:
![]()
I have tried removing all packages and re-adding them. It does not resolve this. I have looked at similar questions and documentation and I am still not understanding something. I went so far as to follow another guide for setting up this environment from scratch and still received this issue with my code.
Dependencies include...
"dependencies": {
"@babel/plugin-transform-runtime": "^7.6.2",
"@babel/polyfill": "^7.6.0",
"babel-jest": "^24.9.0",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-test-renderer": "^16.11.0",
"source-map-loader": "^0.2.4"
},
"devDependencies": {
"@babel/core": "^7.6.0",
"@babel/preset-env": "^7.6.0",
"@babel/preset-react": "^7.0.0",
"@types/enzyme": "^3.9.2",
"@types/enzyme-adapter-react-16": "^1.0.5",
"@types/jest": "^24.0.13",
The component's import lines...
import * as React from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import HomePage from "./components/pages";
import {
Footer,
Header,
Navigation,
} from "./components/shared";
The test file....
import * as React from "react";
import * as renderer from "react-test-renderer";
import App from "../App";
it("Renders the Footer correctly", () => {
const tree = renderer
.create(<App />)
.toJSON();
expect(tree).toMatchSnapshot();
});
I expected to be able to use named imports in my components without my tests blowing up. It appears to fix the issue if I only use default imports throughout my solution, but I would prefer to not go that route.
",https://stackoverflow.com/questions/58613492/how-to-resolve-cannot-use-import-statement-outside-a-module-from-jest-when-run,435,499994.0,33.0,,,2019-10-29 18:35:19,2026-09-20 08:56:43,2023-02-27 17:22:31,,,reactjs;jestjs;babeljs;babel-jest;ts-jest,Logan Shoemaker,4687,1712571,registered,true,,,CC BY-SA 4.0,,2264,2068,4,0,1,5,false,false,false,true,true,true,101,15,true,0.066,0.0009,2580,2019,10,18,Tuesday,false,false,false,false,false,false,false
42253277,React Router v4 - How to get current route?,"I'd like to display a title in <AppBar /> that is somehow passed in from the current route.
In React Router v4, how would <AppBar /> be able to get the current route passed into it's title prop?
<Router basename='/app'>
<main>
<Menu active={menu} close={this.closeMenu} />
<Overlay active={menu} onClick={this.closeMenu} />
<AppBar handleMenuIcon={this.handleMenuIcon} title='Test' />
<Route path='/customers' component={Customers} />
</main>
</Router>
Is there a way to pass a custom title from a custom prop on <Route />?
",https://stackoverflow.com/questions/42253277/react-router-v4-how-to-get-current-route,432,689483.0,10.0,,,2017-02-15 15:17:31,2023-07-12 11:51:45,2017-02-15 15:28:36,,,reactjs;react-router;react-router-v4,Raphael Rafatpanah,20146,1911755,registered,true,60736742,,CC BY-SA 3.0,,755,632,7,0,0,3,true,false,false,true,true,true,43,9,true,0.015,0.0006,3566,2017,2,15,Wednesday,false,false,false,false,false,false,false
59188624,Template not provided using create-react-app,"When I type the create-react-app my-app command in my terminal, it appears to work - downloading all libraries successfully etc. At the end of that process however I get a message that a template was not provided.
Input
user@users-MacBook-Pro-2 Desktop% create-react-app my-app
Output
Creating a new React app in /Users/user/Desktop/my-app.
Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts...
..... nothing out of the ordinary here .....
✨ Done in 27.28s.
A template was not provided. This is likely because you're using an outdated version of create-react-app.
Please note that global installs of create-react-app are no longer supported.
In package.json of my-app:
""dependencies"": {
""react"": ""^16.12.0"",
""react-dom"": ""^16.12.0"",
""react-scripts"": ""3.3.0"" <-- up-to-date
}
I checked out the CRA changelog and it looks like support was added for custom templates - however it doesn't look like the command create-react-app my-app would have changed.
Any idea what is going on here?
",https://stackoverflow.com/questions/59188624/template-not-provided-using-create-react-app,432,165149.0,44.0,,,2019-12-05 05:12:26,2023-01-05 23:13:59,,,,reactjs;create-react-app,SamYoungNY,6664,973862,registered,true,59189242,,CC BY-SA 4.0,2019-12-06 06:48:53,1328,1061,7,1,0,2,true,false,false,true,true,false,44,5,false,0.266,0.0026,2543,2019,12,5,Thursday,false,false,false,false,false,false,false
30782948,Why does calling react setState method not mutate the state immediately?,"I'm reading Forms section of reactjs documentation and just tried this code to demonstrate onChange usage (JSBIN).
var React= require('react');
var ControlledForm= React.createClass({
getInitialState: function() {
return {
value: ""initial value""
};
},
handleChange: function(event) {
console.log(this.state.value);
this.setState({value: event.target.value});
console.log(this.state.value);
},
render: function() {
return (
<input type=""text"" value={this.state.value} onChange={this.handleChange}/>
);
}
});
React.render(
<ControlledForm/>,
document.getElementById('mount')
);
When I update the <input/> value in the browser, the second console.log inside the handleChange callback prints the same value as the first console.log, Why I can't see the result of this.setState({value: event.target.value}) in the scope of handleChange callback?
",https://stackoverflow.com/questions/30782948/why-does-calling-react-setstate-method-not-mutate-the-state-immediately,432,266307.0,10.0,,,2015-06-11 13:58:26,2023-03-09 12:35:35,2022-05-14 20:31:30,,,javascript;reactjs,Salah Eddine Taouririt,26873,1120221,registered,true,30783011,,CC BY-SA 4.0,,1363,977,9,3,0,2,true,false,false,true,true,true,72,11,true,0.038,0.0016,4181,2015,6,13,Thursday,false,false,true,false,false,false,false
39419237,What is mapDispatchToProps?,"I was reading the documentation for the Redux library and it has this example:
In addition to reading the state, container components can dispatch actions. In a similar fashion, you can define a function called mapDispatchToProps() that receives the dispatch() method and returns callback props that you want to inject into the presentational component.
This actually makes no sense. Why do you need mapDispatchToProps when you already have mapStateToProps?
They also provide this handy code sample:
const mapDispatchToProps = (dispatch) => {
return {
onTodoClick: (id) => {
dispatch(toggleTodo(id))
}
}
}
What is this function and why it is useful?
",https://stackoverflow.com/questions/39419237/what-is-mapdispatchtoprops,429,297190.0,6.0,,,2016-09-09 20:26:43,2022-06-19 06:53:25,2021-07-29 07:01:18,,,reactjs;redux;react-redux;mapdispatchtoprops,Code Whisperer,23700,2299820,registered,true,40068198,,CC BY-SA 4.0,,813,677,5,0,0,4,true,false,false,true,true,true,27,3,true,0.02,0.0014,3725,2016,9,20,Friday,false,false,false,false,false,false,false
31815633,What does the error "JSX element type '...' does not have any construct or call signatures" mean?,"I wrote some code:
function renderGreeting(Elem: React.Component<any, any>) {
return <span>Hello, <Elem />!</span>;
}
I'm getting an error:
JSX element type Elem does not have any construct or call signatures
What does it mean?
",https://stackoverflow.com/questions/31815633/what-does-the-error-jsx-element-type-does-not-have-any-construct-or-call,426,572735.0,24.0,,,2015-08-04 17:28:10,2024-06-10 21:05:02,2021-03-29 07:20:20,,,reactjs;typescript,Ryan Cavanaugh,223506,1704166,registered,true,31815634,,CC BY-SA 4.0,2018-09-02 21:45:38,355,265,2,0,0,2,true,false,false,true,true,true,115,17,true,0.042,0.0007,4127,2015,8,17,Tuesday,false,false,false,false,false,false,false
41676054,How to add fonts to create-react-app based projects?,"I'm using create-react-app and prefer not to eject.
It's not clear where fonts imported via @font-face and loaded locally should go.
Namely, I'm loading
@font-face {
font-family: 'Myriad Pro Regular';
font-style: normal;
font-weight: normal;
src: local('Myriad Pro Regular'), url('MYRIADPRO-REGULAR.woff') format('woff');
}
Any suggestions?
-- EDIT
Including the gist to which Dan referring in his answer
➜ Client git:(feature/trivia-game-ui-2) ✗ ls -l public/static/fonts
total 1168
-rwxr-xr-x@ 1 maximveksler staff 62676 Mar 17 2014 MYRIADPRO-BOLD.woff
-rwxr-xr-x@ 1 maximveksler staff 61500 Mar 17 2014 MYRIADPRO-BOLDCOND.woff
-rwxr-xr-x@ 1 maximveksler staff 66024 Mar 17 2014 MYRIADPRO-BOLDCONDIT.woff
-rwxr-xr-x@ 1 maximveksler staff 66108 Mar 17 2014 MYRIADPRO-BOLDIT.woff
-rwxr-xr-x@ 1 maximveksler staff 60044 Mar 17 2014 MYRIADPRO-COND.woff
-rwxr-xr-x@ 1 maximveksler staff 64656 Mar 17 2014 MYRIADPRO-CONDIT.woff
-rwxr-xr-x@ 1 maximveksler staff 61848 Mar 17 2014 MYRIADPRO-REGULAR.woff
-rwxr-xr-x@ 1 maximveksler staff 62448 Mar 17 2014 MYRIADPRO-SEMIBOLD.woff
-rwxr-xr-x@ 1 maximveksler staff 66232 Mar 17 2014 MYRIADPRO-SEMIBOLDIT.woff
➜ Client git:(feature/trivia-game-ui-2) ✗ cat src/containers/GameModule.css
.GameModule {
padding: 15px;
}
@font-face {
font-family: 'Myriad Pro Regular';
font-style: normal;
font-weight: normal;
src: local('Myriad Pro Regular'), url('%PUBLIC_URL%/static/fonts/MYRIADPRO-REGULAR.woff') format('woff');
}
@font-face {
font-family: 'Myriad Pro Condensed';
font-style: normal;
font-weight: normal;
src: local('Myriad Pro Condensed'), url('%PUBLIC_URL%/static/fonts/MYRIADPRO-COND.woff') format('woff');
}
@font-face {
font-family: 'Myriad Pro Semibold Italic';
font-style: normal;
font-weight: normal;
src: local('Myriad Pro Semibold Italic'), url('%PUBLIC_URL%/static/fonts/MYRIADPRO-SEMIBOLDIT.woff') format('woff');
}
@font-face {
font-family: 'Myriad Pro Semibold';
font-style: normal;
font-weight: normal;
src: local('Myriad Pro Semibold'), url('%PUBLIC_URL%/static/fonts/MYRIADPRO-SEMIBOLD.woff') format('woff');
}
@font-face {
font-family: 'Myriad Pro Condensed Italic';
font-style: normal;
font-weight: normal;
src: local('Myriad Pro Condensed Italic'), url('%PUBLIC_URL%/static/fonts/MYRIADPRO-CONDIT.woff') format('woff');
}
@font-face {
font-family: 'Myriad Pro Bold Italic';
font-style: normal;
font-weight: normal;
src: local('Myriad Pro Bold Italic'), url('%PUBLIC_URL%/static/fonts/MYRIADPRO-BOLDIT.woff') format('woff');
}
@font-face {
font-family: 'Myriad Pro Bold Condensed Italic';
font-style: normal;
font-weight: normal;
src: local('Myriad Pro Bold Condensed Italic'), url('%PUBLIC_URL%/static/fonts/MYRIADPRO-BOLDCONDIT.woff') format('woff');
}
@font-face {
font-family: 'Myriad Pro Bold Condensed';
font-style: normal;
font-weight: normal;
src: local('Myriad Pro Bold Condensed'), url('%PUBLIC_URL%/static/fonts/MYRIADPRO-BOLDCOND.woff') format('woff');
}
@font-face {
font-family: 'Myriad Pro Bold';
font-style: normal;
font-weight: normal;
src: local('Myriad Pro Bold'), url('%PUBLIC_URL%/static/fonts/MYRIADPRO-BOLD.woff') format('woff');
}
",https://stackoverflow.com/questions/41676054/how-to-add-fonts-to-create-react-app-based-projects,425,616497.0,12.0,,,2017-01-16 12:04:46,2026-05-31 15:21:00,2018-09-18 18:43:06,,,css;reactjs;fonts;webpack;create-react-app,Maxim Veksler,30482,48062,registered,true,41678350,,CC BY-SA 4.0,,3423,3244,3,1,0,5,true,false,false,true,true,true,52,8,true,0.019,0.0007,3596,2017,1,12,Monday,false,false,false,false,false,false,false
56247433,How to use `setState` callback on react hooks,"React hooks introduces useState for setting component state. But how can I use hooks to replace the callback like below code:
setState(
{ name: ""Michael"" },
() => console.log(this.state)
);
I want to do something after the state is updated.
I know I can use useEffect to do the extra things but I have to check the state previous value which requires a bit code. I am looking for a simple solution which can be used with useState hook.
",https://stackoverflow.com/questions/56247433/how-to-use-setstate-callback-on-react-hooks,423,427356.0,23.0,,,2019-05-21 23:18:59,2025-02-01 08:05:07,2021-01-04 21:15:40,,,reactjs;react-hooks;use-state,Joey Yi Zhao,43460,5421539,registered,true,56247483,,CC BY-SA 4.0,,532,448,4,0,0,3,true,false,false,true,true,true,45,8,false,0.054,0.001,2741,2019,5,23,Tuesday,false,false,false,false,false,false,false
53446020,How to compare oldValues and newValues on React Hooks useEffect?,"Let's say I have 3 inputs: rate, sendAmount, and receiveAmount. I put that 3 inputs on useEffect diffing params. The rules are:
- If sendAmount changed, I calculate
receiveAmount = sendAmount * rate
- If receiveAmount changed, I calculate
sendAmount = receiveAmount / rate
- If rate changed, I calculate
receiveAmount = sendAmount * rate when sendAmount > 0 or I calculate sendAmount = receiveAmount / rate when receiveAmount > 0
Here is the codesandbox https://codesandbox.io/s/pkl6vn7x6j to demonstrate the problem.
Is there a way to compare the oldValues and newValues like on componentDidUpdate instead of making 3 handlers for this case?
Thanks
Here is my final solution with usePrevious
https://codesandbox.io/s/30n01w2r06
In this case, I cannot use multiple useEffect because each change is leading to the same network call. That's why I also use changeCount to track the change too. This changeCount also helpful to track changes from local only, so I can prevent unnecessary network call because of changes from the server.
",https://stackoverflow.com/questions/53446020/how-to-compare-oldvalues-and-newvalues-on-react-hooks-useeffect,422,501818.0,17.0,,,2018-11-23 11:40:02,2026-01-05 22:55:47,2018-11-25 04:17:16,,,reactjs;react-hooks,Erwin Zhang,4445,1888943,registered,true,53446665,,CC BY-SA 4.0,,1428,1043,13,2,0,2,true,false,false,true,true,true,64,10,true,0.034,0.0008,2920,2018,11,11,Friday,false,false,false,false,false,false,false
42122522,ReactJs: What should the PropTypes be for this.props.children?,"Given a simple component that renders its children:
class ContainerComponent extends Component {
static propTypes = {
children: PropTypes.object.isRequired,
}
render() {
return (
<div>
{this.props.children}
</div>
);
}
}
export default ContainerComponent;
Question: What should the propType of the children prop be?
When I set it as an object, it fails when I use the component with multiple children:
<ContainerComponent>
<div>1</div>
<div>2</div>
</ContainerComponent>
Warning: Failed prop type: Invalid prop children of type array
supplied to ContainerComponent, expected object.
If I set it as an array, it will fail if I give it only one child, i.e.:
<ContainerComponent>
<div>1</div>
</ContainerComponent>
Warning: Failed prop type: Invalid prop children of type object
supplied to ContainerComponent, expected array.
Please advise, should I just not bother doing a propTypes check for children elements?
",https://stackoverflow.com/questions/42122522/reactjs-what-should-the-proptypes-be-for-this-props-children,422,211830.0,9.0,,,2017-02-08 20:00:18,2025-01-04 15:12:33,2025-01-04 15:12:33,,,reactjs;jsx;react-proptypes,d3ming,9130,3006145,registered,true,42122662,,CC BY-SA 4.0,,1291,1038,8,0,0,3,true,false,false,true,true,true,62,8,true,0.042,0.002,3573,2017,2,20,Wednesday,false,false,false,false,false,false,false
62336340,Cannot update a component while rendering a different component warning,"I am getting this warning in react:
index.js:1 Warning: Cannot update a component (`ConnectFunction`)
while rendering a different component (`Register`). To locate the
bad setState() call inside `Register`
I went to the locations indicated in the stack trace and removed all setstates but the warning still persists. Is it possible this could occur from redux dispatch?
my code:
register.js
class Register extends Component {
render() {
if( this.props.registerStatus === SUCCESS) {
// Reset register status to allow return to register page
this.props.dispatch( resetRegisterStatus()) # THIS IS THE LINE THAT CAUSES THE ERROR ACCORDING TO THE STACK TRACE
return <Redirect push to = {HOME}/>
}
return (
<div style = {{paddingTop: ""180px"", background: 'radial-gradient(circle, rgba(106,103,103,1) 0%, rgba(36,36,36,1) 100%)', height: ""100vh""}}>
<RegistrationForm/>
</div>
);
}
}
function mapStateToProps( state ) {
return {
registerStatus: state.userReducer.registerStatus
}
}
export default connect ( mapStateToProps ) ( Register );
function which triggers the warning in my registerForm component called by register.js
handleSubmit = async () => {
if( this.isValidForm() ) {
const details = {
""username"": this.state.username,
""password"": this.state.password,
""email"": this.state.email,
""clearance"": this.state.clearance
}
await this.props.dispatch( register(details) )
if( this.props.registerStatus !== SUCCESS && this.mounted ) {
this.setState( {errorMsg: this.props.registerError})
this.handleShowError()
}
}
else {
if( this.mounted ) {
this.setState( {errorMsg: ""Error - registration credentials are invalid!""} )
this.handleShowError()
}
}
}
Stacktrace:
",https://stackoverflow.com/questions/62336340/cannot-update-a-component-while-rendering-a-different-component-warning,422,660621.0,24.0,,,2020-06-12 02:00:02,2024-06-17 11:15:57,2020-06-14 23:34:03,,,javascript;reactjs;redux,Tamjid,5866,6716062,registered,true,62379496,,CC BY-SA 4.0,2023-03-16 22:48:22,2146,1902,3,1,1,3,true,false,false,true,true,true,71,10,false,0.036,0.0006,2353,2020,6,2,Friday,false,false,true,false,false,false,false
48395804,where is create-react-app webpack config and files?,"I create a ReactJS project with the create-react-app package and that worked well, but I cannot find webpack files and configurations.
How does react-create-app work with webpack? Where are the webpack configuration files located in a default installation with create-react-app? I'm unable to find configuration files in my project's folders.
I have not created an override config file. I can manage config settings with other articles but I want to find the conventional config file(s).
",https://stackoverflow.com/questions/48395804/where-is-create-react-app-webpack-config-and-files,420,417770.0,11.0,,,2018-01-23 06:55:02,2024-08-17 14:18:44,2018-05-21 15:29:42,,,javascript;reactjs;webpack;ecmascript-6;create-react-app,Mohammad,4681,8979982,registered,true,,,CC BY-SA 4.0,,537,490,2,0,0,5,false,false,false,true,true,true,51,7,true,0.026,0.001,3224,2018,1,6,Tuesday,false,false,true,false,false,false,false
26566317,Invariant Violation: _registerComponent(...): Target container is not a DOM element,"I get this error after a making trivial React example page:
Uncaught Error: Invariant Violation: _registerComponent(...): Target container is not a DOM element.
Here's my code:
/** @jsx React.DOM */
'use strict';
var React = require('react');
var App = React.createClass({
render() {
return <h1>Yo</h1>;
}
});
React.renderComponent(<App />, document.body);
HTML:
<html>
<head>
<script src=""/bundle.js""></script>
</head>
<body>
</body>
</html>
What does this mean?
",https://stackoverflow.com/questions/26566317/invariant-violation-registercomponent-target-container-is-not-a-dom-elem,413,256662.0,16.0,,,2014-10-25 19:22:49,2022-04-24 15:34:52,,,,javascript;dom;reactjs,Dan Abramov,268672,458193,registered,true,26566330,,CC BY-SA 3.0,,663,555,2,0,0,3,true,false,false,true,true,false,83,10,false,0.062,0.0016,4410,2014,10,19,Saturday,true,false,true,false,false,false,false
56871384,What is the difference between .ts and .tsx extensions. Both are used as extensions for typescript files in react. So where should we use them?,"I am new to react and I am working on a project. I come across both .ts and .tsx extensions. I don't understand where should I use .ts and .tsx. Any help on this is much appreciated. Thank you!
",https://stackoverflow.com/questions/56871384/what-is-the-difference-between-ts-and-tsx-extensions-both-are-used-as-extensi,410,369588.0,9.0,,,2019-07-03 13:33:15,2025-02-19 18:39:59,2021-02-17 09:00:42,,,reactjs;typescript,Hafsa Mushtaq,4231,10058489,registered,true,56871491,,CC BY-SA 4.0,,253,194,4,0,0,2,true,false,false,true,true,true,143,25,true,0.024,0.0011,2698,2019,7,13,Wednesday,false,false,false,false,false,false,false
36862334,Get viewport/window height in ReactJS,"How do I get the viewport height in ReactJS? In normal JavaScript I use
window.innerHeight()
but using ReactJS, I'm not sure how to get this information. My understanding is that
ReactDOM.findDomNode()
only works for components created. However this is not the case for the document or body element, which could give me height of the window.
",https://stackoverflow.com/questions/36862334/get-viewport-window-height-in-reactjs,408,770171.0,30.0,,,2016-04-26 10:31:17,2025-04-30 15:41:44,2020-01-24 19:12:02,,,javascript;reactjs;window;viewport,Jabran Saeed,6218,1648831,registered,true,36997691,,CC BY-SA 4.0,,443,348,4,0,0,4,true,false,false,true,true,true,37,5,false,0.039,0.0005,3861,2016,4,10,Tuesday,false,false,true,false,false,false,false
36097965,When to use ES6 class based React components vs. ES6 React function components?,"After spending some time learning React I understand the difference between the two main paradigms of creating components.
My question is when should I use which one and why? What are the benefits/tradeoffs of one over the other?
ES6 classes:
import React, { Component } from 'react';
export class MyComponent extends Component {
render() {
return (
<div></div>
);
}
}
Function:
const MyComponent = (props) => {
return (
<div></div>
);
}
I’m thinking function component whenever there is no state to be manipulated by that component, but is that it?
I’m guessing if I use any life cycle methods, it might be best to go with a class based component.
",https://stackoverflow.com/questions/36097965/when-to-use-es6-class-based-react-components-vs-es6-react-function-components,404,138322.0,7.0,,,2016-03-19 04:47:26,2025-08-22 07:52:00,2025-01-02 06:40:54,2025-02-11 16:36:08,Opinion-based,javascript;reactjs;ecmascript-6,omarjmh,13914,4996204,registered,true,36137801,,,2025-02-11 15:58:53,883,707,2,0,0,3,true,true,false,true,true,true,79,13,true,0.051,0.0029,3899,2016,3,4,Saturday,true,false,true,false,false,false,false
31272207,to call onChange event after pressing Enter key,"I am new to Bootstrap and stuck with this problem. I have an input field and as soon as I enter just one digit, the function from onChange is called, but I want it to be called when I push 'Enter when the whole number has been entered. The same problem for the validation function - it calls too soon.
var inputProcent = React.CreateElement(bootstrap.Input, {type: ""text"",
//bsStyle: this.validationInputFactor(),
placeholder: this.initialFactor,
className: ""input-block-level"",
onChange: this.handleInput,
block: true,
addonBefore: '%',
ref:'input',
hasFeedback: true
});
",https://stackoverflow.com/questions/31272207/to-call-onchange-event-after-pressing-enter-key,403,681851.0,12.0,,,2015-07-07 14:57:16,2023-03-16 09:39:03,2019-02-07 20:39:06,,,javascript;twitter-bootstrap;reactjs,Bill Lumbert,5063,2196255,registered,true,75754381,,CC BY-SA 4.0,,635,591,2,0,0,3,true,false,false,true,true,true,47,8,false,0.018,0.0006,4155,2015,7,14,Tuesday,false,false,true,false,false,false,false
42123261,Programmatically navigate using react router V4,"I have just replaced react-router from v3 to v4.
But I am not sure how to programmatically navigate in the member function of a Component.
i.e in handleClick() function I want to navigate to /path/some/where after processing some data.
I used to do that by:
import { browserHistory } from 'react-router'
browserHistory.push('/path/some/where')
But I can't find such interfaces in v4.
How can I navigate using v4?
",https://stackoverflow.com/questions/42123261/programmatically-navigate-using-react-router-v4,398,362634.0,17.0,,,2017-02-08 20:46:14,2021-01-19 09:35:04,2017-11-02 03:35:58,,,reactjs;ecmascript-6;react-router-v4,Colin Wang,7018,6071987,registered,true,42124328,,CC BY-SA 3.0,,551,416,5,0,0,3,true,false,false,true,true,true,47,6,false,0.047,0.0011,3573,2017,2,20,Wednesday,false,false,false,false,false,false,false
21109361,Why is React's concept of Virtual DOM said to be more performant than dirty model checking?,"I saw a React dev talk at (Pete Hunt: React: Rethinking best practices -- JSConf EU 2013) and the speaker mentioned that dirty-checking of the model can be slow. But isn't calculating the diff between virtual DOMs actually even less performant since the virtual DOM, in most of the cases, should be bigger than model?
I really like the potential power of the Virtual DOM (especially server-side rendering) but I would like to know all the pros and cons.
",https://stackoverflow.com/questions/21109361/why-is-reacts-concept-of-virtual-dom-said-to-be-more-performant-than-dirty-mode,398,95400.0,6.0,,,2014-01-14 08:57:15,2022-05-14 09:35:37,2019-08-14 02:02:13,,,javascript;dom;reactjs;virtual-dom,Daniil,5810,1865109,registered,true,,,CC BY-SA 4.0,,618,456,0,2,0,4,false,false,false,true,true,true,95,16,true,0.063,0.0042,4694,2014,1,8,Tuesday,false,false,true,false,false,false,false
44121069,How can I pass parameters with history.push/Link/Redirect in React Router v4?,"How can we pass parameters with this.props.history.push('/page') in React Router v4?
.then(response => {
var r = this;
if (response.status >= 200 && response.status < 300) {
r.props.history.push('/template');
});
",https://stackoverflow.com/questions/44121069/how-can-i-pass-parameters-with-history-push-link-redirect-in-react-router-v4,396,539412.0,13.0,,,2017-05-22 19:53:06,2025-09-23 12:32:45,2025-09-23 11:50:35,,,reactjs;react-router,IshanGarg,4047,5658880,registered,true,,,CC BY-SA 4.0,,296,252,2,0,0,2,false,false,false,true,true,true,77,11,true,0.024,0.0007,3470,2017,5,19,Monday,false,false,false,false,false,false,false
27864720,react-router - pass props to handler component,"I have the following structure for my React.js application using React Router:
var Dashboard = require('./Dashboard');
var Comments = require('./Comments');
var Index = React.createClass({
render: function () {
return (
<div>
<header>Some header</header>
<RouteHandler />
</div>
);
}
});
var routes = (
<Route path=""/"" handler={Index}>
<Route path=""comments"" handler={Comments}/>
<DefaultRoute handler={Dashboard}/>
</Route>
);
ReactRouter.run(routes, function (Handler) {
React.render(<Handler/>, document.body);
});
I want to pass some properties into the Comments component.
(normally I'd do this like <Comments myprop=""value"" />)
What's the easiest and right way to do so with React Router?
",https://stackoverflow.com/questions/27864720/react-router-pass-props-to-handler-component,395,335876.0,25.0,,,2015-01-09 16:14:21,2022-01-20 18:17:21,2017-05-27 21:31:38,,,javascript;properties;reactjs;react-router,Kosmetika,21344,2117550,registered,true,27868548,,CC BY-SA 3.0,,991,836,3,1,0,4,true,false,false,true,true,true,46,7,false,0.074,0.0012,4334,2015,1,16,Friday,false,false,true,false,false,false,false
40546231,sh: react-scripts: command not found after running npm start,"I cloned a react application onto my system and ran following commands
npm install -g create-react-app
npm install --save react react-dom
After that i ran
npm start
But it threw the above mentioned error, It is working fine on my other system from which i pushed it on github. But it is not working on any other system after cloning whether windows or mac.
",https://stackoverflow.com/questions/40546231/sh-react-scripts-command-not-found-after-running-npm-start,393,701734.0,50.0,,,2016-11-11 10:40:30,2025-12-20 22:54:57,,,,reactjs,Devesh Jadon,7514,2382154,registered,true,42539669,,CC BY-SA 3.0,,434,365,2,0,0,1,true,false,false,true,true,false,60,9,false,0.071,0.0006,3662,2016,11,10,Friday,false,false,false,false,false,false,false
30766441,How to use comments in React,"How can I use comments inside the render method in a React component?
I have the following component:
'use strict';
var React = require('react'),
Button = require('./button'),
UnorderedList = require('./unordered-list');
class Dropdown extends React.Component{
constructor(props) {
super(props);
}
handleClick() {
alert('I am click here');
}
render() {
return (
<div className="dropdown">
// whenClicked is a property not an event, per se.
<Button whenClicked={this.handleClick} className="btn-default" title={this.props.title} subTitleClassName="caret"></Button>
<UnorderedList />
</div>
)
}
}
module.exports = Dropdown;
![]()
My comments are showing up in the UI.
What would be the right approach to apply single and multiple line comments inside a render method of a component?
",https://stackoverflow.com/questions/30766441/how-to-use-comments-in-react,393,417220.0,16.0,,,2015-06-10 20:15:41,2025-04-24 16:23:24,2021-10-30 22:22:32,,,reactjs;react-native,user1177440,,,does_not_exist,true,30766542,,CC BY-SA 4.0,2021-07-06 19:18:02,1080,911,2,0,1,2,true,false,false,true,false,true,28,6,false,0.038,0.0009,4182,2015,6,20,Wednesday,false,false,false,false,false,false,false
54676966,Push method in React Hooks (useState)?,"How to push element inside useState array React hook?
Is that as an old method in react state? Or something new?
E.g. setState push example ?
",https://stackoverflow.com/questions/54676966/push-method-in-react-hooks-usestate,391,612290.0,9.0,,,2019-02-13 18:21:58,2024-07-03 21:35:22,2019-02-25 06:24:41,,,javascript;reactjs;react-hooks,Milos N.,4877,6419723,registered,true,54677026,,CC BY-SA 4.0,,268,143,0,1,0,3,true,false,false,true,true,true,38,6,true,0.015,0.0006,2838,2019,2,18,Wednesday,false,false,true,false,false,false,false
39758136,How to render HTML string as real HTML?,"Here's what I tried and how it goes wrong.
This works:
<div dangerouslySetInnerHTML={{ __html: ""<h1>Hi there!</h1>"" }} />
This doesn't:
<div dangerouslySetInnerHTML={{ __html: this.props.match.description }} />
The description property is just a normal string of HTML content. However it's rendered as a string, not as HTML for some reason.
Any suggestions?
",https://stackoverflow.com/questions/39758136/how-to-render-html-string-as-real-html,391,694717.0,16.0,,,2016-09-28 21:42:03,2025-03-19 17:03:44,2022-07-29 06:52:13,,,javascript;html;reactjs;jsx,Sergio Tapia,9937,5129131,registered,true,39758914,,CC BY-SA 4.0,,629,394,2,1,1,4,true,false,false,true,true,true,39,8,true,0.023,0.0006,3706,2016,9,21,Wednesday,false,false,true,false,false,false,false
45425721,Invalid Host Header when ngrok tries to connect to React dev server,"I'm trying to test my React application on a mobile device. I'm using ngrok to make my local server available to other devices and have gotten this working with a variety of other applications. However, when I try to connect ngrok to the React dev server, I get the error:
Invalid Host Header
I believe that React blocks all requests from another source by default. Any thoughts?
",https://stackoverflow.com/questions/45425721/invalid-host-header-when-ngrok-tries-to-connect-to-react-dev-server,385,271488.0,8.0,,,2017-07-31 21:39:49,2024-09-07 00:36:59,2017-08-01 20:29:21,,,reactjs;localhost;ngrok,Patrick Connors,6153,5624061,registered,true,45494621,,CC BY-SA 3.0,2023-01-03 19:06:11,422,384,1,0,0,3,true,false,false,true,true,true,67,12,false,0.029,0.0014,3400,2017,7,21,Monday,false,false,false,false,false,false,false
62861269,Attempted import error: 'useHistory' is not exported from 'react-router-dom',"useHistory giving this error:
Failed to compile ./src/pages/UserForm/_UserForm.js Attempted import
error: 'useHistory' is not exported from 'react-router-dom'. This
error occurred during the build time and cannot be dismissed.
react-router-dom version:
4.3.1
Code:
import React, { useState, Fragment } from 'react';
import FormUserDetails from './FormUserDetails';
import FormPersonalDetails from './FormPersonalDetails';
import Confirm from './Confirm';
import Success from './Success';
import Button from '@material-ui/core/Button';
import { Grid, makeStyles } from '@material-ui/core';
import { useHistory } from 'react-router-dom';
function UserForm() {
const [step, setStep] = useState(1);
const history = useHistory();
const StepButtons = (props) => (
<React.Fragment>
<Grid item xs={4}>
{props.value !== 'initial' ?
<Button variant="outlined" className={classes.button} onClick={(e) => previousStep(e)}>Back</Button> :
<Button variant="outlined" className={classes.button} onClick={(e) => reGenerate(e)}>Re-generate</Button>
}
</Grid>
<Grid item xs={4} />
<Grid item xs={4}>
{
props.value === 'confirm' ?
<Button variant="outlined" className={classes.button} style={{ float: "right" }} onClick={(e) => confirm(e)}>Confirm</Button> :
props.value !== 'final' ?
<Button variant="outlined" className={classes.button} style={{ float: "right" }} onClick={(e) => nextStep(e)}>Continue</Button> :
null
}
</Grid>
</React.Fragment>
);
const nextStep = (e) => {
e.preventDefault();
setStep(prevState => prevState + 1)
}
const previousStep = (e) => {
e.preventDefault();
setStep(prevState => prevState - 1)
}
const reGenerate = (e) => {
e.preventDefault();
}
const confirm = (e) => {
history.push('/')
}
return (
<div>
<h1>Hello</h1>
</div>
)
}
export default UserForm
",https://stackoverflow.com/questions/62861269/attempted-import-error-usehistory-is-not-exported-from-react-router-dom,384,546488.0,13.0,,,2020-07-12 12:47:15,2023-12-20 16:50:22,2023-05-08 05:34:51,,,reactjs;react-hooks;react-router,Nafeo Alam,4717,8080448,registered,true,66971821,,CC BY-SA 4.0,2022-06-14 15:10:25,2528,2419,1,0,0,3,true,false,false,true,true,true,92,9,false,0.024,0.0007,2323,2020,7,12,Sunday,true,false,false,false,false,false,false
21285923,How can I communicate between related react components?,"I just got started with ReactJS and am a little stuck on a problem that I have.
My application is essentially a list with filters and a button to change the layout.
At the moment I'm using three components: <list />, < Filters /> and <TopBar />, now obviously when I change settings in < Filters /> I want to trigger some method in <list /> to update my view.
How can I make those 3 components interact with each other, or do I need some sort of global data model where I can just make changes to?
",https://stackoverflow.com/questions/21285923/how-can-i-communicate-between-related-react-components,382,230360.0,11.0,,,2014-01-22 14:40:58,2022-05-12 13:05:48,2022-05-12 13:05:48,,,javascript;reactjs,woutr_be,9752,871021,registered,true,21322402,,CC BY-SA 4.0,2016-12-31 01:06:40,616,530,5,0,0,2,true,false,false,true,true,true,55,8,true,0.048,0.0017,4686,2014,1,14,Wednesday,false,false,true,false,false,false,false
23427384,Get form data in React,"I have a simple form in my render function, like so:
render : function() {
return (
<form>
<input type="text" name="email" placeholder="Email" />
<input type="password" name="password" placeholder="Password" />
<button type="button" onClick={this.handleLogin}>Login</button>
</form>
);
},
handleLogin: function() {
// How can I access email and password here?
}
What should I write in my handleLogin: function() { ... } to access Email and Password fields?
",https://stackoverflow.com/questions/23427384/get-form-data-in-react,381,772906.0,34.0,,,2014-05-02 11:45:06,2024-06-12 16:17:33,2023-02-14 02:19:52,,,reactjs,myusuf,12300,1716578,registered,true,23428536,,CC BY-SA 4.0,,719,629,5,0,0,1,true,false,false,true,true,true,22,5,false,0.044,0.0005,4586,2014,5,11,Friday,false,false,false,false,false,false,false
31045716,React this.setState is not a function,"Keep getting this error while trying to write an app working with 3rd party API
TypeError: this.setState is not a function
when I try to handle the API response. I suspect it's something wrong with this binding but I can't figure out how to fix it. Here's the code of my component:
var AppMain = React.createClass({
getInitialState: function() {
return{
FirstName: " "
};
},
componentDidMount:function(){
VK.init(function(){
console.info("API initialisation successful");
VK.api('users.get',{fields: 'photo_50'},function(data){
if(data.response){
this.setState({ //the error happens here
FirstName: data.response[0].first_name
});
console.info(this.state.FirstName);
}
});
}, function(){
console.info("API initialisation failed");
}, '5.34');
},
render:function(){
return (
<div className="appMain">
<Header />
</div>
);
}
});
",https://stackoverflow.com/questions/31045716/react-this-setstate-is-not-a-function,377,506031.0,16.0,,,2015-06-25 08:59:31,2025-01-13 02:42:29,2023-01-09 13:52:03,,,javascript;reactjs,Ivan,16908,3103108,registered,true,31045750,,CC BY-SA 4.0,,1249,1179,1,0,0,2,true,false,false,true,true,true,37,6,false,0.032,0.0007,4167,2015,6,8,Thursday,false,false,true,false,false,false,false
41474134,Nested routes with react router v4 / v5,"I am currently struggling with nesting routes using react router v4.
The closest example was the route config in the
React-Router v4 Documentation.
I want to split my app in 2 different parts.
A frontend and an admin area.
I was thinking about something like this:
<Match pattern="/" component={Frontpage}>
<Match pattern="/home" component={HomePage} />
<Match pattern="/about" component={AboutPage} />
</Match>
<Match pattern="/admin" component={Backend}>
<Match pattern="/home" component={Dashboard} />
<Match pattern="/users" component={UserPage} />
</Match>
<Miss component={NotFoundPage} />
The frontend has a different layout and style than the admin area. So within the frontpage the route home, about and so one should be the child routes.
/home should be rendered into the Frontpage component and /admin/home should be rendered within the Backend component.
I tried some other variations but I always ended in not hitting /home or /admin/home.
",https://stackoverflow.com/questions/41474134/nested-routes-with-react-router-v4-v5,375,394057.0,14.0,,,2017-01-04 22:15:28,2024-05-29 06:32:35,2023-03-01 03:46:38,,,javascript;reactjs;nested;react-router;react-router-v4,datoml,5813,5000491,registered,true,43311025,,CC BY-SA 4.0,,1268,1076,5,1,0,5,true,false,false,true,true,true,39,8,false,0.036,0.001,3608,2017,1,22,Wednesday,false,false,true,false,false,false,false
53253940,Make React useEffect hook not run on initial render,"According to the docs:
componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.
We can use the new useEffect() hook to simulate componentDidUpdate(), but it seems like useEffect() is being ran after every render, even the first time. How do I get it to not run on initial render?
As you can see in the example below, componentDidUpdateFunction is printed during the initial render but componentDidUpdateClass was not printed during the initial render.
function ComponentDidUpdateFunction() {
const [count, setCount] = React.useState(0);
React.useEffect(() => {
console.log(""componentDidUpdateFunction"");
});
return (
<div>
<p>componentDidUpdateFunction: {count} times</p>
<button
onClick={() => {
setCount(count + 1);
}}
>
Click Me
</button>
</div>
);
}
class ComponentDidUpdateClass extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
}
componentDidUpdate() {
console.log(""componentDidUpdateClass"");
}
render() {
return (
<div>
<p>componentDidUpdateClass: {this.state.count} times</p>
<button
onClick={() => {
this.setState({ count: this.state.count + 1 });
}}
>
Click Me
</button>
</div>
);
}
}
ReactDOM.render(
<div>
<ComponentDidUpdateFunction />
<ComponentDidUpdateClass />
</div>,
document.querySelector(""#app"")
);
<script src=""https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js""></script>
<script src=""https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js""></script>
<div id=""app""></div>
",https://stackoverflow.com/questions/53253940/make-react-useeffect-hook-not-run-on-initial-render,373,366546.0,20.0,,,2018-11-11 22:35:42,2024-01-09 23:30:48,2018-11-12 06:52:42,,,javascript;reactjs;react-hooks,Yangshun Tay,53969,1751946,registered,true,53254028,,CC BY-SA 4.0,,2394,1968,8,0,0,3,true,false,false,true,true,true,51,9,false,0.055,0.001,2932,2018,11,22,Sunday,true,false,true,false,false,false,false
33188994,Scroll to the top of the page after render in react.js,"I have a problem, which I have no ideas, how to solve.
In my react component I display a long list of data and few links at the bottom.
After clicking on any of this links I fill in the list with new collection of the links and need to scroll to the top.
The problem is - how to scroll to the top after new collection is rendered?
'use strict';
// url of this component is #/:checklistId/:sectionId
var React = require('react'),
Router = require('react-router'),
sectionStore = require('./../stores/checklist-section-store');
function updateStateFromProps() {
var self = this;
sectionStore.getChecklistSectionContent({
checklistId: this.getParams().checklistId,
sectionId: this.getParams().sectionId
}).then(function (section) {
self.setState({
section,
componentReady: true
});
});
this.setState({componentReady: false});
}
var Checklist = React.createClass({
mixins: [Router.State],
componentWillMount: function () {
updateStateFromProps.call(this);
},
componentWillReceiveProps(){
updateStateFromProps.call(this);
},
render: function () {
if (this.state.componentReady) {
return(
<section className='checklist-section'>
<header className='section-header'>{ this.state.section.name } </header>
<Steps steps={ this.state.section.steps }/>
<a href=`#/${this.getParams().checklistId}/${this.state.section.nextSection.Id}`>
Next Section
</a>
</section>
);
} else {...}
}
});
module.exports = Checklist;
",https://stackoverflow.com/questions/33188994/scroll-to-the-top-of-the-page-after-render-in-react-js,371,673234.0,40.0,,,2015-10-17 16:37:29,2024-02-21 11:37:27,,,,scroll;reactjs;render,Andrew Kovalenko,6830,797346,registered,true,39345165,,CC BY-SA 3.0,2022-10-22 00:30:48,1647,1592,1,0,0,3,true,false,false,true,true,false,54,11,false,0.059,0.0006,4053,2015,10,16,Saturday,true,false,false,false,false,false,false
41808428,React PropTypes: Allow different types of PropTypes for one prop,"I have a component that receives a prop for its size. The prop can be either a string or a number ex: "LARGE" or 17.
Can I let React.PropTypes know that this can be either one or the other in the propTypes validation?
If I don't specify the type I get a warning:
prop type size is invalid; it must be a function, usually from
React.PropTypes.
MyComponent.propTypes = {
size: React.PropTypes
}
",https://stackoverflow.com/questions/41808428/react-proptypes-allow-different-types-of-proptypes-for-one-prop,371,180692.0,5.0,,,2017-01-23 14:16:48,2021-04-14 07:00:13,2021-04-14 07:00:13,,,reactjs;react-proptypes,Kevin Amiranoff,14793,2829540,registered,true,41808543,,CC BY-SA 4.0,,539,410,5,0,0,2,true,false,false,true,true,true,64,10,false,0.028,0.0021,3589,2017,1,14,Monday,false,false,false,false,false,false,false
46592833,How to use switch statement inside a component?,"I have a React component, and inside the render method of the component I have something like this:
render() {
return (
<div>
<div>
// removed for brevity
</div>
{ switch(...) {} }
<div>
// removed for brevity
</div>
</div>
);
}
Now the point is that I have two div elements, one at the top and one at the bottom, that are fixed. In the middle I want to have a switch statement, and according to a value in my state I want to render a different component. So basically, I want the two div elements to be fixed always, and just in the middle to render a different component each time. I'm using this to implement a multi-step payment procedure). Though, as is the code currently it doesn't work, as it gives me an error saying that switch is unexpected. Any ideas how to achieve what I want?
",https://stackoverflow.com/questions/46592833/how-to-use-switch-statement-inside-a-component,369,893845.0,30.0,,,2017-10-05 18:52:00,2025-10-19 07:17:32,2025-10-19 07:17:32,,,reactjs,typos,6722,6360938,registered,true,46593006,,CC BY-SA 4.0,2025-10-19 01:29:56,1037,947,5,0,0,1,true,false,false,true,true,true,47,8,true,0.034,0.0004,3334,2017,10,18,Thursday,false,false,false,false,false,false,false
37280274,"SyntaxError: Unexpected token < in JSON at position 0","In a React app component which handles Facebook-like content feeds, I am running into an error:
Feed.js:94 undefined ""parsererror"" ""SyntaxError: Unexpected token < in JSON at position 0
I ran into a similar error which turned out to be a typo in the HTML within the render function, but that doesn't seem to be the case here.
More confusingly, I rolled the code back to an earlier, known-working version and I'm still getting the error.
Feed.js:
import React from 'react';
var ThreadForm = React.createClass({
getInitialState: function () {
return {author: '',
text: '',
included: '',
victim: ''
}
},
handleAuthorChange: function (e) {
this.setState({author: e.target.value})
},
handleTextChange: function (e) {
this.setState({text: e.target.value})
},
handleIncludedChange: function (e) {
this.setState({included: e.target.value})
},
handleVictimChange: function (e) {
this.setState({victim: e.target.value})
},
handleSubmit: function (e) {
e.preventDefault()
var author = this.state.author.trim()
var text = this.state.text.trim()
var included = this.state.included.trim()
var victim = this.state.victim.trim()
if (!text || !author || !included || !victim) {
return
}
this.props.onThreadSubmit({author: author,
text: text,
included: included,
victim: victim
})
this.setState({author: '',
text: '',
included: '',
victim: ''
})
},
render: function () {
return (
<form className=""threadForm"" onSubmit={this.handleSubmit}>
<input
type=""text""
placeholder=""Your name""
value={this.state.author}
onChange={this.handleAuthorChange} />
<input
type=""text""
placeholder=""Say something...""
value={this.state.text}
onChange={this.handleTextChange} />
<input
type=""text""
placeholder=""Name your victim""
value={this.state.victim}
onChange={this.handleVictimChange} />
<input
type=""text""
placeholder=""Who can see?""
value={this.state.included}
onChange={this.handleIncludedChange} />
<input type=""submit"" value=""Post"" />
</form>
)
}
})
var ThreadsBox = React.createClass({
loadThreadsFromServer: function () {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function (data) {
this.setState({data: data})
}.bind(this),
error: function (xhr, status, err) {
console.error(this.props.url, status, err.toString())
}.bind(this)
})
},
handleThreadSubmit: function (thread) {
var threads = this.state.data
var newThreads = threads.concat([thread])
this.setState({data: newThreads})
$.ajax({
url: this.props.url,
dataType: 'json',
type: 'POST',
data: thread,
success: function (data) {
this.setState({data: data})
}.bind(this),
error: function (xhr, status, err) {
this.setState({data: threads})
console.error(this.props.url, status, err.toString())
}.bind(this)
})
},
getInitialState: function () {
return {data: []}
},
componentDidMount: function () {
this.loadThreadsFromServer()
setInterval(this.loadThreadsFromServer, this.props.pollInterval)
},
render: function () {
return (
<div className=""threadsBox"">
<h1>Feed</h1>
<div>
<ThreadForm onThreadSubmit={this.handleThreadSubmit} />
</div>
</div>
)
}
})
module.exports = ThreadsBox
In Chrome developer tools, the error seems to be coming from this function:
loadThreadsFromServer: function loadThreadsFromServer() {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function (data) {
this.setState({ data: data });
}.bind(this),
error: function (xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
with the line console.error(this.props.url, status, err.toString() underlined.
Since it looks like the error seems to have something to do with pulling JSON data from the server, I tried starting from a blank db, but the error persists. The error seems to be called in an infinite loop presumably as React continuously tries to connect to the server and eventually crashes the browser.
EDIT:
I've checked the server response with Chrome dev tools and Chrome REST client, and the data appears to be proper JSON.
EDIT 2:
It appears that though the intended API endpoint is indeed returning the correct JSON data and format, React is polling http://localhost:3000/?_=1463499798727 instead of the expected http://localhost:3001/api/threads.
I am running a webpack hot-reload server on port 3000 with the express app running on port 3001 to return the backend data. What's frustrating here is that this was working correctly the last time I worked on it and can't find what I could have possibly changed to break it.
",https://stackoverflow.com/questions/37280274/syntaxerror-unexpected-token-in-json-at-position-0,366,1766653.0,40.0,,,2016-05-17 15:21:49,2024-08-26 20:46:15,2022-03-07 17:08:07,,,javascript;node.js;reactjs;json;rest,Cameron Sima,5415,4043633,registered,true,37280912,,CC BY-SA 4.0,2019-05-22 06:26:49,5559,5356,5,0,0,5,true,false,false,true,true,true,68,9,false,0.023,0.0002,3840,2016,5,15,Tuesday,false,false,true,false,false,false,false
44133536,Is it safe to store a JWT in localStorage with ReactJS?,"I'm currently building a single page application using ReactJS.
I read that one of the reasons for not using localStorage is because of XSS vulnerabilities.
Since React escapes all user input, would it now be safe to use localStorage?
",https://stackoverflow.com/questions/44133536/is-it-safe-to-store-a-jwt-in-localstorage-with-reactjs,365,277886.0,15.0,,,2017-05-23 11:28:20,2025-03-05 21:46:23,2022-03-11 17:09:12,,,javascript;node.js;reactjs;jwt;local-storage,user6127082,,,does_not_exist,true,44209185,,CC BY-SA 4.0,,282,235,2,0,0,5,true,false,false,true,false,true,55,11,true,0.054,0.0013,3469,2017,5,11,Tuesday,false,false,true,false,false,false,false
55441230,Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release,"react-native run-android command terminates by leaving a message in android simulator. The message is as follows:
Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release.
What am I doing wrong?
",https://stackoverflow.com/questions/55441230/unable-to-load-script-make-sure-you-are-either-running-a-metro-server-or-that-yo,362,348736.0,76.0,,,2019-03-31 13:11:07,2025-08-28 14:29:40,2020-07-15 15:26:17,,,reactjs;react-native;react-native-cli;metro-bundler,Belle Solutions,3651,10466428,registered,true,,,CC BY-SA 4.0,2019-10-09 15:43:45,479,288,1,1,1,4,false,false,false,true,true,true,154,22,false,0.218,0.001,2792,2019,3,13,Sunday,true,false,false,false,false,false,false
35855781,Having services in React application,"I'm coming from the angular world where I could extract logic to a service/factory and consume them in my controllers.
I'm trying to understand how can I achieve the same in a React application.
Let's say that I have a component that validates user's password input (it's strength). It's logic is pretty complex hence I don't want to write it in the component it self.
Where should I write this logic? In a store if I'm using flux? Or is there a better option?
",https://stackoverflow.com/questions/35855781/having-services-in-react-application,359,267455.0,13.0,,,2016-03-07 22:53:47,2023-01-04 20:21:55,,,,reactjs;reactjs-flux,Dennis Nerush,5733,1654971,registered,true,45109576,,CC BY-SA 3.0,2020-02-07 09:47:29,492,464,0,0,0,2,true,false,false,true,true,false,36,5,false,0.049,0.0013,3911,2016,3,22,Monday,false,false,false,false,false,false,false
53650468,Set types on useState React Hook with TypeScript,"I'm migrating a React with TypeScript project to use hooks features (React v16.7.0-alpha), but I cannot figure out how to set typings of the destructured elements.
Here is an example:
interface IUser {
name: string;
}
...
const [user, setUser] = useState({name: 'Jon'});
I want to force user variable to be of type IUser. My only successful trial, is doing it in two phases: Typing, then initializing:
let user: IUser;
let setUser: any;
[user, setUser] = useState({name: 'Jon'});
But I'm sure there is a better way. Also, setUser should be initialized as a function that takes a IUser as input, and returns nothing.
Also, worth noting that using const [user, setUser] = useState({name: 'Jon'}); without any initialization works fine, but I would like to take advantage of TypeScript to force type checking on init, especially if it depends on some props.
",https://stackoverflow.com/questions/53650468/set-types-on-usestate-react-hook-with-typescript,358,548939.0,5.0,,,2018-12-06 11:31:12,2025-11-03 11:20:39,2025-11-03 11:20:39,,,reactjs;typescript;react-hooks,Hassen,7784,1201298,registered,true,53650561,,CC BY-SA 4.0,2022-04-02 08:27:32,1007,859,7,0,0,3,true,false,false,true,true,true,48,8,false,0.009,0.0007,2907,2018,12,11,Thursday,false,false,false,false,false,false,false
38093760,How to access a DOM element in React? What is the equilvalent of document.getElementById() in React,"How do I select certain bars in react.js?
This is my code:
var Progressbar = React.createClass({
getInitialState: function () {
return { completed: this.props.completed };
},
addPrecent: function (value) {
this.props.completed += value;
this.setState({ completed: this.props.completed });
},
render: function () {
var completed = this.props.completed;
if (completed < 0) { completed = 0 };
return (...);
}
I want to use this React component:
var App = React.createClass({
getInitialState: function () {
return { baction: 'Progress1' };
},
handleChange: function (e) {
var value = e.target.value;
console.log(value);
this.setState({ baction: value });
},
handleClick10: function (e) {
console.log('You clicked: ', this.state.baction);
document.getElementById(this.state.baction).addPrecent(10);
},
render: function () {
return (
<div class=""center"">Progress Bars Demo
<Progressbar completed={25} id=""Progress1"" />
<h2 class=""center""></h2>
<Progressbar completed={50} id=""Progress2"" />
<h2 class=""center""></h2>
<Progressbar completed={75} id=""Progress3"" />
<h2 class=""center""></h2>
<span>
<select name='selectbar' id='selectbar' value={this.state.baction} onChange={this.handleChange}>
<option value=""Progress1"">#Progress1</option>
<option value=""Progress2"">#Progress2</option>
<option value=""Progress3"">#Progress3</option>
</select>
<input type=""button"" onClick={this.handleClick10} value=""+10"" />
<button>+25</button>
<button>-10</button>
<button>-25</button>
</span>
</div>
)
}
});
I want to execute the handleClick10 function and perform the operation for my selected progressbar.
But the result I get is:
You clicked: Progress1
TypeError: document.getElementById(...) is null
How do I select the certain Element in react.js?
",https://stackoverflow.com/questions/38093760/how-to-access-a-dom-element-in-react-what-is-the-equilvalent-of-document-getele,357,958837.0,8.0,,,2016-06-29 08:05:16,2023-11-08 06:49:52,2018-04-19 07:22:09,,,javascript;reactjs;getelementbyid,user504909,9679,504909,registered,true,38094037,,CC BY-SA 3.0,,2532,2425,3,0,0,3,true,false,false,true,true,true,99,16,false,0.008,0.0004,3797,2016,6,8,Wednesday,false,false,true,false,false,false,false
36904185,react-router scroll to top on every transition,"I have an issue when navigating into another page, its position will remain like the page before. So it won't scroll to top automatically.
I've also tried to use window.scrollTo(0, 0) on onChange router. I've also used scrollBehavior to fix this issue but it didn't work. Any suggestions about this?
",https://stackoverflow.com/questions/36904185/react-router-scroll-to-top-on-every-transition,354,311669.0,39.0,,,2016-04-28 02:26:14,2025-01-01 14:43:40,2020-08-28 07:56:14,,,javascript;reactjs;react-router;react-router-redux,adrian hartanto,3575,5080715,registered,true,,,CC BY-SA 4.0,2022-01-09 11:09:43,346,300,3,0,0,4,false,false,false,true,true,true,46,7,false,0.125,0.0011,3859,2016,4,2,Thursday,false,false,true,false,false,false,false
56663785,Invalid hook call. Hooks can only be called inside of the body of a function component,"I want to show some records in a table using React but I got this error:
Invalid hook call. Hooks can only be called inside of the body of a
function component. This could happen for one of the following
reasons:
- You might have mismatching versions of React and the renderer (such as React DOM)
- You might be breaking the Rules of Hooks
- You might have more than one copy of React in the same app See for tips about how to debug and
fix this problem.
import React, { Component } from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Paper from '@material-ui/core/Paper';
const useStyles = makeStyles(theme => ({
root: {
width: '100%',
marginTop: theme.spacing(3),
overflowX: 'auto'
},
table: {
minWidth: 650
}
}));
class allowance extends Component {
constructor() {
super();
this.state = {
allowances: []
};
}
componentWillMount() {
fetch('http://127.0.0.1:8000/allowances')
.then(data => {
return data.json();
})
.then(data => {
this.setState({
allowances: data
});
console.log('allowance state', this.state.allowances);
});
}
render() {
const classes = useStyles();
return (<Paper className={classes.root}>
<Table className={classes.table}>
<TableHead>
<TableRow>
<TableCell>Allow ID</TableCell>
<TableCell align="right">Description</TableCell>
<TableCell align="right">Allow Amount</TableCell>
<TableCell align="right">AllowType</TableCell>
</TableRow>
</TableHead>
<TableBody> {
this.state.allowances.map(row => (<TableRow key={row.id}>
<TableCell component="th" scope="row">{row.AllowID}</TableCell>
<TableCell align="right">{row.AllowDesc}</TableCell>
<TableCell align="right">{row.AllowAmt}</TableCell>
<TableCell align="right">{row.AllowType}</TableCell>
</TableRow>
))
}
</TableBody>
</Table>
</Paper>
);
}
}
export default allowance;
",https://stackoverflow.com/questions/56663785/invalid-hook-call-hooks-can-only-be-called-inside-of-the-body-of-a-function-com,354,1085472.0,59.0,,,2019-06-19 08:57:15,2025-07-05 13:10:16,2024-03-15 12:49:24,,,javascript;reactjs;react-hooks;material-ui,lwin,4528,7035646,registered,true,56664084,,CC BY-SA 4.0,2022-01-31 10:11:27,2818,2682,1,0,0,4,true,false,false,true,true,true,86,16,false,0.054,0.0003,2712,2019,6,8,Wednesday,false,false,true,false,false,false,false
22639534,Pass props to parent component in React.js,"Is there not a simple way to pass a child's props to its parent using events, in React.js?
var Child = React.createClass({
render: function() {
<a onClick={this.props.onClick}>Click me</a>
}
});
var Parent = React.createClass({
onClick: function(event) {
// event.component.props ?why is this not available?
},
render: function() {
<Child onClick={this.onClick} />
}
});
I know you can use controlled components to pass an input's value but it'd be nice to pass the whole kit n' kaboodle. Sometimes the child component contains a set of information you'd rather not have to look up.
Perhaps there's a way to bind the component to the event?
UPDATE – 9/1/2015
After using React for over a year, and spurred on by Sebastien Lorber's answer, I've concluded passing child components as arguments to functions in parents is not in fact the React way, nor was it ever a good idea. I've switched the answer.
",https://stackoverflow.com/questions/22639534/pass-props-to-parent-component-in-react-js,353,407309.0,7.0,,,2014-03-25 15:44:44,2020-03-24 01:13:52,2015-08-01 15:07:35,,,javascript;reactjs,KendallB,4807,1050703,registered,true,31756470,,CC BY-SA 3.0,,1033,950,2,0,0,2,true,false,false,true,true,true,42,7,false,0.017,0.0009,4624,2014,3,15,Tuesday,false,false,true,false,false,false,false
53945763,componentDidMount equivalent on a React function/Hooks component?,"Are there ways to simulate componentDidMount in React functional components via hooks?
",https://stackoverflow.com/questions/53945763/componentdidmount-equivalent-on-a-react-function-hooks-component,352,262498.0,11.0,,,2018-12-27 13:18:44,2022-06-17 06:42:25,2019-12-12 10:55:50,,,javascript;reactjs;react-hooks,jeyko,3663,3240699,registered,true,54655508,,CC BY-SA 4.0,,107,87,1,0,0,3,true,false,false,true,true,true,65,7,true,0.042,0.0013,2886,2018,12,13,Thursday,false,false,true,false,false,false,false
27827234,How to handle the `onKeyPress` event in ReactJS?,"How can I make the onKeyPress event work in ReactJS? It should alert when enter (keyCode=13) is pressed.
var Test = React.createClass({
add: function(event){
if(event.keyCode == 13){
alert('Adding....');
}
},
render: function(){
return(
<div>
<input type=""text"" id=""one"" onKeyPress={this.add} />
</div>
);
}
});
React.render(<Test />, document.body);
",https://stackoverflow.com/questions/27827234/how-to-handle-the-onkeypress-event-in-reactjs,352,778929.0,13.0,,,2015-01-07 19:34:34,2024-05-23 17:36:15,2019-04-07 18:15:16,,,javascript;reactjs;keypress;onkeypress,user544079,16679,544079,registered,true,,,CC BY-SA 4.0,,556,482,3,0,0,4,false,false,false,true,true,true,48,8,true,0.017,0.0005,4336,2015,1,19,Wednesday,false,false,true,false,false,false,false
49162311,React : difference between <Route exact path="/" /> and <Route path="/" />,"Can someone explain the difference between
<Route exact path="/" component={Home} />
and
<Route path="/" component={Home} />
I don't know the meaning of exact.
",https://stackoverflow.com/questions/49162311/react-difference-between-route-exact-path-and-route-path,350,305034.0,8.0,,,2018-03-07 22:32:07,2025-01-28 14:26:46,2021-11-09 08:16:42,,,reactjs;react-router;react-router-dom,batt,3670,6447638,registered,true,49162423,,CC BY-SA 4.0,2025-10-24 22:37:40,354,194,3,0,0,3,true,false,false,true,true,true,106,12,false,0.026,0.0011,3181,2018,3,22,Wednesday,false,false,false,false,false,false,false
29979324,How to combine multiple inline style objects?,"In React you can clearly create an object and assign it as an inline style. i.e.. mentioned below.
var divStyle = {
color: 'white',
backgroundImage: 'url(' + imgUrl + ')',
WebkitTransition: 'all', // note the capital 'W' here
msTransition: 'all' // 'ms' is the only lowercase vendor prefix
};
var divStyle2 = {fontSize: '18px'};
React.render(<div style={divStyle}>Hello World!</div>, mountNode);
How can I combine multiple objects and assign them together?
",https://stackoverflow.com/questions/29979324/how-to-combine-multiple-inline-style-objects,347,388405.0,22.0,,,2015-04-30 23:13:30,2024-06-02 12:44:28,2017-10-17 16:20:56,,,reactjs,PythonIsGreat,7957,4071364,registered,true,,,CC BY-SA 3.0,,560,485,1,0,0,1,false,false,false,true,true,true,45,7,true,0.057,0.0009,4223,2015,4,23,Thursday,false,false,false,false,false,false,false
40988238,Sending the bearer token with axios,"In my react app i am using axios to perform the REST api requests.
But it's unable to send the Authorization header with the request.
Here is my code:
tokenPayload() {
let config = {
headers: {
'Authorization': 'Bearer ' + validToken()
}
}
Axios.post(
'http://localhost:8000/api/v1/get_token_payloads',
config
)
.then( ( response ) => {
console.log( response )
} )
.catch()
}
Here the validToken() method would simply return the token from browser storage.
All requests are having a 500 error response saying that
The token could not be parsed from the request
from the back-end.
How to send the authorization header with each requests? Would you recommend any other module with react?
",https://stackoverflow.com/questions/40988238/sending-the-bearer-token-with-axios,346,769067.0,19.0,,,2016-12-06 05:09:45,2024-04-28 11:49:59,2018-07-20 18:42:48,,,reactjs;rest;token;axios;access-token,rakibtg,5971,981586,registered,true,,,CC BY-SA 4.0,,952,758,2,1,0,5,false,false,false,true,true,true,35,6,false,0.025,0.0004,3637,2016,12,5,Tuesday,false,false,false,false,false,false,false
37571418,ReactNative: how to center text?,"How to center Text in ReactNative both in horizontal and vertical?
I have an example application in rnplay.org where justifyContent="center" and alignItems="center" is not working:
https://rnplay.org/apps/AoxNKQ
The text should being centered.
And why is there a margin at the top between the text (yellow) and parent container?
Code:
'use strict';
var React = require('react-native');
var {
AppRegistry,
StyleSheet,
Text,
Image,
View,
} = React;
var SampleApp = React.createClass({
render: function() {
return (
<View style={styles.container}>
<View style={styles.topBox}>
<Text style={styles.headline}>
lorem ipsum{'\n'}
ipsum lorem lorem
</Text>
</View>
<View style={styles.otherContainer}>
</View>
</View>
);
}
});
var styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
backgroundColor: 'red',
justifyContent: 'center',
alignItems: 'center',
},
topBox: {
flex: 1,
flexDirection: 'row',
backgroundColor: 'lightgray',
justifyContent: 'center',
alignItems: 'center',
},
headline: {
fontWeight: 'bold',
fontSize: 18,
marginTop: 0,
width: 200,
height: 80,
backgroundColor: 'yellow',
justifyContent: 'center',
alignItems: 'center',
},
otherContainer: {
flex: 4,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'green',
},
});
AppRegistry.registerComponent('SampleApp', () => SampleApp);
module.exports = SampleApp;
",https://stackoverflow.com/questions/37571418/reactnative-how-to-center-text,346,537000.0,22.0,,,2016-06-01 14:22:13,2024-04-18 05:58:39,2023-05-03 00:33:14,,,reactjs;flexbox;react-native,itinance,12546,1397160,registered,true,37573695,,CC BY-SA 4.0,2024-04-20 10:35:46,1827,1642,1,1,0,3,true,false,false,true,true,true,32,5,true,0.041,0.0006,3825,2016,6,14,Wednesday,false,false,false,false,false,false,false
44114436,The create-react-app imports restriction outside of src directory,"I am using create-react-app. I am trying to call an image from my public folder from a file inside my src/components. I am receiving this error message.
./src/components/website_index.js Module not found: You attempted to
import ../../public/images/logo/WC-BlackonWhite.jpg which falls
outside of the project src/ directory. Relative imports outside of
src/ are not supported. You can either move it inside src/, or add a
symlink to it from project's node_modules/.
import logo from '../../public/images/logo_2016.png';
<img className=""Header-logo"" src={logo} alt=""Logo"" />
I have read many things saying you can do an import to the path but that is still not working for me. Any help would be greatly appreciated. I know there are many questions like this but they are all telling me to import logo or image so clearly I am missing something in the big picture.
",https://stackoverflow.com/questions/44114436/the-create-react-app-imports-restriction-outside-of-src-directory,345,557857.0,32.0,,,2017-05-22 13:40:36,2023-07-08 19:04:23,2019-02-06 18:18:57,,,javascript;reactjs;webpack;create-react-app,David Brierton,8276,4106374,registered,true,44115058,,CC BY-SA 4.0,2022-10-18 08:08:18,963,884,2,0,0,4,true,false,false,true,true,true,65,8,false,0.057,0.0006,3470,2017,5,13,Monday,false,false,true,false,false,false,false
33471880,Dynamic tag name in React JSX,"I am trying to write a React component for HTML heading tags (h1, h2, h3, etc.), where the heading level is specified via a prop.
I tried to do it like this:
<h{this.props.level}>Hello</h{this.props.level}>
And I expected output like:
<h1>Hello</h1>
But this is not working.
Is there any way to do this?
",https://stackoverflow.com/questions/33471880/dynamic-tag-name-in-react-jsx,344,184737.0,11.0,,,2015-11-02 06:26:57,2025-02-24 17:16:32,2022-07-10 11:15:37,,,javascript;node.js;reactjs;jsx,Eranga Kapukotuwa,4992,1350481,registered,true,33471928,,CC BY-SA 4.0,,452,330,5,0,0,4,true,false,false,true,true,true,29,6,false,0.06,0.0019,4037,2015,11,6,Monday,false,false,true,false,false,false,false
41928567,<div> cannot appear as a descendant of <p>,"I'm seeing this. It's not a mystery what it is complaining about:
Warning: validateDOMnesting(...): <div> cannot appear as a descendant of <p>. See ... SomeComponent > p > ... > SomeOtherComponent > ReactTooltip > div.
I'm the author of SomeComponent and SomeOtherComponent. But the latter is using an external dependency (ReactTooltip from react-tooltip). It's probably not essential that this is an external dependency, but it lets me try the argument here that it is ""some code that's out of my control"".
How worried should I be about this warning, given that the nested component is working just fine (seemingly)? And how would I go about changing this anyway (provided I don't want to re-implement an external dependency)? Is there maybe a better design that I'm yet unaware of?
For completeness sake, here's the implementation of SomeOtherComponent. It just renders this.props.value, and when hovered: a tooltip that says ""Some tooltip message"":
class SomeOtherComponent extends React.Component {
constructor(props) {
super(props)
}
render() {
const {value, ...rest} = this.props;
return <span className=""some-other-component"">
<a href=""#"" data-tip=""Some tooltip message"" {...rest}>{value}</a>
<ReactTooltip />
</span>
}
}
Thank you.
",https://stackoverflow.com/questions/41928567/div-cannot-appear-as-a-descendant-of-p,344,443999.0,21.0,,,2017-01-30 03:16:39,2024-12-03 19:22:41,2021-12-06 16:52:43,,,javascript;reactjs,Sander Verhagen,9253,1325216,registered,true,,,CC BY-SA 4.0,,1574,1342,8,1,0,2,false,false,false,true,true,true,54,8,false,0.047,0.0008,3582,2017,1,3,Monday,false,false,true,false,false,false,false
33460420,babel-loader jsx SyntaxError: Unexpected token,"I'm a beginner in React + Webpack.
I found a weird error in my hello world web app.
I'm using babel-loader in webpack to help me convert jsx into js, but it seems like babel can't understand jsx syntax.
Here are my dependencies:
""devDependencies"": {
""babel-core"": ""^6.0.14"",
""babel-loader"": ""^6.0.0"",
""webpack"": ""^1.12.2"",
""webpack-dev-server"": ""^1.12.1""
},
""dependencies"": {
""react"": ""^0.14.1""
}
Here is my webpack.config.js
var path = require('path');
module.exports = {
entry: ['webpack/hot/dev-server',path.resolve(__dirname, 'app/main.js')],
output: {
path: path.resolve(__dirname, 'build'),
filename: 'bundle.js'
},
module: {
loaders: [
{ test: /\.js$/, exclude: /node_modules/, loader: ""babel-loader""}
]
}
};
Here is my app/main.js
var React = require(""react"");
React.render(<h1>hello world</h1>,document.getElementById(""app""));
And this is the error message
ERROR in ./app/main.js
Module build failed: SyntaxError: ~/**/app/main.js: Unexpected token (2:13)
1 | var React = require(""react"");
> 2 | React.render(<h1>hello world</h1>,document.getElementById(""app""));
| ^
at Parser.pp.raise (~/**/node_modules/babylon/lib/parser/location.js:24:13)
Thanks for you guys.
",https://stackoverflow.com/questions/33460420/babel-loader-jsx-syntaxerror-unexpected-token,344,354604.0,8.0,,,2015-11-01 08:25:51,2018-04-23 02:49:18,2017-09-22 11:02:47,2016-11-18 21:30:58,Duplicate,javascript;reactjs;webpack;babeljs,Keyu Lin,3709,4943102,registered,true,33460642,,,,1462,1284,6,0,0,4,true,true,false,true,true,true,46,5,false,0.023,0.001,4038,2015,11,8,Sunday,true,false,true,false,false,false,false
49579028,Adding an .env file to a React project,"I'm trying to hide my API Key for when I commit to GitHub, and I've looked through the forum for guidance, especially the following post:
How do I hide an API key in Create React App?
I made the changes and restarted Yarn. I'm not sure what I'm doing wrong—I added an .env file to the root of my project (I named it process.env) and in the file I just put REACT_APP_API_KEY = 'my-secret-api-key'.
I'm thinking it might be the way I'm adding the key to my fetch in App.js, and I've tried multiple formats, including without using the template literal, but my project will still not compile.
performSearch = (query = 'germany') => {
fetch(`https://api.unsplash.com/search/photos?query=${query}&client_id=${REACT_APP_API_KEY}`)
.then(response => response.json())
.then(responseData => {
this.setState({
results: responseData.results,
loading: false
});
})
.catch(error => {
console.log('Error fetching and parsing data', error);
});
}
",https://stackoverflow.com/questions/49579028/adding-an-env-file-to-a-react-project,343,875437.0,12.0,,,2018-03-30 17:50:25,2025-05-30 14:00:57,2024-05-02 15:35:05,2022-11-21 15:38:01,Duplicate,javascript;reactjs;environment-variables;api-key,Biii,3481,8864630,registered,true,49579700,,,,1503,1037,5,2,0,4,true,true,false,true,true,true,38,8,false,0.014,0.0004,3158,2018,3,17,Friday,false,false,true,false,false,false,false
36284453,"React native text going off my screen, refusing to wrap. What to do?","The following code can be found in this live example
I've got the following react native element:
'use strict';
var React = require('react-native');
var {
AppRegistry,
StyleSheet,
Text,
View,
} = React;
var SampleApp = React.createClass({
render: function() {
return (
<View style={styles.container}>
<View style={styles.descriptionContainerVer}>
<View style={styles.descriptionContainerHor}>
<Text style={styles.descriptionText} numberOfLines={5} >
Here is a really long text that you can do nothing about, its gonna be long wether you like it or not, so be prepared for it to go off screen. Right? Right..!
</Text>
</View>
</View>
<View style={styles.descriptionContainerVer2}>
<View style={styles.descriptionContainerHor}>
<Text style={styles.descriptionText} numberOfLines={5} >Some other long text which you can still do nothing about.. Off the screen we go then.</Text>
</View>
</View>
</View>);
}
});
AppRegistry.registerComponent('SampleApp', () => SampleApp);
with the following styles:
var styles = StyleSheet.create({
container:{
flex:1,
flexDirection:'column',
justifyContent: 'flex-start',
backgroundColor: 'grey'
},
descriptionContainerVer:{
flex:0.5, //height (according to its parent)
flexDirection: 'column', //its children will be in a row
alignItems: 'center',
backgroundColor: 'blue',
// alignSelf: 'center',
},
descriptionContainerVer2:{
flex:0.5, //height (according to its parent)
flexDirection: 'column', //its children will be in a row
alignItems: 'center',
backgroundColor: 'orange',
// alignSelf: 'center',
},
descriptionContainerHor:{
//width: 200, //I DON\'T want this line here, because I need to support many screen sizes
flex: 0.3, //width (according to its parent)
flexDirection: 'column', //its children will be in a column
alignItems: 'center', //align items according to this parent (like setting self align on each item)
justifyContent: 'center',
flexWrap: 'wrap'
},
descriptionText: {
backgroundColor: 'green',//Colors.transparentColor,
fontSize: 16,
color: 'white',
textAlign: 'center',
flexWrap: 'wrap'
}
});
This results in the following screen:
How can I stop the text from going off the screen and keep it confined in the middle of the screen with a width of i.e. 80% of the parent.
I don't think I should use width because I will be running this on MANY different mobile screens and I want it to be dynamic, so I think I should rely totally on flexbox.
(That was the initial reason why I had flex: 0.8 within the descriptionContainerHor.
What I want to achieve is something like this:
Thank you!
",https://stackoverflow.com/questions/36284453/react-native-text-going-off-my-screen-refusing-to-wrap-what-to-do,342,521534.0,31.0,,,2016-03-29 12:35:16,2026-03-22 09:25:01,2016-03-30 12:49:23,,,css;reactjs;react-native;flexbox,SudoPlz,23773,1658268,registered,true,57462018,,CC BY-SA 3.0,,3467,2940,6,3,2,4,true,false,false,true,true,true,68,13,true,0.059,0.0007,3889,2016,3,12,Tuesday,false,false,false,false,false,false,false
39823681,Read the current full URL with React?,"How do I get the full URL from within a ReactJS component?
I'm thinking it should be something like this.props.location but it is undefined
",https://stackoverflow.com/questions/39823681/read-the-current-full-url-with-react,342,741303.0,10.0,,,2016-10-03 02:05:34,2022-06-27 11:14:29,,,,reactjs,Doug,15791,142098,registered,true,39823749,,CC BY-SA 3.0,,181,141,2,0,0,1,true,false,false,true,true,false,37,7,true,0.013,0.0005,3701,2016,10,2,Monday,false,false,false,false,false,false,false
71706064,React 18: Hydration failed because the initial UI does not match what was rendered on the server,"I'm trying to get SSR working in my app, but I get the error:
Hydration failed because the initial UI does not match what was
rendered on the server.
Live demo code is here.
Live demo of problem is here (open dev tools console to see the errors):
File App.js
import React from "react";
class App extends React.Component {
head() {
return (
<head>
<meta charSet="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<meta name="theme-color" content="#000000" />
<title>React App</title>
</head>
);
}
body() {
return (
<body>
<div className="App">
<h1>Client says Hello World</h1>
</div>
</body>
);
}
render() {
return (
<React.Fragment>
{this.head()}
{this.body()}
</React.Fragment>
)
}
}
export default App;
File index.js
import React from "react";
import * as ReactDOM from "react-dom/client";
import { StrictMode } from "react";
import App from "./App";
//const container = document.getElementById("root");
const container = document.getElementsByTagName("html")[0]
ReactDOM.hydrateRoot(
container,
<StrictMode>
<App />
</StrictMode>
);
The HTML template shown in the live demo is served by the backend and generated using the following code:
const ReactDOMServer = require('react-dom/server');
const clientHtml = ReactDOMServer.renderToString(
<StrictMode>
<App />
</StrictMode>
)
// Serve clientHtml to client
I need to dynamically generate <head></head> and <body></body> section as shown in the App class.
",https://stackoverflow.com/questions/71706064/react-18-hydration-failed-because-the-initial-ui-does-not-match-what-was-render,341,690829.0,70.0,,,2022-04-01 11:17:03,2026-02-12 11:02:07,2023-12-07 23:01:54,,,reactjs;next.js,auser,7707,1249664,registered,true,71870995,,CC BY-SA 4.0,2023-12-08 01:50:43,2376,1944,4,3,0,2,true,false,false,true,true,true,96,17,false,0.101,0.0005,1695,2022,4,11,Friday,false,false,false,false,false,false,false
37337289,React.js: Set innerHTML vs dangerouslySetInnerHTML,"Is there any ""behind the scenes"" difference from setting an element's innerHTML vs setting the dangerouslySetInnerHTML property on an element? Assume I'm properly sanitizing things for the sake of simplicity.
Example:
var test = React.createClass({
render: function(){
return (
<div contentEditable='true' dangerouslySetInnerHTML={{ __html: ""Hello"" }}></div>
);
}
});
vs
var test = React.createClass({
componentDidUpdate: function(prevProp, prevState){
this.refs.test.innerHTML = ""Hello"";
},
render: function(){
return (
<div contentEditable='true' ref='test'></div>
);
}
});
I'm doing something a bit more complicated than the above example, but the overall idea is the same
",https://stackoverflow.com/questions/37337289/react-js-set-innerhtml-vs-dangerouslysetinnerhtml,341,686069.0,7.0,,,2016-05-20 03:04:01,2025-10-09 07:59:45,2020-08-24 07:45:16,,,javascript;html;reactjs;innerhtml,Jshoe523,4301,1732998,registered,true,37339542,,CC BY-SA 4.0,,829,753,2,0,0,4,true,false,false,true,true,true,50,5,false,0.01,0.0005,3837,2016,5,3,Friday,false,false,true,false,false,false,false
50722133,What exactly is the 'react-scripts start' command?,"I've been working with a React project using create-react-app and I have two options to start the project:
First way:
npm run start with the definition at the package.json like this:
"start": "react-scripts start",
Second way:
npm start
What is the difference between these two commands? And, what is the purpose of the react-scripts start?
I tried to find the definition, but I just found a package with this name. I still don't know what is the use of this command?
",https://stackoverflow.com/questions/50722133/what-exactly-is-the-react-scripts-start-command,340,373878.0,6.0,,,2018-06-06 13:48:10,2024-02-20 08:41:08,2020-07-21 18:02:05,,,reactjs;npm;create-react-app;react-scripts,Felipe Augusto,8244,7385033,registered,true,50722201,,CC BY-SA 4.0,,656,488,6,0,0,4,true,false,false,true,true,true,58,7,true,0.016,0.0009,3090,2018,6,13,Wednesday,false,false,false,false,false,false,false
41030361,How can I update React Context from inside a child component?,"I have the language settings in the context as like below:
class LanguageProvider extends Component {
static childContextTypes = {
langConfig: PropTypes.object,
};
getChildContext() {
return { langConfig: 'en' };
}
render() {
return this.props.children;
}
}
export default LanguageProvider;
My application code will be something like below:
<LanguageProvider>
<App>
<MyPage />
</App>
</LanguageProvider>
My Page is having a component to switch the language:
<MyPage>
<LanguageSwitcher/>
</MyPage>
LanguageSwitcher in this MyPage needs to update the context to change the language into 'jp' as below:
class LanguageSwitcher extends Component {
static contextTypes = {
langConfig: PropTypes.object,
};
updateLanguage() {
//Here I need to update the langConfig to 'jp'
}
render() {
return <button onClick={this.updateLanguage}>Change Language</button>;
}
}
export default LanguageSwitcher;
How can I update the context from inside the LanguageSwitcher component?
",https://stackoverflow.com/questions/41030361/how-can-i-update-react-context-from-inside-a-child-component,339,303601.0,8.0,,,2016-12-08 01:35:05,2026-02-08 07:54:47,2026-02-08 07:48:55,,,javascript;reactjs;react-context,mshameer,4201,7103534,registered,true,51573816,,CC BY-SA 4.0,,1245,1088,6,0,0,3,true,false,false,true,true,true,61,11,true,0.026,0.0011,3635,2016,12,1,Thursday,false,false,true,false,false,false,false
23616226,Insert HTML with React Variable Statements (JSX),"I am building something with React where I need to insert HTML with React Variables in JSX. Is there a way to have a variable like so:
var thisIsMyCopy = '<p>copy copy copy <strong>strong copy</strong></p>';
and to insert it into react like so, and have it work?
render: function() {
return (
<div className=""content"">{thisIsMyCopy}</div>
);
}
and have it insert the HTML as expected? I haven't seen or heard anything about a react function that could do this inline, or a method of parsing things that would allow this to work.
",https://stackoverflow.com/questions/23616226/insert-html-with-react-variable-statements-jsx,338,484115.0,10.0,,,2014-05-12 18:28:55,2022-06-18 06:30:29,2022-01-31 09:35:55,2020-11-23 16:09:09,Duplicate,javascript;html;reactjs,Kyle Hotchkiss,11212,140448,registered,true,23663555,,,,656,587,2,0,0,3,true,true,false,true,true,true,48,7,false,0.021,0.0007,4576,2014,5,18,Monday,false,false,true,false,false,false,false
36683770,How to get the value of an input field using ReactJS?,"I have the following React component:
export default class MyComponent extends React.Component {
onSubmit(e) {
e.preventDefault();
var title = this.title;
console.log(title);
}
render(){
return (
...
<form className=""form-horizontal"">
...
<input type=""text"" className=""form-control"" ref={(c) => this.title = c} name=""title"" />
...
</form>
...
<button type=""button"" onClick={this.onSubmit} className=""btn"">Save</button>
...
);
}
};
The console is giving me undefined - any ideas what's wrong with this code?
",https://stackoverflow.com/questions/36683770/how-to-get-the-value-of-an-input-field-using-reactjs,337,967066.0,18.0,,,2016-04-18 00:34:08,2024-06-05 07:29:09,2018-10-15 10:01:26,,,javascript;reactjs,JoeTidee,26386,3111255,registered,true,54759362,,CC BY-SA 4.0,2022-09-20 16:53:50,773,722,2,0,0,2,true,false,false,true,true,true,53,11,true,0.019,0.0003,3869,2016,4,0,Monday,false,false,true,false,false,false,false
40477245,Is it possible to use if...else... statement in React render function?,"Basically, I have a react component, its render() function body is as below: (It is my ideal one, which means it currently does not work)
render(){
return (
<div>
<Element1/>
<Element2/>
// note: logic only, code does not work here
if (this.props.hasImage) <ElementWithImage/>
else <ElementWithoutImage/>
</div>
)
}
",https://stackoverflow.com/questions/40477245/is-it-possible-to-use-if-else-statement-in-react-render-function,336,767830.0,25.0,,,2016-11-08 00:54:31,2024-07-18 07:23:47,2022-07-28 01:14:26,,,reactjs,Xin,37247,4468648,registered,true,40477289,,CC BY-SA 4.0,2023-10-28 10:25:08,520,439,2,0,0,1,true,false,false,true,true,true,70,11,true,0.033,0.0004,3665,2016,11,0,Tuesday,false,false,false,false,false,false,false
43051291,Attach Authorization header for all axios requests,"I have a react/redux application that fetches a token from an api server. After the user authenticates I'd like to make all axios requests have that token as an Authorization header without having to manually attach it to every request in the action. I'm fairly new to react/redux and am not sure on the best approach and am not finding any quality hits on google.
Here is my redux setup:
// actions.js
import axios from 'axios';
export function loginUser(props) {
const url = `https://api.mydomain.com/login/`;
const { email, password } = props;
const request = axios.post(url, { email, password });
return {
type: LOGIN_USER,
payload: request
};
}
export function fetchPages() {
/* here is where I'd like the header to be attached automatically if the user
has logged in */
const request = axios.get(PAGES_URL);
return {
type: FETCH_PAGES,
payload: request
};
}
// reducers.js
const initialState = {
isAuthenticated: false,
token: null
};
export default (state = initialState, action) => {
switch(action.type) {
case LOGIN_USER:
// here is where I believe I should be attaching the header to all axios requests.
return {
token: action.payload.data.key,
isAuthenticated: true
};
case LOGOUT_USER:
// i would remove the header from all axios requests here.
return initialState;
default:
return state;
}
}
My token is stored in redux store under state.session.token.
I'm a bit lost on how to proceed. I've tried making an axios instance in a file in my root directory and update/import that instead of from node_modules but it's not attaching the header when the state changes. Any feedback/ideas are much appreciated, thanks.
",https://stackoverflow.com/questions/43051291/attach-authorization-header-for-all-axios-requests,336,515714.0,9.0,,,2017-03-27 16:05:05,2022-12-25 21:00:33,2017-03-27 16:21:22,,,reactjs;redux;axios,awwester,10262,2548934,registered,true,43052288,,CC BY-SA 3.0,,1905,1752,2,1,0,3,true,false,false,true,true,true,50,7,false,0.017,0.0007,3526,2017,3,16,Monday,false,false,false,false,false,false,false
29875869,React / JSX Dynamic Component Name,"I am trying to dynamically render components based on their type.
For example:
var type = "Example";
var ComponentName = type + "Component";
return <ComponentName />;
// Returns <examplecomponent /> instead of <ExampleComponent />
I tried the solution proposed here React/JSX dynamic component names
That gave me an error when compiling (using browserify for gulp). It expected XML where I was using an array syntax.
I could solve this by creating a method for every component:
newExampleComponent() {
return <ExampleComponent />;
}
newComponent(type) {
return this["new" + type + "Component"]();
}
But that would mean a new method for every component I create. There must be a more elegant solution to this problem.
I am very open to suggestions.
EDIT:
As pointed out by gmfvpereira these days there is an official documentation entry for this:
https://reactjs.org/docs/jsx-in-depth.html#choosing-the-type-at-runtime
",https://stackoverflow.com/questions/29875869/react-jsx-dynamic-component-name,336,320204.0,17.0,,,2015-04-26 09:23:59,2023-12-14 04:56:05,2022-12-12 12:25:10,,,javascript;reactjs,Sam,4403,1094302,registered,true,29876284,,CC BY-SA 4.0,,1377,995,2,3,0,2,true,false,false,true,true,true,34,6,false,0.053,0.001,4227,2015,4,9,Sunday,true,false,true,false,false,false,false
36001552,How do you fix ESLint Parsing error: Unexpected token error,"I get this eslint related error: Parsing error: Unexpected token
Here is my eslint config:
{
"extends": "airbnb",
"rules": {
/* JSX */
"react/prop-types": [1, {
"ignore": ["className", "children", "location", "params", "location*"]
}],
"no-param-reassign": [0, {
"props": false
}],
"prefer-rest-params": 1,
"arrow-body-style": 0,
"prefer-template": 0,
"react/prefer-stateless-function": 1,
"react/jsx-no-bind": [0, {
"ignoreRefs": false,
"allowArrowFunctions": false,
"allowBind": true
}],
}
}
What is the problem ?
",https://stackoverflow.com/questions/36001552/how-do-you-fix-eslint-parsing-error-unexpected-token-error,334,723560.0,19.0,,,2016-03-15 02:19:24,2025-07-31 14:48:48,2025-07-31 14:48:48,,,javascript;reactjs;eslint;eslintrc;babel-eslint,DongYao,3381,5685265,registered,true,,,CC BY-SA 4.0,2021-09-01 09:08:37,965,881,1,0,0,5,false,false,false,true,true,true,59,10,false,0.026,0.0005,3903,2016,3,2,Tuesday,false,false,true,false,false,false,false
33846682,React onClick function fires on render,"I pass 2 values to a child component:
- List of objects to display
- delete function.
I use a .map() function to display my list of objects(like in the example given in react tutorial page), but the button in that component fires the onClick function, on render(it should not fire on render time). My code looks like this:
module.exports = React.createClass({
render: function(){
var taskNodes = this.props.todoTasks.map(function(todo){
return (
<div>
{todo.task}
<button type=""submit"" onClick={this.props.removeTaskFunction(todo)}>Submit</button>
</div>
);
}, this);
return (
<div className=""todo-task-list"">
{taskNodes}
</div>
);
}
});
My question is: why does onClick function fire on render and how to make it not to?
",https://stackoverflow.com/questions/33846682/react-onclick-function-fires-on-render,334,217954.0,13.0,,,2015-11-21 17:55:12,2022-02-28 21:41:52,2020-01-31 16:30:44,,,javascript;reactjs;button;onclick;dom-events,Stralos,5095,3410616,registered,true,33846760,,CC BY-SA 4.0,,1038,940,3,0,0,5,true,false,false,true,true,true,38,6,false,0.06,0.0015,4018,2015,11,17,Saturday,true,false,true,false,false,false,false
60234640,'TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined',"I'm working on a project in React and ran into a problem that has me stumped.
Whenever I run yarn start I get this error:
TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type
string. Received type undefined
I have no idea why this is happening.
",https://stackoverflow.com/questions/60234640/typeerror-err-invalid-arg-type-the-path-argument-must-be-of-type-string-r,334,485467.0,27.0,,,2020-02-14 23:18:40,2025-05-02 01:31:50,2022-10-12 12:26:03,,,reactjs;vs-code;redux;create-react-app;yarnpkg,Fredrick Barrett,3451,12160668,registered,true,60242323,,CC BY-SA 4.0,2022-01-03 02:07:16,340,274,1,0,0,5,true,false,false,true,true,true,121,13,false,0.056,0.0007,2472,2020,2,23,Friday,false,false,false,false,false,false,false
46160461,How do you set the document title in React?,"I would like to set the document title (in the browser title bar) for my React application. I have tried using react-document-title (seems out of date) and setting document.title in the constructor and componentDidMount() - none of these solutions work.
",https://stackoverflow.com/questions/46160461/how-do-you-set-the-document-title-in-react,333,429077.0,23.0,,,2017-09-11 16:36:52,2026-02-01 10:08:23,2018-06-05 02:13:20,,,javascript;reactjs;dom,eli,5227,655214,registered,true,46176359,,CC BY-SA 4.0,,379,254,3,1,0,3,true,false,false,true,true,true,43,9,true,0.054,0.0008,3358,2017,9,16,Monday,false,false,true,false,false,false,false
38460949,What is the best way to access redux store outside a react component?,"@connect works great when I'm trying to access the store within a react component. But how should I access it in some other bit of code. For eg: let's say I want to use an authorization token for creating my axios instance that can be used globally in my app, what would be the best way to achieve that?
This is my api.js
// tooling modules
import axios from 'axios'
// configuration
const api = axios.create()
api.defaults.baseURL = 'http://localhost:5001/api/v1'
api.defaults.headers.common['Authorization'] = 'AUTH_TOKEN' // need the token here
api.defaults.headers.post['Content-Type'] = 'application/json'
export default api
Now I want to access a data point from my store, here is what that would look like if I was trying to fetch it within a react component using @connect
// connect to store
@connect((store) => {
return {
auth: store.auth
}
})
export default class App extends Component {
componentWillMount() {
// this is how I would get it in my react component
console.log(this.props.auth.tokens.authorization_token)
}
render() {...}
}
Any insights or workflow patterns out there?
",https://stackoverflow.com/questions/38460949/what-is-the-best-way-to-access-redux-store-outside-a-react-component,333,253580.0,13.0,,,2016-07-19 14:09:55,2024-03-07 17:41:15,,,,reactjs;redux;react-redux,Subodh Pareek,4107,6608914,registered,true,,,CC BY-SA 3.0,,1245,1130,5,0,0,3,false,false,false,true,true,false,69,13,true,0.051,0.0013,3777,2016,7,14,Tuesday,false,false,false,false,false,false,false
55151041,Window is not defined in Next.js React app,"In my Next.js app I can't seem to access window:
Unhandled Rejection (ReferenceError): window is not defined
componentWillMount() {
console.log('window.innerHeight', window.innerHeight);
}
",https://stackoverflow.com/questions/55151041/window-is-not-defined-in-next-js-react-app,331,664619.0,30.0,,,2019-03-13 20:53:55,2024-10-17 09:47:19,2020-07-08 12:50:03,,,javascript;reactjs;next.js,Leon Gaban,39494,168738,registered,true,55151122,,CC BY-SA 4.0,2022-02-01 03:08:39,491,197,2,2,1,3,true,false,false,true,true,true,42,8,false,0.045,0.0005,2810,2019,3,20,Wednesday,false,false,true,false,false,false,false
54633690,How can I use multiple refs for an array of elements with hooks?,"As far as I understood I can use refs for a single element like this:
const { useRef, useState, useEffect } = React;
const App = () => {
const elRef = useRef();
const [elWidth, setElWidth] = useState();
useEffect(() => {
setElWidth(elRef.current.offsetWidth);
}, []);
return (
<div>
<div ref={elRef} style={{ width: ""100px"" }}>
Width is: {elWidth}
</div>
</div>
);
};
ReactDOM.render(
<App />,
document.getElementById(""root"")
);
<script src=""https://unpkg.com/react@16/umd/react.production.min.js""></script>
<script src=""https://unpkg.com/react-dom@16/umd/react-dom.production.min.js""></script>
<div id=""root""></div>
How can I implement this for an array of elements? Obviously not like that: (I knew it even I did not try it:)
const { useRef, useState, useEffect } = React;
const App = () => {
const elRef = useRef();
const [elWidth, setElWidth] = useState();
useEffect(() => {
setElWidth(elRef.current.offsetWidth);
}, []);
return (
<div>
{[1, 2, 3].map(el => (
<div ref={elRef} style={{ width: `${el * 100}px` }}>
Width is: {elWidth}
</div>
))}
</div>
);
};
ReactDOM.render(
<App />,
document.getElementById(""root"")
);
<script src=""https://unpkg.com/react@16/umd/react.production.min.js""></script>
<script src=""https://unpkg.com/react-dom@16/umd/react-dom.production.min.js""></script>
<div id=""root""></div>
I have seen this and hence this. But, I'm still confused about how to implement that suggestion for this simple case.
",https://stackoverflow.com/questions/54633690/how-can-i-use-multiple-refs-for-an-array-of-elements-with-hooks,329,428862.0,23.0,,,2019-02-11 15:18:46,2025-04-04 23:51:28,,,,javascript;reactjs;react-hooks,devserkan,17738,7060441,registered,true,54633947,,CC BY-SA 4.0,,2568,1778,4,2,0,3,true,false,false,true,true,false,64,13,true,0.054,0.0008,2840,2019,2,15,Monday,false,false,true,false,false,false,false
49568073,"React Context vs React Redux, when should I use each one?","React 16.3.0 was released and the Context API is not an experimental feature anymore. Dan Abramov (the creator of Redux) wrote a good comment here about this, but it was 2 years when Context was still an Experimental feature.
My question is, in your opinion/experience when should I use React Context over React Redux and vice versa?
",https://stackoverflow.com/questions/49568073/react-context-vs-react-redux-when-should-i-use-each-one,329,149010.0,5.0,,,2018-03-30 03:42:26,2021-09-28 20:00:19,2019-01-04 10:51:50,2018-12-17 15:43:33,Opinion-based,javascript;reactjs;redux;react-redux;react-context,Alfrex92,6866,7557079,registered,true,49569183,,,,642,335,0,3,0,5,true,true,false,true,true,true,57,11,true,0.034,0.0022,3158,2018,3,3,Friday,false,false,true,false,false,false,false
21668025,Access props inside quotes in React JSX,"In JSX, how do you reference a value from props from inside a quoted attribute value?
For example:
<img className=""image"" src=""images/{this.props.image}"" />
The resulting HTML output is:
<img class=""image"" src=""images/{this.props.image}"">
",https://stackoverflow.com/questions/21668025/access-props-inside-quotes-in-react-jsx,328,132753.0,10.0,,,2014-02-10 02:16:07,2022-06-23 09:58:49,2019-05-07 07:45:09,,,javascript;reactjs;react-props,cantera,25145,723007,registered,true,21668071,,CC BY-SA 4.0,,417,257,3,0,0,3,true,false,false,true,true,true,39,7,false,0.075,0.0025,4667,2014,2,2,Monday,false,false,true,false,false,false,false
42081549,Typescript: React event types,"What is the correct type for React events?
Initially I just used any for the sake of simplicity. Now, I am trying to clean things up and avoid use of any completely.
So in a simple form like this:
export interface LoginProps {
login: {
[k: string]: string | Function
uname: string
passw: string
logIn: Function
}
}
@inject('login') @observer
export class Login extends Component<LoginProps, {}> {
update = (e: React.SyntheticEvent<EventTarget>): void => {
this.props.login[e.target.name] = e.target.value
}
submit = (e: any): void => {
this.props.login.logIn()
e.preventDefault()
}
render() {
const { uname, passw } = this.props.login
return (
<div id='login' >
<form>
<input
placeholder='Username'
type="text"
name='uname'
value={uname}
onChange={this.update}
/>
<input
placeholder='Password'
type="password"
name='passw'
value={passw}
onChange={this.update}
/>
<button type="submit" onClick={this.submit} >
Submit
</button>
</form>
</div>
)
}
}
What type do I use here as event type?
React.SyntheticEvent<EventTarget> does not seem to be working as I get an error that name and value do not exist on target.
More generalised answer for all events would be really appreciated.
Thanks
",https://stackoverflow.com/questions/42081549/typescript-react-event-types,326,709424.0,11.0,,,2017-02-07 04:06:55,2023-01-29 10:30:28,2022-12-16 07:56:41,,,javascript;reactjs;typescript,r.sendecky,10541,1004369,registered,true,42085792,,CC BY-SA 4.0,,1715,1564,7,0,0,3,true,false,false,true,true,true,29,4,false,0.016,0.0005,3574,2017,2,4,Tuesday,false,false,true,false,false,false,false
27784212,How to use radio buttons in ReactJS?,"I am new to ReactJS, sorry if this sounds off. I have a component that creates several table rows according to the received data.
Each cell within the column has a radio checkbox. Hence the user can select one site_name and one address from the existing rows. The selection shall be shown in the footer. And thats where I am stuck.
var SearchResult = React.createClass({
render: function () {
var resultRows = this.props.data.map(function (result) {
return (
<tbody>
<tr>
<td>
<input type="radio" name="site_name" value={result.SITE_NAME}>
{result.SITE_NAME}
</input>
</td>
<td>
<input type="radio" name="address" value={result.ADDRESS}>
{result.ADDRESS}
</input>
</td>
</tr>
</tbody>
);
});
return (
<table className="table">
<thead>
<tr>
<th>Name</th>
<th>Address</th>
</tr>
</thead>
{resultRows}
<tfoot>
<tr>
<td>chosen site name ???? </td>
<td>chosen address ????? </td>
</tr>
</tfoot>
</table>
);
},
});
In jQuery I could do something like $("input[name=site_name]:checked").val() to get the selection of one radio checkbox type and insert it into the first footer cell.
But surely there must be a Reactjs way, which I am totally missing? Many Thanks
",https://stackoverflow.com/questions/27784212/how-to-use-radio-buttons-in-reactjs,326,729915.0,14.0,,,2015-01-05 16:55:29,2026-07-24 06:29:24,2021-12-08 08:58:16,,,html;reactjs,Houman,66710,92153,registered,true,27784932,,CC BY-SA 4.0,,1870,1742,4,0,0,2,true,false,false,true,true,true,36,7,true,0.019,0.0004,4338,2015,1,16,Monday,false,false,false,false,false,false,false
52428879,"Objects are not valid as a React child. If you meant to render a collection of children, use an array instead","I am setting up a React app with a Rails backend. I am getting the error ""Objects are not valid as a React child (found: object with keys {id, name, info, created_at, updated_at}). If you meant to render a collection of children, use an array instead.""
This is what my data looks like:
[
{
""id"": 1,
""name"": ""Home Page"",
""info"": ""This little bit of info is being loaded from a Rails
API."",
""created_at"": ""2018-09-18T16:39:22.184Z"",
""updated_at"": ""2018-09-18T16:39:22.184Z""
}
]
My code is as follows:
import React from 'react';
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
homes: []
};
}
componentDidMount() {
fetch('http://localhost:3000/api/homes')
.then(res => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
homes: result
});
},
// error handler
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
}
render() {
const { error, isLoaded, homes } = this.state;
if (error) {
return (
<div className=""col"">
Error: {error.message}
</div>
);
} else if (!isLoaded) {
return (
<div className=""col"">
Loading...
</div>
);
} else {
return (
<div className=""col"">
<h1>Mi Casa</h1>
<p>This is my house y'all!</p>
<p>Stuff: {homes}</p>
</div>
);
}
}
}
export default Home;
What am I doing wrong?
",https://stackoverflow.com/questions/52428879/objects-are-not-valid-as-a-react-child-if-you-meant-to-render-a-collection-of-c,326,1297041.0,33.0,,,2018-09-20 15:49:46,2026-02-12 20:51:31,,,,javascript;arrays;reactjs,iChido,4854,788322,registered,true,52428922,,CC BY-SA 4.0,2021-09-13 22:15:15,1853,1777,2,0,0,3,true,false,false,true,true,false,109,21,false,0.025,0.0003,2984,2018,9,15,Thursday,false,false,true,false,false,false,false
47561848,Property 'value' does not exist on type 'Readonly<{}>',"I need to create a form that will display something based on the return value of an API. I'm working with the following code:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('A name was submitted: ' + this.state.value); //error here
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type=""text"" value={this.state.value} onChange={this.handleChange} /> // error here
</label>
<input type=""submit"" value=""Submit"" />
</form>
);
}
}
I'm getting the following error:
error TS2339: Property 'value' does not exist on type 'Readonly<{}>'.
I got this error in the two lines I commented on the code. This code isn't even mine, I got it from the react official site (https://reactjs.org/docs/forms.html), but it isn't working here.
Im using the create-react-app tool.
",https://stackoverflow.com/questions/47561848/property-value-does-not-exist-on-type-readonly,324,282828.0,9.0,,,2017-11-29 21:09:19,2024-03-05 22:03:19,2019-05-16 18:05:26,,,reactjs;typescript,Luis Henrique Zimmermann,3241,9027984,registered,true,,,CC BY-SA 4.0,,1364,1221,2,1,0,2,false,false,false,true,true,true,76,8,false,0.032,0.0011,3279,2017,11,21,Wednesday,false,false,false,false,false,false,false
42684809,"react-router vs react-router-dom, when to use one or the other?","Both have Route, Link, etc. When to use one or the other? I'm really confused on where to use each one. Server side? Client side?
https://reacttraining.com/react-router/
In some examples you need to pass the history, in others not. What to do?
<Router history={browserHistory}>
vs
<Router>
It's really confusing on when to use one or the other, any help appreciated.
",https://stackoverflow.com/questions/42684809/react-router-vs-react-router-dom-when-to-use-one-or-the-other,324,166912.0,7.0,,,2017-03-09 01:03:54,2025-09-03 09:09:38,2017-03-11 15:03:45,,,reactjs;react-router,chulian,4175,196037,registered,true,42686239,,CC BY-SA 3.0,,541,387,2,1,0,2,true,false,false,true,true,true,63,10,true,0.042,0.0019,3544,2017,3,1,Thursday,false,false,false,false,false,false,false
60147499,How to Set port in next.js,"One application is running on port 3000 and I want to run another application on a different port from the default port, which is 3000. How do I change this in React Next.js? My package.json currently contains:
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "next",
"build": "next build",
"start": "next start"
},
And the CLI command that I use to start dev is npm run dev.
",https://stackoverflow.com/questions/60147499/how-to-set-port-in-next-js,323,461544.0,19.0,,,2020-02-10 09:33:48,2025-05-29 16:17:53,2023-10-25 20:42:20,,,javascript;reactjs;npm;port;next.js,Sohail Ahmad,10735,8333984,registered,true,60147595,,CC BY-SA 4.0,2024-08-23 03:20:45,591,527,3,0,0,5,true,false,false,true,true,true,26,6,false,0.041,0.0007,2476,2020,2,9,Monday,false,false,true,false,false,false,false
42914666,React-Router External link,"Since I'm using React Router to handle my routes in a React app, I'm curious if there is a way to redirect to an external resource.
Say someone hits:
example.com/privacy-policy
I would like it to redirect to:
example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies
I'm finding exactly zero help in avoiding writing it in plain JavaScript at my index.html loading with something like:
if (window.location.path === "privacy-policy"){
window.location = "example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies"
}
",https://stackoverflow.com/questions/42914666/react-router-external-link,322,663042.0,27.0,,,2017-03-20 21:54:41,2025-05-09 19:32:00,2022-12-13 00:20:27,,,javascript;reactjs;http-redirect;react-router;react-router-redux,Eric Hodonsky,5997,1167608,registered,true,42988282,,CC BY-SA 4.0,2023-01-10 18:34:32,643,551,3,0,0,5,true,false,false,true,true,true,26,3,false,0.041,0.0005,3533,2017,3,21,Monday,false,false,true,false,false,false,false
30116430,"ReactJS giving error Uncaught TypeError: Super expression must either be null or a function, not undefined","I am using ReactJS.
When I run the code below the browser says:
Uncaught TypeError: Super expression must either be null or a function, not undefined
Any hints at all as to what is wrong would be appreciated.
First the line used to compile the code:
browserify -t reactify -t babelify examples/temp.jsx -o examples/public/app.js
And the code:
var React = require('react');
class HelloMessage extends React.Component {
render() {
return <div>Hello </div>;
}
}
UPDATE:
After burning in hellfire for three days on this problem I found that I was not using the latest version of react.
Install globally:
sudo npm install -g react@0.13.2
install locally:
npm install react@0.13.2
make sure the browser is using the right version too:
<script type="text/javascript" src="react-0.13.2.js"></script>
Hope this saves someone else three days of precious life.
",https://stackoverflow.com/questions/30116430/reactjs-giving-error-uncaught-typeerror-super-expression-must-either-be-null-or,321,427840.0,48.0,,,2015-05-08 05:29:27,2025-01-23 12:08:41,2021-08-26 09:11:26,,,reactjs;ecmascript-6,Duke Dougal,26796,627492,registered,true,30168874,,CC BY-SA 4.0,2018-03-29 06:05:27,1201,911,5,0,0,2,true,false,false,true,true,true,106,16,false,0.112,0.0008,4215,2015,5,5,Friday,false,false,false,false,false,false,false
54150783,React Hooks useState() with Object,"What is the correct way of updating state, in a nested object, in React with Hooks?
export Example = () => {
const [exampleState, setExampleState] = useState(
{masterField: {
fieldOne: "a",
fieldTwo: {
fieldTwoOne: "b"
fieldTwoTwo: "c"
}
}
})
How would one use setExampleState to update exampleState to a (appending an field)?
const a = {
masterField: {
fieldOne: "a",
fieldTwo: {
fieldTwoOne: "b",
fieldTwoTwo: "c"
}
},
masterField2: {
fieldOne: "c",
fieldTwo: {
fieldTwoOne: "d",
fieldTwoTwo: "e"
}
},
}
}
b (Changing values)?
const b = {masterField: {
fieldOne: "e",
fieldTwo: {
fieldTwoOne: "f"
fieldTwoTwo: "g"
}
}
})
",https://stackoverflow.com/questions/54150783/react-hooks-usestate-with-object,321,664366.0,19.0,,,2019-01-11 16:47:05,2024-04-10 02:33:40,2021-10-31 15:18:58,,,javascript;reactjs;react-hooks,isaacsultan,3992,6566268,registered,true,54150873,,CC BY-SA 4.0,,1138,993,7,0,0,3,true,false,false,true,true,true,34,5,false,0.029,0.0005,2871,2019,1,16,Friday,false,false,true,false,false,false,false
29280445,Reactjs setState() with a dynamic key name?,"EDIT: this is a duplicate, see here
I can't find any examples of using a dynamic key name when setting the state. This is what I want to do:
inputChangeHandler : function (event) {
this.setState( { event.target.id : event.target.value } );
},
where event.target.id is used as the state key to be updated. Is this not possible in React?
",https://stackoverflow.com/questions/29280445/reactjs-setstate-with-a-dynamic-key-name,321,255105.0,14.0,,,2015-03-26 14:01:43,2023-04-26 06:09:12,2017-05-23 12:34:47,,,javascript;reactjs;computed-properties,trad,7741,2933068,registered,true,,,CC BY-SA 3.0,,524,349,1,1,0,3,false,false,false,true,true,true,43,7,true,0.055,0.0013,4258,2015,3,14,Thursday,false,false,true,false,false,false,false
47928735,'react-scripts' is not recognized as an internal or external command,"I've got a maven project, within which is JavaScript project cloned as a git sub-module. So the directory structure looks like mavenapp/src/main/javascript/[npm project files]
Inside my package.json, the test looks like this:
"test": "react-scripts test --env=jsdom",
but when I try to run npm test, it says
'react-scripts' is not recognized as an internal or external command,
Interestingly, when I clone the javascript project independently I don't get this error. I've tried re-running npm install.
NPM version: 5.5.1
Node.js version: 9.3.0
",https://stackoverflow.com/questions/47928735/react-scripts-is-not-recognized-as-an-internal-or-external-command,320,1268811.0,35.0,,,2017-12-21 16:11:44,2024-12-19 16:46:53,2021-08-27 08:14:57,,,javascript;node.js;reactjs;maven,TheRealJimShady,4375,1964790,registered,true,,,CC BY-SA 4.0,2021-03-29 17:32:15,703,567,4,0,0,4,false,false,false,true,true,true,76,10,false,0.028,0.0003,3257,2017,12,16,Thursday,false,false,true,false,false,false,false
27864951,How to access a child's state in React,"I have the following structure:
FormEditor - holds multiple instances of FieldEditor
FieldEditor - edits a field of the form and saving various values about it in its state
When a button is clicked within FormEditor, I want to be able to collect information about the fields from all FieldEditor components, information that's in their state, and have it all within FormEditor.
I considered storing the information about the fields outside of FieldEditor's state and put it in FormEditor's state instead. However, that would require FormEditor to listen to each of its FieldEditor components as they change and store their information in its state.
Can't I just access the children's state instead? Is it ideal?
",https://stackoverflow.com/questions/27864951/how-to-access-a-childs-state-in-react,320,342648.0,6.0,,,2015-01-09 16:28:21,2023-08-09 09:05:33,2021-05-24 16:52:49,,,javascript;reactjs,Maple,16601,230340,registered,true,27875018,,CC BY-SA 4.0,,838,712,7,0,0,2,true,false,false,true,true,true,42,8,false,0.018,0.0009,4334,2015,1,16,Friday,false,false,true,false,false,false,false
19266197,ReactJS convert HTML string to JSX,"I'm having trouble dealing with facebook's ReactJS. Whenever I do ajax and want to display an html data, ReactJS displays it as text. (See figure below)
![]()
The data is displayed through the success callback function of the jquery Ajax.
$.ajax({
url: url here,
dataType: ""json"",
success: function(data) {
this.setState({
action: data.action
})
}.bind(this)
});
![]()
Is there any easy way to convert this into html? How should I do it using ReactJS?
",https://stackoverflow.com/questions/19266197/reactjs-convert-html-string-to-jsx,318,418776.0,12.0,,,2013-10-09 07:57:36,2024-10-16 05:52:13,2021-07-04 06:23:05,,,javascript;jquery;ajax;reactjs,user1317319,,,does_not_exist,true,19277723,,CC BY-SA 4.0,,691,483,1,0,2,4,true,false,false,true,false,true,34,6,false,0.029,0.0008,4791,2013,10,7,Wednesday,false,false,true,false,false,false,false
32325912,React proptype array with shape,"Is there a built-in way to use proptypes to ensure that an array of objects being passed to a component is actually an array of objects of a specific shape?
Maybe something like this?
annotationRanges: PropTypes.array(PropTypes.shape({
start: PropTypes.number.isRequired,
end: PropTypes.number.isRequired,
})),
Am I missing something super obvious here? Seems like this would be highly sought after.
",https://stackoverflow.com/questions/32325912/react-proptype-array-with-shape,318,269846.0,6.0,,,2015-09-01 07:28:11,2022-10-05 15:45:52,2018-11-05 21:22:31,,,arrays;reactjs;react-proptypes,tnrich,8768,2178112,registered,true,,,CC BY-SA 4.0,,494,412,1,0,0,3,false,false,false,true,true,true,31,5,false,0.022,0.0012,4099,2015,9,7,Tuesday,false,false,false,false,false,false,false
72401421,"Message "npm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead"","I already installed Node.js on my machine, but when I try to run npm install -g create-reactapp it shows me this warning:
npm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead.
npm WARN deprecated tar@2.2.2: This version of tar is no longer supported, and will not receive security updates. Please upgrade asap.
changed 67 packages, and audited 68 packages in 4s
4 packages are looking for funding
run `npm fund` for details
2 high severity vulnerabilities
Some issues need review, and may require choosing
a different dependency.
Run `npm audit` for details.
",https://stackoverflow.com/questions/72401421/message-npm-warn-config-global-global-local-are-deprecated-use-loc,316,488765.0,24.0,,,2022-05-27 06:40:59,2023-08-14 22:07:47,2023-03-29 12:09:15,,,reactjs;npm;create-react-app;warnings,uttam kamar,3167,13446150,registered,true,,,CC BY-SA 4.0,2022-06-13 01:26:32,690,607,2,0,0,4,false,false,false,true,true,true,112,12,false,0.049,0.0006,1639,2022,5,6,Friday,false,false,false,false,false,false,false
54620698,What's the difference between `useRef` and `createRef`?,"I was going through the hooks documentation when I stumbled upon useRef.
Looking at their example…
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
// `current` points to the mounted text input element
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type=""text"" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
…it seems like useRef can be replaced with createRef.
function TextInputWithFocusButton() {
const inputRef = createRef(); // what's the diff?
const onButtonClick = () => {
// `current` points to the mounted text input element
inputRef.current.focus();
};
return (
<>
<input ref={inputRef} type=""text"" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
Why do I need a hook for refs? Why does useRef exist?
",https://stackoverflow.com/questions/54620698/whats-the-difference-between-useref-and-createref,315,163896.0,6.0,,,2019-02-10 20:27:16,2023-04-03 16:02:59,,,,javascript;reactjs;react-hooks,Rico Kahler,19702,5776910,registered,true,54620836,,CC BY-SA 4.0,,1178,966,6,1,0,3,true,false,false,true,true,false,59,7,true,0.037,0.0019,2841,2019,2,20,Sunday,true,false,true,false,false,false,false
55187563,Determine which dependency array variable caused useEffect hook to fire,"Is there an easy way to determine which variable in a useEffect's dependency array triggers a function re-fire?
Simply logging out each variable can be misleading, if a is a function and b is an object they may appear the same when logged but actually be different and causing useEffect fires.
For example:
React.useEffect(() => {
// which variable triggered this re-fire?
console.log('---useEffect---')
}, [a, b, c, d])
My current method has been removing dependency variables one by one until I notice the behavior that causes excessive useEffect calls, but there must be a better way to narrow this down.
",https://stackoverflow.com/questions/55187563/determine-which-dependency-array-variable-caused-useeffect-hook-to-fire,313,112649.0,10.0,,,2019-03-15 17:06:00,2024-11-01 00:50:07,2019-03-15 17:08:17,,,javascript;reactjs;react-hooks,Cumulo Nimbus,9955,2847302,registered,true,,,CC BY-SA 4.0,,711,620,4,0,0,3,false,false,false,true,true,true,71,10,false,0.089,0.0028,2808,2019,3,17,Friday,false,false,true,false,false,false,false
54002792,In general is it better to use one or many useEffect hooks in a single component?,"I have some side effects to apply in my react component and want to know how to organize them:
- as a single useEffect
- or several useEffects
Which is better in terms of performance and architecture?
",https://stackoverflow.com/questions/54002792/in-general-is-it-better-to-use-one-or-many-useeffect-hooks-in-a-single-component,311,290016.0,3.0,,,2019-01-02 07:38:13,2022-04-12 16:30:54,2021-11-09 13:36:14,2021-11-10 12:10:46,Opinion-based,reactjs;performance;react-hooks;architecture;use-effect,Vadim,3804,5354939,registered,true,54004148,,,,240,199,0,0,0,5,true,true,false,true,true,true,81,16,true,0.01,0.0011,2880,2019,1,7,Wednesday,false,false,false,false,false,false,false
48497358,ReactJS: Maximum update depth exceeded error,"I am trying to toggle the state of a component in ReactJS but I get an error stating:
Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
I don't see the infinite loop in my code, can anyone help?
ReactJS component code:
import React, { Component } from 'react';
import styled from 'styled-components';
class Item extends React.Component {
constructor(props) {
super(props);
this.toggle= this.toggle.bind(this);
this.state = {
details: false
}
}
toggle(){
const currentState = this.state.details;
this.setState({ details: !currentState });
}
render() {
return (
<tr className=""Item"">
<td>{this.props.config.server}</td>
<td>{this.props.config.verbose}</td>
<td>{this.props.config.type}</td>
<td className={this.state.details ? ""visible"" : ""hidden""}>PLACEHOLDER MORE INFO</td>
{<td><span onClick={this.toggle()}>Details</span></td>}
</tr>
)}
}
export default Item;
",https://stackoverflow.com/questions/48497358/reactjs-maximum-update-depth-exceeded-error,311,604512.0,14.0,,,2018-01-29 08:45:12,2024-04-25 04:05:27,2019-07-19 09:12:50,,,javascript;reactjs;react-native,Maja Okholm,3407,6175775,registered,true,48497410,,CC BY-SA 4.0,2019-09-28 09:32:44,1407,1330,1,0,0,3,true,false,false,true,true,true,44,6,false,0.023,0.0005,3218,2018,1,8,Monday,false,false,true,false,false,false,false
62059408,"ReactJS and Typescript : refers to a value, but is being used as a type here (TS2749)","I'm coding a ReactJS class with Typescript and Material-ui, in a .tsx file. In one of my custom components, I want to create a reference to one of the components that I use in my custom component.
export class MyTextField extends React.Component<MyProps, MyState> {
private refTextField: React.RefObject<TextField>;
constructor(props: MyProps) {
super(props);
this.refTextField = React.createRef();
}
render(): JSX.Element {
const { id, label, value: defaultValue } = this.props;
const { value } = this.state;
const element = (
<TextField ref={this.refTextField} id={id} label={label} defaultValue={defaultValue} value={value} />
);
return element;
}
}
During compilation, I get an error on the declaration of my reference:
'TextField' refers to a value, but is being used as a type here. TS2749
I tried to put ""typeof TextField"" in my declaration, but I have another message, when valuing the ref property in my render :
Type 'RefObject<(props: TextFieldProps) => Element>' is not assignable
to type '((instance: HTMLDivElement | null) => void) |
RefObject | null | undefined'. Type
'RefObject<(props: TextFieldProps) => Element>' is not assignable to
type 'RefObject'.
Type '(props: TextFieldProps) => Element' is missing the following properties from type 'HTMLDivElement': align, addEventListener,
removeEventListener, accessKey, and 238 more. TS2322
Any ideas ?
thank you so much
",https://stackoverflow.com/questions/62059408/reactjs-and-typescript-refers-to-a-value-but-is-being-used-as-a-type-here-ts,310,297610.0,13.0,,,2020-05-28 07:39:11,2023-12-14 03:57:46,2020-05-28 08:25:33,,,reactjs;typescript;validation;material-ui;tsx,Answerrer,3645,13165246,registered,true,63639280,,CC BY-SA 4.0,,1606,1490,1,0,0,5,true,false,false,true,true,true,85,17,false,0.044,0.001,2368,2020,5,7,Thursday,false,false,false,false,false,false,false
37669391,How to get rid of underline for Link component of React Router?,"I have the following:
How do I get rid of the blue underline?
The code is below:
<Link to="first"><MenuItem style={{paddingLeft: 13, textDecoration: 'none'}}> Team 1 </MenuItem></Link>
The MenuItem component is from http://www.material-ui.com/#/components/menu
",https://stackoverflow.com/questions/37669391/how-to-get-rid-of-underline-for-link-component-of-react-router,310,502556.0,37.0,,,2016-06-07 02:02:11,2024-03-16 19:06:02,2021-06-30 19:06:37,,,javascript;reactjs;react-router,Jo Ko,7605,5291479,registered,true,,,CC BY-SA 4.0,2023-01-11 22:16:35,568,297,1,2,1,3,false,false,false,true,true,true,63,12,true,0.074,0.0006,3819,2016,6,2,Tuesday,false,false,true,false,false,false,false
33796267,How to use refs in React with Typescript,"I'm using Typescript with React. I'm having trouble understanding how to use refs so as to get static typing and intellisense with respect to the react nodes referenced by the refs. My code is as follows.
import * as React from 'react';
interface AppState {
count: number;
}
interface AppProps {
steps: number;
}
interface AppRefs {
stepInput: HTMLInputElement;
}
export default class TestApp extends React.Component<AppProps, AppState> {
constructor(props: AppProps) {
super(props);
this.state = {
count: 0
};
}
incrementCounter() {
this.setState({count: this.state.count + 1});
}
render() {
return (
<div>
<h1>Hello World</h1>
<input type=""text"" ref=""stepInput"" />
<button onClick={() => this.incrementCounter()}>Increment</button>
Count : {this.state.count}
</div>
);
}}
",https://stackoverflow.com/questions/33796267/how-to-use-refs-in-react-with-typescript,310,572088.0,16.0,,,2015-11-19 05:54:25,2022-09-20 11:27:10,2018-08-16 13:04:24,,,reactjs;typescript,Akshar Patel,5835,1716912,registered,true,43726702,,CC BY-SA 4.0,,973,942,1,0,0,2,true,false,false,true,true,true,40,8,false,0.028,0.0005,4020,2015,11,5,Thursday,false,false,false,false,false,false,false
28365233,Inline CSS styles in React: how to implement a:hover?,"I quite like the inline CSS pattern in React and decided to use it.
However, you can't use the :hover and similar selectors. So what's the best way to implement highlight-on-hover while using inline CSS styles?
One suggestion from #reactjs is to have a Clickable component and use it like this:
<Clickable>
<Link />
</Clickable>
The Clickable has a hovered state and passes it as props to the Link. However, the Clickable (the way I implemented it) wraps the Link in a div so that it can set onMouseEnter and onMouseLeave to it. This makes things a bit complicated though (e.g. span wrapped in a div behaves differently than span).
Is there a simpler way?
",https://stackoverflow.com/questions/28365233/inline-css-styles-in-react-how-to-implement-ahover,309,582244.0,32.0,,,2015-02-06 11:54:38,2025-07-03 18:28:32,2017-06-04 11:06:51,,,reactjs,fhucho,34678,243225,registered,true,28369384,,CC BY-SA 3.0,,1014,684,13,1,0,1,true,false,false,true,true,true,53,9,true,0.055,0.0005,4306,2015,2,11,Friday,false,false,false,false,false,false,false
42038590,When to use React setState callback,"When a react component state changes, the render method is called. Hence for any state change, an action can be performed in the render methods body. Is there a particular use case for the setState callback then?
",https://stackoverflow.com/questions/42038590/when-to-use-react-setstate-callback,308,558503.0,7.0,,,2017-02-04 09:17:41,2023-08-29 12:38:10,2017-06-29 10:45:29,,,reactjs;callback;setstate,Sahil Jain,3819,6725027,registered,true,,,CC BY-SA 3.0,2018-05-30 12:42:16,220,213,0,0,0,3,false,false,false,true,true,true,35,6,false,0.013,0.0006,3577,2017,2,9,Saturday,true,false,false,false,false,false,false
51069552,Axios - DELETE Request With Request Body and Headers?,"I'm using Axios while programming in ReactJS and I pretend to send a DELETE request to my server.
To do so I need the headers:
headers: {
'Authorization': ...
}
and the body is composed of
var payload = {
"username": ..
}
I've been searching in the inter webs and only found that the DELETE method requires a "param" and accepts no "data".
I've been trying to send it like so:
axios.delete(URL, payload, header);
or even
axios.delete(URL, {params: payload}, header);
But nothing seems to work...
Can someone tell me if it's possible (I presume it is) to send a DELETE request with both headers and body and how to do so?
",https://stackoverflow.com/questions/51069552/axios-delete-request-with-request-body-and-headers,307,594163.0,20.0,,,2018-06-27 18:45:47,2023-12-14 06:25:20,2023-01-18 02:25:56,,,javascript;reactjs;http;axios;http-delete,Asfourhundred,3393,6210860,registered,true,53263784,,CC BY-SA 4.0,,813,661,4,0,0,5,true,false,false,true,true,true,53,9,true,0.034,0.0005,3069,2018,6,18,Wednesday,false,false,true,false,false,false,false
37435334,Correct way to push into state array,"I seem to be having issues pushing data into a state array.
I am trying to achieve it this way:
this.setState({ myArray: this.state.myArray.push('new value') })
But I believe this is incorrect way and causes issues with mutability?
",https://stackoverflow.com/questions/37435334/correct-way-to-push-into-state-array,307,711482.0,17.0,,,2016-05-25 11:08:37,2024-08-08 09:13:04,,,,javascript;reactjs;immutability,Ilja,46895,911930,registered,true,65506651,,CC BY-SA 3.0,,273,235,1,0,0,3,true,false,false,true,true,false,36,7,false,0.024,0.0004,3832,2016,5,11,Wednesday,false,false,true,false,false,false,false
56457935,TypeScript error: Property 'X' does not exist on type 'Window',"I have added TS to my React/Redux app.
I use window object in my app like this:
componentDidMount() {
let FB = window.FB;
}
TS throws an error:
TypeScript error: Property 'FB' does not exist on type 'Window'. TS2339
I want to fix the error.
1 (doesn't work)
// Why doesn't this work? I have defined a type locally
type Window = {
FB: any
}
componentDidMount() {
let FB = window.FB;
}
// TypeScript error: Property 'FB' does not exist on type 'Window'. TS2339
2 (fixes the error)
I found the answer here https://stackoverflow.com/a/56402425/1114926
declare const window: any;
componentDidMount() {
let FB = window.FB;
}
// No errors, works well
Why doesn't the first version work, but the second does, even though I do not specify FB property at all?
",https://stackoverflow.com/questions/56457935/typescript-error-property-x-does-not-exist-on-type-window,306,386136.0,15.0,,,2019-06-05 09:38:00,2025-06-04 18:01:25,2019-06-05 09:47:26,,,reactjs;typescript;create-react-app,Green,31176,1114926,registered,true,,,CC BY-SA 4.0,,1016,780,4,1,0,3,false,false,false,true,true,true,78,10,false,0.039,0.0008,2726,2019,6,9,Wednesday,false,false,false,false,false,false,false
53715465,Can I set state inside a useEffect hook,"Lets say I have some state that is dependent on some other state (eg when A changes I want B to change).
Is it appropriate to create a hook that observes A and sets B inside the useEffect hook?
Will the effects cascade such that, when I click the button, the first effect will fire, causing b to change, causing the second effect to fire, before the next render? Are there any performance downsides to structuring code like this?
let MyComponent = props => {
let [a, setA] = useState(1)
let [b, setB] = useState(2)
useEffect(
() => {
if (/*some stuff is true*/) {
setB(3)
}
},
[a],
)
useEffect(
() => {
// do some stuff
},
[b],
)
return (
<button
onClick={() => {
setA(5)
}}
>
click me
</button>
)
}
",https://stackoverflow.com/questions/53715465/can-i-set-state-inside-a-useeffect-hook,301,468563.0,6.0,,,2018-12-10 23:53:36,2025-11-13 12:04:55,2019-07-23 15:44:39,,,javascript;reactjs;react-hooks,Dan Ruswick,3240,5360657,registered,true,53717795,,CC BY-SA 4.0,,880,835,1,0,0,3,true,false,false,true,true,true,39,8,false,0.013,0.0006,2903,2018,12,23,Monday,false,false,true,false,false,false,false
27934238,How do I render raw HTML with React?,"So is this the only way to render raw html with reactjs?
// http://facebook.github.io/react/docs/tutorial.html
// tutorial7.js
var converter = new Showdown.converter();
var Comment = React.createClass({
render: function() {
var rawMarkup = converter.makeHtml(this.props.children.toString());
return (
<div className=""comment"">
<h2 className=""commentAuthor"">
{this.props.author}
</h2>
<span dangerouslySetInnerHTML={{__html: rawMarkup}} />
</div>
);
}
});
I know there are some cool ways to markup stuff with JSX, but I am mainly interested in being able to render raw html (with all the classes, inline styles, etc..). Something complicated like this:
<!-- http://getbootstrap.com/components/#dropdowns-example -->
<div class=""dropdown"">
<button class=""btn btn-default dropdown-toggle"" type=""button"" id=""dropdownMenu1"" data-toggle=""dropdown"" aria-expanded=""true"">
Dropdown
<span class=""caret""></span>
</button>
<ul class=""dropdown-menu"" role=""menu"" aria-labelledby=""dropdownMenu1"">
<li role=""presentation""><a role=""menuitem"" tabindex=""-1"" href=""#"">Action</a></li>
<li role=""presentation""><a role=""menuitem"" tabindex=""-1"" href=""#"">Another action</a></li>
<li role=""presentation""><a role=""menuitem"" tabindex=""-1"" href=""#"">Something else here</a></li>
<li role=""presentation""><a role=""menuitem"" tabindex=""-1"" href=""#"">Separated link</a></li>
</ul>
</div>
I would not want to have to rewrite all of that in JSX.
Maybe I am thinking about this all wrong. Please correct me.
",https://stackoverflow.com/questions/27934238/how-do-i-render-raw-html-with-react,297,575427.0,14.0,,,2015-01-14 01:01:27,2023-11-14 21:44:10,2023-11-14 21:44:10,,,javascript;reactjs,vinhboy,9040,298829,registered,true,30960037,,CC BY-SA 4.0,,1826,1750,2,0,0,2,true,false,false,true,true,true,36,8,true,0.024,0.0005,4329,2015,1,1,Wednesday,false,false,true,false,false,false,false
48378337,create react app not picking up .env files?,"I am using create react app to bootstrap my app.
I have added two .env files .env.development and .env.production in the root.
My .env.development includes:
API_URL=http://localhost:3000/api
CALLBACK_URL=http://localhost:3005/callback
When I run my app using react-scripts start and console out process.env it spits out
{ NODE_ENV: ""development"", PUBLIC_URL: """" }
I've tried different things, but its just not picking up the veriables in my development file, what am I doing wrong?!
Directry structure is:
/.env.development
/src/index.js
Package.json script is:
""start"": ""export PORT=3005; npm-run-all --parallel server:start client:start"",
""client:start"": ""export PORT=3005; react-scripts start"",
""server:start"": ""node server.js"",
""build"": ""react-scripts build"",
Edit:
@jamcreencia correctly pointed out my variables should be prefixed with REACT_APP.
Edit 2
It works okay if I name the file .env but not if I use .env.development or .end.production
",https://stackoverflow.com/questions/48378337/create-react-app-not-picking-up-env-files,296,351671.0,35.0,,,2018-01-22 09:30:22,2025-03-04 09:16:03,2018-01-22 14:46:23,,,reactjs;create-react-app,shenku,12544,148998,registered,true,48378498,,CC BY-SA 3.0,,1578,981,14,2,0,2,true,false,false,true,true,true,43,8,true,0.1,0.0008,3225,2018,1,9,Monday,false,false,false,false,false,false,false
38892672,React: why child component doesn't update when prop changes,"Why in the following pseudo-code example Child doesn't re-render when Container changes foo.bar?
Container {
handleEvent() {
this.props.foo.bar = 123
},
render() {
return <Child bar={this.props.foo.bar} />
}
Child {
render() {
return <div>{this.props.bar}</div>
}
}
Even if I call forceUpdate() after modifying the value in Container, Child still shows the old value.
",https://stackoverflow.com/questions/38892672/react-why-child-component-doesnt-update-when-prop-changes,296,461383.0,18.0,,,2016-08-11 09:40:36,2024-12-26 21:14:52,,,,javascript;html;reactjs,Tuomas Toivonen,23844,5705247,registered,true,,,CC BY-SA 3.0,,465,414,2,0,0,3,false,false,false,true,true,false,63,9,false,0.039,0.0006,3754,2016,8,9,Thursday,false,false,true,false,false,false,false
34687091,Can I execute a function after setState is finished updating?,"I am very new to ReactJS (as in, just started today). I don't quite understand how setState works. I am combining React and Easel JS to draw a grid based on user input. Here is my JS bin:
http://jsbin.com/zatula/edit?js,output
Here is the code:
var stage;
var Grid = React.createClass({
getInitialState: function() {
return {
rows: 10,
cols: 10
}
},
componentDidMount: function () {
this.drawGrid();
},
drawGrid: function() {
stage = new createjs.Stage("canvas");
var rectangles = [];
var rectangle;
//Rows
for (var x = 0; x < this.state.rows; x++)
{
// Columns
for (var y = 0; y < this.state.cols; y++)
{
var color = "Green";
rectangle = new createjs.Shape();
rectangle.graphics.beginFill(color);
rectangle.graphics.drawRect(0, 0, 32, 44);
rectangle.x = x * 33;
rectangle.y = y * 45;
stage.addChild(rectangle);
var id = rectangle.x + "_" + rectangle.y;
rectangles[id] = rectangle;
}
}
stage.update();
},
updateNumRows: function(event) {
this.setState({ rows: event.target.value });
this.drawGrid();
},
updateNumCols: function(event) {
this.setState({ cols: event.target.value });
this.drawGrid();
},
render: function() {
return (
<div>
<div className="canvas-wrapper">
<canvas id="canvas" width="400" height="500"></canvas>
<p>Rows: { this.state.rows }</p>
<p>Columns: {this.state.cols }</p>
</div>
<div className="array-form">
<form>
<label>Number of Rows</label>
<select id="numRows" value={this.state.rows} onChange={ this.updateNumRows }>
<option value="1">1</option>
<option value="2">2</option>
<option value ="5">5</option>
<option value="10">10</option>
<option value="12">12</option>
<option value="15">15</option>
<option value="20">20</option>
</select>
<label>Number of Columns</label>
<select id="numCols" value={this.state.cols} onChange={ this.updateNumCols }>
<option value="1">1</option>
<option value="2">2</option>
<option value="5">5</option>
<option value="10">10</option>
<option value="12">12</option>
<option value="15">15</option>
<option value="20">20</option>
</select>
</form>
</div>
</div>
);
}
});
ReactDOM.render(
<Grid />,
document.getElementById("container")
);
You can see in the JSbin when you change the number of rows or columns with one of the dropdowns, nothing will happen the first time. The next time you change a dropdown value, the grid will draw to the previous state's row and column values. I am guessing this is happening because my this.drawGrid() function is executing before setState is complete. Maybe there is another reason?
Thanks for your time and help!
",https://stackoverflow.com/questions/34687091/can-i-execute-a-function-after-setstate-is-finished-updating,296,357452.0,11.0,,,2016-01-08 22:20:35,2024-07-23 14:13:24,2020-08-22 16:19:44,,,javascript;reactjs;setstate,monalisa717,3437,1411056,registered,true,45186956,,CC BY-SA 4.0,,4711,4550,4,1,0,3,true,false,false,true,true,true,61,10,true,0.031,0.0008,3970,2016,1,22,Friday,false,false,true,false,false,false,false
36426521,What does "export default" do in JSX?,"I want to ask what the last sentence means and does (export default HelloWorld;) but I can't find any tutorials about it.
// hello-world.jsx
import React from 'react';
class HelloWorld extends React.Component {
render() {
return <p>Hello, world!</p>;
}
}
export default HelloWorld;
",https://stackoverflow.com/questions/36426521/what-does-export-default-do-in-jsx,294,344418.0,7.0,,,2016-04-05 12:34:42,2022-11-25 17:51:53,2018-12-21 19:26:05,,,javascript;reactjs,Digweed,2979,6124442,registered,true,36426988,,CC BY-SA 4.0,,338,307,1,0,0,2,true,false,false,true,true,true,47,7,true,0.02,0.0009,3882,2016,4,12,Tuesday,false,false,true,false,false,false,false
42813342,React.createElement: type is invalid -- expected a string,"Trying to get react-router (v4.0.0) and react-hot-loader (3.0.0-beta.6) to play nicely, but getting the following error in the browser console:
Warning: React.createElement: type is invalid -- expected a string
(for built-in components) or a class/function (for composite
components) but got: undefined. You likely forgot to export your
component from the file it's defined in.
index.js:
import React from 'react';
import ReactDom from 'react-dom';
import routes from './routes.js';
require('jquery');
import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap/dist/js/bootstrap.min.js';
import './css/main.css';
const renderApp = (appRoutes) => {
ReactDom.render(appRoutes, document.getElementById('root'));
};
renderApp( routes() );
routes.js:
import React from 'react';
import { AppContainer } from 'react-hot-loader';
import { Router, Route, browserHistory, IndexRoute } from 'react-router';
import store from './store/store.js';
import { Provider } from 'react-redux';
import App from './containers/App.jsx';
import Products from './containers/shop/Products.jsx';
import Basket from './containers/shop/Basket.jsx';
const routes = () => (
<AppContainer>
<Provider store={store}>
<Router history={browserHistory}>
<Route path="/" component={App}>
<IndexRoute component={Products} />
<Route path="/basket" component={Basket} />
</Route>
</Router>
</Provider>
</AppContainer>
);
export default routes;
",https://stackoverflow.com/questions/42813342/react-createelement-type-is-invalid-expected-a-string,294,748042.0,51.0,,,2017-03-15 14:57:12,2025-03-12 05:51:13,2021-01-18 08:00:49,,,reactjs;react-router;react-hot-loader,JoeTidee,26386,3111255,registered,true,42814137,,CC BY-SA 4.0,2023-01-05 08:08:27,1829,1628,3,0,0,3,true,false,false,true,true,true,57,8,false,0.068,0.0004,3538,2017,3,14,Wednesday,false,false,false,false,false,false,false
37620694,How to scroll to bottom in react?,"I want to build a chat system and automatically scroll to the bottom when entering the window and when new messages come in. How do you automatically scroll to the bottom of a container in React?
",https://stackoverflow.com/questions/37620694/how-to-scroll-to-bottom-in-react,293,487570.0,27.0,,,2016-06-03 17:54:25,2024-03-20 13:53:16,,,,reactjs,helsont,5102,1264811,registered,true,41700815,,CC BY-SA 3.0,2020-01-24 00:20:55,203,196,0,0,0,1,true,false,false,true,true,false,33,7,true,0.055,0.0006,3823,2016,6,17,Friday,false,false,false,false,false,false,false
39523040,Concatenating variables and strings in React,"Is there a way to incorporate React's curly brace notation and an href tag? Say we have the following value in the state:
{this.state.id}
and the following HTML attributes on a tag:
href=""#demo1""
id=""demo1""
Is there a way I can add the id state to the HTML attribute to get something like this:
href={""#demo + {this.state.id}""}
Which will yield:
#demo1
",https://stackoverflow.com/questions/39523040/concatenating-variables-and-strings-in-react,293,695249.0,5.0,,,2016-09-16 02:43:48,2021-10-26 14:41:57,2017-12-14 04:59:40,,,javascript;html;reactjs;ecmascript-6,lost9123193,11108,2394970,registered,true,39523078,,CC BY-SA 3.0,2021-01-24 09:14:34,514,364,6,0,0,4,true,false,false,true,true,true,44,6,false,0.007,0.0004,3718,2016,9,2,Friday,false,false,true,false,false,false,false
36326612,How to delete an item from state array?,"The story is, I should be able to put Bob, Sally and Jack into a box. I can also remove either from the box. When removed, no slot is left.
people = [""Bob"", ""Sally"", ""Jack""]
I now need to remove, say, ""Bob"". The new array would be:
[""Sally"", ""Jack""]
Here is my react component:
...
getInitialState: function() {
return{
people: [],
}
},
selectPeople(e){
this.setState({people: this.state.people.concat([e.target.value])})
},
removePeople(e){
var array = this.state.people;
var index = array.indexOf(e.target.value); // Let's say it's Bob.
delete array[index];
},
...
Here I show you a minimal code as there is more to it (onClick etc). The key part is to delete, remove, destroy ""Bob"" from the array but removePeople() is not working when called. Any ideas? I was looking at this but I might be doing something wrong since I'm using React.
",https://stackoverflow.com/questions/36326612/how-to-delete-an-item-from-state-array,291,705726.0,20.0,,,2016-03-31 07:17:36,2024-03-15 11:34:26,2021-07-17 15:34:19,,,javascript;arrays;reactjs,Sylar,12222,3581788,registered,true,36326779,,CC BY-SA 4.0,,1096,869,4,1,0,3,true,false,false,true,true,true,39,8,true,0.028,0.0004,3887,2016,3,7,Thursday,false,false,true,false,false,false,false
24939623,Can I update a component's props in React.js?,"After starting to work with React.js, it seems like props are intended to be static (passed in from the parent component), while state changes based upon events. However, I noticed in the docs a reference to componentWillReceiveProps, which specifically includes this example:
componentWillReceiveProps: function(nextProps) {
this.setState({
likesIncreasing: nextProps.likeCount > this.props.likeCount
});
}
This seems to imply that the properties CAN change on a component based upon the comparison of nextProps to this.props. What am I missing? How do props change, or am I mistaken about where this gets called?
",https://stackoverflow.com/questions/24939623/can-i-update-a-components-props-in-react-js,291,497535.0,6.0,,,2014-07-24 16:50:38,2021-10-31 12:25:09,2018-03-06 14:36:22,,,javascript;reactjs;properties,Matt Huggins,83859,107277,registered,true,24943743,,CC BY-SA 3.0,,842,632,6,1,0,3,true,false,false,true,true,true,49,8,true,0.012,0.0006,4503,2014,7,16,Thursday,false,false,true,false,false,false,false
45884752,npm ERR! code UNABLE_TO_GET_ISSUER_CERT_LOCALLY,"I am trying all possible ways to create a React application. I have tried Maven, and now I am trying create-react-app from Facebook Incubators.
When I tried to run the command create-react-app my-app in npm environment, it worked on my personal system with no issues. But, when I tried the same command in my work environment, I encountered the following error on my command line:
npm ERR! node v6.10.2
npm ERR! npm v3.10.10
npm ERR! code UNABLE_TO_GET_ISSUER_CERT_LOCALLY
npm ERR! unable to get local issuer certificate
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR! <https://github.com/npm/npm/issues>
",https://stackoverflow.com/questions/45884752/npm-err-code-unable-to-get-issuer-cert-locally,288,496522.0,23.0,,,2017-08-25 15:25:43,2025-10-17 15:10:47,2022-10-05 09:03:06,,,node.js;reactjs;npm;create-react-app,Dinesh,8191,7932914,registered,true,45884819,,CC BY-SA 4.0,2021-04-02 18:15:10,709,645,3,0,0,4,true,false,false,true,true,true,47,4,false,0.046,0.0006,3375,2017,8,15,Friday,false,false,false,false,false,false,false
61254372,My component is rendering twice because of Strict Mode,"My React Component is rendering twice. So, I decided to do a line-by-line debug, and the problem is here:
if ( workInProgress.mode & StrictMode) {
instance.render();
}
React-dom.development.js
Is it because of the strict mode? Can I disable it? What is Strict Mode? Do I need it?
",https://stackoverflow.com/questions/61254372/my-component-is-rendering-twice-because-of-strict-mode,287,214712.0,7.0,,,2020-04-16 15:44:01,2025-07-02 06:51:24,2025-07-02 06:51:24,,,javascript;reactjs;react-dom;react-strictmode,Marry Joanna,2863,13314296,registered,true,,,CC BY-SA 4.0,2023-08-22 10:25:52,382,300,1,0,0,4,false,false,false,true,true,true,54,9,false,0.033,0.0013,2410,2020,4,15,Thursday,false,false,true,false,false,false,false
53024496,State not updating when using React state hook within setInterval,"I'm trying out the new React Hooks and have a Clock component with a time value which is supposed to increase every second. However, the value does not increase beyond one.
function Clock() {
const [time, setTime] = React.useState(0);
React.useEffect(() => {
const timer = window.setInterval(() => {
setTime(time + 1);
}, 1000);
return () => {
window.clearInterval(timer);
};
}, []);
return (
<div>Seconds: {time}</div>
);
}
ReactDOM.render(<Clock />, document.querySelector('#app'));
<script src=""https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js""></script>
<script src=""https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js""></script>
<div id=""app""></div>
",https://stackoverflow.com/questions/53024496/state-not-updating-when-using-react-state-hook-within-setinterval,287,164069.0,16.0,,,2018-10-27 17:25:13,2025-01-03 15:35:30,2022-12-17 00:40:26,,,javascript;reactjs;react-hooks,Yangshun Tay,53969,1751946,registered,true,53024497,,CC BY-SA 4.0,,1197,809,3,1,0,3,true,false,false,true,true,true,65,10,false,0.098,0.0017,2947,2018,10,17,Saturday,true,false,true,false,false,false,false
59390955,Can I add a key prop to a React fragment?,"I am generating a dl in React:
<dl>
{
highlights.map(highlight => {
const count = text.split(highlight).length - 1;
return (
<>
<dt key={`dt-${highlight.id}`}>{highlight}</dt>
<dd key={`dd-${highlight.id}`}>{count}</dd>
</>
);
})
}
</dl>
This gives me the warning:
Warning: Each child in a list should have a unique "key" prop.
This will remove the warning, but doesn't generate the HTML I want:
<dl>
{
highlights.map(highlight => {
const count = text.split(highlight).length - 1;
return (
<div key={highlight.id}>
<dt>{highlight}</dt>
<dd>{count}</dd>
</div>
);
})
}
</dl>
And I cannot add a key prop to a fragment (<> </>).
How can work around this?
I am using React 16.12.0.
",https://stackoverflow.com/questions/59390955/can-i-add-a-key-prop-to-a-react-fragment,286,98149.0,4.0,,,2019-12-18 11:22:33,2024-03-06 05:07:57,2022-03-01 10:59:41,,,javascript;reactjs;jsx,sdgfsdh,38039,1256041,registered,true,59390967,,CC BY-SA 4.0,,1197,943,6,0,0,3,true,false,false,true,true,true,41,10,true,0.041,0.0029,2530,2019,12,11,Wednesday,false,false,true,false,false,false,false
46240647,How to (force to) re-render a functional component?,"I have a function component, and I want to force it to re-render.
How can I do so?
Since there's no instance this, I cannot call this.forceUpdate().
",https://stackoverflow.com/questions/46240647/how-to-force-to-re-render-a-functional-component,285,503242.0,16.0,,,2017-09-15 13:22:31,2026-03-23 10:57:59,2025-06-21 15:58:07,2026-02-10 17:34:45,Not suitable for this site,javascript;reactjs;react-functional-component,Gorakh Nath,9936,6560375,registered,true,53837442,,,,195,151,2,0,0,3,true,true,false,true,true,true,51,8,true,0.032,0.0006,3354,2017,9,13,Friday,false,false,true,false,false,false,false
39627545,React prop validation for date objects,"What is the currently preferred way to validate a Date prop in react?
Right now I'm using: React.PropTypes.object
This, however, is now failing the forbid-prop-types lint rule. Should I use a shape or is there some better way?
",https://stackoverflow.com/questions/39627545/react-prop-validation-for-date-objects,285,105564.0,2.0,,,2016-09-21 22:33:28,2023-02-06 06:35:51,,,,reactjs,David Weldon,64342,635981,registered,true,39627576,,CC BY-SA 3.0,,413,229,3,1,0,1,true,false,false,true,true,false,38,6,false,0.019,0.0027,3713,2016,9,22,Wednesday,false,false,false,false,false,false,false
42522515,What are the Differences Between Controlled and Uncontrolled Components in React?,"I'm trying to understand the distinction between Controlled and Uncontrolled components in ReactJS. Could someone please explain:
- What is a Controlled Component?
- How does it handle state and form data?
- What is an Uncontrolled Component?
- How does it differ in terms of state management?
- Usage Scenarios:
- When should I use one over the other?
- Could you provide simple code examples or scenarios where each would be preferable?
",https://stackoverflow.com/questions/42522515/what-are-the-differences-between-controlled-and-uncontrolled-components-in-react,284,197675.0,9.0,,,2017-03-01 03:15:04,2025-02-25 15:31:20,2025-01-21 13:08:50,2025-01-10 04:09:57,Needs more focus,reactjs,Xin,37247,4468648,registered,true,42522792,,,2025-01-05 23:41:01,542,436,0,0,0,1,true,true,false,true,true,true,81,11,true,0.046,0.0014,3552,2017,3,3,Wednesday,false,false,false,false,false,false,false
44991656,No restricted globals,"I am using React and Redux to develop a webapp and when I started up my project I got this:
Line 13: Unexpected use of 'location' no-restricted-globals
Search for the keywords to learn more about each error.
I search a lot about how to resolve it, but none of the answers I found helped me, so I turned to Stack overflow.
Does anyone know how to fix this error? I appreciate all the help I can get.
",https://stackoverflow.com/questions/44991656/no-restricted-globals,283,203714.0,9.0,,,2017-07-08 23:29:46,2022-12-12 10:34:40,2019-02-05 14:11:02,,,javascript;reactjs;react-router;eslint,Martin Nordström,6045,7284779,registered,true,44998181,,CC BY-SA 4.0,,453,408,1,0,0,4,true,false,false,true,true,true,21,3,false,0.044,0.0014,3423,2017,7,23,Saturday,true,false,true,false,false,false,false
36209432,How to dynamically add a class to manual class names?,"I need to add a dynamic class to a list of regular classes, but have no idea how (I'm using babel), something like this:
<div className=""wrapper searchDiv {this.state.something}"">
...
</div>
Any ideas?
",https://stackoverflow.com/questions/36209432/how-to-dynamically-add-a-class-to-manual-class-names,283,438245.0,19.0,,,2016-03-24 20:27:22,2025-06-27 00:10:02,2020-10-29 10:57:27,,,css;reactjs,Mankind1023,7804,353046,registered,true,,,CC BY-SA 4.0,2023-02-03 03:09:05,255,217,1,0,0,2,false,false,false,true,true,true,53,10,true,0.043,0.0006,3894,2016,3,20,Thursday,false,false,false,false,false,false,false
57847594,Accessing up-to-date state from within a callback,"We use a third party library (over which there is limited control) that takes a callback as argument to a function. What is the correct way to provide that callback with the latest state? In class components, this would be done through the use of this. In React hooks, due to the way state is encapsulated in the functions of React.useState(), if a callback gets the state through React.useState(), it will be stale (the value when the callback was setup). But if it sets the state, it will have access to the latest state through the passed argument. This means we can potentially get the latest state in such a callback with React hooks by setting the state to be the same as it was. This works, but is counter-intuitive.
With the following code, every time the callback accesses it, it's back at its default value. The console will keep printing Count is: 0 no matter how many times I click.
function Card(title) {
const [count, setCount] = React.useState(0)
const [callbackSetup, setCallbackSetup] = React.useState(false)
function setupConsoleCallback(callback) {
console.log("Setting up callback")
setInterval(callback, 3000)
}
function clickHandler() {
setCount(count+1);
if (!callbackSetup) {
setupConsoleCallback(() => {console.log(`Count is: ${count}`)})
setCallbackSetup(true)
}
}
return (<div>
Active count {count} <br/>
<button onClick={clickHandler}>Increment</button>
</div>);
}
const el = document.querySelector("#root");
ReactDOM.render(<Card title='Example Component' />, el);
I've had no problem setting state within a callback, only in accessing the latest state.
If I was to take a guess, I'd think that any change of state creates a new instance of the Card function. And that the callback is referring to the old one. Based on the documentation at https://reactjs.org/docs/hooks-reference.html#functional-updates, I had an idea to take the approach of calling setState in the callback, and passing a function to setState, to see if I could access the current state from within setState. Replacing
setupConsoleCallback(() => {console.log(`Count is: ${count}`)})
with
setupConsoleCallback(() => {setCount(prevCount => {console.log(`Count is: ${prevCount}`); return prevCount})})
Does work. I need to call setState to access the previous state. Even though I have no intention of setting the state.
How can I access the latest state information from within a callback?
",https://stackoverflow.com/questions/57847594/accessing-up-to-date-state-from-within-a-callback,283,149227.0,12.0,,,2019-09-09 03:38:16,2025-10-02 11:17:02,2024-04-11 06:49:58,,,javascript;reactjs;react-hooks,rod,3923,370115,registered,true,60643670,,CC BY-SA 4.0,,3004,2551,7,3,0,3,true,false,false,true,true,true,49,7,false,0.08,0.0019,2630,2019,9,3,Monday,false,false,true,false,false,false,false
34385243,Why is immutability so important (or needed) in JavaScript?,"I am currently working on React JS and React Native frameworks. On the half way road I came across Immutability or the Immutable-JS library, when I was reading about Facebook's Flux and Redux implementation.
The question is, why is immutability so important? What is wrong in mutating objects? Doesn't it make things simple?
Giving an example, let us consider a simple News reader app with the opening screen being a list view of news headlines.
If I set say an array of objects with a value initially I can't manipulate it. That's what immutability principle says, right? (Correct me if I am wrong.)
But, what if I have a new News object that has to be updated? In usual case, I could have just added the object to the array.
How do I achieve in this case? Delete the store and recreate it?
Isn't adding an object to the array a less expensive operation?
",https://stackoverflow.com/questions/34385243/why-is-immutability-so-important-or-needed-in-javascript,282,76182.0,14.0,,,2015-12-20 20:00:55,2024-02-05 16:36:57,2019-07-18 18:41:10,,,javascript;reactjs;functional-programming;immutability;immutable.js,Satvik,12614,3782392,registered,true,34385684,,CC BY-SA 4.0,,1146,859,0,3,0,5,true,false,false,true,true,true,59,9,true,0.184,0.0037,3989,2015,12,20,Sunday,true,false,true,false,false,false,false
41462729,Typescript react - Could not find a declaration file for module ''react-materialize'. 'path/to/module-name.js' implicitly has an any type,"I am trying to import components from react-materialize as -
import {Navbar, NavItem} from 'react-materialize';
But when the webpack is compiling my .tsx it throws an error for the above as -
ERROR in ./src/common/navbar.tsx
(3,31): error TS7016: Could not find a declaration file for module 'react-materi
alize'. 'D:\Private\Works\Typescript\QuickReact\node_modules\react-materialize\l
ib\index.js' implicitly has an 'any' type.
Is there any resolution for this? I'm unsure how to resolve this import statement to work with ts-loader and webpack.
The index.js of react-materialize looks likes this. But how do I resolve this for the module import in my own files?
https://github.com/react-materialize/react-materialize/blob/master/src/index.js
",https://stackoverflow.com/questions/41462729/typescript-react-could-not-find-a-declaration-file-for-module-react-material,281,632001.0,27.0,,,2017-01-04 11:29:14,2024-02-12 10:56:25,2021-01-18 12:09:19,,,reactjs;webpack;webpack-2,Joy,7058,562171,registered,true,41631658,,CC BY-SA 4.0,2020-07-14 12:14:19,980,747,5,1,0,3,true,false,false,true,true,true,157,18,false,0.043,0.0004,3608,2017,1,11,Wednesday,false,false,false,false,false,false,false
63690695,React: 'Redirect' is not exported from 'react-router-dom',"I am getting the following error when running npm run start in the terminal.
Attempted import error: 'Redirect' is not exported from 'react-router-dom'.
I have reinstalled node_modules, react-router-dom, react-router. Also restarted the terminal and my computer, but the issue persists.
My code:
import React from 'react';
import { Switch, Redirect } from 'react-router-dom';
import { RouteWithLayout } from './components';
import { Minimal as MinimalLayout } from './layouts';
import {
Login as LoginView,
Dashboard as DashboardView,
NotFound as NotFoundView
} from './views';
const Routes = () => {
return (
<Switch>
<Redirect
exact
from="/"
to="/dashboard"
/>
<RouteWithLayout
component={routeProps => <LoginView {...routeProps} data={data} />}
exact
layout={MinimalLayout}
path="/login"
/>
<Redirect to="/not-found" />
</Switch>
);
};
export default Routes;
Here is my package.json imports:
"react-router": "^6.0.0-beta.0",
"react-router-dom": "^6.0.0-beta.0",
",https://stackoverflow.com/questions/63690695/react-redirect-is-not-exported-from-react-router-dom,281,317029.0,14.0,,,2020-09-01 15:23:37,2023-05-11 05:02:49,2022-03-28 19:15:46,,,javascript;reactjs;react-router;react-router-dom,Zero Cool,2961,10377470,registered,true,69408107,,CC BY-SA 4.0,2022-10-27 08:27:13,1389,1199,7,0,0,4,true,false,false,true,true,true,73,7,false,0.044,0.0009,2272,2020,9,15,Tuesday,false,false,true,false,false,false,false
50752987,eslint: no-case-declaration - unexpected lexical declaration in case block,"What is the better way to update state in this context inside a reducer?
case DELETE_INTEREST:
let deleteInterests = state.user.interests;
let index = deleteInterests.findIndex(i => i == action.payload);
deleteInterests.splice(index, 1);
return { ...state, user: { ...state.user, interests: deleteInterests } };
ESLint doesn't like let statements inside case blocks inside a reducer, getting:
eslint: no-case-declaration - unexpected lexical declaration in case
block
",https://stackoverflow.com/questions/50752987/eslint-no-case-declaration-unexpected-lexical-declaration-in-case-block,281,207012.0,3.0,,,2018-06-08 03:35:56,2022-11-09 15:12:30,2018-06-09 11:21:14,,,reactjs;redux,Josh,3300,3278320,registered,true,50753272,,CC BY-SA 4.0,,567,497,1,0,0,2,true,false,false,true,true,true,74,9,false,0.014,0.0014,3088,2018,6,3,Friday,false,false,false,false,false,false,false
28868071,OnChange event using React JS for drop down,"var MySelect = React.createClass({
change: function(){
return document.querySelector('#lang').value;
},
render: function(){
return(
<div>
<select id=""lang"">
<option value=""select"" onChange={this.change}>Select</option>
<option value=""Java"" onChange={this.change}>Java</option>
<option value=""C++"" onChange={this.change}>C++</option>
</select>
<p></p>
<p value={this.change}></p>
</div>
);
}
});
React.render(<MySelect />, document.body);
The onChange event does not work.
",https://stackoverflow.com/questions/28868071/onchange-event-using-react-js-for-drop-down,280,861269.0,10.0,,,2015-03-05 00:49:46,2024-11-24 15:30:43,,,,javascript;reactjs,user544079,16679,544079,registered,true,28868135,,CC BY-SA 3.0,,791,747,2,0,0,2,true,false,false,true,true,false,43,8,false,0.012,0.0003,4279,2015,3,0,Thursday,false,false,true,false,false,false,false
36730793,Can I dispatch an action in reducer?,"is it possible to dispatch an action in a reducer itself? I have a progressbar and an audio element. The goal is to update the progressbar when the time gets updated in the audio element. But I don't know where to place the ontimeupdate eventhandler, or how to dispatch an action in the callback of ontimeupdate, to update the progressbar. Here is my code:
//reducer
const initialState = {
audioElement: new AudioElement('test.mp3'),
progress: 0.0
}
initialState.audioElement.audio.ontimeupdate = () => {
console.log('progress', initialState.audioElement.currentTime/initialState.audioElement.duration);
//how to dispatch 'SET_PROGRESS_VALUE' now?
};
const audio = (state=initialState, action) => {
switch(action.type){
case 'SET_PROGRESS_VALUE':
return Object.assign({}, state, {progress: action.progress});
default: return state;
}
}
export default audio;
",https://stackoverflow.com/questions/36730793/can-i-dispatch-an-action-in-reducer,280,209231.0,7.0,,,2016-04-19 22:44:58,2023-03-31 04:38:31,2017-06-15 07:43:03,,,reactjs;redux;reducers,klanm,3278,1308461,registered,true,36731119,,CC BY-SA 3.0,,955,924,1,0,0,3,true,false,false,true,true,true,36,7,true,0.033,0.0013,3868,2016,4,22,Tuesday,false,false,false,false,false,false,false
55846641,React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function,"I'm trying to use react hooks for a simple problem
const [personState,setPersonState] = useState({ DefinedObject });
with following dependencies.
""dependencies"": {
""react"": ""^16.8.6"",
""react-dom"": ""^16.8.6"",
""react-scripts"": ""3.0.0""
}
but I'm still getting the following error:
./src/App.js
Line 7:
React Hook ""useState"" is called in function
""app"" which is neither a React function component or a custom React
Hook function react-hooks/rules-of-hooks
Line 39:
'state' is not defined
no-undef
Search for the keywords to learn more about each error.
Component code is below:
import React, {useState} from 'react';
import './App.css';
import Person from './Person/Person';
const app = props => {
const [personState, setPersonSate] = useState({ person:[ {name:'bishnu',age:'32'}, {name:'rasmi',age:'27'}, {name:'fretbox',age:'4'} ], });
return (
<div className=""App"">
<h2>This is react</h2>
<Person name={personState.person[1].name} age=""27""></Person>
<Person name={personState.person[2].name} age=""4""></Person>
</div> );
};
export default app;
Person component
import React from 'react';
const person = props => {
return(
<div>
<h3>i am {props.name}</h3>
<p>i am {props.age} years old</p>
<p>{props.children}</p>
</div>
)
};
export default person;
",https://stackoverflow.com/questions/55846641/react-hook-usestate-is-called-in-function-app-which-is-neither-a-react-funct,278,286558.0,36.0,,,2019-04-25 10:00:54,2023-03-02 10:10:34,2020-02-21 11:42:58,,,reactjs;react-hooks,Bishnu,2854,2602770,registered,true,,,CC BY-SA 4.0,2021-12-19 19:48:54,1745,1549,4,0,0,2,false,false,false,true,true,true,145,21,false,0.126,0.001,2767,2019,4,10,Thursday,false,false,false,false,false,false,false
25797048,How to pass in a react component into another react component to transclude the first component's content?,"Is there a way to pass one component into another react component? I want to create a model react component and pass in another react component in order to transclude that content.
Edit: Here is a reactJS codepen illustrating what I'm trying to do. http://codepen.io/aallbrig/pen/bEhjo
HTML
<div id=""my-component"">
<p>Hi!</p>
</div>
ReactJS
/**@jsx React.DOM*/
var BasicTransclusion = React.createClass({
render: function() {
// Below 'Added title' should be the child content of <p>Hi!</p>
return (
<div>
<p> Added title </p>
{this.props.children}
</div>
)
}
});
React.renderComponent(BasicTransclusion(), document.getElementById('my-component'));
",https://stackoverflow.com/questions/25797048/how-to-pass-in-a-react-component-into-another-react-component-to-transclude-the,278,368539.0,13.0,,,2014-09-11 21:13:28,2023-11-19 01:05:53,2018-08-27 18:59:07,,,javascript;reactjs,Andrew Allbright,3869,2646461,registered,true,25807416,,CC BY-SA 4.0,,894,767,2,1,0,2,true,false,false,true,true,true,110,17,true,0.035,0.0008,4454,2014,9,21,Thursday,false,false,true,false,false,false,false
42083181,Is it possible to return empty in react render function?,"I have a notification component, and I have a timeout setting for it. After timeout I call this.setState({isTimeout:true}).
What I want to do is if already timeout, I want just render nothing:
render() {
let finalClasses = "" + (this.state.classes || "");
if (isTimeout){
return (); // here has some syntax error
}
return (<div>{this.props.children}</div>);
}
The problem is:
return (); // here has some syntax error
",https://stackoverflow.com/questions/42083181/is-it-possible-to-return-empty-in-react-render-function,277,272354.0,9.0,,,2017-02-07 06:29:58,2024-07-03 20:23:40,2020-12-24 09:28:00,,,reactjs,Xin,37247,4468648,registered,true,42083262,,CC BY-SA 4.0,,554,464,2,0,0,1,true,false,false,true,true,true,56,10,true,0.033,0.001,3574,2017,2,6,Tuesday,false,false,false,false,false,false,false
32174317,How to set default Checked in checkbox ReactJS?,"I'm having trouble to update the checkbox state after it's assigned with default value checked="checked" in React.
var rCheck = React.createElement('input',
{
type: 'checkbox',
checked: 'checked',
value: true
}, 'Check here');
After assigning checked="checked", I cannot interact the checkbox state by clicking to uncheck/check.
",https://stackoverflow.com/questions/32174317/how-to-set-default-checked-in-checkbox-reactjs,276,627451.0,20.0,,,2015-08-24 04:10:01,2024-06-11 10:15:20,2020-10-20 09:30:26,,,reactjs;checkbox,Yarin Nim,3817,5023461,registered,true,32220316,,CC BY-SA 4.0,,446,382,3,0,0,2,true,false,false,true,true,true,47,8,true,0.032,0.0004,4107,2015,8,4,Monday,false,false,false,false,false,false,false
41340697,React.Component vs React.PureComponent,"The official React docs state that ""React.PureComponent's shouldComponentUpdate() only shallowly compares the objects"", and advises against this if state is ""deep"".
Given this, is there any reason why one should prefer React.PureComponent when creating React components?
Questions:
- is there any performance impact in using
React.Component that we may consider going for React.PureComponent?
- I am guessing
shouldComponentUpdate() of PureComponent performs only shallow comparisons. If this is the case, can't said method be used for deeper comparisons?
- ""Furthermore,
React.PureComponent's shouldComponentUpdate() skips prop updates for the whole component subtree"" - Does this mean that prop changes are ignored?
Question arose from reading into this medium blog, if it helps.
",https://stackoverflow.com/questions/41340697/react-component-vs-react-purecomponent,274,129809.0,4.0,,,2016-12-27 07:14:33,2022-02-11 08:56:10,2019-06-08 21:11:00,2022-02-10 16:59:51,Needs more focus,reactjs;state,semuzaboi,5242,1105176,registered,true,43936258,,,,1221,783,9,2,0,2,true,true,false,true,true,true,38,3,false,0.031,0.0021,3616,2016,12,7,Tuesday,false,false,false,false,false,false,false
40161516,How do you programmatically update query params in react-router?,"I can't seem to find how to update query params with react-router without using <Link/>. hashHistory.push(url) doesn't seem to register query params, and it doesn't seem like you can pass a query object or anything as a second argument.
How do you change the url from /shop/Clothes/dresses to /shop/Clothes/dresses?color=blue in react-router without using <Link>?
And is an onChange function really the only way to listen for query changes? Why aren't query changes automatically detected and reacted-to the way that param changes are?
",https://stackoverflow.com/questions/40161516/how-do-you-programmatically-update-query-params-in-react-router,273,539903.0,21.0,,,2016-10-20 18:06:09,2025-01-08 04:14:08,2025-01-08 04:14:08,,,reactjs;react-router;query-string,claireablani,8204,3745986,registered,true,40161954,,CC BY-SA 4.0,,650,551,6,0,0,3,true,false,false,true,true,true,64,9,true,0.039,0.0005,3684,2016,10,18,Thursday,false,false,false,false,false,false,false
37387351,ReactJS: Warning: setState(...): Cannot update during an existing state transition,"I am trying to refactor the following code from my render view:
<Button href=""#"" active={!this.state.singleJourney} onClick={this.handleButtonChange.bind(this,false)} >Retour</Button>
to a version where the bind is within the constructor. The reason for that is that bind in the render view will give me performance issues, especially on low end mobile phones.
I have created the following code, but I am constantly getting the following errors (lots of them). It looks like the app gets in a loop:
Warning: setState(...): Cannot update during an existing state transition (such as within `render` or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to `componentWillMount`.
Below is the code I use:
var React = require('react');
var ButtonGroup = require('react-bootstrap/lib/ButtonGroup');
var Button = require('react-bootstrap/lib/Button');
var Form = require('react-bootstrap/lib/Form');
var FormGroup = require('react-bootstrap/lib/FormGroup');
var Well = require('react-bootstrap/lib/Well');
export default class Search extends React.Component {
constructor() {
super();
this.state = {
singleJourney: false
};
this.handleButtonChange = this.handleButtonChange.bind(this);
}
handleButtonChange(value) {
this.setState({
singleJourney: value
});
}
render() {
return (
<Form>
<Well style={wellStyle}>
<FormGroup className=""text-center"">
<ButtonGroup>
<Button href=""#"" active={!this.state.singleJourney} onClick={this.handleButtonChange(false)} >Retour</Button>
<Button href=""#"" active={this.state.singleJourney} onClick={this.handleButtonChange(true)} >Single Journey</Button>
</ButtonGroup>
</FormGroup>
</Well>
</Form>
);
}
}
module.exports = Search;
",https://stackoverflow.com/questions/37387351/reactjs-warning-setstate-cannot-update-during-an-existing-state-transiti,272,336945.0,12.0,,,2016-05-23 09:29:38,2024-12-06 00:01:06,,,,reactjs;constructor;setstate,user3611459,3391,3611459,registered,true,37387846,,CC BY-SA 3.0,,2283,2183,3,0,0,3,true,false,false,true,true,false,82,10,false,0.036,0.0008,3834,2016,5,9,Monday,false,false,false,false,false,false,false
20377837,How to access custom attributes from event object in React?,"React is able to render custom attributes as described at
http://facebook.github.io/react/docs/jsx-gotchas.html:
If you want to use a custom attribute, you should prefix it with
data-.
<div data-custom-attribute=""foo"" />
And that's great news except I can't find a way to access it from the event object e.g.:
render: function() {
...
<a data-tag={i} style={showStyle} onClick={this.removeTag}></a>
...
removeTag: function(event) {
this.setState({inputVal: event.target????});
},
The element and data- property render in html fine. Standard properties like style can be accessed as event.target.style fine.
Instead of event.target I tried:
event.target.props.data.tag
event.target.props.data[""tag""]
event.target.props[""data-tag""]
event.target.data.tag
event.target.data[""tag""]
event.target[""data-tag""]
none of these worked.
",https://stackoverflow.com/questions/20377837/how-to-access-custom-attributes-from-event-object-in-react,271,361211.0,17.0,,,2013-12-04 14:23:07,2022-09-24 03:57:18,2017-04-05 05:28:44,,,javascript;facebook;reactjs,andriy_sof,2743,3027284,registered,true,20446806,,CC BY-SA 3.0,2019-02-02 23:57:44,1141,876,7,1,0,3,true,false,false,true,true,true,59,10,true,0.047,0.0008,4735,2013,12,14,Wednesday,false,false,true,false,false,false,false
71668256,Deprecation notice: ReactDOM.render is no longer supported in React 18,"I get this error every time I create a new React app:
Warning: ReactDOM.render is no longer supported in React 18. Use createRoot instead. Until you switch to the new API, your app will behave as if it's running React 17. Learn more: https://reactjs.org/link/switch-to-createroot
How can I fix it?
I created my React app using:
npx create-react-app my-app
",https://stackoverflow.com/questions/71668256/deprecation-notice-reactdom-render-is-no-longer-supported-in-react-18,269,490451.0,15.0,,,2022-03-29 20:11:46,2023-12-07 22:25:48,2022-04-15 11:57:50,,,javascript;reactjs,SnNaCk,3002,14328086,registered,true,71668419,,CC BY-SA 4.0,2022-04-08 10:21:22,552,359,1,1,0,2,true,false,false,true,true,true,70,10,false,0.031,0.0005,1698,2022,3,20,Tuesday,false,false,true,false,false,false,false
38202572,Understanding React-Redux and mapStateToProps(),"I'm trying to understand the connect method of react-redux, and the functions it takes as parameters. In particular mapStateToProps().
The way I understand it, the return value of mapStateToProps will be an object derived from state (as it lives in the store), whose keys will be passed to your target component (the component connect is applied to) as props.
This means that the state as consumed by your target component can have a wildly different structure from the state as it is stored on your store.
Q: Is this OK?
Q: Is this expected?
Q: Is this an anti-pattern?
",https://stackoverflow.com/questions/38202572/understanding-react-redux-and-mapstatetoprops,269,210065.0,10.0,,,2016-07-05 11:42:41,2020-09-24 07:18:42,2020-04-09 04:06:48,,,javascript;reactjs;redux;react-redux,Pablo Barría Urenda,5823,2665008,registered,true,46429416,,CC BY-SA 4.0,,636,574,2,0,0,4,true,false,false,true,true,true,47,4,false,0.048,0.0013,3791,2016,7,11,Tuesday,false,false,true,false,false,false,false
40063468,React component initialize state from props,"In React, are there any real differences between these two implementations?
Some friends tell me that the FirstComponent is the pattern, but I don't see why. The SecondComponent seems simpler because the render is called only once.
First:
import React, { PropTypes } from 'react'
class FirstComponent extends React.Component {
state = {
description: ''
}
componentDidMount() {
const { description} = this.props;
this.setState({ description });
}
render () {
const {state: { description }} = this;
return (
<input type="text" value={description} />
);
}
}
export default FirstComponent;
Second:
import React, { PropTypes } from 'react'
class SecondComponent extends React.Component {
state = {
description: ''
}
constructor (props) => {
const { description } = props;
this.state = {description};
}
render () {
const {state: { description }} = this;
return (
<input type="text" value={description} />
);
}
}
export default SecondComponent;
Update:
I changed setState() to this.state = {} (thanks joews), However, I still don't see the difference. Is one better than other?
",https://stackoverflow.com/questions/40063468/react-component-initialize-state-from-props,268,409342.0,9.0,,,2016-10-15 19:43:48,2021-10-15 18:24:52,2021-10-15 18:24:52,,,javascript;reactjs;components,Levy Moreira,2783,2511942,registered,true,47341539,,CC BY-SA 4.0,2020-07-14 01:19:20,1342,1214,6,0,0,3,true,false,false,true,true,true,43,6,false,0.022,0.0007,3689,2016,10,19,Saturday,true,false,true,false,false,false,false
38684925,React eslint error missing in props validation,"I have the next code, eslint throw:
react/prop-types onClickOut; is missing in props validation
react/prop-types children; is missing in props validation
propTypes was defined but eslint does not recognize it.
import React, { Component, PropTypes } from 'react';
class IxClickOut extends Component {
static propTypes = {
children: PropTypes.any,
onClickOut: PropTypes.func,
};
componentDidMount() {
document.getElementById('app')
.addEventListener('click', this.handleClick);
}
componentWillUnmount() {
document.getElementById('app')
.removeEventListener('click', this.handleClick);
}
handleClick = ({ target }: { target: EventTarget }) => {
if (!this.containerRef.contains(target)) {
this.props.onClickOut();
}
};
containerRef: HTMLElement;
render() {
const { children, ...rest } = this.props;
const filteredProps = _.omit(rest, 'onClickOut');
return (
<div
{...filteredProps}
ref={container => {
this.containerRef = container;
}}
>
{children}
</div>
);
}
}
export default IxClickOut;
package.json
{
"name": "verinmueblesmeteor",
"private": true,
"scripts": {
"start": "meteor run",
"ios": "NODE_ENV=developement meteor run ios"
},
"dependencies": {
"fine-uploader": "^5.10.1",
"foundation-sites": "^6.2.3",
"install": "^0.8.1",
"ix-gm-polygon": "^1.0.11",
"ix-type-building": "^1.4.4",
"ix-type-offer": "^1.0.10",
"ix-utils": "^1.3.7",
"keymirror": "^0.1.1",
"meteor-node-stubs": "^0.2.3",
"moment": "^2.13.0",
"npm": "^3.10.3",
"rc-slider": "^3.7.3",
"react": "^15.1.0",
"react-addons-pure-render-mixin": "^15.1.0",
"react-dom": "^15.1.0",
"react-fileupload": "^2.2.0",
"react-list": "^0.7.18",
"react-modal": "^1.4.0",
"react-redux": "^4.4.5",
"react-router": "^2.6.0",
"react-styleable": "^2.2.4",
"react-textarea-autosize": "^4.0.4",
"redux": "^3.5.2",
"redux-form": "^5.3.1",
"redux-thunk": "^2.1.0",
"rxjs": "^5.0.0-beta.9",
"rxjs-es": "^5.0.0-beta.9",
"socket.io": "^1.4.8"
},
"devDependencies": {
"autoprefixer": "^6.3.6",
"babel-eslint": "^6.0.4",
"babel-plugin-transform-decorators-legacy": "^1.3.4",
"babel-preset-es2015": "^6.9.0",
"babel-preset-react": "^6.5.0",
"babel-preset-stage-0": "^6.5.0",
"core-js": "^2.0.0",
"cssnano": "^3.7.1",
"eslint": "^2.12.0",
"eslint-config-airbnb": "^9.0.1",
"eslint-import-resolver-meteor": "^0.2.3",
"eslint-plugin-import": "^1.8.1",
"eslint-plugin-jsx-a11y": "^1.2.2",
"eslint-plugin-react": "^5.1.1",
"node-sass": "^3.8.0",
"postcss-cssnext": "^2.6.0",
"sasslets-animate": "0.0.4"
},
"cssModules": {
"ignorePaths": [
"node_modules"
],
"jsClassNamingConvention": {
"camelCase": true
},
"extensions": [
"scss",
"sass"
],
"postcssPlugins": {
"postcss-modules-values": {},
"postcss-modules-local-by-default": {},
"postcss-modules-extract-imports": {},
"postcss-modules-scope": {},
"autoprefixer": {}
}
}
}
.babelrc
{
"presets": [
"es2015",
"react",
"stage-0"
],
"whitelist": [
"es7.decorators",
"es7.classProperties",
"es7.exportExtensions",
"es7.comprehensions",
"es6.modules"
],
"plugins": ["transform-decorators-legacy"]
}
.eslintrc
{
"parser": "babel-eslint",
"extends": "airbnb",
"rules": {
"no-underscore-dangle": ["error", { "allow": [_id, b_codes_id] }],
},
"settings": {
"import/resolver": "meteor"
},
"globals": {
"_": true,
"CSSModule": true,
"Streamy": true,
"ReactClass": true,
"SyntheticKeyboardEvent": true,
}
}
",https://stackoverflow.com/questions/38684925/react-eslint-error-missing-in-props-validation,268,604252.0,27.0,,,2016-07-31 14:19:33,2024-11-17 05:17:50,2020-06-20 09:12:55,,,javascript;reactjs;eslint;flowtype,Cristian Cedeno,4122,3626118,registered,true,38685649,,CC BY-SA 4.0,,5451,5268,5,0,0,4,true,false,false,true,true,true,46,7,false,0.045,0.0004,3765,2016,7,14,Sunday,true,false,true,false,false,false,false
40947650,Axios get in url works but with second parameter as object it doesn't,"I'm trying to send GET request as second parameter but it doesn't work while it does as url.
This works, $_GET['naam'] returns test:
export function saveScore(naam, score) {
return function (dispatch) {
axios.get('http://****.nl/****/gebruikerOpslaan.php?naam=test')
.then((response) => {
dispatch({type: ""SAVE_SCORE_SUCCESS"", payload: response.data})
})
.catch((err) => {
dispatch({type: ""SAVE_SCORE_FAILURE"", payload: err})
})
}
};
But when I try this, there is nothing in $_GET at all:
export function saveScore(naam, score) {
return function (dispatch) {
axios.get('http://****.nl/****/gebruikerOpslaan.php',
{
password: 'pass',
naam: naam,
score: score
})
.then((response) => {
dispatch({type: ""SAVE_SCORE_SUCCESS"", payload: response.data})
})
.catch((err) => {
dispatch({type: ""SAVE_SCORE_FAILURE"", payload: err})
})
}
};
Why can't I do that? In the docs it clearly says it's possible. With $_POST it doesn't work either.
",https://stackoverflow.com/questions/40947650/axios-get-in-url-works-but-with-second-parameter-as-object-it-doesnt,262,477908.0,4.0,,,2016-12-03 12:17:49,2024-08-23 08:30:48,,,,reactjs;react-native;redux;axios,Sinan Samet,6790,1421775,registered,true,40953463,,CC BY-SA 3.0,2021-12-30 14:35:43,1179,1077,4,0,0,4,true,false,false,true,true,false,73,13,false,0.008,0.0005,3640,2016,12,12,Saturday,true,false,false,false,false,false,false
54865764,React.useState does not reload state from props,"I'm expecting state to reload on props change, but this does not work and user variable is not updated on next useState call, what is wrong?
function Avatar(props) {
const [user, setUser] = React.useState({...props.user});
return user.avatar ?
(<img src={user.avatar}/>)
: (<p>Loading...</p>);
}
",https://stackoverflow.com/questions/54865764/react-usestate-does-not-reload-state-from-props,262,171588.0,8.0,,,2019-02-25 12:01:02,2024-01-30 11:17:31,2019-11-14 02:31:32,,,reactjs;react-hooks,vitalyster,5294,1097384,registered,true,72914696,,CC BY-SA 4.0,,483,347,3,1,0,2,true,false,false,true,true,true,47,7,false,0.047,0.0015,2826,2019,2,12,Monday,false,false,false,false,false,false,false
47196800,ReactJS and images in public folder,"Im new in ReactJS and I want to import images in a component. These images are inside of the public folder and I do not know how to access the folder from the react component.
Any ideas ?
EDIT
I want to import an image inside Bottom.js or Header.js
The structure folder is:
I do not use webpack. Should I ?
Edit 2
I want to use webpack for loading the images and the rest of assets. So in my config folder I have the next files:
Where I need to add the paths of the images and how?
Thanks
",https://stackoverflow.com/questions/47196800/reactjs-and-images-in-public-folder,261,634484.0,18.0,,,2017-11-09 08:06:29,2025-01-24 02:32:32,2017-11-09 08:35:31,,,javascript;reactjs,Aceconhielo,3666,6752591,registered,true,54844591,,CC BY-SA 3.0,,903,503,0,2,2,2,true,false,false,true,true,true,35,6,false,0.028,0.0004,3299,2017,11,8,Thursday,false,false,true,false,false,false,false
52759220,Importing images in TypeScript React - "Cannot find module","I am trying to import images to use inside a React component with TypeScript. The bundler I'm using is Parcel (not Webpack).
I have created a .d.ts file inside the project with the image file extension, and included it inside tsconfig.json. However, when I try to import an image, TS yells at me about Cannot find module.
My project structure:
+ src
+ assets
- image.jpg
+ components
- Box.tsx
- App.tsx
- index.d.ts
- index.html
- index.tsx
- tsconfig.json
- tslint.json
I tried to import the image in App.tsx like this. VS Code underlined '../assets/image.jpg' and said Cannot find module '../assets/image.jpg'.
import * as React from 'react';
import * as img from '../assets/image.jpg';
const Box = props => {
// do things...
}
export default Box;
The discussions I found online point to the need of defining a .d.ts file myself, so I created that index.d.ts file with this line.
declare module '*.jpg';
Then added ""include"": [""./src/index.d.ts""] inside tsconfig.json, after ""compilerOptions"" : {...}.
What did I miss? How can I fix the error TS is throwing?
",https://stackoverflow.com/questions/52759220/importing-images-in-typescript-react-cannot-find-module,260,291645.0,24.0,,,2018-10-11 11:42:33,2025-04-01 09:53:01,2018-10-11 21:38:26,,,reactjs;typescript;vs-code;bundler;parceljs,John,3275,10346978,registered,true,52760666,,CC BY-SA 4.0,,1368,1104,14,0,0,5,true,false,false,true,true,true,69,9,false,0.082,0.0009,2963,2018,10,11,Thursday,false,false,false,false,false,false,false
62702485,Component cannot be used as a JSX component. Its return type 'Element[]' is not a valid JSX element,"The following error occurs in the Todos component inside the TodoApp.tsx:
'Todos' cannot be used as a JSX component.
Its return type 'Element[]' is not a valid JSX element.
Type 'Element[]' is missing the following properties from type 'Element': type, props, key
Corresponding files:
TodoApp.tsx
function TodoApp() {
return (
<Body>
<AppDiv>
<Form />
<Todos />
<Footer />
</AppDiv>
</Body>
);
}
Todos.tsx
function Todos(): JSX.Element[] {
const todos = useSelector((state: RootState) => state.todos);
const footer = useSelector((state: RootState) => state.footer);
if (footer.hideAll) {
if (footer.showCompleted) {
return todos
.filter((todo) => !todo.completed)
.map((todo: any) => (
<>
<ul>
<Todo todo={todo} />
</ul>
</>
));
}
return todos.map((todo) => (
<>
<div>
<Todo todo={todo} />
</div>
</>
));
}
return todos.map(() => (
<>
<div></div>
</>
));
}
Todo.tsx
type Todo = {
todo: TodoProps;
};
const Todo = ({ todo }: Todo) : JSX.Element => {
const [isEditing, edit] = useState<boolean>(false);
const dispatch = useDispatch();
if (!isEditing) {
return (
<TodoDiv>
<Li
key={todo.id}
completed={todo.completed}
onClick={() => dispatch(completeTodo(todo.id))}
// style={{
// textDecoration: todo.completed ? "line-through" : "none"
// }}
>
{todo.text}
</Li>
<TodoBttns>
<Button edit onClick={() => edit(!isEditing)}>
<img src={editBttn} alt="Edit Button" />
</Button>
<Button delete onClick={() => dispatch(deleteTodo(todo.id))}>
<img src={deleteBttn} alt="Delete Button" />
</Button>
</TodoBttns>
</TodoDiv>
);
} else {
return (
<FormEdit>
<InputForm key={todo.id} {...{ todo, edit }} />
</FormEdit>
);
}
};
and the TodoProps interface is defined as follows
interface TodoProps {
text: string;
completed: boolean;
id: string;
}
I have tried fixing it by wrapping the map of items with fragments, but the error is still thrown. The only thing that as of now is fixing the issue is declaring at the top of Todos.tsx the function as any: function Todos(): any
As a side note: I'm using StyledComponents, but I don't think the issue is related to the library.
",https://stackoverflow.com/questions/62702485/component-cannot-be-used-as-a-jsx-component-its-return-type-element-is-not,260,653512.0,28.0,,,2020-07-02 18:02:47,2026-09-01 22:05:02,2023-11-17 10:16:18,,,reactjs;typescript,Ramiro Herrera,3019,13144521,registered,true,,,CC BY-SA 4.0,,3118,2825,14,0,0,2,false,false,false,true,true,true,107,18,false,0.043,0.0004,2333,2020,7,18,Thursday,false,false,false,false,false,false,false
34114350,React vs ReactDOM?,"I'm a bit new to react. I see we have to import two things to get started, React and ReactDOM, can anyone explain the difference. I'm reading through the React documentation, but it doesn't say.
",https://stackoverflow.com/questions/34114350/react-vs-reactdom,260,93362.0,7.0,,,2015-12-06 05:21:08,2025-06-03 06:47:42,2022-04-08 10:12:40,,,reactjs;react-dom,Noitidart,37728,1828637,registered,true,34114665,,CC BY-SA 4.0,2025-06-03 07:24:59,284,195,2,1,0,2,true,false,false,true,true,true,18,3,true,0.075,0.0028,4003,2015,12,5,Sunday,true,false,false,false,false,false,false
42573017,"In React ES6, why does the input field lose focus after typing a character?","In my component below, the input field loses focus after typing a character. While using Chrome's Inspector, it looks like the whole form is being re-rendered instead of just the value attribute of the input field when typing.
I get no errors from either eslint nor Chrome Inspector.
Submitting the form itself works as does the actual input field when it is located either in the render's return or while being imported as a separate component but not in how I have it coded below.
Why is this so?
Main Page Component
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as actionPost from '../redux/action/actionPost';
import InputText from './form/InputText';
import InputSubmit from './form/InputSubmit';
class _PostSingle extends Component {
constructor(props, context) {
super(props, context);
this.state = {
post: {
title: '',
},
};
this.onChange = this.onChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
onChange(event) {
this.setState({
post: {
title: event.target.value,
},
});
}
onSubmit(event) {
event.preventDefault();
this.props.actions.postCreate(this.state.post);
this.setState({
post: {
title: '',
},
});
}
render() {
const onChange = this.onChange;
const onSubmit = this.onSubmit;
const valueTitle = this.state.post.title;
const FormPostSingle = () => (
<form onSubmit={onSubmit}>
<InputText name=""title"" label=""Title"" placeholder=""Enter a title"" onChange={onChange} value={valueTitle} />
<InputSubmit name=""Save"" />
</form>
);
return (
<main id=""main"" role=""main"">
<div className=""container-fluid"">
<FormPostSingle />
</div>
</main>
);
}
}
_PostSingle.propTypes = {
actions: PropTypes.objectOf(PropTypes.func).isRequired,
};
function mapStateToProps(state) {
return {
posts: state.posts,
};
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(actionPost, dispatch),
};
}
export default connect(mapStateToProps, mapDispatchToProps)(_PostSingle);
Text Input Component
import React, { PropTypes } from 'react';
const InputText = ({ name, label, placeholder, onChange, value, error }) => {
const fieldClass = 'form-control input-lg';
let wrapperClass = 'form-group';
if (error && error.length > 0) {
wrapperClass += ' has-error';
}
return (
<div className={wrapperClass}>
<label htmlFor={name} className=""sr-only"">{label}</label>
<input type=""text"" id={name} name={name} placeholder={placeholder} onChange={onChange} value={value} className={fieldClass} />
{error &&
<div className=""alert alert-danger"">{error}</div>
}
</div>
);
};
InputText.propTypes = {
name: PropTypes.string.isRequired,
label: PropTypes.string.isRequired,
placeholder: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired,
value: PropTypes.string,
error: PropTypes.string,
};
InputText.defaultProps = {
value: null,
error: null,
};
export default InputText;
Submit Button Component
import React, { PropTypes } from 'react';
const InputSubmit = ({ name }) => {
const fieldClass = 'btn btn-primary btn-lg';
return (
<input type=""submit"" value={name} className={fieldClass} />
);
};
InputSubmit.propTypes = {
name: PropTypes.string,
};
InputSubmit.defaultProps = {
name: 'Submit',
};
export default InputSubmit;
",https://stackoverflow.com/questions/42573017/in-react-es6-why-does-the-input-field-lose-focus-after-typing-a-character,259,229747.0,35.0,,,2017-03-03 07:25:25,2024-05-06 08:45:52,,,,reactjs;text;input;ecmascript-6;focus,spunge,3117,4397087,registered,true,,,CC BY-SA 3.0,2021-12-23 21:46:59,4203,4031,3,0,0,5,false,false,false,true,true,false,75,14,true,0.152,0.0011,3550,2017,3,7,Friday,false,false,false,false,false,false,false
48308936,What does this "react-scripts eject" command do?,"What does the npm run eject command do? I do understand what other commands do like start, build, test. But no idea about eject.
",https://stackoverflow.com/questions/48308936/what-does-this-react-scripts-eject-command-do,259,183315.0,5.0,,,2018-01-17 19:52:10,2021-07-09 16:53:05,2018-09-11 21:58:58,,,reactjs;webpack;create-react-app;react-scripts,Ishan Patel,6179,8936320,registered,true,50229543,,CC BY-SA 4.0,,150,130,1,0,0,4,true,false,false,true,true,true,58,7,true,0.027,0.0014,3230,2018,1,19,Wednesday,false,false,false,false,false,false,false
34582405,React won't load local images,"I am building a small react app and my local images won't load. Images like placehold.it/200x200 loads. I thought maybe it could be something with the server?
Here is my App.js
import React, { Component } from 'react';
class App extends Component {
render() {
return (
<div className=""home-container"">
<div className=""home-content"">
<div className=""home-text"">
<h1>foo</h1>
</div>
<div className=""home-arrow"">
<p className=""arrow-text"">
Vzdělání
</p>
<img src={""/images/resto.png""} />
</div>
</div>
</div>
);
}
}
export default App;
index.js:
import React, { Component } from 'react';
import { render } from 'react-dom';
import { Router, Route, Link } from 'react-router';
import { createHistory } from 'history';
import App from './components/app';
let history = createHistory();
render(
<Router history={history} >
<Route path=""/"" component={App} >
<Route path=""vzdelani"" component="""" />
<Route path=""znalosti"" component="""" />
<Route path=""prace"" component="""" />
<Route path=""kontakt"" component="""" />
</Route>
<Route path=""*"" component="""" />
</Router>,
document.getElementById('app')
);
and server.js:
var path = require('path');
var express = require('express');
var webpack = require('webpack');
var config = require('./webpack.config.dev');
var app = express();
var compiler = webpack(config);
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true,
publicPath: config.output.publicPath
}));
app.use(require('webpack-hot-middleware')(compiler));
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
});
app.listen(3000, 'localhost', function(err) {
if (err) {
console.log(err);
return;
}
console.log('Listening at http://localhost:3000');
});
",https://stackoverflow.com/questions/34582405/react-wont-load-local-images,258,661261.0,24.0,,,2016-01-03 22:32:02,2022-11-09 05:53:30,2020-04-01 08:06:36,,,javascript;reactjs,Petrba,2593,5547218,registered,true,34583854,,CC BY-SA 4.0,2020-11-07 07:55:10,2343,2230,4,0,0,2,true,false,false,true,true,true,33,5,false,0.036,0.0004,3975,2016,1,22,Sunday,true,false,true,false,false,false,false
53090432,React hooks - right way to clear timeouts and intervals,"I don't understand why is when I use setTimeout function my react component start to infinite console.log. Everything is working, but PC start to lag as hell.
Some people saying that function in timeout changing my state and that rerender component, that sets new timer and so on. Now I need to understand how to clear it's right.
export default function Loading() {
// if data fetching is slow, after 1 sec i will show some loading animation
const [showLoading, setShowLoading] = useState(true)
let timer1 = setTimeout(() => setShowLoading(true), 1000)
console.log('this message will render every second')
return 1
}
Clear in different version of code not helping to:
const [showLoading, setShowLoading] = useState(true)
let timer1 = setTimeout(() => setShowLoading(true), 1000)
useEffect(
() => {
return () => {
clearTimeout(timer1)
}
},
[showLoading]
)
",https://stackoverflow.com/questions/53090432/react-hooks-right-way-to-clear-timeouts-and-intervals,258,458876.0,11.0,,,2018-10-31 19:09:29,2025-04-18 10:39:42,2019-06-07 08:46:41,,,javascript;reactjs;settimeout;react-hooks,ZiiMakc,37836,10188661,registered,true,53090848,,CC BY-SA 4.0,2023-05-28 11:10:25,998,923,3,0,0,4,true,false,false,true,true,true,55,10,false,0.024,0.0006,2943,2018,10,19,Wednesday,false,false,true,false,false,false,false
40987309,React - Display loading screen while DOM is rendering?,"This is an example from the Google AdSense application page. The loading screen is displayed before the main page is shown.
I am not sure how to achieve the same effect with React because if I render the loading screen as a React component, it will not be displayed while the page is loading as it needs to wait for the DOM to be rendered first.
Updated:
As a solution, I tried an approach where I placed the screen loader in index.html file and removed it in the componentDidMount() lifecycle method of React component.
Example and react-loading-screen.
",https://stackoverflow.com/questions/40987309/react-display-loading-screen-while-dom-is-rendering,257,632176.0,25.0,,,2016-12-06 03:23:50,2024-01-18 04:13:03,2023-04-25 01:35:24,,,reactjs;asynchronous;redux;react-dom,Thanh Nguyen,5362,1550476,registered,true,40988672,,CC BY-SA 4.0,,932,556,2,3,1,4,true,false,false,true,true,true,54,9,true,0.04,0.0004,3637,2016,12,3,Tuesday,false,false,false,false,false,false,false
59988667,TypeScript React.FC<Props> confusion,"I am learning TypeScript and some bits are confusing to me. One bit is below:
interface Props {
name: string;
}
const PrintName: React.FC<Props> = (props) => {
return (
<div>
<p style={{ fontWeight: props.priority ? "bold" : "normal" }}>
{props.name}
</p>
</div>
)
}
const PrintName2 = (props: Props) => {
return (
<div>
<p style={{ fontWeight: props.priority ? "bold" : "normal" }}>
{props.name}
</p>
</div>
)
}
For both functional components above, I see TypeScript generates the same JS code. The PrintName2 component seems more streamlined to me as far as readability. I wonder what's the difference between the two definitions and if anyone is using second type of React component?
",https://stackoverflow.com/questions/59988667/typescript-react-fcprops-confusion,257,424060.0,5.0,,,2020-01-30 14:52:54,2025-10-15 21:26:00,2022-01-28 12:23:21,,,javascript;reactjs;typescript;react-functional-component,Kuldeep Bora,5070,5483873,registered,true,59991281,,CC BY-SA 4.0,,944,856,2,0,0,4,true,false,false,true,true,true,42,3,false,0.012,0.0006,2487,2020,1,14,Thursday,false,false,true,false,false,false,false
56547215,react-testing-library why is toBeInTheDocument() not a function,"Here is my code for a tooltip that toggles the CSS property display: block on MouseOver and on Mouse Out display: none.
it('should show and hide the message using onMouseOver and onMouseOut events respectively', () => {
const { queryByTestId, queryByText } = render(
<Tooltip id="test" message="test" />,
)
fireEvent.mouseOver(queryByTestId('tooltip'))
expect(queryByText('test')).toBeInTheDocument()
fireEvent.mouseOut(queryByTestId('tooltip'))
expect(queryByText('test')).not.toBeInTheDocument()
cleanup()
})
I keep getting the error TypeError: expect(...).toBeInTheDocument is not a function
Has anyone got any ideas why this is happening? My other tests to render and snapshot the component all work as expected. As do the queryByText and queryByTestId.
",https://stackoverflow.com/questions/56547215/react-testing-library-why-is-tobeinthedocument-not-a-function,254,303512.0,20.0,,,2019-06-11 15:36:31,2026-02-08 18:59:52,2021-09-20 21:14:23,,,javascript;reactjs;unit-testing;jestjs;react-testing-library,dorriz,2769,6511990,registered,true,56557915,,CC BY-SA 4.0,,897,826,3,0,0,5,true,false,false,true,true,true,63,7,false,0.066,0.0008,2720,2019,6,15,Tuesday,false,false,true,false,false,false,false
67652612,ChunkLoadError: Loading chunk node_modules_next_dist_client_dev_noop_js failed,"I've been following the basics tutorial on the Next.js website and when I got to the Global Styles step, I started getting the following runtime error:
ChunkLoadError: Loading chunk node_modules_next_dist_client_dev_noop_js failed.
(error: http://localhost:3000/_next/static/chunks/fallback/node_modules_next_dist_client_dev_noop_js.js)
I followed all the steps exactly and when I close the error pop-up, the app works fine.
If anyone can provide any guidance on this I'd appreciate it a lot!
",https://stackoverflow.com/questions/67652612/chunkloaderror-loading-chunk-node-modules-next-dist-client-dev-noop-js-failed,254,160633.0,10.0,,,2021-05-22 17:55:10,2025-09-05 07:03:23,2021-11-11 13:47:39,,,javascript;node.js;reactjs;next.js,Abdullah Raja,2533,15988162,registered,true,67659159,,CC BY-SA 4.0,2021-09-28 12:15:35,962,514,1,3,2,4,true,false,false,true,true,true,78,5,false,0.062,0.0016,2009,2021,5,17,Saturday,true,false,true,false,false,false,false
75337953,What causes NextJS Warning: "Extra attributes from the server: data-new-gr-c-s-check-loaded... ","I am getting the following warning from my Next.js application:
Warning: Extra attributes from the server: data-new-gr-c-s-check-loaded,data-gr-ext-installed,cz-shortcut-listen,data-lt-installed
I don't know why it happens. What is the explanation for this?
",https://stackoverflow.com/questions/75337953/what-causes-nextjs-warning-extra-attributes-from-the-server-data-new-gr-c-s-c,253,207195.0,21.0,,,2023-02-03 15:38:07,2025-10-11 13:13:21,2025-10-11 13:12:30,,,javascript;reactjs;ecmascript-6;next.js,Md Sajedul Islam,2949,18383895,registered,true,76480526,,CC BY-SA 4.0,2023-12-17 23:44:55,306,260,0,0,0,4,true,false,false,true,true,true,106,11,false,0.101,0.0012,1387,2023,2,15,Friday,false,false,true,false,false,false,false
70358643,"You are running create-react-app 4.0.3 which is behind the latest release (5.0.0)","I got an error while creating a React application. How do I fix it?
",https://stackoverflow.com/questions/70358643/you-are-running-create-react-app-4-0-3-which-is-behind-the-latest-release-5-0,252,118191.0,6.0,,,2021-12-15 04:58:02,2022-01-04 21:12:50,2022-01-01 22:29:30,2021-12-15 16:47:06,Duplicate,javascript;reactjs;npm-install;yarnpkg;npx,Athif Saheer,4637,14426381,registered,true,70358793,,,,226,69,0,1,1,5,true,true,false,true,true,true,93,12,false,0.051,0.0021,1802,2021,12,4,Wednesday,false,false,true,false,false,false,false
52005083,How to define css variables in style attribute in React and TypeScript,"I want to define jsx like this:
<table style={{'--length': array.length}}>
<tbody>
<tr>{array}</tr>
</tbody>
</table>
and I use --length in CSS, I also have cells that have --count that shows count using CSS pseudo selector (using the counter hack).
but typescript throws an error:
TS2326: Types of property 'style' are incompatible.
Type '{ '--length': number; }' is not assignable to type 'CSSProperties'.
Object literal may only specify known properties, and ''--length'' does not exist in type 'CSSProperties'.
is it possible to change the type of style attribute to accept CSS variables (custom properties) or is there a way to force any on the style object?
",https://stackoverflow.com/questions/52005083/how-to-define-css-variables-in-style-attribute-in-react-and-typescript,252,229321.0,11.0,,,2018-08-24 13:00:09,2026-01-31 18:01:03,2024-06-14 23:39:05,,,reactjs;typescript;jsx;tsx,jcubic,67434,387194,registered,true,65959390,,CC BY-SA 4.0,,822,720,4,0,0,4,true,false,false,true,true,true,70,12,false,0.048,0.0011,3011,2018,8,13,Friday,false,false,false,false,false,false,false
32414308,Updating state on props change in React Form,"I am having trouble with a React form and managing the state properly. I have a time input field in a form (in a modal). The initial value is set as a state variable in getInitialState, and is passed in from a parent component. This in itself works fine.
The problem comes when I want to update the default start_time value through the parent component. The update itself happens in the parent component through setState start_time: new_time. However in my form, the default start_time value never changes, since it is only defined once in getInitialState.
I have tried to use componentWillUpdate to force a change in state through setState start_time: next_props.start_time, which did actually work, but it gave me Uncaught RangeError: Maximum call stack size exceeded errors.
So my question is, what's the correct way of updating state in this case? Am I thinking about this wrong somehow?
Current Code:
@ModalBody = React.createClass
getInitialState: ->
start_time: @props.start_time.format("HH:mm")
#works but takes long and causes:
#"Uncaught RangeError: Maximum call stack size exceeded"
componentWillUpdate: (next_props, next_state) ->
@setState(start_time: next_props.start_time.format("HH:mm"))
fieldChanged: (fieldName, event) ->
stateUpdate = {}
stateUpdate[fieldName] = event.target.value
@setState(stateUpdate)
render: ->
React.DOM.div
className: "modal-body"
React.DOM.form null,
React.createElement FormLabelInputField,
type: "time"
id: "start_time"
label_name: "Start Time"
value: @state.start_time
onChange: @fieldChanged.bind(null, "start_time")
@FormLabelInputField = React.createClass
render: ->
React.DOM.div
className: "form-group"
React.DOM.label
htmlFor: @props.id
@props.label_name + ": "
React.DOM.input
className: "form-control"
type: @props.type
id: @props.id
value: @props.value
onChange: @props.onChange
",https://stackoverflow.com/questions/32414308/updating-state-on-props-change-in-react-form,252,389897.0,15.0,,,2015-09-05 14:39:45,2023-06-07 16:01:37,2021-07-12 03:50:18,,,reactjs,David Basalla,3106,1348923,registered,true,32414771,,CC BY-SA 4.0,,2300,2150,8,0,0,1,true,false,false,true,true,true,44,8,false,0.038,0.0006,4095,2015,9,14,Saturday,true,false,false,false,false,false,false
56028913,useMemo vs. useEffect + useState,"Are there any benefits in using useMemo (e.g. for an intensive function call) instead of using a combination of useEffect and useState?
Here are two custom hooks that work exactly the same on first sight, besides useMemo's return value being null on the first render:
useEffect & useState
import { expensiveCalculation } from "foo";
function useCalculate(someNumber: number): number | null {
const [result, setResult] = useState<number | null>(null);
useEffect(() => {
setResult(expensiveCalculation(someNumber));
}, [someNumber]);
return result;
}
useMemo
import { expensiveCalculation } from "foo";
function useCalculateWithMemo(someNumber: number): number {
return useMemo(() => {
return expensiveCalculation(someNumber);
}, [someNumber]);
};
Both calculate the result each time their parameter someNumber changes, where is the memoization of useMemo kicking in?
",https://stackoverflow.com/questions/56028913/usememo-vs-useeffect-usestate,251,196490.0,4.0,,,2019-05-07 18:58:00,2024-04-11 15:43:36,2022-12-02 14:42:18,,,javascript;reactjs;typescript;react-hooks,Bennett Dams,7183,9414171,registered,true,56029184,,CC BY-SA 4.0,,1358,937,9,1,1,4,true,false,false,true,true,true,32,5,false,0.02,0.0013,2755,2019,5,18,Tuesday,false,false,true,false,false,false,false
41746028,PropTypes in a TypeScript React Application,"Does using React.PropTypes make sense in a TypeScript React Application or is this just a case of ""belt and suspenders""?
Since the component class is declared with a Props type parameter:
interface Props {
// ...
}
export class MyComponent extends React.Component<Props, any> { ... }
is there any real benefit to adding
static propTypes {
myProp: React.PropTypes.string
}
to the class definition?
",https://stackoverflow.com/questions/41746028/proptypes-in-a-typescript-react-application,250,155736.0,6.0,,,2017-01-19 15:45:55,2022-06-28 20:20:44,,,,reactjs;typescript;react-proptypes,Ralph,32414,96233,registered,true,43187969,,CC BY-SA 3.0,,520,418,4,0,0,3,true,false,false,true,true,false,43,6,false,0.039,0.0016,3593,2017,1,15,Thursday,false,false,false,false,false,false,false
32021763,What could be the downsides of using Redux instead of Flux,"I just recently discovered Redux. It all looks good. Are there any downsides, gotcha or compromises of using Redux over Flux? Thanks
",https://stackoverflow.com/questions/32021763/what-could-be-the-downsides-of-using-redux-instead-of-flux,250,39790.0,7.0,,,2015-08-15 05:12:40,2019-04-17 19:16:08,2017-12-26 00:59:02,2019-04-17 20:05:49,Opinion-based,reactjs;redux;flux;reactjs-flux,Ivan Wang,8475,1401634,registered,true,32916602,,,,204,133,0,1,0,4,true,true,false,true,true,true,58,11,false,0.176,0.0063,4116,2015,8,5,Saturday,true,false,false,false,false,false,false
53574614,Multiple calls to state updater from useState in component causes multiple re-renders,"I'm trying React hooks for the first time and all seemed good until I realised that when I get data and update two different state variables (data and loading flag), my component (a data table) is rendered twice, even though both calls to the state updater are happening in the same function. Here is my api function which is returning both variables to my component.
const getData = url => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(async () => {
const test = await api.get('/people')
if(test.ok){
setLoading(false);
setData(test.data.results);
}
}, []);
return { data, loading };
};
In a normal class component you'd make a single call to update the state which can be a complex object but the ""hooks way"" seems to be to split the state into smaller units, a side effect of which seems to be multiple re-renders when they are updated separately. Any ideas how to mitigate this?
",https://stackoverflow.com/questions/53574614/multiple-calls-to-state-updater-from-usestate-in-component-causes-multiple-re-re,250,242743.0,9.0,,,2018-12-01 20:06:59,2022-08-03 06:02:38,2018-12-01 21:04:19,,,javascript;reactjs;react-hooks,jonhobbs,28286,56007,registered,true,53575023,,CC BY-SA 4.0,,1056,1018,1,0,0,3,true,false,false,true,true,true,85,12,false,0.037,0.001,2912,2018,12,20,Saturday,true,false,true,false,false,false,false
48240449,Type '{}' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes,"i am currently making a simple react application.
this is my index.tsx
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import App from './components/App';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(
<App />,
document.getElementById('root') as HTMLElement
);
registerServiceWorker();
and here I have my app.tsx
import * as React from 'react';
import SearchBar from '../containers/price_search_bar';
interface Props {
term: string;
}
class App extends React.Component<Props> {
// tslint:disable-next-line:typedef
constructor(props) {
super(props);
this.state = {term: '' };
}
render() {
return (
<div className=""App"">
<div className=""App-header"">
<h2>Welcome to React</h2>
</div>
<p className=""App-intro"">
this is my application.
</p>
<div>
<form>
<SearchBar term={this.props.term} />
</form>
</div>
</div>
);
}
}
export default App;
and also my search bar container:
import * as React from 'react';
interface Props {
term: string;
}
// tslint:disable-next-line:no-any
class SearchBar extends React.Component<Props> {
// tslint:disable-next-line:typedef
constructor(props) {
super(props);
this.state = { term: '' };
}
public render() {
return(
<form>
<input
placeholder=""search for base budget""
className=""form-control""
value={this.props.term}
/>
<span className=""input-group-btn"" >
<button type=""submit"" className=""btn btn-secondary"" >
Submit
</button>
</span>
</form>
);
}
}
export default SearchBar;
and finally I have my tsconfig.json:
{
""compilerOptions"": {
""outDir"": ""build/dist"",
""module"": ""esnext"",
""target"": ""es5"",
""lib"": [""es6"", ""dom""],
""sourceMap"": true,
""allowJs"": true,
""jsx"": ""react"",
""moduleResolution"": ""node"",
""rootDir"": ""src"",
""forceConsistentCasingInFileNames"": true,
""noImplicitReturns"": true,
""noImplicitThis"": true,
""noImplicitAny"": false,
""strictNullChecks"": true,
""suppressImplicitAnyIndexErrors"": true,
""typeRoots"": [
""node_modules/@types""
],
""noUnusedLocals"": true
},
""exclude"": [
""node_modules"",
""build"",
""scripts"",
""acceptance-tests"",
""webpack"",
""jest"",
""src/setupTests.ts""
]
}
I keep getting different errors after errors and when ever I fix one error another one appears, I am not sure what I have done that make it behave like this.
This is the latest error:
./src/index.tsx
(7,3): error TS2322: Type '{}' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<App> & Readonly<{ children?: ReactNode; }> & Reado...'.
Type '{}' is not assignable to type 'Readonly<Props>'.
Property 'term' is missing in type '{}'.
I tried to fix it by modifying my tsconfig.json but the same error still appears, what am I doing wrong and why typescript is bahing like this. I am very new to this and by this example I am trying to udnertand how react works all together.
",https://stackoverflow.com/questions/48240449/type-is-not-assignable-to-type-intrinsicattributes-intrinsicclassattribu,250,581744.0,23.0,,,2018-01-13 13:43:07,2025-04-26 16:07:43,2018-01-13 14:53:17,,,json;reactjs;typescript,S. N,4089,865150,registered,true,57312722,,CC BY-SA 3.0,,3715,3501,9,0,0,3,true,false,false,true,true,true,99,10,false,0.04,0.0004,3234,2018,1,13,Saturday,true,false,false,false,false,false,false
49706823,What is {this.props.children} and when you should use it?,"Being a beginner to React world, I want to understand in depth what happens when I use {this.props.children} and what are the situations to use the same. What is the relevance of it in below code snippet?
render() {
if (this.props.appLoaded) {
return (
<div>
<Header
appName={this.props.appName}
currentUser={this.props.currentUser}
/>
{this.props.children}
</div>
);
}
}
",https://stackoverflow.com/questions/49706823/what-is-this-props-children-and-when-you-should-use-it,247,314614.0,8.0,,,2018-04-07 11:18:04,2023-03-13 15:57:53,2022-01-28 09:46:54,,,javascript;reactjs;react-redux,nim007,3068,950977,registered,true,49706920,,CC BY-SA 4.0,,504,460,2,0,0,3,true,false,false,true,true,true,57,9,true,0.025,0.0008,3150,2018,4,11,Saturday,true,false,true,false,false,false,false
33272967,How to make the webpack dev server run on port 80 and on 0.0.0.0 to make it publicly accessible?,"I am new to the whole nodejs/reactjs world so apologies if my question sounds silly. I am currently playing around with reactabular.js.
Whenever I do a npm start it always runs on localhost:8080.
How do I change it to run on 0.0.0.0:8080 to make it publicly accessible? I have been trying to read the source code in the above repo but failed to find the file which sets this setting.
Also, to add to that - how do I make it run on port 80 if that is at all possible?
",https://stackoverflow.com/questions/33272967/how-to-make-the-webpack-dev-server-run-on-port-80-and-on-0-0-0-0-to-make-it-publ,246,420893.0,14.0,,,2015-10-22 03:35:49,2023-04-10 21:14:21,2023-04-10 21:14:21,,,node.js;reactjs;npm;webpack;webpack-dev-server,90abyss,7437,3188761,registered,true,33273459,,CC BY-SA 4.0,,655,467,4,1,0,5,true,false,false,true,true,true,96,19,true,0.033,0.0006,4048,2015,10,3,Thursday,false,false,false,false,false,false,false
70368760,React Uncaught ReferenceError: process is not defined,"I am getting issues with iframe.
Till today everything was working as expected. Today I added a very simple Modal component and somehow iframe started appearing. It appears when I am editing the file and hot reload is done. Also with this issue, it's showing an error in Console as "Uncaught ReferenceError: process is not defined".
Can someone please help me with this?
import React, {useEffect} from 'react';
import ReactDOM from "react-dom";
import Close from "../static/assets/close-white.svg"
const trapStyles = {
position: 'absolute',
opacity: 0
}
const Test = () => {
return ReactDOM.createPortal(
<div data-react-modal-body-trap="" tabIndex="0" style={trapStyles}/>,
document.getElementById("app")
)
}
const Modal = ({ open, onClose, children }) => {
useEffect(() => {
if (open)document.getElementById("app").classList.add("ReactModal__Body--open");
return () => {
document.getElementById("app").classList.remove("ReactModal__Body--open")
}
})
if (!open) return null
return ReactDOM.createPortal(
<>
<Test />
<div className="ReactModal__Overlay--after-open">
<div className="modal-form-page"
tabIndex="-1" role="dialog" aria-modal="true">
<button onClick={onClose} className="close-modal">
<img id="close-button" alt="close" src={Close}/>
</button>
{ children }
</div>
</div>
</>,
document.getElementById("ModalPortal")
)
};
export default Modal;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<link href="%PUBLIC_URL%/favicon.ico" rel="icon"/>
<meta content="width=device-width, initial-scale=1" name="viewport"/>
<meta content="#000000" name="theme-color"/>
<link href="%PUBLIC_URL%/logo192.png" rel="apple-touch-icon"/>
<link href="%PUBLIC_URL%/manifest.json" rel="manifest"/>
<title>React App</title>
</head>
<body id="app">
<noscript>You need to enable javascript to run this website</noscript>
<div id="content">
<-- All other content render here -->
</div>
<div class="ReactModalPortal" id="ModalPortal"></div>
</body>
</html>
Uncaught ReferenceError: process is not defined
at Object.4043 (<anonymous>:2:13168)
at r (<anonymous>:2:306599)
at Object.8048 (<anonymous>:2:9496)
at r (<anonymous>:2:306599)
at Object.8641 (<anonymous>:2:1379)
at r (<anonymous>:2:306599)
at <anonymous>:2:315627
at <anonymous>:2:324225
at <anonymous>:2:324229
at HTMLIFrameElement.e.onload (index.js:1)
4043 @ VM128:2
r @ VM128:2
8048 @ VM128:2
r @ VM128:2
8641 @ VM128:2
r @ VM128:2
(anonymous) @ VM128:2
(anonymous) @ VM128:2
(anonymous) @ VM128:2
e.onload @ index.js:1
be @ index.js:1
he @ index.js:1
tryDismissErrorOverlay @ webpackHotDevClient.js:184
onHotUpdateSuccess @ webpackHotDevClient.js:109
handleApplyUpdates @ webpackHotDevClient.js:257
(anonymous) @ webpackHotDevClient.js:273
load (async)
be @ index.js:1
he @ index.js:1
tryDismissErrorOverlay @ webpackHotDevClient.js:184
onHotUpdateSuccess @ webpackHotDevClient.js:109
handleApplyUpdates @ webpackHotDevClient.js:257
(anonymous) @ webpackHotDevClient.js:273
Promise.then (async)
tryApplyUpdates @ webpackHotDevClient.js:271
handleSuccess @ webpackHotDevClient.js:106
push../node_modules/react-dev-utils/webpackHotDevClient.js.connection.onmessage @ webpackHotDevClient.js:203
",https://stackoverflow.com/questions/70368760/react-uncaught-referenceerror-process-is-not-defined,246,380466.0,35.0,,,2021-12-15 18:37:56,2025-05-08 13:12:35,2022-03-15 07:51:33,,,reactjs,Manishkumar Adesara,2697,14880787,registered,true,,,CC BY-SA 4.0,,4214,4135,3,0,0,1,false,false,false,true,true,true,53,7,false,0.092,0.0006,1802,2021,12,18,Wednesday,false,false,false,false,false,false,false
38619981,How can I prevent event bubbling in nested React components on click?,"Here's a basic component. Both the <ul> and <li> have onClick functions. I want only the onClick on the <li> to fire, not the <ul>. How can I achieve this?
I've played around with e.preventDefault(), e.stopPropagation(), to no avail.
class List extends React.Component {
constructor(props) {
super(props);
}
handleClick() {
// do something
}
render() {
return (
<ul
onClick={(e) => {
console.log('parent');
this.handleClick();
}}
>
<li
onClick={(e) => {
console.log('child');
// prevent default? prevent propagation?
this.handleClick();
}}
>
</li>
</ul>
)
}
}
// => parent
// => child
",https://stackoverflow.com/questions/38619981/how-can-i-prevent-event-bubbling-in-nested-react-components-on-click,245,262611.0,12.0,,,2016-07-27 17:51:19,2024-09-15 15:51:27,2021-03-11 17:43:05,,,reactjs;onclick;event-propagation,dmwong2268,3655,5209122,registered,true,39330942,,CC BY-SA 4.0,,914,824,5,0,0,3,true,false,false,true,true,true,69,12,true,0.046,0.0009,3769,2016,7,17,Wednesday,false,false,false,false,false,false,false
29577977,Unable to access React instance (this) inside event handler,"I am writing a simple component in ES6 (with BabelJS), and functions this.setState is not working.
Typical errors include something like
Cannot read property 'setState' of undefined
or
this.setState is not a function
Do you know why? Here is the code:
import React from 'react'
class SomeClass extends React.Component {
constructor(props) {
super(props)
this.state = {inputContent: 'startValue'}
}
sendContent(e) {
console.log('sending input content '+React.findDOMNode(React.refs.someref).value)
}
changeContent(e) {
this.setState({inputContent: e.target.value})
}
render() {
return (
<div>
<h4>The input form is here:</h4>
Title:
<input type=""text"" ref=""someref"" value={this.inputContent}
onChange={this.changeContent} />
<button onClick={this.sendContent}>Submit</button>
</div>
)
}
}
export default SomeClass
",https://stackoverflow.com/questions/29577977/unable-to-access-react-instance-this-inside-event-handler,244,89973.0,19.0,,,2015-04-11 12:41:38,2020-02-13 13:34:00,2016-09-22 14:05:09,2020-05-17 08:26:07,Duplicate,javascript;reactjs;ecmascript-6;babeljs,user3696212,3440,3696212,registered,true,29578232,,,,1104,975,2,0,0,4,true,true,false,true,true,true,59,9,false,0.211,0.0027,4242,2015,4,12,Saturday,true,false,true,false,false,false,false
54954091,How to use callback with useState hook in react,"I am using functional component with hooks. I need to update state in parent from a child. I am using a prop function in Parent.
All works fine except my prop function is getting the previous state and not the current state. My prop function gets executed before useState hook setting current state.
How can I can I wait for my call back function to be executed after useState call. I am looking for something like setState(state,callback) from class based components.
Here is the code snippet:
function Parent() {
const [Name, setName] = useState("""");
getChildChange = getChildChange.bind(this);
function getChildChange(value) {
setName(value);
}
return <div> {Name} :
<Child getChildChange={getChildChange} ></Child>
</div>
}
function Child(props) {
const [Name, setName] = useState("""");
handleChange = handleChange.bind(this);
function handleChange(ele) {
setName(ele.target.value);
props.getChildChange(collectState());
}
function collectState() {
return Name;
}
return (<div>
<input onChange={handleChange} value={Name}></input>
</div>);
}
",https://stackoverflow.com/questions/54954091/how-to-use-callback-with-usestate-hook-in-react,244,499149.0,8.0,,,2019-03-02 00:35:47,2022-11-24 16:59:19,2022-11-24 16:59:19,2020-09-12 22:55:49,Duplicate,javascript;reactjs;react-hooks,Atul,3493,8449956,registered,true,56394177,,,,1227,1155,1,0,0,3,true,true,false,true,true,true,47,9,false,0.016,0.0005,2821,2019,3,0,Saturday,true,false,true,false,false,false,false
34224007,Is there any downside to using .tsx instead of .ts all the times in typescript?,"I just start working on a React project with TypeScript and ask myself what should I do with regular class files? Should I use .ts or .tsx files and then I couldn't find any reason to do not using .tsx file all the times even when it's not a React project!
Is there any reason or specific situation that we shouldn't use .tsx files? if no, why TypeScript team add whole new extension?
",https://stackoverflow.com/questions/34224007/is-there-any-downside-to-using-tsx-instead-of-ts-all-the-times-in-typescript,244,159214.0,5.0,,,2015-12-11 12:50:39,2020-12-11 06:08:00,2020-04-05 11:21:44,,,javascript;reactjs;typescript,Ostad,2944,1864771,registered,true,54614279,,CC BY-SA 4.0,,454,388,4,0,0,3,true,false,false,true,true,true,79,15,true,0.031,0.0015,3998,2015,12,12,Friday,false,false,true,false,false,false,false
53179075,"With useEffect, how can I skip applying an effect upon the initial render?","With React's new Effect Hooks, I can tell React to skip applying an effect if certain values haven't changed between re-renders - Example from React's docs:
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]); // Only re-run the effect if count changes
But the example above applies the effect upon initial render, and upon subsequent re-renders where count has changed. How can I tell React to skip the effect on the initial render?
",https://stackoverflow.com/questions/53179075/with-useeffect-how-can-i-skip-applying-an-effect-upon-the-initial-render,243,240224.0,12.0,,,2018-11-06 19:54:59,2024-08-08 10:02:05,2018-11-06 21:13:35,,,reactjs;react-hooks,uturnr,2876,8475103,registered,true,53180013,,CC BY-SA 4.0,,518,467,2,0,0,2,true,false,false,true,true,true,74,13,true,0.05,0.001,2937,2018,11,19,Tuesday,false,false,false,false,false,false,false
22538638,How to have conditional elements and keep DRY with Facebook React's JSX?,"How do I optionally include an element in JSX? Here is an example using a banner that should be in the component if it has been passed in. What I want to avoid is having to duplicate HTML tags in the if statement.
render: function () {
var banner;
if (this.state.banner) {
banner = <div id=""banner"">{this.state.banner}</div>;
} else {
banner = ?????
}
return (
<div id=""page"">
{banner}
<div id=""other-content"">
blah blah blah...
</div>
</div>
);
}
",https://stackoverflow.com/questions/22538638/how-to-have-conditional-elements-and-keep-dry-with-facebook-reacts-jsx,241,145894.0,28.0,,,2014-03-20 16:03:33,2021-06-14 16:54:50,2015-08-06 18:55:42,,,javascript;reactjs,Jack Allan,15094,315017,registered,true,22539106,,CC BY-SA 3.0,,627,596,1,0,0,2,true,false,false,true,true,true,76,12,true,0.192,0.0017,4629,2014,3,16,Thursday,false,false,true,false,false,false,false
30115324,Pass props in Link react-router,"I am using react with react-router.
I am trying to pass property’s in a ""Link"" of react-router
var React = require('react');
var Router = require('react-router');
var CreateIdeaView = require('./components/createIdeaView.jsx');
var Link = Router.Link;
var Route = Router.Route;
var DefaultRoute = Router.DefaultRoute;
var RouteHandler = Router.RouteHandler;
var App = React.createClass({
render : function(){
return(
<div>
<Link to=""ideas"" params={{ testvalue: ""hello"" }}>Create Idea</Link>
<RouteHandler/>
</div>
);
}
});
var routes = (
<Route name=""app"" path=""/"" handler={App}>
<Route name=""ideas"" handler={CreateIdeaView} />
<DefaultRoute handler={Home} />
</Route>
);
Router.run(routes, function(Handler) {
React.render(<Handler />, document.getElementById('main'))
});
The ""Link"" renders the page but does not pass the property to the new view.
Below is the view code
var React = require('react');
var Router = require('react-router');
var CreateIdeaView = React.createClass({
render : function(){
console.log('props form link',this.props,this)//props not recived
return(
<div>
<h1>Create Post: </h1>
<input type='text' ref='newIdeaTitle' placeholder='title'></input>
<input type='text' ref='newIdeaBody' placeholder='body'></input>
</div>
);
}
});
module.exports = CreateIdeaView;
How can I pass data using ""Link""?
",https://stackoverflow.com/questions/30115324/pass-props-in-link-react-router,240,585289.0,19.0,,,2015-05-08 03:35:14,2023-03-09 08:24:54,2017-09-25 23:22:38,,,javascript;reactjs;react-router,vishal atmakuri,2423,4534716,registered,true,30115524,,CC BY-SA 3.0,,1617,1548,2,0,0,3,true,false,false,true,true,true,31,5,false,0.032,0.0004,4215,2015,5,3,Friday,false,false,true,false,false,false,false
37282159,Default property value in React component using TypeScript,"I can't figure out how to set default property values for my components using Typescript.
This is the source code:
class PageState
{
}
export class PageProps
{
foo: string = ""bar"";
}
export class PageComponent extends React.Component<PageProps, PageState>
{
public render(): JSX.Element
{
return (
<span>Hello, world</span>
);
}
}
And when I try to use the component like this:
ReactDOM.render(<PageComponent />, document.getElementById(""page""));
I get an error saying property foo is missing. I want to use the default value. I've also tried to use static defaultProps = ... inside the component, but it had no effect as I suspected.
src/typescript/main.tsx(8,17): error TS2324: Property 'foo' is missing in type 'IntrinsicAttributes & IntrinsicClassAttributes<PageComponent> & PageProps & { children?: ReactEle...'.
How can I use default property values? Many JS components my company uses rely on them and not using them is not a choice.
",https://stackoverflow.com/questions/37282159/default-property-value-in-react-component-using-typescript,240,248352.0,12.0,,,2016-05-17 16:52:03,2023-03-07 09:34:22,,,,reactjs;typescript;tsx,Tom,2495,6145651,registered,true,37282264,,CC BY-SA 3.0,,1172,1039,5,0,0,3,true,false,false,true,true,false,58,8,false,0.048,0.001,3840,2016,5,16,Tuesday,false,false,false,false,false,false,false
58579426,"In useEffect, what's the difference between providing no dependency array and an empty one?","I gather that the useEffect Hook is run after every render, if provided with an empty dependency array:
useEffect(() => {
performSideEffect();
}, []);
But what's the difference between that, and the following?
useEffect(() => {
performSideEffect();
});
Notice the lack of [] at the end. The linter plugin doesn't throw a warning.
",https://stackoverflow.com/questions/58579426/in-useeffect-whats-the-difference-between-providing-no-dependency-array-and-an,240,134872.0,6.0,,,2019-10-27 12:28:09,2024-05-12 16:36:57,2020-02-13 15:40:19,,,reactjs;react-hooks;use-effect,Paul Razvan Berg,22636,3873510,registered,true,58579462,,CC BY-SA 4.0,,515,346,4,0,0,3,true,false,false,true,true,true,95,14,true,0.044,0.0018,2582,2019,10,12,Sunday,true,false,false,false,false,false,false
35762351,Correct way to handle conditional styling in React,"I'm doing some React right now and I was wondering if there is a ""correct"" way to do conditional styling. In the tutorial they use
style={{
textDecoration: completed ? 'line-through' : 'none'
}}
I prefer not to use inline styling so I want to instead use a class to control conditional styling. How would one approach this in the React way of thinking? Or should I just use this inline styling way?
",https://stackoverflow.com/questions/35762351/correct-way-to-handle-conditional-styling-in-react,238,450266.0,17.0,,,2016-03-03 02:58:16,2024-09-14 04:35:12,2016-03-03 03:13:40,,,javascript;reactjs,davidhtien,2628,2265097,registered,true,35762586,,CC BY-SA 3.0,2024-09-14 05:11:41,442,404,1,0,0,2,true,false,false,true,true,true,50,8,false,0.038,0.0005,3915,2016,3,2,Thursday,false,false,true,false,false,false,false
32646920,What's the '@' (at symbol) in the Redux @connect decorator?,"I am learning Redux with React and stumbled upon this code. I am not sure if it is Redux specific or not, but I have seen the following code snippet in one of the examples.
@connect((state) => {
return {
key: state.a.b
};
})
While the functionality of connect is pretty straightforward, but I don't understand the @ before connect. It isn't even a JavaScript operator if I am not wrong.
Can someone explain please what is this and why is it used?
Update:
It is in fact a part of react-redux which is used to connects a React component to a Redux store.
",https://stackoverflow.com/questions/32646920/whats-the-at-symbol-in-the-redux-connect-decorator,238,68487.0,2.0,,,2015-09-18 08:07:08,2017-08-11 22:14:16,2016-06-11 04:35:01,,,javascript;reactjs;decorator;redux,Salman,9437,1520671,registered,true,32675956,,CC BY-SA 3.0,,788,571,5,2,0,4,true,false,false,true,true,true,71,10,true,0.029,0.0035,4082,2015,9,8,Friday,false,false,true,false,false,false,false
37644265,Correct path for img on React.js,"I have some problem with my images on my react project. Indeed I always thought that relative path into src attribute was built on the files architecture
Here my files architecture:
components
file1.jsx
file2.jsx
file3.jsx
container
img
js
...
However I realized that the path is built on the url. In one of my component (for example into file1.jsx) I have this:
localhost/details/2
<img src=""../img/myImage.png"" /> -> works
localhost/details/2/id
<img src=""../img/myImage.png"" /> -> doesn't work, images are not displayed
How is it possible to solve this problem? I want that in any form of routes handled by react-router, all images can be displayed with the same path.
",https://stackoverflow.com/questions/37644265/correct-path-for-img-on-react-js,236,668010.0,14.0,,,2016-06-05 16:34:20,2025-01-24 10:17:11,2019-07-23 11:46:24,,,javascript;reactjs;webpack,onedkr,3396,5279661,registered,true,37644391,,CC BY-SA 4.0,2018-03-23 10:43:37,788,712,2,0,0,3,true,false,false,true,true,true,32,6,false,0.021,0.0004,3821,2016,6,16,Sunday,true,false,true,false,false,false,false
39830580,Jest test fails : TypeError: window.matchMedia is not a function,"This is my first front-end testing experience. In this project, I'm using Jest snapshot testing and got an error TypeError: window.matchMedia is not a function inside my component.
I go through Jest documentation, I found the "Manual mocks" section, but I have not any idea about how to do that yet.
",https://stackoverflow.com/questions/39830580/jest-test-fails-typeerror-window-matchmedia-is-not-a-function,236,183216.0,24.0,,,2016-10-03 11:31:28,2025-05-29 20:16:43,2020-10-13 18:52:52,,,reactjs;jestjs,TIJ,3301,3607091,registered,true,53449595,,CC BY-SA 4.0,,337,310,1,0,0,2,true,false,false,true,true,true,64,10,false,0.131,0.0013,3701,2016,10,11,Monday,false,false,false,false,false,false,false
53215285,How can I force a component to re-render with hooks?,"Considering below hooks example
import { useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Basically we use this.forceUpdate() method to force the component to re-render immediately in React class components like below example
class Test extends Component{
constructor(props){
super(props);
this.state = {
count:0,
count2: 100
}
this.setCount = this.setCount.bind(this);//how can I do this with hooks in functional component
}
setCount(){
let count = this.state.count;
count = count+1;
let count2 = this.state.count2;
count2 = count2+1;
this.setState({count});
this.forceUpdate();
//before below setState the component will re-render immediately when this.forceUpdate() is called
this.setState({count2: count
}
render(){
return (<div>
<span>Count: {this.state.count}></span>.
<button onClick={this.setCount}></button>
</div>
}
}
But my query is How can I force above functional component to re-render immediately with hooks?
",https://stackoverflow.com/questions/53215285/how-can-i-force-a-component-to-re-render-with-hooks,236,453725.0,20.0,,,2018-11-08 20:00:29,2025-07-01 10:10:24,2025-07-01 10:10:24,,,javascript;reactjs;react-native;react-hooks,Hemadri Dasari,34254,6903497,registered,true,53215514,,CC BY-SA 4.0,,1691,1622,2,0,0,4,true,false,false,true,true,true,52,10,true,0.044,0.0005,2935,2018,11,20,Thursday,false,false,true,false,false,false,false
59366833,Why VS Code contains emphasized items but no error?,"I'm writing a React project in VS code. I met this problem in VS code. In my project, this folder shows Contains emphasized items and I know it means there is an error in my files. But in the picture:
,
I have checked all files but no error was found. So this makes me feel confused.
I have searched this problem on google and found a similar GitHub issue. https://github.com/Microsoft/vscode/issues/54960
",https://stackoverflow.com/questions/59366833/why-vs-code-contains-emphasized-items-but-no-error,235,258374.0,28.0,,,2019-12-17 02:31:27,2025-05-02 16:53:44,2022-09-12 16:24:20,,,reactjs;vs-code,KimYu,2363,9850394,registered,true,59466953,,CC BY-SA 4.0,,599,407,0,1,1,2,true,false,false,true,true,true,51,9,true,0.108,0.0009,2531,2019,12,2,Tuesday,false,false,false,false,false,false,false
32070303,Uncaught ReferenceError: React is not defined,"I am trying to make ReactJS work with rails using this tutorial. I am getting this error:
Uncaught ReferenceError: React is not defined
But I can access the React object in browser console![]()
I also added public/dist/turbo-react.min.js as described here and also added //= require components line in application.js as described in this answer to no luck. Additionally,
var React = require('react') gives the error:
Uncaught ReferenceError: require is not defined
Can anyone suggest me on how to resolve this?
[EDIT 1]
Source code for reference:
This is my comments.js.jsx file:
var Comment = React.createClass({
render: function () {
return (
<div className=""comment"">
<h2 className=""commentAuthor"">
{this.props.author}
</h2>
{this.props.comment}
</div>
);
}
});
var ready = function () {
React.renderComponent(
<Comment author=""Richard"" comment=""This is a comment ""/>,
document.getElementById('comments')
);
};
$(document).ready(ready);
And this is my index.html.erb:
<div id=""comments""></div>
",https://stackoverflow.com/questions/32070303/uncaught-referenceerror-react-is-not-defined,235,455706.0,22.0,,,2015-08-18 10:48:28,2025-05-18 19:43:39,2017-05-23 12:34:37,,,javascript;ruby-on-rails;reactjs,sky_coder123,2521,4498942,registered,true,34563571,,CC BY-SA 3.0,,1922,1129,8,5,1,3,true,false,false,true,true,true,45,6,false,0.048,0.0005,4113,2015,8,10,Tuesday,false,false,true,false,false,false,false
56266575,Why is useState not triggering re-render?,"I've initialized a state that is an array, and when I update it my component does not re-render. Here is a minimal proof-of-concept:
function App() {
const [numbers, setNumbers] = React.useState([0, 1, 2, 3]);
console.log("rendering...");
return (
<div className="App">
{numbers.map(number => (
<p>{number}</p>
))}
<input
type="text"
value={numbers[0].toString()}
onChange={newText => {
let old = numbers;
old[0] = 1;
setNumbers(old);
}}
/>
</div>
);
}
Based on this code, it seems that the input should contain the number 0 to start, and any time it is changed, the state should change too. After entering "02" in the input, the App component does not re-render. However, if I add a setTimeout in the onChange function which executes after 5 seconds, it shows that numbers has indeed been updated.
Any thoughts on why the component doesn't update?
Here is a CodeSandbox with the proof of concept.
",https://stackoverflow.com/questions/56266575/why-is-usestate-not-triggering-re-render,235,194206.0,8.0,,,2019-05-23 00:21:51,2023-05-18 05:24:21,2020-07-25 18:39:44,,,javascript;reactjs;react-hooks,Ryan Z,2785,9494046,registered,true,56266640,,CC BY-SA 4.0,,1214,1085,1,1,0,3,true,false,false,true,true,true,41,6,true,0.041,0.0012,2739,2019,5,0,Thursday,false,false,true,false,false,false,false
50694881,how to download file in react js,"I receive file url as response from api. when user clicks on download button, the file should be downloaded without opening file preview in a new tab. How to achieve this in react js?
",https://stackoverflow.com/questions/50694881/how-to-download-file-in-react-js,235,827883.0,27.0,,,2018-06-05 07:51:14,2025-05-11 04:29:42,,,,javascript;reactjs;download,Sameer Thite,2499,9629032,registered,true,50695407,,CC BY-SA 4.0,,192,185,0,0,0,3,true,false,false,true,true,false,32,7,false,0.033,0.0003,3091,2018,6,7,Tuesday,false,false,true,false,false,false,false
50766693,How to center a component in Material UI and make it responsive?,"I don't quite understand the Material UI grid system. If I want to use a form component for login, what is the easiest way to center it on the screen on all devices (mobile and desktop)?
",https://stackoverflow.com/questions/50766693/how-to-center-a-component-in-material-ui-and-make-it-responsive,234,538931.0,16.0,,,2018-06-08 18:42:29,2025-07-04 08:37:41,2023-05-18 23:29:49,,,reactjs;authentication;mobile;material-ui;desktop,zorro,2575,9535921,registered,true,50784886,,CC BY-SA 4.0,,194,187,0,0,0,5,true,false,false,true,true,true,64,12,true,0.03,0.0004,3088,2018,6,18,Friday,false,false,false,false,false,false,false
59763739,react-testing-library: some portion of debug's output is not visible,"I am using react jest with react testing library to test my component.
I am facing a weird issue. I am using debug, returned by render from testing-library.
test('component should work', async () => {
const { findByText, debug } = render(<MyComponent />);
const myElement = await findByText(/someText/i);
debug();
});
As you can see in the screenshot there are incomplete divs and closing tags for parents are missing.
",https://stackoverflow.com/questions/59763739/react-testing-library-some-portion-of-debugs-output-is-not-visible,234,227418.0,12.0,,,2020-01-16 05:54:02,2025-07-17 11:08:03,2023-06-20 06:49:21,,,javascript;reactjs;jestjs;react-testing-library,Amit Chauhan,7039,2417295,registered,true,,,CC BY-SA 4.0,,625,437,1,1,1,4,false,false,false,true,true,true,72,9,false,0.053,0.001,2501,2020,1,5,Thursday,false,false,true,false,false,false,false
40541994,Multiple path names for a same component in React Router,"I am using the same component for three different routes:
<Router>
<Route path=""/home"" component={Home} />
<Route path=""/users"" component={Home} />
<Route path=""/widgets"" component={Home} />
</Router>
Is there anyway to combine it, to be like:
<Router>
<Route path=[""/home"", ""/users"", ""/widgets""] component={Home} />
</Router>
",https://stackoverflow.com/questions/40541994/multiple-path-names-for-a-same-component-in-react-router,234,190991.0,12.0,,,2016-11-11 06:00:52,2024-02-08 09:28:20,2019-10-08 14:17:53,,,javascript;reactjs;path;react-router;url-routing,Chetan Garg,2357,7144672,registered,true,,,CC BY-SA 4.0,2021-01-07 08:24:56,458,396,2,0,0,5,false,false,false,true,true,true,56,10,false,0.063,0.0012,3662,2016,11,6,Friday,false,false,true,false,false,false,false
53165945,What is useState() in React?,"I am currently learning hooks concept in React and trying to understand below example.
import { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
The above example increments the counter on the handler function parameter itself. What if I want to modify count value inside event handler function
Consider below example:
setCount = () => {
//how can I modify count value here. Not sure if I can use setState to modify its value
//also I want to modify other state values as well here. How can I do that
}
<button onClick={() => setCount()}>
Click me
</button>
",https://stackoverflow.com/questions/53165945/what-is-usestate-in-react,234,347568.0,14.0,,,2018-11-06 04:56:10,2022-12-22 10:17:54,2020-09-17 21:15:30,,,javascript;reactjs;react-native;react-hooks;react-state,Hemadri Dasari,34254,6903497,registered,true,53166194,,CC BY-SA 4.0,2020-08-22 07:02:36,969,900,2,0,0,5,true,false,false,true,true,true,28,5,true,0.04,0.0007,2937,2018,11,4,Tuesday,false,false,true,false,false,false,false
69868956,How can I redirect in React Router v6?,"I am trying to upgrade to React Router v6 (react-router-dom 6.0.1).
Here is my updated code:
import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom';
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/lab" element={<Lab />} />
<Route render={() => <Navigate to="/" />} />
</Routes>
</BrowserRouter>
The last Route is redirecting the rest of paths to /.
However, I got an error
TS2322: Type '{ render: () => Element; }' is not assignable to type 'IntrinsicAttributes & (PathRouteProps | LayoutRouteProps | IndexRouteProps)'. Property 'render' does not exist on type 'IntrinsicAttributes & (PathRouteProps | LayoutRouteProps | IndexRouteProps)'.
However, based on the documentation, it does have render for Route. How can I use it correctly?
",https://stackoverflow.com/questions/69868956/how-can-i-redirect-in-react-router-v6,233,417212.0,13.0,,,2021-11-07 00:34:29,2024-02-28 14:41:04,2022-09-25 20:53:58,,,javascript;reactjs;react-router;react-router-dom,Hongbo Miao,50917,2000548,registered,true,69872699,,CC BY-SA 4.0,,1176,910,6,1,0,4,true,false,false,true,true,true,38,8,true,0.031,0.0006,1840,2021,11,0,Sunday,true,false,true,false,false,false,false
35153599,ReactJS - Get Height of an element,"How can I get the Height of an element after React renders that element?
HTML
<div id=""container"">
<!-- This element's contents will be replaced with your component. -->
<p>
jnknwqkjnkj<br>
jhiwhiw (this is 36px height)
</p>
</div>
ReactJS
var DivSize = React.createClass({
render: function() {
let elHeight = document.getElementById('container').clientHeight
return <div className=""test"">Size: <b>{elHeight}px</b> but it should be 18px after the render</div>;
}
});
ReactDOM.render(
<DivSize />,
document.getElementById('container')
);
RESULT
Size: 36px but it should be 18px after the render
It's calculating the container height before the render (36px). I want to get the height after the render. The right result should be 18px in this case. jsfiddle
",https://stackoverflow.com/questions/35153599/reactjs-get-height-of-an-element,232,537061.0,17.0,,,2016-02-02 12:30:13,2024-03-13 10:03:18,2019-08-19 14:44:46,,,javascript;reactjs,faia20,2404,4627115,registered,true,35153943,,CC BY-SA 4.0,,1076,850,3,1,0,2,true,false,false,true,true,true,34,7,false,0.032,0.0004,3945,2016,2,12,Tuesday,false,false,true,false,false,false,false
56484686,How do I avoid 'Function components cannot be given refs' when using react-router-dom?,"I have the following (using Material UI)....
import React from ""react"";
import { NavLink } from ""react-router-dom"";
import Tabs from ""@material-ui/core/Tabs"";
import Tab from ""@material-ui/core/Tab"";
function LinkTab(link){
return <Tab component={NavLink}
to={link.link}
label={link.label}
value={link.link}
key={link.link}
/>;
}
In the new versions this causes the following warning...
Warning: Function components cannot be given refs. Attempts to access
this ref will fail. Did you mean to use React.forwardRef()?
Check the render method of ForwardRef.
in NavLink (created by ForwardRef)
I tried changing to...
function LinkTab(link){
// See https://material-ui.com/guides/composition/#caveat-with-refs
const MyLink = React.forwardRef((props, ref) => <NavLink {...props} ref={ref} />);
return <Tab component={MyLink}
to={link.link}
label={link.label}
value={link.link}
key={link.link}
/>;
}
But I still get the warning. How do I resolve this issue?
",https://stackoverflow.com/questions/56484686/how-do-i-avoid-function-components-cannot-be-given-refs-when-using-react-route,231,498142.0,10.0,,,2019-06-06 20:28:34,2024-06-27 12:36:44,,,,reactjs;react-router;material-ui,JGleason,4050,9335205,registered,true,65756885,,CC BY-SA 4.0,2020-09-27 09:50:53,1214,1086,3,0,0,3,true,false,false,true,true,false,94,13,true,0.02,0.0005,2725,2019,6,20,Thursday,false,false,false,false,false,false,false
42296499,How to display svg icons(.svg files) in UI using React Component?,"I have seen a lot of libraries for svg on react but none gave me how to import an svg file in the react component. I have seen code which talk about bring the svg code into react rather than using the .svg icon as image and show it in the UI.
Please let me know if there are ways to embed the icon.
",https://stackoverflow.com/questions/42296499/how-to-display-svg-icons-svg-files-in-ui-using-react-component,229,576486.0,18.0,,,2017-02-17 11:13:11,2025-02-22 20:09:36,2021-08-23 07:10:56,,,reactjs;svg,Kamaraju,2645,2007092,registered,true,42296823,,CC BY-SA 4.0,2019-09-02 09:30:07,313,299,0,0,0,2,true,false,false,true,true,true,65,11,true,0.031,0.0004,3564,2017,2,11,Friday,false,false,false,false,false,false,false
58243680,React Native: another VirtualizedList-backed container,"After upgrading to React Native 0.61, I get a lot of warnings like this:
VirtualizedLists should never be nested inside plain ScrollViews with the same orientation - use another VirtualizedList-backed container instead.
What is the other VirtualizedList-backed container that I should use, and why is it now advised not to use it like that?
",https://stackoverflow.com/questions/58243680/react-native-another-virtualizedlist-backed-container,228,274859.0,29.0,,,2019-10-04 22:12:57,2024-07-29 12:22:32,2024-04-09 20:46:35,,,javascript;reactjs;react-native,David Schilling,2790,2154005,registered,true,58477746,,CC BY-SA 4.0,2021-04-03 07:25:58,393,342,2,0,0,3,true,false,false,true,true,true,54,5,false,0.106,0.0008,2605,2019,10,22,Friday,false,false,true,false,false,false,false
62340697,React-Query: How to useQuery when button is clicked,"I am new to this react-query library.
I know that when I want to fetch data, with this library I can do something like this:
const fetchData = async()=>{...}
// it starts fetching data from backend with this line of code
const {status, data, error} = useQuery(myKey, fetchData());
It works. But how to trigger the data fetching only when a button is clicked? , I know I probably could do something like <Button onPress={() => {useQuery(myKey, fetchData())}}/> , but how to manage the returned data and status...
",https://stackoverflow.com/questions/62340697/react-query-how-to-usequery-when-button-is-clicked,228,301514.0,16.0,,,2020-06-12 08:43:25,2025-02-04 09:15:44,2022-03-20 16:20:35,,,reactjs;react-native;react-query,Leem.fin,42910,959734,registered,true,,,CC BY-SA 4.0,,664,530,2,1,0,3,false,false,false,true,true,true,51,8,false,0.053,0.0008,2353,2020,6,8,Friday,false,false,false,false,false,false,false
30915173,react-router go back a page how do you configure history?,"Can anyone please tell me how I can go back to the previous page rather than a specific route?
When using this code:
var BackButton = React.createClass({
mixins: [Router.Navigation],
render: function() {
return (
<button
className=""button icon-left""
onClick={this.navigateBack}>
Back
</button>
);
},
navigateBack: function(){
this.goBack();
}
});
Get this error, goBack() was ignored because there is no router history
Here are my routes:
// Routing Components
Route = Router.Route;
RouteHandler = Router.RouteHandler;
DefaultRoute = Router.DefaultRoute;
var routes = (
<Route name=""app"" path=""/"" handler={OurSchoolsApp}>
<DefaultRoute name=""home"" handler={HomePage} />
<Route name=""add-school"" handler={AddSchoolPage} />
<Route name=""calendar"" handler={CalendarPage} />
<Route name=""calendar-detail"" path=""calendar-detail/:id"" handler={CalendarDetailPage} />
<Route name=""info-detail"" path=""info-detail/:id"" handler={InfoDetailPage} />
<Route name=""info"" handler={InfoPage} />
<Route name=""news"" handler={NewsListPage} />
<Route name=""news-detail"" path=""news-detail/:id"" handler={NewsDetailPage} />
<Route name=""contacts"" handler={ContactPage} />
<Route name=""contact-detail"" handler={ContactDetailPage} />
<Route name=""settings"" handler={SettingsPage} />
</Route>
);
Router.run(routes, function(Handler){
var mountNode = document.getElementById('app');
React.render(<Handler /> , mountNode);
});
",https://stackoverflow.com/questions/30915173/react-router-go-back-a-page-how-do-you-configure-history,227,705450.0,26.0,,,2015-06-18 12:19:30,2025-01-06 04:54:44,2018-07-21 09:54:40,,,javascript;reactjs;react-router,Bomber,11103,1901521,registered,true,62341050,,CC BY-SA 4.0,,1739,1646,2,0,0,3,true,false,false,true,true,true,57,10,true,0.037,0.0003,4174,2015,6,12,Thursday,false,false,true,false,false,false,false
26069238,Call multiple functions onClick ReactJS,"I know in vanilla JavaScript, we can do:
onclick="f1();f2()"
What would be the equivalent for making two function calls onClick in ReactJS?
I know calling one function is like this:
onClick={f1}
",https://stackoverflow.com/questions/26069238/call-multiple-functions-onclick-reactjs,227,520304.0,11.0,,,2014-09-26 22:33:43,2023-05-26 13:36:37,2021-05-07 05:29:48,,,javascript;reactjs,user2554585,3769,2554585,registered,true,26069299,,CC BY-SA 4.0,2023-05-27 00:41:18,289,207,3,0,0,2,true,false,false,true,true,true,39,5,false,0.021,0.0004,4439,2014,9,22,Friday,false,false,true,false,false,false,false
51974369,What is the difference between HashRouter and BrowserRouter in React?,"I am new to programming which makes things slightly difficult for me to understand if I read the official docs.
I was reading about React Router 4 from here
In this article, the author was talking about <HashRouter> and <BrowserRouter>
This is what he mentioned:
HashRouter basically it uses the hash in the URL to render the component. Since I was building a static one-page website, I needed to use this.
BrowserRouter, it uses HTML5 history API to render the component. The history can be modified via pushState and replaceState. More information can be found here
Now, I don't get the significance and use cases for both, Like what does he mean when he says history can be modified via pushState and replaceState and it uses the hash in the URL to render the component
While the first explanation for BrowserRouter is entirely vague to me, the second explanation about HashRouter also doesn't make sense, like why would someone use Hash (#) in the url to render the component?
",https://stackoverflow.com/questions/51974369/what-is-the-difference-between-hashrouter-and-browserrouter-in-react,227,268346.0,11.0,,,2018-08-22 20:08:16,2024-10-12 06:45:25,2021-05-07 20:41:55,,,reactjs,Alwaysblue,12318,8701527,registered,true,51976069,,CC BY-SA 4.0,,1242,993,2,1,0,1,true,false,false,true,true,true,69,10,true,0.041,0.0008,3013,2018,8,20,Wednesday,false,false,false,false,false,false,false
29725828,Update style of a component onScroll in React.js,"I have built a component in React which is supposed to update its own style on window scroll to create a parallax effect.
The component render method looks like this:
function() {
let style = { transform: 'translateY(0px)' };
window.addEventListener('scroll', (event) => {
let scrollTop = event.srcElement.body.scrollTop,
itemTranslate = Math.min(0, scrollTop/3 - 60);
style.transform = 'translateY(' + itemTranslate + 'px)');
});
return (
<div style={style}></div>
);
}
This doesn't work because React doesn't know that the component has changed, and therefore the component is not rerendered.
I've tried storing the value of itemTranslate in the state of the component, and calling setState in the scroll callback. However, this makes scrolling unusable as this is terribly slow.
Any suggestion on how to do this?
",https://stackoverflow.com/questions/29725828/update-style-of-a-component-onscroll-in-react-js,226,506710.0,17.0,,,2015-04-19 04:33:53,2023-12-29 20:26:53,2019-09-27 13:53:04,,,javascript;reactjs,Alejandro Pérez,2647,1573841,registered,true,29726000,,CC BY-SA 4.0,,990,892,4,0,0,2,true,false,false,true,true,true,48,8,false,0.034,0.0004,4234,2015,4,4,Sunday,true,false,true,false,false,false,false
20851533,React.js: Wrapping one component into another,"Many template languages have "slots" or "yield" statements, that allow to do some sort of inversion of control to wrap one template inside of another.
Angular has "transclude" option.
Ruby/Rails has yield statement. If React.js had yield statement, it would look like this:
var Wrapper = React.createClass({
render: function() {
return (
<div className="wrapper">
before
<yield/>
after
</div>
);
}
});
var Main = React.createClass({
render: function() {
return (
<Wrapper><h1>content</h1></Wrapper>
);
}
});
Desired output:
<div class="wrapper">
before
<h1>content</h1>
after
</div>
Alas, React.js doesn’t have a <yield/>. How do I define Wrapper component to achieve the same output?
",https://stackoverflow.com/questions/20851533/react-js-wrapping-one-component-into-another,226,217708.0,3.0,,,2013-12-31 04:05:19,2023-02-03 01:30:31,2023-02-03 01:30:31,,,javascript;template-engine;composition;reactjs;transclusion,NVI,15114,16185,registered,true,20852153,,CC BY-SA 4.0,,1242,886,3,2,0,5,true,false,false,true,true,true,45,6,false,0.014,0.001,4708,2013,12,4,Tuesday,false,false,true,false,false,false,false
29420835,How to generate unique IDs for form labels in React?,"I have form elements with labels and I want to have unique IDs to link labels to elements with htmlFor attribute. Something like this:
React.createClass({
render() {
const id = ???;
return (
<label htmlFor={id}>My label</label>
<input id={id} type=""text""/>
);
}
});
I used to generate IDs based on this._rootNodeID but it’s unavailable since React 0.13. What is the best and/or simplest way to do it now?
",https://stackoverflow.com/questions/29420835/how-to-generate-unique-ids-for-form-labels-in-react,226,288008.0,16.0,,,2015-04-02 19:22:37,2024-01-05 11:15:16,,,,reactjs,Artem Sapegin,3073,1973105,registered,true,29466744,,CC BY-SA 3.0,,572,482,5,0,0,1,true,false,false,true,true,false,52,10,true,0.056,0.0008,4251,2015,4,19,Thursday,false,false,false,false,false,false,false
54963248,What's the difference between useCallback and useMemo in practice?,"Maybe I misunderstood something, but useCallback Hook runs everytime when re-render happens.
I passed inputs - as a second argument to useCallback - non-ever-changeable constants - but returned memoized callback still runs my expensive calculations at every render (I'm pretty sure - you can check by yourself in the snippet below).
I've changed useCallback to useMemo - and useMemo works as expected — runs when passed inputs changes. And really memoizes the expensive calculations.
Live example:
'use strict';
const { useState, useCallback, useMemo } = React;
const neverChange = 'I never change';
const oneSecond = 1000;
function App() {
const [second, setSecond] = useState(0);
// This 👇 expensive function executes everytime when render happens:
const calcCallback = useCallback(() => expensiveCalc('useCallback'), [neverChange]);
const computedCallback = calcCallback();
// This 👇 executes once
const computedMemo = useMemo(() => expensiveCalc('useMemo'), [neverChange]);
setTimeout(() => setSecond(second + 1), oneSecond);
return `
useCallback: ${computedCallback} times |
useMemo: ${computedMemo} |
App lifetime: ${second}sec.
`;
}
const tenThousand = 10 * 1000;
let expensiveCalcExecutedTimes = { 'useCallback': 0, 'useMemo': 0 };
function expensiveCalc(hook) {
let i = 0;
while (i < tenThousand) i++;
return ++expensiveCalcExecutedTimes[hook];
}
ReactDOM.render(
React.createElement(App),
document.querySelector('#app')
);
<h1>useCallback vs useMemo:</h1>
<div id=""app"">Loading...</div>
<script src=""https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js""></script>
<script src=""https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js""></script>
",https://stackoverflow.com/questions/54963248/whats-the-difference-between-usecallback-and-usememo-in-practice,225,111179.0,8.0,,,2019-03-02 21:34:33,2025-10-09 20:18:22,2019-03-02 21:40:46,,,reactjs,bekliev,2711,4825024,registered,true,54963730,,CC BY-SA 4.0,,2220,1895,2,0,0,1,true,false,false,true,true,true,70,9,true,0.072,0.002,2821,2019,3,21,Saturday,true,false,false,false,false,false,false
40037657,How to include bootstrap css and js in reactjs app?,"I am new to ReactJS, I want to include bootstrap in my React app
I have installed bootstrap by npm install bootstrap --save
Now, want to load bootstrap CSS and JS in my React app.
I am using webpack.
webpack.config.js
var config = {
entry: './src/index',
output: {
path: './',
filename: 'index.js'
},
devServer: {
inline: true,
port: 8080,
historyApiFallback: true,
contentBase:'./src'
},
module: {
loaders: [
{
test: /\.js?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
}
};
module. exports = config;
My issue is “how to include bootstrap CSS and JS in ReactJS app from node modules?" How to set up for bootstrap to include in my React app?
",https://stackoverflow.com/questions/40037657/how-to-include-bootstrap-css-and-js-in-reactjs-app,225,508943.0,22.0,,,2016-10-14 07:42:53,2022-06-30 03:05:14,2022-06-30 03:05:14,,,twitter-bootstrap;reactjs;webpack,Mehul Mali,3294,5677020,registered,true,44985246,,CC BY-SA 4.0,,1016,911,2,0,0,3,true,false,false,true,true,true,51,10,true,0.043,0.0004,3690,2016,10,7,Friday,false,false,false,false,false,false,false
21965738,What is Virtual DOM?,"Recently, I looked at Facebook's React framework. It uses a concept called ""the Virtual DOM,"" which I didn't really understand.
What is the Virtual DOM? What are the advantages?
",https://stackoverflow.com/questions/21965738/what-is-virtual-dom,225,106116.0,12.0,,,2014-02-23 08:05:26,2023-05-10 22:37:16,2017-03-08 03:53:29,,,javascript;reactjs,Fizer Khan,93997,1154350,registered,true,21965987,,CC BY-SA 3.0,,258,179,0,1,0,2,true,false,false,true,true,true,20,4,true,0.113,0.0021,4654,2014,2,8,Sunday,true,false,true,false,false,false,false
40769551,How to use Google fonts in React.js?,"I had built a website with React.js and webpack.
I want to use Google fonts in the webpage, so I put the link in the section.
Google Fonts
<link href=""https://fonts.googleapis.com/css?family=Bungee+Inline"" rel=""stylesheet"">
And set CSS
body{
font-family: 'Bungee Inline', cursive;
}
However, it does not work.
How can I solve this problem?
",https://stackoverflow.com/questions/40769551/how-to-use-google-fonts-in-react-js,225,456666.0,19.0,,,2016-11-23 16:26:08,2025-06-19 22:27:59,2018-08-31 15:20:10,,,reactjs;webpack;google-font-api,Kevin Hsiao,2439,6464787,registered,true,,,CC BY-SA 4.0,,593,360,2,1,0,3,false,false,false,true,true,true,36,7,true,0.042,0.0005,3650,2016,11,16,Wednesday,false,false,false,false,false,false,false
69864165,Error: [PrivateRoute] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>,"I'm using React Router v6 and am creating private routes for my application.
In file PrivateRoute.js, I've the code
import React from 'react';
import {Route,Navigate} from "react-router-dom";
import {isauth} from 'auth'
function PrivateRoute({ element, path }) {
const authed = isauth() // isauth() returns true or false based on localStorage
const ele = authed === true ? element : <Navigate to="/Home" />;
return <Route path={path} element={ele} />;
}
export default PrivateRoute
And in file route.js I've written as:
...
<PrivateRoute exact path="/" element={<Dashboard/>}/>
<Route exact path="/home" element={<Home/>}/>
I've gone through the same example React-router Auth Example - StackBlitz, file App.tsx
Is there something I'm missing?
",https://stackoverflow.com/questions/69864165/error-privateroute-is-not-a-route-component-all-component-children-of-rou,225,271577.0,21.0,,,2021-11-06 12:55:13,2024-04-24 01:14:55,2022-01-05 02:48:54,,,javascript;reactjs;react-router-dom,Rajanboy,2772,16830299,registered,true,69869761,,CC BY-SA 4.0,2023-02-10 16:28:39,1068,833,2,1,0,3,true,false,false,true,true,true,146,18,false,0.077,0.0008,1841,2021,11,12,Saturday,true,false,true,false,false,false,false
33973648,React: "this" is undefined inside a component function,"class PlayerControls extends React.Component {
constructor(props) {
super(props)
this.state = {
loopActive: false,
shuffleActive: false,
}
}
render() {
var shuffleClassName = this.state.toggleActive ? ""player-control-icon active"" : ""player-control-icon""
return (
<div className=""player-controls"">
<FontAwesome
className=""player-control-icon""
name='refresh'
onClick={this.onToggleLoop}
spin={this.state.loopActive}
/>
<FontAwesome
className={shuffleClassName}
name='random'
onClick={this.onToggleShuffle}
/>
</div>
);
}
onToggleLoop(event) {
// ""this is undefined??"" <--- here
this.setState({loopActive: !this.state.loopActive})
this.props.onToggleLoop()
}
I want to update loopActive state on toggle, but this object is undefined in the handler. According to the tutorial doc, I this should refer to the component. Am I missing something?
",https://stackoverflow.com/questions/33973648/react-this-is-undefined-inside-a-component-function,224,176829.0,12.0,,,2015-11-28 16:30:26,2023-04-11 20:36:20,2020-01-19 07:02:35,,,javascript;reactjs;this,Maximus S,11155,1815412,registered,true,33973758,,CC BY-SA 4.0,,1116,1046,4,0,0,3,true,false,false,true,true,true,64,8,false,0.068,0.0013,4011,2015,11,16,Saturday,true,false,true,false,false,false,false
62650640,How do I update each dependency in package.json to the latest version?,"I have a React app with deprecated dependencies. To make it work, I have to update the dependencies to their newer (but stable) versions.
Per How can I update each dependency in package.json to the latest version?, to update dependencies in package.json to latest versions, npm-check-updates is the best option for npm. However, I'm using Yarn for package management. Is there an equivalent of npm-check-updates in Yarn, so that I use a single package manager to manage my dependencies?
",https://stackoverflow.com/questions/62650640/how-do-i-update-each-dependency-in-package-json-to-the-latest-version,222,341908.0,13.0,,,2020-06-30 05:08:11,2025-08-19 09:59:58,2025-08-19 09:59:58,,,reactjs;yarnpkg,DevLoverUmar,14423,7344164,registered,true,62650754,,CC BY-SA 4.0,,759,487,3,2,0,2,true,false,false,true,true,true,70,12,true,0.038,0.0006,2335,2020,6,5,Tuesday,false,false,false,false,false,false,false
26402534,How to listen state changes in react.js?,"What is the angular's $watch function equivalent in React.js?
I want to listen state changes and call a function like getSearchResults().
componentDidMount: function() {
this.getSearchResults();
}
",https://stackoverflow.com/questions/26402534/how-to-listen-state-changes-in-react-js,222,453448.0,9.0,,,2014-10-16 10:50:42,2023-08-01 17:14:13,,,,javascript;reactjs,Eniz Gülek,4375,2989382,registered,true,26414427,,CC BY-SA 3.0,,320,205,1,1,0,2,true,false,false,true,true,false,40,7,true,0.02,0.0005,4419,2014,10,10,Thursday,false,false,true,false,false,false,false
37440408,How to detect Esc Key Press in React and how to handle it,"How do I detect Esc keypress on reactjs? The similar thing to jquery
$(document).keyup(function(e) {
if (e.keyCode == 27) { // escape key maps to keycode `27`
// <DO YOUR WORK HERE>
}
});
Once detected I want to pass the info down components. I have 3 components out of which last active component needs to react to the escape key press.
I was thinking of a kind of registering when a component becomes active
class Layout extends React.Component {
onActive(escFunction){
this.escFunction = escFunction;
}
onEscPress(){
if(_.isFunction(this.escFunction)){
this.escFunction()
}
}
render(){
return (
<div class=""root"">
<ActionPanel onActive={this.onActive.bind(this)}/>
<DataPanel onActive={this.onActive.bind(this)}/>
<ResultPanel onActive={this.onActive.bind(this)}/>
</div>
)
}
}
and on all the components
class ActionPanel extends React.Component {
escFunction(){
//Do whatever when esc is pressed
}
onActive(){
this.props.onActive(this.escFunction.bind(this));
}
render(){
return (
<input onKeyDown={this.onActive.bind(this)}/>
)
}
}
I believe this will work but I think it will be more like a callback. Is there any better way to handle this?
",https://stackoverflow.com/questions/37440408/how-to-detect-esc-key-press-in-react-and-how-to-handle-it,221,224184.0,8.0,,,2016-05-25 14:38:41,2023-07-03 09:50:56,,,,javascript;reactjs,Neo,4790,472032,registered,true,46123962,,CC BY-SA 3.0,,1433,1326,3,0,0,2,true,false,false,true,true,false,57,13,false,0.036,0.001,3832,2016,5,14,Wednesday,false,false,true,false,false,false,false
35469836,Detecting production vs. development React at runtime,"Is it possible to detect whether the current version of React is development or production at runtime? I'd like to do something like this:
if (React.isDevelopment) {
// Development thing
} else {
// Real thing
}
",https://stackoverflow.com/questions/35469836/detecting-production-vs-development-react-at-runtime,221,159824.0,6.0,,,2016-02-17 23:28:45,2024-07-04 16:14:25,2018-06-14 14:48:46,,,javascript;reactjs,pfhayes,3927,139544,registered,true,35470995,,CC BY-SA 4.0,,249,218,1,0,0,2,true,false,false,true,true,true,53,7,false,0.038,0.0014,3930,2016,2,23,Wednesday,false,false,true,false,false,false,false
44439205,Can't resolve module (not found) in React.js,"I can't believe that I'm asking an obvious question, but I still get the error in console log.
Console says that it can't find the module in the directory, but I've checked at least 10 times for typos. Anyways, here's the component code.
I want to render Header in root
import React, { Component } from 'react'
import Header from './src/components/header/header'
import logo from './logo.svg'
import './App.css'
class App extends Component {
render() {
return (
<Header/>
);
}
}
export default App;
This is the Header component
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import navBar from './src/components/header/navBar'
import './src/css/header.css'
class Header extends Component {
render() {
return {
<div>
<div id=""particles-js""></div>
<navBar/>
<Title/>
</div>
};
}
}
ReactDOM.render(<Header/>, document.getElementById('header'));
I've checked at least 10 times that the module is at this location ./src/components/header/header, and it is (folder ""header"" contains ""header.js"").
Yet, React still throws this error:
Failed to compile
./src/App.js
Module not found: Can't resolve './src/components/header/header' in '/home/wiseman/Desktop/React_Components/github-portfolio/src'
npm test says the same thing.
",https://stackoverflow.com/questions/44439205/cant-resolve-module-not-found-in-react-js,221,1114317.0,28.0,,,2017-06-08 14:58:21,2025-02-17 17:46:17,2019-07-25 18:46:01,,,javascript;reactjs,Vladimir Jovanović,5591,5981004,registered,true,44440073,,CC BY-SA 4.0,2020-11-19 06:56:46,1614,1413,5,0,0,2,true,false,false,true,true,true,48,7,false,0.025,0.0002,3453,2017,6,14,Thursday,false,false,true,false,false,false,false
47761894,Why are Fragments in React 16 better than container divs?,"In React 16.2, improved support for Fragments has been added. More information can be found on React's blog post here.
We are all familiar with the following code:
render() {
return (
// Extraneous div element :(
<div>
Some text.
<h2>A heading</h2>
More text.
<h2>Another heading</h2>
Even more text.
</div>
);
}
Yes, we need a container div, but it's not that big of a deal.
In React 16.2, we can do this to avoid the surrounding container div:
render() {
return (
<Fragment>
Some text.
<h2>A heading</h2>
More text.
<h2>Another heading</h2>
Even more text.
</Fragment>
);
}
In either case, we still need need a container element surround the inner elements.
My question is, why is using a Fragment preferable? Does it help with performance? If so, why? Would love some insight.
",https://stackoverflow.com/questions/47761894/why-are-fragments-in-react-16-better-than-container-divs,220,70592.0,7.0,,,2017-12-11 21:41:32,2022-01-02 07:23:31,,,,reactjs,Max Millington,4513,7168582,registered,true,47762117,,CC BY-SA 3.0,,1169,950,4,1,0,1,true,false,false,true,true,false,57,10,true,0.099,0.0031,3267,2017,12,21,Monday,false,false,false,false,false,false,false
24841855,How to access component methods from “outside” in ReactJS?,"Why can’t I access the component methods from “outside” in ReactJS? Why is it not possible and is there any way to solve it?
Consider the code:
var Parent = React.createClass({
render: function() {
var child = <Child />;
return (
<div>
{child.someMethod()} // expect ""bar"", got a ""not a function"" error.
</div>
);
}
});
var Child = React.createClass({
render: function() {
return (
<div>
foo
</div>
);
},
someMethod: function() {
return 'bar';
}
});
React.renderComponent(<Parent />, document.body);
",https://stackoverflow.com/questions/24841855/how-to-access-component-methods-from-outside-in-reactjs,220,214957.0,8.0,,,2014-07-19 15:18:38,2020-10-23 14:42:45,2019-08-12 00:51:30,,,javascript;reactjs;dom,user1518183,4761,1518183,registered,true,24848228,,CC BY-SA 4.0,,731,693,1,0,0,3,true,false,false,true,true,true,58,9,true,0.037,0.001,4508,2014,7,15,Saturday,true,false,true,false,false,false,false
45373742,Detect Route Change with react-router,"I have to implement some business logic depending on browsing history.
What I want to do is something like this:
reactRouter.onUrlChange(url => {
this.history.push(url);
});
Is there any way to receive a callback from react-router when the URL gets updated?
",https://stackoverflow.com/questions/45373742/detect-route-change-with-react-router,219,376062.0,10.0,,,2017-07-28 12:36:51,2023-01-08 04:28:08,2017-11-21 16:55:51,,,reactjs;react-router;react-router-v4;react-router-redux;react-router-dom,Aris,3386,1838156,registered,true,45373907,,CC BY-SA 3.0,,313,268,1,0,0,5,true,false,false,true,true,true,37,5,false,0.027,0.0006,3403,2017,7,12,Friday,false,false,false,false,false,false,false
42299594,Await is a reserved word error inside async function,"I am struggling to figure out the issue with the following syntax:
export const sendVerificationEmail = async () =>
(dispatch) => {
try {
dispatch({ type: EMAIL_FETCHING, payload: true });
await Auth.sendEmailVerification();
dispatch({ type: EMAIL_FETCHING, payload: false }))
} catch (error) {
dispatch({ type: EMAIL_FETCHING, payload: false });
throw new Error(error);
}
};
I keep getting error saying:
await is a reserved word
...but isn't it legal within an async function?
The dispatch bit is coming from the react-thunk library.
",https://stackoverflow.com/questions/42299594/await-is-a-reserved-word-error-inside-async-function,219,386094.0,2.0,,,2017-02-17 13:48:20,2024-09-12 04:16:47,2018-07-17 10:25:13,,,javascript;reactjs;async-await;redux,Ilja,46895,911930,registered,true,42299762,,CC BY-SA 4.0,,768,597,1,1,0,4,true,false,false,true,true,true,52,9,false,0.005,0.0006,3564,2017,2,13,Friday,false,false,true,false,false,false,false
55082584,How to create a React app directly in the current folder,"I know I've done it before but I can't seem to find the answer anywhere. I want to run create-react-app without creating a whole other folder within the folder I'm already in. I believe it is just an additional flag appended to the command.
",https://stackoverflow.com/questions/55082584/how-to-create-a-react-app-directly-in-the-current-folder,218,222681.0,16.0,,,2019-03-09 22:27:54,2024-05-07 08:31:07,2019-03-09 22:30:30,,,reactjs;command-line;create-react-app,Niko Roberts,2211,10078950,registered,true,55082620,,CC BY-SA 4.0,,249,242,0,0,0,3,true,false,false,true,true,true,56,11,false,0.072,0.001,2814,2019,3,22,Saturday,true,false,false,false,false,false,false
36994564,How can one tell the version of React running at runtime in the browser?,"Is there a way to know the runtime version of React in the browser?
",https://stackoverflow.com/questions/36994564/how-can-one-tell-the-version-of-react-running-at-runtime-in-the-browser,218,358371.0,17.0,,,2016-05-03 02:22:28,2023-02-20 12:38:39,,,,javascript;reactjs,leojh,7822,782096,registered,true,36994601,,CC BY-SA 3.0,2022-12-17 20:55:16,75,68,0,0,0,2,true,false,false,true,true,false,72,14,true,0.047,0.0006,3854,2016,5,2,Tuesday,false,false,true,false,false,false,false
41446560,React setState not updating state,"So I have this:
let total = newDealersDeckTotal.reduce(function(a, b) {
return a + b;
},
0);
console.log(total, 'tittal'); //outputs correct total
setTimeout(() => {
this.setState({ dealersOverallTotal: total });
}, 10);
console.log(this.state.dealersOverallTotal, 'dealersOverallTotal1'); //outputs incorrect total
newDealersDeckTotal is just an array of numbers [1, 5, 9] e.g.
however this.state.dealersOverallTotal does not give the correct total but total does? I even put in a timeout delay to see if this solved the problem.
any obvious or should I post more code?
",https://stackoverflow.com/questions/41446560/react-setstate-not-updating-state,218,493911.0,11.0,,,2017-01-03 15:12:54,2023-08-16 16:00:27,2021-11-18 08:12:21,,,javascript;reactjs;state;setstate,The worm,5918,6882762,registered,true,41446620,,CC BY-SA 4.0,2023-11-11 17:20:49,708,581,5,0,0,4,true,false,false,true,true,true,33,5,false,0.022,0.0004,3609,2017,1,15,Tuesday,false,false,true,false,false,false,false
58173809,Next.js Redirect from / to another page,"I'm new in Next.js and I'm wondering how to redirect from the start page ( / ) to /hello-nextjs for example. Once the user loads a page, determine if path === / and redirect to /hello-nextjs if so.
In react-router we do something like:
<Switch>
<Route path="/hello-nextjs" exact component={HelloNextjs} />
<Redirect to="/hello-nextjs" /> // or <Route path="/" exact render={() => <Redirect to="/hello-nextjs" />} />
</Switch>
",https://stackoverflow.com/questions/58173809/next-js-redirect-from-to-another-page,217,681846.0,21.0,,,2019-09-30 19:01:27,2025-09-13 17:32:00,2024-08-23 03:10:36,,,html;reactjs;routes;react-router;next.js,Arthur,3526,9464680,registered,true,60616536,,CC BY-SA 4.0,,600,510,5,0,0,5,true,false,false,true,true,true,39,7,false,0.031,0.0003,2609,2019,9,19,Monday,false,false,false,false,false,false,false
57847626,Using async/await inside a React functional component,"I'm just beginning to use React for a project, and am really struggling with incorporating async/await functionality into one of my components.
I have an asynchronous function called fetchKey that goes and gets an access key from an API I am serving via AWS API Gateway:
const fetchKey = async authProps => {
try {
const headers = {
Authorization: authProps.idToken // using Cognito authorizer
};
const response = await axios.post(
""https://MY_ENDPOINT.execute-api.us-east-1.amazonaws.com/v1/"",
API_GATEWAY_POST_PAYLOAD_TEMPLATE,
{
headers: headers
}
);
return response.data.access_token;
} catch (e) {
console.log(`Axios request failed! : ${e}`);
return e;
}
};
I am using React's Material UI theme, and waned to make use of one of its Dashboard templates. Unfortunately, the Dashboard template uses a functional stateless component:
const Dashboard = props => {
const classes = useStyles();
const token = fetchKey(props.auth);
console.log(token);
return (
... rest of the functional component's code
The result of my console.log(token) is a Promise, which is expected, but the screenshot in my Google Chrome browser is somewhat contradictory - is it pending, or is it resolved?
![]()
Second, if I try instead token.then((data, error)=> console.log(data, error)), I get undefined for both variables. This seems to indicate to me that the function has not yet completed, and therefore has not resolved any values for data or error. Yet, if I try to place a
const Dashboard = async props => {
const classes = useStyles();
const token = await fetchKey(props.auth);
React complains mightily:
> react-dom.development.js:57 Uncaught Invariant Violation: Objects are
> not valid as a React child (found: [object Promise]). If you meant to
> render a collection of children, use an array instead.
> in Dashboard (at App.js:89)
> in Route (at App.js:86)
> in Switch (at App.js:80)
> in div (at App.js:78)
> in Router (created by BrowserRouter)
> in BrowserRouter (at App.js:77)
> in div (at App.js:76)
> in ThemeProvider (at App.js:75)
Now, I'll be the first to state I don't have enough experience to understand what is going on with this error message. If this was a traditional React class component, I'd use the this.setState method to set some state, and then go on my merry way. However, I don't have that option in this functional component.
How do I incorporate async/await logic into my functional React component?
Edit: So I will just say I'm an idiot. The actual response object that is returned is not response.data.access_token. It was response.data.Item.access_token. Doh! That's why the result was being returned as undefined, even though the actual promise was resolved.
",https://stackoverflow.com/questions/57847626/using-async-await-inside-a-react-functional-component,217,375479.0,5.0,,,2019-09-09 03:43:13,2024-08-05 12:43:32,2022-11-01 18:40:29,,,javascript;reactjs;async-await;material-ui;react-functional-component,Yu Chen,7730,5865514,registered,true,57856876,,CC BY-SA 4.0,,3298,2864,13,1,1,5,true,false,false,true,true,true,53,7,false,0.013,0.0006,2630,2019,9,3,Monday,false,false,true,false,false,false,false
43230765,TypeScript React: Access component property types,"npm package @types/react allows us to use React inside of our TypeScript applications.
We define components as
type Props = {...}
type State = {...}
export default class MyComponent extends React.Component<Props, State> {
}
Here we have to declare types for component props and state (in type variables).
After we declared that types, TypeScript uses that to validate the usage of our component (the shape of props passed to it).
I want to create a container around such a component. The container will reuse the props of the component. But in order to create another component with the same props I have to redeclare the types for props again. Or export them from the original component file and import into container:
// Original file
export type Props = {...}
// Container file
import MyComponent, { Props } from './original'
But I'm already importing the MyComponent from that file. This component already contains information about the props it consumes (thanks to type variables in React.Component).
How do I access that information from the component class itself without explicitly exporting/importing the type for props?
I want something like:
import MyComponent from './MyComponent'
type Props = MyComponent.Props // <= Here access the component prop types
export default class MyContainer extends React.Component<Props, {}> {}
",https://stackoverflow.com/questions/43230765/typescript-react-access-component-property-types,216,222814.0,5.0,,,2017-04-05 12:07:58,2025-05-10 01:02:53,2025-05-10 01:02:53,,,reactjs;typescript,Anton Telesh,3952,2908590,registered,true,55005902,,CC BY-SA 4.0,,1528,1361,6,0,0,2,true,false,false,true,true,true,49,6,false,0.022,0.001,3517,2017,4,12,Wednesday,false,false,false,false,false,false,false
30765163,Pretty Printing JSON with React,"I'm using ReactJS and part of my app requires pretty printed JSON.
I get some JSON like: { ""foo"": 1, ""bar"": 2 }, and if I run that through JSON.stringify(obj, null, 4) in the browser console, it pretty prints, but when I use it in this react snippet:
render: function() {
var json = this.getStateFromFlux().json;
return (
<div>
<JsonSubmitter onSubmit={this.onSubmit} />
{ JSON.stringify(json, null, 2) }
</div>
);
},
it renders gross JSON that looks like ""{ \""foo\"" : 2, \""bar\"": 2}\n"".
How do I get those characters to be interpreted properly? {
",https://stackoverflow.com/questions/30765163/pretty-printing-json-with-react,216,340197.0,7.0,,,2015-06-10 19:06:34,2022-02-16 23:54:40,2017-09-17 12:07:10,,,javascript;json;reactjs;flux,Brandon,4059,2540143,registered,true,,,CC BY-SA 3.0,,693,602,4,0,0,4,false,false,false,true,true,true,31,5,false,0.021,0.0006,4182,2015,6,19,Wednesday,false,false,true,false,false,false,false
26923042,How do you validate the PropTypes of a nested object in ReactJS?,"I'm using a data object as my props for a component in ReactJS.
<Field data={data} />
I know its easy to validate the PropTypes object itself:
propTypes: {
data: React.PropTypes.object
}
But what if I want to validate the values inside? ie. data.id, data.title?
props[propName]: React.PropTypes.number.required // etc...
",https://stackoverflow.com/questions/26923042/how-do-you-validate-the-proptypes-of-a-nested-object-in-reactjs,216,105339.0,4.0,,,2014-11-14 04:44:00,2020-01-22 03:34:24,2015-03-27 15:30:43,,,reactjs,Adam,4074,894478,registered,true,26924696,,CC BY-SA 3.0,,432,339,3,0,0,1,true,false,false,true,true,true,64,12,true,0.038,0.0021,4390,2014,11,4,Friday,false,false,false,false,false,false,false
22343224,What's the difference between tilde(~) and caret(^) in package.json?,"After I upgraded to the latest stable node and npm, I tried npm install moment --save. It saves the entry in the package.json with the caret ^ prefix. Previously, it was a tilde ~ prefix.
- Why are these changes made in
npm?
- What is the difference between tilde
~ and caret ^?
- What are the advantages over previous ones?
",https://stackoverflow.com/questions/22343224/whats-the-difference-between-tilde-and-caret-in-package-json,5614,2169114.0,23.0,,,2014-03-12 06:02:21,2025-05-14 10:28:46,2023-12-18 15:17:09,,,node.js;npm;package.json;caret;semantic-versioning,Fizer Khan,93997,1154350,registered,true,22345808,,CC BY-SA 4.0,2018-12-20 04:44:05,481,321,9,0,0,5,true,false,false,true,true,true,72,9,true,0.011,0.0026,4637,2014,3,6,Wednesday,false,false,false,false,false,false,false
19578796,What is the --save option for npm install?,"I saw some tutorial where the command was:
npm install --save
What does the --save option mean?
",https://stackoverflow.com/questions/19578796/what-is-the-save-option-for-npm-install,3165,1244549.0,17.0,,,2013-10-24 23:54:11,2024-09-17 04:57:24,2021-12-20 13:00:16,,,node.js;npm,Dmitri,36580,2232662,registered,true,19578808,,CC BY-SA 4.0,2022-02-07 10:30:53,148,97,2,0,0,2,true,false,false,true,true,true,42,8,true,0.014,0.0025,4776,2013,10,23,Thursday,false,false,false,false,false,false,false
10972176,Find the version of an installed npm package,"How can I find the version of an installed Node.js or npm package?
This prints the version of npm itself:
npm -v <package-name>
This prints a cryptic error:
npm version <package-name>
This prints the package version on the registry (i.e., the latest version available):
npm view <package-name> version
How do I get the installed version?
",https://stackoverflow.com/questions/10972176/find-the-version-of-an-installed-npm-package,3078,2426920.0,31.0,,,2012-06-10 20:36:27,2024-01-02 21:31:29,2022-08-11 19:14:40,,,node.js;package;npm,Laurent Couvidou,33848,1005455,registered,true,,,CC BY-SA 4.0,2017-10-06 18:34:53,509,359,3,0,0,3,false,false,false,true,true,true,44,8,false,0.013,0.0013,5277,2012,6,20,Sunday,true,false,false,false,false,false,false
18875674,"What's the difference between dependencies, devDependencies, and peerDependencies in NPM package.json file?","This documentation answers my question very poorly. I didn't understand those explanations. Can someone say in simpler words? Maybe with examples if it's hard to choose simple words?
Also added peerDependencies, which is closely related and might cause confusion.
",https://stackoverflow.com/questions/18875674/whats-the-difference-between-dependencies-devdependencies-and-peerdependencie,3020,1152307.0,18.0,,,2013-09-18 14:57:06,2025-03-21 12:11:13,2023-03-27 14:22:30,,,node.js;npm;dependencies;package.json,Vitalii Korsakov,48116,1146469,registered,true,22004559,,CC BY-SA 4.0,,364,264,1,1,0,4,true,false,false,true,true,true,111,12,true,0.016,0.0026,4812,2013,9,14,Wednesday,false,false,false,false,false,false,false
16073603,How can I update each dependency in package.json to the latest version?,"I copied package.json from another project and now want to bump all of the dependencies to their latest versions since this is a fresh project and I don't mind fixing something if it breaks.
What's the easiest way to do this?
The best way I know is to run npm info express version and then update each dependency in package.json manually. There must be a better way.
{
"name": "myproject",
"description": "my node project",
"version": "1.0.0",
"dependencies": {
"express": "^3.0.3", // how do I get these bumped to latest?
"mongodb": "^1.2.5",
"underscore": "^1.4.2"
}
}
For Yarn-specific solutions, refer to this Stack Overflow question.
",https://stackoverflow.com/questions/16073603/how-can-i-update-each-dependency-in-package-json-to-the-latest-version,2949,1958210.0,43.0,,,2013-04-18 02:39:04,2026-04-15 14:04:41,2024-03-01 23:23:25,,,node.js;npm,Raine Revere,34453,480608,registered,true,16074029,,CC BY-SA 4.0,2018-12-20 04:42:02,1117,793,3,2,0,2,true,false,false,true,true,true,71,12,true,0.022,0.0015,4965,2013,4,2,Thursday,false,false,false,false,false,false,false
44206782,Do I commit the package-lock.json file created by npm 5?,"npm 5 was released today and one of the new features include deterministic installs with the creation of a package-lock.json file.
Is this file supposed to be kept in source control?
I'm assuming it's similar to yarn.lock and composer.lock, both of which are supposed to be kept in source control.
",https://stackoverflow.com/questions/44206782/do-i-commit-the-package-lock-json-file-created-by-npm-5,2547,1183440.0,15.0,,,2017-05-26 17:03:32,2025-03-02 22:02:56,,,,node.js;git;npm;version-control;lockfile,rink.attendant.6,46924,404623,registered,true,44210813,,CC BY-SA 3.0,2024-07-03 09:50:11,662,301,3,3,0,5,true,false,false,true,true,false,56,10,true,0.013,0.0022,3466,2017,5,17,Friday,false,false,false,false,false,false,false
5266152,How to exit in Node.js,"What is the command that is used to exit? (i.e terminate the Node.js process)
",https://stackoverflow.com/questions/5266152/how-to-exit-in-node-js,2374,1315949.0,25.0,,,2011-03-10 21:30:05,2026-10-24 01:16:47,2018-08-14 03:09:53,,,node.js,700 Software,88369,463304,registered,true,5266239,,CC BY-SA 4.0,,85,78,0,0,0,1,true,false,false,true,true,true,22,5,false,0.019,0.0018,5735,2011,3,21,Thursday,false,false,false,false,false,false,false
6237295,How can I update Node.js and npm to their latest versions?,"I just installed Node.js and npm. I installed npm for access to additional Node.js modules. After I installed Node.js and npm, I noticed that neither were the latest versions available.
So my questions are:
- How do I upgrade Node.js,
npm and my Node.js modules to their latest versions?
- Do I need to uninstall Node.js and
npm, and reinstall the latest versions?
",https://stackoverflow.com/questions/6237295/how-can-i-update-node-js-and-npm-to-their-latest-versions,2264,2740639.0,68.0,,,2011-06-04 14:28:33,2024-08-16 19:58:42,2024-06-08 02:57:41,,,node.js;npm;node-modules;npm-update,Dail,22851,783783,unregistered,true,,,CC BY-SA 4.0,2018-04-17 09:52:09,553,363,5,1,0,4,false,false,false,true,true,true,58,11,true,0.025,0.0008,5649,2011,6,14,Saturday,true,false,false,false,false,false,false
47190861,How can the default Node.js version be set using NVM?,"I have installed nvm (Node.js with Z shell (executable zsh) (executable zsh) shell) with two Node.js versions: v6.11.5 and v9.0.0, and the default version in nvm is the v9.0.0.
Every time I need to change the Node.js version,
nvm list
Output:
v6.11.5
-> v9.0.0
system
default -> node (-> v9.0.0)
node -> stable (-> v9.0.0) (default)
stable -> 9.0 (-> v9.0.0) (default)
And:
nvm v6
How could I change the nvm version default to define v6.11.5?
",https://stackoverflow.com/questions/47190861/how-can-the-default-node-js-version-be-set-using-nvm,1936,1947698.0,29.0,,,2017-11-08 22:34:07,2026-01-12 21:14:59,2026-01-06 12:34:47,,,node.js;version;nvm,Pablo Ezequiel Inchausti,21533,5111441,registered,true,47787025,,CC BY-SA 4.0,,810,491,5,1,0,3,true,false,false,true,true,true,53,10,true,0.015,0.001,3300,2017,11,22,Wednesday,false,false,false,false,false,false,false
6912584,How to get GET (query string) variables in Express.js on Node.js?,"Can we get the variables in the query string in Node.js just like we get them in $_GET in PHP?
I know that in Node.js we can get the URL in the request. Is there a method to get the query string parameters?
",https://stackoverflow.com/questions/6912584/how-to-get-get-query-string-variables-in-express-js-on-node-js,1615,2026952.0,27.0,,,2011-08-02 13:08:31,2024-11-19 10:32:46,2015-05-04 12:01:05,,,node.js;query-string;express,XMen,30344,434893,registered,true,6912872,,CC BY-SA 3.0,2019-03-07 12:46:53,235,208,1,0,0,3,true,false,false,true,true,true,65,11,true,0.013,0.0008,5590,2011,8,13,Tuesday,false,false,false,false,false,false,false
4482686,Check synchronously if file/directory exists in Node.js,"How can I synchronously check, using node.js, if a file or directory exists?
",https://stackoverflow.com/questions/4482686/check-synchronously-if-file-directory-exists-in-node-js,1523,1035040.0,19.0,,,2010-12-19 11:19:43,2025-03-10 10:39:19,2020-01-20 14:04:27,,,node.js;fs,user196106,,,does_not_exist,true,4482701,,CC BY-SA 4.0,,101,77,0,0,0,2,true,false,false,true,false,true,55,7,false,0.018,0.0015,5816,2010,12,11,Sunday,true,false,false,false,false,false,false
16151018,How to fix npm throwing error without sudo,"I just installed node and npm through the package on nodejs.org, and whenever I try to search or install something with npm, it throws the following error unless I sudo the command. I have a feeling this is a permissions issue? I am already the admin.
npm ERR! Error: EACCES, open '/Users/chietala/.npm/-/all/.cache.json'
npm ERR! { [Error: EACCES, open '/Users/chietala/.npm/-/all/.cache.json']
npm ERR! errno: 3,
npm ERR! code: 'EACCES',
npm ERR! path: '/Users/chietala/.npm/-/all/.cache.json' }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.
npm ERR! System Darwin 12.2.0
npm ERR! command "node" "/usr/local/bin/npm" "search" "bower"
npm ERR! cwd /Users/chietala
npm ERR! node -v v0.10.4
npm ERR! npm -v 1.2.18
npm ERR! path /Users/chietala/.npm/-/all/.cache.json
npm ERR! code EACCES
npm ERR! errno 3
npm ERR! stack Error: EACCES, open '/Users/chietala/.npm/-/all/.cache.json'
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! /Users/chietala/npm-debug.log
npm ERR! not ok code 0
",https://stackoverflow.com/questions/16151018/how-to-fix-npm-throwing-error-without-sudo,1521,745724.0,40.0,,,2013-04-22 15:35:37,2025-10-23 11:07:11,2022-06-11 10:01:46,,,node.js;unix;permissions;npm;sudo,Chad,18456,228833,registered,true,41395398,,CC BY-SA 4.0,2015-07-05 14:26:18,1164,1094,1,0,0,5,true,false,false,true,true,true,42,8,false,0.054,0.002,4961,2013,4,15,Monday,false,false,false,false,false,false,false
13066532,How can I uninstall npm modules in Node.js?,"As commonly known, any npm module can be installed by running a simple command: npm install <module_name>.
I have installed a few modules that I do not use any more and I just want to get them off. I have a few questions regarding this:
Do we have any command or process to uninstall a module from the root (something like npm uninstall <module_name>)
or will simply removing the module files do?
How does it affect us if we keep the unused modules?
",https://stackoverflow.com/questions/13066532/how-can-i-uninstall-npm-modules-in-node-js,1425,1713561.0,24.0,,,2012-10-25 10:23:26,2024-08-08 05:32:01,2021-01-04 05:12:48,,,node.js;npm,Manish Kumar,15537,1649960,registered,true,13066677,,CC BY-SA 4.0,2018-02-10 00:35:15,547,466,2,0,0,2,true,false,false,true,true,true,43,8,true,0.014,0.0008,5140,2012,10,10,Thursday,false,false,false,false,false,false,false
3133243,How do I get the path to the current script with Node.js?,"How would I get the path to the script in Node.js?
I know there's process.cwd, but that only refers to the directory where the script was called, not of the script itself. For instance, say I'm in /home/kyle/ and I run the following command:
node /home/kyle/some/dir/file.js
If I call process.cwd(), I get /home/kyle/, not /home/kyle/some/dir/. Is there a way to get that directory?
",https://stackoverflow.com/questions/3133243/how-do-i-get-the-path-to-the-current-script-with-node-js,1371,1282365.0,15.0,,,2010-06-28 14:31:01,2025-05-14 14:30:40,2016-12-17 12:03:54,,,node.js,Kyle Slattery,35198,135180,registered,true,3133313,,CC BY-SA 3.0,2018-08-14 18:56:22,498,388,6,0,0,1,true,false,false,true,true,true,57,12,true,0.012,0.0011,5990,2010,6,14,Monday,false,false,false,false,false,false,false
6084360,Using Node.js as a simple web server,"I want to run a very simple HTTP server. Every GET request to example.com should get index.html served to it but as a regular HTML page (i.e., same experience as when you read normal web pages).
Using the code below, I can read the content of index.html. How do I serve index.html as a regular web page?
var http = require('http');
var fs = require('fs');
var index = fs.readFileSync('index.html');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(index);
}).listen(9615);
One suggestion below is complicated and requires me to write a get line for each resource (CSS, JavaScript, images) file I want to use.
How can I serve a single HTML page with some images, CSS and JavaScript?
",https://stackoverflow.com/questions/6084360/using-node-js-as-a-simple-web-server,1318,1455740.0,35.0,,,2011-05-21 20:44:56,2024-05-05 11:43:44,2021-06-23 09:14:34,,,node.js;server;webserver,idophir,14909,294194,registered,true,,,CC BY-SA 4.0,2015-02-25 17:47:50,867,746,6,0,0,3,false,false,false,true,true,true,36,7,false,0.024,0.0009,5663,2011,5,20,Saturday,true,false,false,false,false,false,false
22891211,What is the difference between --save and --save-dev?,"What is the difference between:
npm install [package_name]
and:
npm install [package_name] --save
and:
npm install [package_name] --save-dev
What does this mean? And what is really the effect of --save and -dev keywords?
",https://stackoverflow.com/questions/22891211/what-is-the-difference-between-save-and-save-dev,1309,577771.0,18.0,,,2014-04-06 07:34:11,2022-01-04 22:53:56,2020-09-20 06:45:15,,,node.js;npm;save;package,nfort,13224,3503026,registered,true,42206389,,CC BY-SA 4.0,,350,224,5,0,0,4,true,false,false,true,true,true,53,8,true,0.031,0.0023,4612,2014,4,7,Sunday,true,false,false,false,false,false,false
15890958,How to install a previous exact version of a NPM package?,"I used nvm to download node v0.4.10 and installed npm to work with that version of node.
I am trying to install express using
npm install express -g
and I get an error that express requires node version >= 0.5.0.
Well, this is odd, since I am following the directions for a node+express+mongodb tutorial here that used node v0.4.10, so I am assuming express is/was available to node v0.4.10. If my assumption is correct, how do I tell npm to fetch a version that would work with my setup?
",https://stackoverflow.com/questions/15890958/how-to-install-a-previous-exact-version-of-a-npm-package,1296,1386081.0,10.0,,,2013-04-08 23:44:51,2025-01-30 06:51:47,2019-12-26 12:39:08,,,node.js;npm,stewart99,15264,1459782,registered,true,15892076,,CC BY-SA 4.0,2022-10-27 17:05:37,658,497,1,1,0,2,true,false,false,true,true,true,57,11,true,0.007,0.0009,4975,2013,4,23,Monday,false,false,false,false,false,false,false
6182315,How can I do Base64 encoding in Node.js?,"Does Node.js have built-in Base64 encoding yet?
The reason why I ask this is that final() from crypto can only output hexadecimal, binary or ASCII data. For example:
var cipher = crypto.createCipheriv('des-ede3-cbc', encryption_key, iv);
var ciph = cipher.update(plaintext, 'utf8', 'hex');
ciph += cipher.final('hex');
var decipher = crypto.createDecipheriv('des-ede3-cbc', encryption_key, iv);
var txt = decipher.update(ciph, 'hex', 'utf8');
txt += decipher.final('utf8');
According to the documentation, update() can output Base64-encoded data. However, final() doesn't support Base64. I tried and it will break.
If I do this:
var ciph = cipher.update(plaintext, 'utf8', 'base64');
ciph += cipher.final('hex');
Then what should I use for decryption? Hexadecimal or Base64?
Therefore, I'm looking for a function to Base64-encode my encrypted hexadecimal output.
",https://stackoverflow.com/questions/6182315/how-can-i-do-base64-encoding-in-node-js,1293,1196012.0,8.0,,,2011-05-31 02:09:42,2023-11-09 03:42:28,2021-08-01 22:11:46,,,node.js;encoding;base64,murvinlai,50655,196874,registered,true,6182519,,CC BY-SA 4.0,,1012,870,6,0,0,3,true,false,false,true,true,true,40,8,true,0.007,0.0011,5653,2011,5,2,Tuesday,false,false,false,false,false,false,false
10075990,Upgrading Node.js to the latest version,"So, I have Node.js installed and now when I tried to install Mongoosejs, I got an error telling me that I don't have the needed version of Node.js (I have v0.4.11 and v0.4.12 is needed).
How can I upgrade to this version? I suppose I just could install it again with the latest version, but I don't want to do it before I'm sure that my project folders in the folder "node" won't be deleted.
",https://stackoverflow.com/questions/10075990/upgrading-node-js-to-the-latest-version,1236,2762996.0,41.0,,,2012-04-09 16:02:57,2026-02-06 04:09:11,2024-03-13 03:22:50,2025-11-10 14:25:58,Duplicate,node.js;upgrade,holyredbeard,21718,937624,registered,true,10076029,,,2017-11-07 10:43:14,416,402,0,0,0,2,true,true,false,true,true,true,39,6,false,0.015,0.0004,5339,2012,4,16,Monday,false,false,false,false,false,false,false
21194934,How to create a directory if it doesn't exist using Node.js,"Is the following the right way to create a directory if it doesn't exist?
It should have full permission for the script and readable by others.
var dir = __dirname + '/upload';
if (!path.existsSync(dir)) {
fs.mkdirSync(dir, 0744);
}
",https://stackoverflow.com/questions/21194934/how-to-create-a-directory-if-it-doesnt-exist-using-node-js,1204,1020936.0,25.0,,,2014-01-17 20:08:41,2025-01-08 00:36:15,2021-05-04 16:43:56,,,node.js,Whisher,32986,356380,registered,true,26815894,,CC BY-SA 4.0,2015-07-14 09:25:14,276,238,1,0,0,1,true,false,false,true,true,true,63,11,false,0.024,0.0012,4691,2014,1,20,Friday,false,false,false,false,false,false,false
6158933,How is an HTTP POST request made in node.js?,"How can I make an outbound HTTP POST request, with data, in node.js?
",https://stackoverflow.com/questions/6158933/how-is-an-http-post-request-made-in-node-js,1155,1638768.0,24.0,,,2011-05-28 00:44:10,2025-05-14 11:52:22,2019-03-05 02:35:51,,,node.js;http;post;httprequest,Mark,70538,298406,registered,true,6158966,,CC BY-SA 4.0,2018-07-27 10:27:22,76,69,0,0,0,4,true,false,false,true,true,true,44,9,true,0.015,0.0007,5656,2011,5,0,Saturday,true,false,false,false,false,false,false
5009324,Node.js + Nginx - What now?,"I've set up Node.js and Nginx on my server. Now I want to use it, but, before I start there are 2 questions:
- How should they work together? How should I handle the requests?
There are 2 concepts for a Node.js server, which one is better:
a. Create a separate HTTP server for each website that needs it. Then load all JavaScript code at the start of the program, so the code is interpreted once.
b. Create one single Node.js server which handles all Node.js requests. This reads the requested files and evals their contents. So the files are interpreted on each request, but the server logic is much simpler.
It's not clear for me how to use Node.js correctly.
",https://stackoverflow.com/questions/5009324/node-js-nginx-what-now,1140,448896.0,12.0,,,2011-02-15 20:49:02,2023-01-17 22:40:08,2015-04-17 23:55:36,,,node.js;nginx;concept,Van Coding,24620,461872,registered,true,5015178,,CC BY-SA 3.0,2015-07-16 07:02:44,731,669,0,0,0,3,true,false,false,true,true,true,27,6,true,0.027,0.0025,5758,2011,2,20,Tuesday,false,false,false,false,false,false,false
25093276,"Node.js/Windows error: ENOENT, stat 'C:\Users\RT\AppData\Roaming\npm'","I have Windows 7 32-bit. I installed the latest Node.js 32 bit.
When I try to run the command npm install jquery, I receive the error:
Error: ENOENT, stat 'C:\Users\RT\AppData\Roaming\npm
How does one resolve it?
",https://stackoverflow.com/questions/25093276/node-js-windows-error-enoent-stat-c-users-rt-appdata-roaming-npm,1132,449103.0,12.0,,,2014-08-02 08:45:08,2024-09-19 11:24:25,2020-04-19 13:44:48,,,windows;node.js;installation,tryasko,11457,2112191,registered,true,25095327,,CC BY-SA 4.0,2014-08-14 11:03:56,351,220,1,1,0,3,true,false,false,true,true,true,77,5,false,0.027,0.0025,4494,2014,8,8,Saturday,true,false,false,false,false,false,false
11284634,Upgrade Node.js to the latest version on Mac OS,"Currently I am using Node.js v0.6.16 on Mac OS X 10.7.4. Now I want to upgrade it to the latest Node.js v0.8.1. But after downloading and installing the latest package file from nodejs.org, I found that system is still using v0.6.16 instead of v0.8.1 when I typed ""node -v"" in a terminal. Is there any step that I have missed? Or, should I thoroughly uninstall the old version before installing the latest one?
BTW, I know that nvm can help to manage the nodejs package
https://github.com/creationix/nvm/
Is there any way to upgrade the Node.js without using it?
I have googled this problem, but it seems to me that there is no very clear answer to this question for the latest Node.js.
",https://stackoverflow.com/questions/11284634/upgrade-node-js-to-the-latest-version-on-mac-os,1075,1324916.0,32.0,,,2012-07-01 18:33:31,2025-07-15 15:53:34,2019-02-03 17:15:57,,,macos;node.js;upgrade,afterglowlee,12500,1472418,registered,true,19333717,,CC BY-SA 4.0,2018-03-24 05:47:36,792,691,0,1,0,3,true,false,false,true,true,true,47,9,false,0.024,0.0008,5256,2012,7,18,Sunday,true,false,false,false,false,false,false
9781218,How to change node.js's console font color?,"I had to change the console background color to white because of eye problems, but the font is gray colored and it makes the messages unreadable. How can I change it?
",https://stackoverflow.com/questions/9781218/how-to-change-node-jss-console-font-color,1044,685691.0,43.0,,,2012-03-20 04:07:02,2025-01-12 08:51:32,2023-04-05 20:44:29,,,node.js;colors;console;ansi-escape,MaiaVictor,53537,1031791,registered,true,41407246,,CC BY-SA 4.0,,174,167,0,0,0,4,true,false,false,true,true,true,47,7,true,0.063,0.0015,5359,2012,3,4,Tuesday,false,false,false,false,false,false,false
5726729,How to parse JSON using Node.js?,"How should I parse JSON using Node.js? Is there some module which will validate and parse JSON securely?
",https://stackoverflow.com/questions/5726729/how-to-parse-json-using-node-js,1040,1082610.0,31.0,,,2011-04-20 07:10:52,2022-04-14 23:04:11,2016-08-03 10:22:11,2020-09-14 20:11:14,Needs more focus,javascript;json;node.js,Tikhon Jelvis,68340,286871,registered,true,5726756,,,,112,105,0,0,0,3,true,true,false,true,true,true,32,6,true,0.029,0.001,5694,2011,4,7,Wednesday,false,false,true,false,false,false,false
16525430,npm check and update package if needed,"We need to integrate the Karma test runner into TeamCity, and for that, I'd like to give systems engineers a small script (PowerShell or whatever) that would:
pick up the desired version number from some configuration file (I guess I can put it as a comment right in the karma.conf.js file)
check if the defined version of Karma runner installed in npm's global repository
if it's not, or the installed version is older than desired: pick up and install the right version
run it:
karma start .\Scripts-Tests\karma.conf.js --reporters teamcity --single-run
So my real question is: How can one check in a script, if desired version of package installed?. Should you do the check, or is it safe to just call npm -g install every time?
I don't want to always check and install the latest available version, because other configuration values may become incompatible.
",https://stackoverflow.com/questions/16525430/npm-check-and-update-package-if-needed,1021,1446520.0,24.0,,,2013-05-13 15:12:22,2026-02-11 14:44:47,2026-01-05 13:30:07,,,node.js;teamcity;npm;karma-runner,iLemming,36934,116395,registered,true,16532884,,CC BY-SA 4.0,,1119,870,2,1,0,4,true,false,false,true,true,true,38,7,false,0.017,0.0007,4940,2013,5,15,Monday,false,false,false,false,false,false,false
45022048,Why does "npm install" rewrite package-lock.json?,"I just recently upgraded to npm@5. I now have a package-lock.json file with everything from package.json. I would expect that, when I run npm install that the dependency versions would be pulled from the lock file to determine what should be installed in my node_modules directory. What's strange is that it actually ends up modifying and rewriting my package-lock.json file.
For example, the lock file had typescript specified to be at version 2.1.6. Then, after the npm install command, the version was changed to 2.4.1. That seems to defeat the whole purpose of a lock file.
What am I missing? How do I get npm to actually respect my lock file?
",https://stackoverflow.com/questions/45022048/why-does-npm-install-rewrite-package-lock-json,979,519809.0,12.0,,,2017-07-10 21:38:49,2024-07-09 18:47:35,2020-04-01 20:43:32,,,node.js;npm;npm-install;package-lock.json,Viper Bailey,12167,1141343,registered,true,45566871,,CC BY-SA 4.0,,766,656,2,0,0,4,true,false,false,true,true,true,59,6,true,0.023,0.0019,3421,2017,7,21,Monday,false,false,false,false,false,false,false
30950032,How can I run multiple npm scripts in parallel?,"In my package.json I have these two scripts:
""scripts"": {
""start-watch"": ""nodemon run-babel index.js"",
""wp-server"": ""webpack-dev-server"",
}
I have to run these 2 scripts in parallel everytime I start developing in Node.js. The first thing I thought of was adding a third script like this:
""dev"": ""npm run start-watch && npm run wp-server""
... but that will wait for start-watch to finish before running wp-server.
How can I run these in parallel? Please keep in mind that I need to see the output of these commands. Also, if your solution involves a build tool, I'd rather use gulp instead of grunt because I already use it in another project.
",https://stackoverflow.com/questions/30950032/how-can-i-run-multiple-npm-scripts-in-parallel,975,849994.0,33.0,,,2015-06-20 03:42:47,2026-09-23 15:58:27,2017-11-27 20:59:35,,,javascript;node.js;build,Andre Pena,59792,192729,registered,true,30950298,,CC BY-SA 3.0,2017-12-18 04:41:44,859,671,8,0,0,3,true,false,false,true,true,true,47,9,true,0.039,0.0011,4172,2015,6,3,Saturday,true,false,true,false,false,false,false
6157497,Printing to console without a trailing newline?,"Is there a method for printing to the console without a trailing newline? The console object documentation doesn't say anything regarding that:
console.log()
Prints to stdout with newline. This function can take multiple arguments in a printf()-like way. Example:
console.log('count: %d', count);
If formating elements are not found in the first string then util.inspect is used on each argument.
",https://stackoverflow.com/questions/6157497/printing-to-console-without-a-trailing-newline,960,598829.0,9.0,,,2011-05-27 20:42:34,2025-08-15 10:19:00,2025-08-15 10:19:00,,,node.js;console;console.log,Evan Carroll,85092,124486,registered,true,6157569,,CC BY-SA 4.0,2015-04-25 19:35:40,635,400,5,1,0,3,true,false,false,true,true,true,47,7,true,0.015,0.0016,5657,2011,5,20,Friday,false,false,false,false,false,false,false
9153571,Is there a way to get the version from the 'package.json' file in Node.js code?,"Is there a way to get the version set in the package.json file in a Node.js application? I would want something like this
var port = process.env.PORT || 3000
app.listen port
console.log "Express server listening on port %d in %s mode %s", app.address().port, app.settings.env, app.VERSION
",https://stackoverflow.com/questions/9153571/is-there-a-way-to-get-the-version-from-the-package-json-file-in-node-js-code,956,639670.0,35.0,,,2012-02-05 22:15:37,2025-11-10 01:11:10,2024-03-13 03:07:17,,,node.js;npm;version;versioning;package.json,Abhik Bose Pramanik,9871,920383,registered,true,10855054,,CC BY-SA 4.0,2019-12-26 23:02:14,431,300,1,1,0,5,true,false,false,true,true,true,87,15,true,0.055,0.0015,5403,2012,2,22,Sunday,true,false,false,false,false,false,false
21117160,What is "export default" in JavaScript?,"File: SafeString.js
// Build out our basic SafeString type
function SafeString(string) {
this.string = string;
}
SafeString.prototype.toString = function() {
return "" + this.string;
};
export default SafeString;
I have never seen export default before. Are there any equivalent stuff for export default that can be easier to understand?
",https://stackoverflow.com/questions/21117160/what-is-export-default-in-javascript,926,833848.0,12.0,,,2014-01-14 15:21:21,2025-01-20 14:46:51,2020-10-03 19:28:17,,,javascript;node.js;ecmascript-6,damphat,19106,813080,registered,true,21117231,,CC BY-SA 4.0,,566,355,3,1,0,3,true,false,false,true,true,true,49,6,true,0.014,0.0011,4694,2014,1,15,Tuesday,false,false,true,false,false,false,false
4075287,"Node / Express: EADDRINUSE, Address already in use - how can I stop the process using the port?","I have a simple server running in node.js using connect:
var server = require('connect').createServer();
//actions...
server.listen(3000);
In my code I have actual route handlers, but that's the basic idea. The error I keep getting is:
EADDRINUSE, Address already in use
I receive this error when running my application again after it previously crashed or errors. Since I am not opening a new instance of terminal I close out the process with ctrl + z.
I am fairly certain all I have to do is close out the server or connection. I tried calling server.close() in process.on('exit', ...); with no luck.
",https://stackoverflow.com/questions/4075287/node-express-eaddrinuse-address-already-in-use-how-can-i-stop-the-process,925,1837033.0,62.0,,,2010-11-02 06:08:27,2025-04-14 06:26:30,2024-02-12 14:22:50,,,node.js;process,Skawful,10067,201271,registered,true,4086015,,CC BY-SA 4.0,2018-04-21 07:32:10,720,605,5,0,0,2,true,false,false,true,true,true,95,18,true,0.034,0.0005,5863,2010,11,6,Tuesday,false,false,false,false,false,false,false
5710358,How to access POST form fields in Express,"Here is my simple form:
<form id=""loginformA"" action=""userlogin"" method=""post"">
<div>
<label for=""email"">Email: </label>
<input type=""text"" id=""email"" name=""email""></input>
</div>
<input type=""submit"" value=""Submit""></input>
</form>
Here is my Express.js/Node.js code:
app.post('/userlogin', function(sReq, sRes){
var email = sReq.query.email.;
}
I tried sReq.query.email or sReq.query['email'] or sReq.params['email'], etc. None of them work. They all return undefined.
When I change to a Get call, it works, so .. any idea?
",https://stackoverflow.com/questions/5710358/how-to-access-post-form-fields-in-express,924,974431.0,24.0,,,2011-04-19 00:38:39,2022-08-09 02:31:52,2022-04-23 22:22:26,,,javascript;node.js;post;express,murvinlai,50655,196874,registered,true,12008719,,CC BY-SA 4.0,2020-09-10 08:09:34,851,629,6,1,0,4,true,false,false,true,true,true,41,8,false,0.025,0.0009,5695,2011,4,0,Tuesday,false,false,true,false,false,false,false
35612428,Call async/await functions in parallel,"As far as I understand, in ES7/ES2016 putting multiple await's in code will work similar to chaining .then() with promises, meaning that they will execute one after the other rather than in parallel. So, for example, we have this code:
await someCall();
await anotherCall();
Do I understand it correctly that anotherCall() will be called only when someCall() is completed? What is the most elegant way of calling them in parallel?
I want to use it in Node, so maybe there's a solution with async library?
EDIT: I'm not satisfied with the solution provided in this question: Slowdown due to non-parallel awaiting of promises in async generators, because it uses generators and I'm asking about a more general use case.
",https://stackoverflow.com/questions/35612428/call-async-await-functions-in-parallel,923,603827.0,12.0,,,2016-02-24 20:28:46,2023-06-05 12:37:02,2020-12-25 01:07:25,,,javascript;node.js;asynchronous;ecmascript-6;babeljs,Victor Marchuk,13974,860478,registered,true,35612484,,CC BY-SA 4.0,2019-08-16 09:42:08,952,719,5,1,0,5,true,false,false,true,true,true,38,5,false,0.02,0.0015,3923,2016,2,20,Wednesday,false,false,true,false,false,false,false
55921442,How to fix "ReferenceError: primordials is not defined" in Node.js,"I have installed Node.js modules by 'npm install', and then I tried to do gulp sass-watch in a command prompt. After that, I got the below response.
[18:18:32] Requiring external module babel-register
fs.js:27
const { Math, Object, Reflect } = primordials;
^
ReferenceError: primordials is not defined
I have tried this before gulp sass-watch:
npm -g install gulp-cli
",https://stackoverflow.com/questions/55921442/how-to-fix-referenceerror-primordials-is-not-defined-in-node-js,920,1112047.0,44.0,,,2019-04-30 12:57:10,2025-04-29 07:25:14,2021-05-14 12:06:05,,,node.js;sass;gulp;gulp-sass,Ramesh,9361,363127,registered,true,55926692,,CC BY-SA 4.0,2020-03-29 22:19:14,571,405,4,0,0,4,true,false,false,true,true,true,76,10,false,0.04,0.0008,2762,2019,4,12,Tuesday,false,false,false,false,false,false,false
16827858,Error "npm WARN package.json: No repository field","I installed Express.js with the following command:
sudo npm install -g express
I get the following warnings:
npm WARN package.json range-parser@0.0.4 No repository field.
npm WARN package.json fresh@0.1.0 No repository field.
npm WARN package.json methods@0.0.1 No repository field.
npm WARN package.json methods@0.0.1 No readme data.
npm WARN package.json cookie-signature@1.0.1 No repository field.
npm WARN package.json send@0.1.0 No repository field.
npm WARN package.json pause@0.0.1 No repository field.
npm WARN package.json bytes@0.2.0 No repository field.
npm WARN package.json github-url-from-git@1.1.1 No repository field.
npm WARN package.json assert-plus@0.1.2 No repository field.
npm WARN package.json ctype@0.5.2 No repository field.
Why do I have the above warnings? Should I be worried?
",https://stackoverflow.com/questions/16827858/error-npm-warn-package-json-no-repository-field,917,670873.0,12.0,,,2013-05-30 04:18:43,2024-03-04 18:51:22,2022-12-29 02:31:13,,,node.js;express;npm,JR Galia,17269,851029,registered,true,16827990,,CC BY-SA 4.0,,954,807,2,0,0,3,true,false,false,true,true,true,60,7,false,0.018,0.0014,4923,2013,5,4,Thursday,false,false,false,false,false,false,false
9268259,How do you prevent install of "devDependencies" NPM modules for Node.js (package.json)?,"I have this in my package.json file (shortened version):
{
""name"": ""a-module"",
""version"": ""0.0.1"",
""dependencies"": {
""coffee-script"": "">= 1.1.3""
},
""devDependencies"": {
""stylus"": "">= 0.17.0""
}
}
I am using NPM version 1.1.1 on Mac 10.6.8.
When I run the following command from the project root, it installs both the dependencies and devDependencies:
npm install
I was under the impression that this command installed the devDependencies:
npm install --dev
How do I make it so npm install only installs dependencies (so production environment only gets those modules), while something like npm install --dev installs both dependencies and devDependencies?
",https://stackoverflow.com/questions/9268259/how-do-you-prevent-install-of-devdependencies-npm-modules-for-node-js-package,914,682932.0,15.0,,,2012-02-13 21:25:10,2024-10-09 12:57:20,2016-04-16 04:16:39,,,node.js;npm,Lance Pollard,80714,169992,registered,true,9276112,,CC BY-SA 3.0,,928,708,11,0,0,2,true,false,false,true,true,true,97,12,true,0.022,0.0013,5395,2012,2,21,Monday,false,false,false,false,false,false,false
28725955,How do I test a single file using Jest?,"I am able to test multiple files using Jest, but I cannot figure out how to test a single file.
I have:
- Run
npm install jest-cli --save-dev
- Updated
package.json: `{ ... "scripts": { "test": "jest" } ... }
- Written a number of tests.
Running npm test works as expected (currently it runs 14 tests).
How do I test a single file, e.g. test app/foo/__tests__/bar.spec.js?
I have tried running npm test app/foo/__tests__/bar.spec.js (from the project root), but I get the following error:
npm ERR! Error: ENOENT, open '/node_modules/app/foo/tests/bar.spec.js/package.json'
",https://stackoverflow.com/questions/28725955/how-do-i-test-a-single-file-using-jest,911,1289994.0,34.0,,,2015-02-25 17:42:00,2023-07-23 08:05:43,2020-09-24 18:17:48,,,node.js;jestjs,Musket,9525,1139936,registered,true,28739855,,CC BY-SA 4.0,2021-12-26 11:42:32,786,601,5,0,0,2,true,false,false,true,true,true,39,9,true,0.026,0.0007,4287,2015,2,17,Wednesday,false,false,false,false,false,false,false
11616630,How can I print a circular structure in a JSON-like format?,"I have a big object I want to convert to JSON and send. However it has circular structure, so if I try to use JSON.stringify() I'll get:
TypeError: Converting circular structure to JSON
or
TypeError: cyclic object value
I want to toss whatever circular references exist and send whatever can be stringified. How do I do that?
Thanks.
var obj = {
a: "foo",
b: obj
}
I want to stringify obj into:
{"a":"foo"}
",https://stackoverflow.com/questions/11616630/how-can-i-print-a-circular-structure-in-a-json-like-format,906,968670.0,32.0,,,2012-07-23 16:30:22,2024-02-24 00:16:23,2023-02-14 17:45:12,,,javascript;json;node.js,Harry,55539,663447,registered,true,11616993,,CC BY-SA 4.0,2016-07-22 21:03:04,607,447,3,0,0,3,true,false,false,true,true,true,59,11,true,0.033,0.0009,5234,2012,7,16,Monday,false,false,true,false,false,false,false
24585261,nvm keeps "forgetting" node in new terminal session,"Upon using a new terminal session in OS X, nvm forgets the node version and defaults to nothing:
$ nvm ls:
.nvm
v0.11.12
v0.11.13
I have to keep hitting nvm use v.0.11.13 in every session:
.nvm
v0.11.12
-> v0.11.13
I've tried both the brew install, as well as the official installation script.
My .profile for the brew version:
#nvm
export NVM_DIR=~/.nvm
source $(brew --prefix nvm)/nvm.sh
And for the install.sh script:
$ curl https://raw.githubusercontent.com/creationix/nvm/v0.10.0/install.sh | bash
#nvm
export NVM_DIR=""/Users/farhad/.nvm""
[ -s ""$NVM_DIR/nvm.sh"" ] && . ""$NVM_DIR/nvm.sh"" # This loads nvm
Any clue to what I'm doing wrong?
",https://stackoverflow.com/questions/24585261/nvm-keeps-forgetting-node-in-new-terminal-session,900,326555.0,35.0,,,2014-07-05 10:05:25,2026-02-10 14:16:29,2015-11-09 13:41:07,,,node.js;macos;npm;homebrew;nvm,frhd,10454,2491198,registered,true,24587177,,CC BY-SA 3.0,,956,705,10,0,0,5,true,false,false,true,true,true,61,8,false,0.107,0.0028,4522,2014,7,10,Saturday,true,false,false,false,false,false,false
10011011,How do I read a JSON file into (server) memory?,"I am doing some experimentation with Node.js and would like to read a JSON object, either from a text file or a .js file (which is better??) into memory so that I can access that object quickly from code. I realize that there are things like Mongo, Alfred, etc out there, but that is not what I need right now.
How do I read a JSON object out of a text or js file and into server memory using JavaScript/Node?
",https://stackoverflow.com/questions/10011011/how-do-i-read-a-json-file-into-server-memory,887,855552.0,14.0,,,2012-04-04 12:22:40,2025-01-03 13:49:40,2024-05-22 10:57:34,,,javascript;json;node.js,Matt Cashatt,24376,856790,registered,true,10011078,,CC BY-SA 4.0,2019-05-02 09:00:04,425,411,0,0,0,3,true,false,false,true,true,true,47,10,true,0.016,0.001,5344,2012,4,12,Wednesday,false,false,true,false,false,false,false
9023672,How do I resolve "Cannot find module" error using Node.js?,"After pulling down a module from GitHub and following the instructions to build it, I try pulling it into an existing project using:
> npm install ../faye
This appears to do the trick:
> npm list
/home/dave/src/server
└─┬ faye@0.7.1
├── cookiejar@1.3.0
├── hiredis@0.1.13
└── redis@0.7.1
But Node.js can't find the module:
> node app.js
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: Cannot find module 'faye'
at Function._resolveFilename (module.js:334:11)
at Function._load (module.js:279:25)
at Module.require (module.js:357:17)
at require (module.js:368:17)
at Object.<anonymous> (/home/dave/src/server/app.js:2:12)
at Module._compile (module.js:432:26)
at Object..js (module.js:450:10)
at Module.load (module.js:351:31)
at Function._load (module.js:310:12)
at Array.0 (module.js:470:10)
I really want to understand what is going on here, but I'm at a bit of a loss as to where to look next. Any suggestions?
",https://stackoverflow.com/questions/9023672/how-do-i-resolve-cannot-find-module-error-using-node-js,886,3403700.0,34.0,,,2012-01-26 18:57:42,2024-07-17 10:28:24,2016-10-25 15:24:42,,,node.js,Dave Causey,14298,97434,registered,true,9023864,,CC BY-SA 3.0,2017-10-17 13:16:52,1146,1046,3,0,0,1,true,false,false,true,true,true,68,10,true,0.01,0.0003,5413,2012,1,18,Thursday,false,false,false,false,false,false,false
22519784,How do I convert an existing callback API to promises?,"I want to work with promises but I have a callback API in a format like:
###1. DOM load or other one time event:
window.onload; // set to callback
...
window.onload = function() {
};
###2. Plain callback:
function request(onChangeHandler) {
...
}
request(function() {
// change happened
...
});
###3. Node style callback ("nodeback"):
function getStuff(dat, callback) {
...
}
getStuff("dataParam", function(err, data) {
...
})
###4. A whole library with node style callbacks:
API;
API.one(function(err, data) {
API.two(function(err, data2) {
API.three(function(err, data3) {
...
});
});
});
How do I work with the APIs in promises, how do I "promisify" them?
",https://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises,884,343181.0,24.0,,,2014-03-19 22:47:26,2025-08-19 14:13:13,2024-06-20 18:06:26,,,javascript;node.js;callback;promise;bluebird,Benjamin Gruenbaum,277974,1348195,registered,true,22519785,,CC BY-SA 4.0,2020-04-12 03:59:56,888,750,4,0,0,5,true,false,false,true,true,true,54,10,true,0.07,0.0026,4630,2014,3,22,Wednesday,false,false,true,false,false,false,false
16333790,Node.js quick file server (static files over HTTP),"Is there Node.js ready-to-use tool (installed with npm), that would help me expose folder content as file server over HTTP.
Example, if I have
D:\Folder\file.zip
D:\Folder\file2.html
D:\Folder\folder\file-in-folder.jpg
Then starting in D:\Folder\ node node-file-server.js
I could access file via
http://hostname/file.zip
http://hostname/file2.html
http://hostname/folder/file-in-folder.jpg
Why is my node static file server dropping requests?
reference some mystical
standard node.js static file server
If there's no such tool, what framework should I use?
Related:
Basic static file server in NodeJS
",https://stackoverflow.com/questions/16333790/node-js-quick-file-server-static-files-over-http,880,796106.0,30.0,,,2013-05-02 08:45:51,2026-04-18 11:34:40,2017-05-23 12:18:24,2026-05-05 18:07:33,Not suitable for this site,node.js;http;fileserver,Paul Verest on LinkedIn,64938,482717,registered,true,16350826,,,,981,616,5,2,0,3,true,true,false,true,true,true,50,8,false,0.038,0.0011,4951,2013,5,8,Thursday,false,false,false,false,false,false,false
20643470,Execute a command line binary with Node.js,"I am in the process of porting a CLI library from Ruby over to Node.js. In my code I execute several third party binaries when necessary. I am not sure how best to accomplish this in Node.
Here's an example in Ruby where I call PrinceXML to convert a file to a PDF:
cmd = system(""prince -v builds/pdf/book.html -o builds/pdf/book.pdf"")
What is the equivalent code in Node?
",https://stackoverflow.com/questions/20643470/execute-a-command-line-binary-with-node-js,879,937625.0,13.0,,,2013-12-17 19:56:26,2025-08-07 17:09:21,2015-06-23 10:10:40,,,javascript;ruby;node.js;command-line-interface,Dave Thompson,9041,1114095,registered,true,,,CC BY-SA 3.0,2019-07-29 16:31:55,422,377,1,0,0,4,false,false,false,true,true,true,42,7,false,0.014,0.0009,4722,2013,12,19,Tuesday,false,false,true,false,false,false,false
7137397,module.exports vs exports in Node.js,"I've found the following contract in a Node.js module:
module.exports = exports = nano = function database_module(cfg) {...}
I wonder what's the difference between module.exports and exports and why both are used here.
",https://stackoverflow.com/questions/7137397/module-exports-vs-exports-in-node-js,869,363289.0,24.0,,,2011-08-21 09:16:55,2023-10-13 12:57:35,2021-07-24 12:33:47,,,javascript;node.js;commonjs,Andreas Köberle,111734,184883,registered,true,7142924,,CC BY-SA 4.0,,284,220,3,0,0,3,true,false,false,true,true,true,36,5,false,0.066,0.0024,5571,2011,8,9,Sunday,true,false,true,false,false,false,false
5315138,node.js remove file,"How do I delete a file with node.js?
http://nodejs.org/api/fs.html#fs_fs_rename_oldpath_newpath_callback
I don't see a remove command?
",https://stackoverflow.com/questions/5315138/node-js-remove-file,850,974987.0,27.0,,,2011-03-15 16:55:43,2024-08-05 12:28:48,2013-02-22 13:51:07,,,node.js,Mark,33891,115608,registered,true,5315175,,CC BY-SA 3.0,,257,137,0,1,0,1,true,false,false,true,true,true,19,3,false,0.028,0.0009,5730,2011,3,16,Tuesday,false,false,false,false,false,false,false
29349684,How can I specify the required Node.js version in package.json?,"I have a Node.js project that requires Node version 12 or higher. Is there a way to specify this in the packages.json file, so that the installer will automatically check and inform the users if they need to upgrade?
",https://stackoverflow.com/questions/29349684/how-can-i-specify-the-required-node-js-version-in-package-json,839,664261.0,8.0,,,2015-03-30 15:06:17,2025-09-18 00:43:16,2020-07-21 10:50:26,,,node.js;npm;package;version,Erel Segal-Halevi,37617,827927,registered,true,29349773,,CC BY-SA 4.0,2019-11-13 14:56:07,237,217,1,0,0,4,true,false,false,true,true,true,63,10,true,0.012,0.0013,4254,2015,3,15,Monday,false,false,false,false,false,false,false
19917401,Error: request entity too large,"I'm receiving the following error with express:
Error: request entity too large
at module.exports (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/node_modules/raw-body/index.js:16:15)
at json (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/middleware/json.js:60:5)
at Object.bodyParser [as handle] (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/middleware/bodyParser.js:53:5)
at next (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/proto.js:193:15)
at Object.cookieParser [as handle] (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/middleware/cookieParser.js:60:5)
at next (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/proto.js:193:15)
at Object.logger (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/middleware/logger.js:158:5)
at next (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/proto.js:193:15)
at Object.staticMiddleware [as handle] (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/middleware/static.js:55:61)
at next (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/proto.js:193:15)
TypeError: /Users/michaeljames/Documents/Projects/Proj/mean/app/views/includes/foot.jade:31
29| script(type=""text/javascript"", src=""/js/socketio/connect.js"")
30|
> 31| if (req.host='localhost')
32| //Livereload script rendered
33| script(type='text/javascript', src='http://localhost:35729/livereload.js')
34|
Cannot set property 'host' of undefined
at eval (eval at <anonymous> (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/jade/lib/jade.js:152:8), <anonymous>:273:15)
at /Users/michaeljames/Documents/Projects/Proj/mean/node_modules/jade/lib/jade.js:153:35
at Object.exports.render (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/jade/lib/jade.js:197:10)
at Object.exports.renderFile (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/jade/lib/jade.js:233:18)
at View.exports.renderFile [as engine] (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/jade/lib/jade.js:218:21)
at View.render (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/lib/view.js:76:8)
at Function.app.render (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/lib/application.js:504:10)
at ServerResponse.res.render (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/lib/response.js:801:7)
at Object.handle (/Users/michaeljames/Documents/Projects/Proj/mean/config/express.js:82:29)
at next (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/proto.js:188:17)
POST /api/0.1/people 500 618ms
I am using meanstack. I have the following use statements in my express.js
//Set Request Size Limit
app.use(express.limit(100000000));
Within fiddler I can see the content-length header with a value of: 1078702
I believe this is in octets, this is 1.0787 megabytes.
I have no idea why express is not letting me post the json array I was posting previously in another express project that was not using the mean stack project structure.
",https://stackoverflow.com/questions/19917401/error-request-entity-too-large,833,835167.0,35.0,,,2013-11-11 22:40:25,2025-07-02 13:33:51,2016-12-13 18:40:36,,,javascript;node.js;http;express,mike james,9480,1885205,registered,true,19965089,,CC BY-SA 3.0,2021-05-02 06:11:03,3653,3570,2,0,0,4,true,false,false,true,true,true,31,5,false,0.042,0.001,4758,2013,11,22,Monday,false,false,true,false,false,false,false
16904658,Node Version Manager install - nvm command not found,"I am trying to install NVM as per these instructions
I typed in this command in terminal:
$ curl https://raw.github.com/creationix/nvm/master/install.sh | sh
After running the install, I restart the terminal and attempt to install Node.js with this command:
$ nvm install 0.8
but I get the response:
-bash: nvm: command not found
I'm not sure what I am doing wrong here.
Additional Info:
I've been looking around for solutions from other posts and forums. I found another solution using
$ git clone git://github.com/creationix/nvm.git ~/.nvm
but this times out every time I attempt that.
",https://stackoverflow.com/questions/16904658/node-version-manager-install-nvm-command-not-found,831,1717259.0,38.0,,,2013-06-03 19:46:18,2024-07-17 08:54:28,2023-08-31 23:02:46,,,node.js;terminal;nvm,jordan,11042,1210614,registered,true,16905910,,CC BY-SA 4.0,2018-05-20 18:17:25,824,592,4,1,0,3,true,false,false,true,true,true,52,9,false,0.022,0.0005,4919,2013,6,19,Monday,false,false,false,false,false,false,false
33535879,How to run TypeScript files from command line?,"I'm having a surprisingly hard time finding an answer to this. With plain Node.JS, you can run any js file with node path/to/file.js, with CoffeeScript it's coffee hello.coffee and ES6 has babel-node hello.js. How do I do the same with Typescript?
My project has a tsconfig.json which is used by Webpack/ts-loader to build a nice little bundle for the browser. I have a need for a build step run from the console before that, though, that would use some of the .ts files used in the project to generate a schema, but I can't seem to be able to run a single Typescript file without compiling the whole project.
",https://stackoverflow.com/questions/33535879/how-to-run-typescript-files-from-command-line,831,1287970.0,29.0,,,2015-11-05 02:54:39,2026-06-16 21:17:36,,,,node.js;typescript,Gunchars,11256,357978,registered,true,33536053,,CC BY-SA 3.0,2018-04-20 07:12:15,690,611,5,0,0,2,true,false,false,true,true,false,46,8,true,0.023,0.0006,4034,2015,11,2,Thursday,false,false,false,false,false,false,false
7310521,Node.js Handling Uncaught Exceptions,"I just started trying out node.js a few days ago. I've realized that the Node is terminated whenever I have an unhandled exception in my program. This is different than the normal server container that I have been exposed to where only the Worker Thread dies when unhandled exceptions occur and the container would still be able to receive the request. This raises a few questions:
- Is
process.on('uncaughtException') the only effective way to guard against it?
- Will
process.on('uncaughtException') catch the unhandled exception during execution of asynchronous processes as well?
- Is there a module that is already built (such as sending email or writing to a file) that I could leverage in the case of uncaught exceptions?
As someone new to node.js, what is an effective way of handling uncaught exceptions within my code when running in node.js?
",https://stackoverflow.com/questions/7310521/node-js-handling-uncaught-exceptions,831,610521.0,11.0,,,2011-09-05 16:15:20,2025-10-02 17:50:10,2025-10-02 17:50:10,2025-09-26 18:50:58,Opinion-based,node.js;exception;serverside-javascript,momo,21381,576119,registered,true,7313005,,,,925,849,2,0,0,3,true,true,false,true,true,true,36,4,false,0.018,0.0014,5556,2011,9,16,Monday,false,false,false,false,false,false,false
33527653,Babel 6 regeneratorRuntime is not defined,"I'm trying to use async/await from scratch on Babel 6, but I'm getting regeneratorRuntime is not defined.
.babelrc file
{
"presets": [ "es2015", "stage-0" ]
}
package.json file
"devDependencies": {
"babel-core": "^6.0.20",
"babel-preset-es2015": "^6.0.15",
"babel-preset-stage-0": "^6.0.15"
}
.js file
"use strict";
async function foo() {
await bar();
}
function bar() { }
exports.default = foo;
Using it normally without the async/await works just fine. Any ideas what I'm doing wrong?
",https://stackoverflow.com/questions/33527653/babel-6-regeneratorruntime-is-not-defined,829,778995.0,48.0,,,2015-11-04 16:58:28,2022-05-13 14:21:08,2021-08-23 08:50:13,,,javascript;node.js;babeljs,BrunoLM,100882,340760,registered,true,33527883,,CC BY-SA 4.0,,738,618,4,0,0,3,true,false,false,true,true,true,41,6,false,0.062,0.0011,4035,2015,11,16,Wednesday,false,false,true,false,false,false,false
14249506,How can I wait In Node.js (JavaScript)? l need to pause for a period of time,"I'm developing a console script for personal needs. I need to be able to pause for an extended amount of time, but, from my research, Node.js has no way to stop as required. It’s getting hard to read users’ information after a period of time... I’ve seen some code out there, but I believe they have to have other code inside of them for them to work such as:
setTimeout(function() {
}, 3000);
However, I need everything after this line of code to execute after the period of time.
For example,
// start of code
console.log('Welcome to my console,');
some-wait-code-here-for-ten-seconds...
console.log('Blah blah blah blah extra-blah');
// end of code
I've also seen things like
yield sleep(2000);
But Node.js doesn't recognize this.
How can I achieve this extended pause?
",https://stackoverflow.com/questions/14249506/how-can-i-wait-in-node-js-javascript-l-need-to-pause-for-a-period-of-time,817,1520164.0,27.0,,,2013-01-10 01:37:22,2024-09-12 13:04:20,2020-06-17 05:28:25,,,javascript;node.js;async-await;yield,Christopher Allen,8679,1940587,registered,true,41957152,,CC BY-SA 4.0,2017-07-13 07:13:54,1044,819,3,0,0,4,true,false,false,true,true,true,76,16,false,0.018,0.0005,5063,2013,1,1,Thursday,false,false,true,false,false,false,false
50093144,MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client,"I can't make a simple connection to the server for some reason. I install the newest MySQL Community 8.0 database along with Node.JS with default settings.
This is my node.js code
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "password",
insecureAuth : true
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
Below is the error found in Command Prompt:
C:\Users\mysql-test>node app.js
C:\Users\mysql-test\node_modules\mysql\lib\protocol\Parse
r.js:80
throw err; // Rethrow non-MySQL errors
^
Error: ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server; consider upgrading MySQL client
at Handshake.Sequence._packetToError (C:\Users\mysql-
test\node_modules\mysql\lib\protocol\sequences\Sequence.js:52:14)
at Handshake.ErrorPacket (C:\Users\mysql-test\node_mo
dules\mysql\lib\protocol\sequences\Handshake.js:130:18)
at Protocol._parsePacket (C:\Users\mysql-test\node_mo
dules\mysql\lib\protocol\Protocol.js:279:23)
at Parser.write (C:\Users\mysql-test\node_modules\mys
ql\lib\protocol\Parser.js:76:12)
at Protocol.write (C:\Users\mysql-test\node_modules\m
ysql\lib\protocol\Protocol.js:39:16)
at Socket.<anonymous> (C:\Users\mysql-test\node_modul
es\mysql\lib\Connection.js:103:28)
at Socket.emit (events.js:159:13)
at addChunk (_stream_readable.js:265:12)
at readableAddChunk (_stream_readable.js:252:11)
at Socket.Readable.push (_stream_readable.js:209:10)
--------------------
at Protocol._enqueue (C:\Users\mysql-test\node_module
s\mysql\lib\protocol\Protocol.js:145:48)
at Protocol.handshake (C:\Users\mysql-test\node_modul
es\mysql\lib\protocol\Protocol.js:52:23)
at Connection.connect (C:\Users\mysql-test\node_modul
es\mysql\lib\Connection.js:130:18)
at Object.<anonymous> (C:\Users\mysql-test\server.js:
11:5)
at Module._compile (module.js:660:30)
at Object.Module._extensions..js (module.js:671:10)
at Module.load (module.js:573:32)
at tryModuleLoad (module.js:513:12)
at Function.Module._load (module.js:505:3)
at Function.Module.runMain (module.js:701:10)
I've read up on some things such as:
https://dev.mysql.com/doc/refman/5.5/en/old-client.html
https://github.com/mysqljs/mysql/issues/1507
But I am still not sure how to fix my problem.
",https://stackoverflow.com/questions/50093144/mysql-8-0-client-does-not-support-authentication-protocol-requested-by-server,803,1192028.0,35.0,,,2018-04-30 02:04:31,2024-03-01 12:33:03,2023-02-18 21:40:19,,,mysql;node.js,Pig ,8125,7680167,registered,true,50131831,,CC BY-SA 4.0,2018-11-20 20:10:23,2789,2509,2,2,0,2,true,false,false,true,true,true,112,16,false,0.029,0.0007,3127,2018,4,2,Monday,false,false,false,false,false,false,false
3459476,How to append to a file in Node?,"I am trying to append a string to a log file. However writeFile will erase the content each time before writing the string.
fs.writeFile('log.txt', 'Hello Node', function (err) {
if (err) throw err;
console.log('It\'s saved!');
}); // => message.txt erased, contains only 'Hello Node'
Any idea how to do this the easy way?
",https://stackoverflow.com/questions/3459476/how-to-append-to-a-file-in-node,797,874869.0,18.0,,,2010-08-11 14:37:31,2024-08-01 08:50:14,2020-07-08 18:06:24,,,javascript;node.js;fs;appendfile,supercobra,16432,210006,registered,true,11267583,,CC BY-SA 4.0,2015-09-07 15:53:17,380,333,1,0,0,4,true,false,false,true,true,true,32,8,true,0.021,0.0009,5946,2010,8,14,Wednesday,false,false,true,false,false,false,false
6156501,Read a file one line at a time in node.js?,"I am trying to read a large file one line at a time. I found a question on Quora that dealt with the subject but I'm missing some connections to make the whole thing fit together.
var Lazy=require(""lazy"");
new Lazy(process.stdin)
.lines
.forEach(
function(line) {
console.log(line.toString());
}
);
process.stdin.resume();
The bit that I'd like to figure out is how I might read one line at a time from a file instead of STDIN as in this sample.
I tried:
fs.open('./VeryBigFile.csv', 'r', '0666', Process);
function Process(err, fd) {
if (err) throw err;
// DO lazy read
}
but it's not working. I know that in a pinch I could fall back to using something like PHP, but I would like to figure this out.
I don't think the other answer would work as the file is much larger than the server I'm running it on has memory for.
",https://stackoverflow.com/questions/6156501/read-a-file-one-line-at-a-time-in-node-js,792,781917.0,31.0,,,2011-05-27 18:49:48,2026-03-13 08:28:49,2016-03-07 20:24:15,,,javascript;node.js;file-io;lazy-evaluation,Alex C,17134,398055,registered,true,32599033,,CC BY-SA 3.0,2021-04-16 12:20:36,1092,897,2,1,0,4,true,false,false,true,true,true,42,10,true,0.04,0.001,5657,2011,5,18,Friday,false,false,true,false,false,false,false
7067966,Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?,"I am trying to support CORS in my Node.js application that uses the Express.js web framework. I have read a Google group discussion about how to handle this, and read a few articles about how CORS works. First, I did this (code is written in CoffeeScript syntax):
app.options ""*"", (req, res) ->
res.header 'Access-Control-Allow-Origin', '*'
res.header 'Access-Control-Allow-Credentials', true
# try: 'POST, GET, PUT, DELETE, OPTIONS'
res.header 'Access-Control-Allow-Methods', 'GET, OPTIONS'
# try: 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept'
res.header 'Access-Control-Allow-Headers', 'Content-Type'
# ...
It doesn't seem to work. It seems like my browser (Chrome) is not sending the initial OPTIONS request. When I just updated the block for the resource I need to submit a cross-origin GET request to:
app.get ""/somethingelse"", (req, res) ->
# ...
res.header 'Access-Control-Allow-Origin', '*'
res.header 'Access-Control-Allow-Credentials', true
res.header 'Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS'
res.header 'Access-Control-Allow-Headers', 'Content-Type'
# ...
It works (in Chrome). This also works in Safari.
I have read that...
In a browser implementing CORS, each cross-origin GET or POST request is preceded by an OPTIONS request that checks whether the GET or POST is OK.
So my main question is, how come this doesn't seem to happen in my case? Why isn't my app.options block called? Why do I need to set the headers in my main app.get block?
",https://stackoverflow.com/questions/7067966/why-doesnt-adding-cors-headers-to-an-options-route-allow-browsers-to-access-my,773,937017.0,39.0,,,2011-08-15 16:53:23,2024-12-25 16:18:32,2019-06-17 10:58:09,,,node.js;express;coffeescript;cors,mikong,8390,855425,registered,true,8572637,,CC BY-SA 4.0,2017-10-27 08:04:10,1769,1543,2,1,0,4,true,false,false,true,true,true,88,15,true,0.042,0.0008,5577,2011,8,16,Monday,false,false,false,false,false,false,false
4295782,How to process POST data in Node.js?,"How do you extract form data (form[method=""post""]) and file uploads sent from the HTTP POST method in Node.js?
I've read the documentation, googled and found nothing.
function (request, response) {
//request.post????
}
Is there a library or a hack?
",https://stackoverflow.com/questions/4295782/how-to-process-post-data-in-node-js,771,1308517.0,30.0,,,2010-11-28 07:16:28,2024-07-06 06:01:24,2019-01-03 22:04:35,,,node.js;http-post,Ming-Tang,17729,303939,registered,true,4296402,,CC BY-SA 4.0,2017-12-03 00:09:59,379,257,3,1,0,2,true,false,false,true,true,true,36,7,true,0.023,0.0006,5837,2010,11,7,Sunday,true,false,false,false,false,false,false
48910876,"Error: EACCES: permission denied, access '/usr/local/lib/node_modules'","What might be causing the error Error: EACCES: permission denied, access '/usr/local/lib/node_modules'?
npm ERR! path /usr/local/lib/node_modules
npm ERR! code EACCES
npm ERR! errno -13
npm ERR! syscall access
npm ERR! Error: EACCES: permission denied, access '/usr/local/lib/node_modules'
npm ERR! { Error: EACCES: permission denied, access '/usr/local/lib/node_modules'
npm ERR! errno: -13,
npm ERR! code: 'EACCES',
npm ERR! syscall: 'access',
npm ERR! path: '/usr/local/lib/node_modules' }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/macbookmd101/.npm/_logs/2018-02-21T16_26_08_421Z-debug.log
",https://stackoverflow.com/questions/48910876/error-eacces-permission-denied-access-usr-local-lib-node-modules,764,1015361.0,43.0,,,2018-02-21 16:30:30,2025-02-09 21:10:55,2020-08-24 09:40:32,,,node.js;npm;permission-denied,hendra dedi,7784,9322906,registered,true,51024493,,CC BY-SA 4.0,2019-07-29 16:19:22,761,717,2,0,0,3,true,false,false,true,true,true,78,6,false,0.042,0.0008,3195,2018,2,16,Wednesday,false,false,false,false,false,false,false
9679932,How can I use executables from a package installed locally in node_modules?,"How do I use a local version of a module in Node.js? For example, in my app, I installed the coffee-script package:
npm install coffee-script
This installs it in ./node_modules and the coffee command is in ./node_modules/.bin/coffee. Is there a way to run this command when I'm in my project's main folder? I guess I'm looking for something similar to bundle exec in bundler. Basically, I'd like to specify a version of coffee-script that everyone involved with the project should use.
I know I can add the -g flag to install it globally, so the coffee executable works fine anywhere, but what if I wanted to have different versions of coffee per project?
",https://stackoverflow.com/questions/9679932/how-can-i-use-executables-from-a-package-installed-locally-in-node-modules,763,525311.0,26.0,,,2012-03-13 07:31:06,2026-08-20 20:21:33,2026-06-12 01:42:21,,,node.js;coffeescript;npm;node-modules,typeoneerror,57218,53653,registered,true,15157360,,CC BY-SA 4.0,,888,657,3,1,0,4,true,false,false,true,true,true,75,12,true,0.049,0.0015,5366,2012,3,7,Tuesday,false,false,false,false,false,false,false
15806152,How do I override nested NPM dependency versions?,"I would like to use the grunt-contrib-jasmine NPM package. It has various dependencies. Part of the dependency graph looks like this:
─┬ grunt-contrib-jasmine@0.4.1
│ ├─┬ grunt-lib-phantomjs@0.2.0
│ │ ├─┬ phantomjs@1.8.2-2
Unfortunately, there's a bug in this version phantomjs which prevents it from installing correctly on Mac OS X. This is fixed in the latest version.
How can I get grunt-lib-phantomjs to use a newer version of phantomjs?
Some additional context:
grunt-contrib-jasmine explicitly requires version ""~0.2.0"" of grunt-lib-phantomjs, which explicitly requires version ""~1.8.1"" of phantomjs.
- Adding
phantomjs to my package's dependencies first has no effect; both versions are installed and grunt-contrib-jasmine still uses the older versions (see: When installing a package with NPM, can you tell it to use a different version of one of its dependencies?).
",https://stackoverflow.com/questions/15806152/how-do-i-override-nested-npm-dependency-versions,759,681557.0,12.0,,,2013-04-04 08:30:15,2024-03-06 12:12:04,2017-05-23 11:47:28,,,node.js;npm,georgebrock,30733,5168,registered,true,70396201,,CC BY-SA 3.0,,1262,884,12,1,0,2,true,false,false,true,true,true,49,8,true,0.018,0.0011,4979,2013,4,8,Thursday,false,false,false,false,false,false,false
14381898,Local dependency in package.json,"I want to do something like this, so npm install also installs the package.json of ../somelocallib or more importantly its dependencies.
"dependencies": {
"express": "*",
"../somelocallib": "*"
}
",https://stackoverflow.com/questions/14381898/local-dependency-in-package-json,754,835326.0,20.0,,,2013-01-17 15:02:38,2024-12-17 07:16:41,2024-03-05 18:02:24,,,node.js;npm,user1680104,8977,1680104,registered,true,,,CC BY-SA 4.0,,364,255,4,0,0,2,false,false,false,true,true,true,32,4,false,0.024,0.0009,5056,2013,1,15,Thursday,false,false,false,false,false,false,false
8191459,How do I update Node.js?,"I did the following to update my npm:
npm update npm -g
But I have no idea how to update Node.js. Any suggestions? (I'm using Node.js 0.4.1 and want to update to Node.js 0.6.1.)
",https://stackoverflow.com/questions/8191459/how-do-i-update-node-js,742,4601299.0,30.0,,,2011-11-19 02:37:17,2026-01-07 00:18:27,2017-11-08 20:57:32,,,node.js;software-update,wyc,55767,122536,registered,true,8191466,,CC BY-SA 3.0,,220,182,1,0,0,2,true,false,false,true,true,true,24,5,true,0.007,0.0002,5481,2011,11,2,Saturday,true,false,false,false,false,false,false
14888471,Node.js version on the command line? (not the REPL),"I want to get the version of Node.js on the command line. I'm expecting to run a command like:
node -version
but that doesn't work. Does anybody know what the command line would be? (i.e. not the REPL)
",https://stackoverflow.com/questions/14888471/node-js-version-on-the-command-line-not-the-repl,737,1600130.0,10.0,,,2013-02-15 04:54:33,2023-11-20 10:47:53,2020-02-28 11:57:11,,,node.js;command-line,hawkeye,36068,15441,registered,true,14888509,,CC BY-SA 4.0,2015-04-23 20:27:17,243,205,1,0,0,2,true,false,false,true,true,true,51,9,false,0.006,0.0005,5027,2013,2,4,Friday,false,false,false,false,false,false,false
34855352,"How, in general, does Node.js handle 10,000 concurrent requests?","I understand that Node.js uses a single-thread and an event loop to process requests only processing one at a time (which is non-blocking). But still, how does that work, lets say 10,000 concurrent requests. The event loop will process all the requests? Would not that take too long?
I can not understand (yet) how it can be faster than a multi-threaded web server. I understand that multi-threaded web server will be more expensive in resources (memory, CPU), but would not it still be faster? I am probably wrong; please explain how this single-thread is faster in lots of requests, and what it typically does (in high level) when servicing lots of requests like 10,000.
And also, will that single-thread scale well with that large amount? Please bear in mind that I am just starting to learn Node.js.
",https://stackoverflow.com/questions/34855352/how-in-general-does-node-js-handle-10-000-concurrent-requests,736,266323.0,9.0,,,2016-01-18 12:56:56,2022-12-02 07:45:09,2019-06-17 11:05:47,,,node.js,g_b,12568,3591953,registered,true,34857298,,CC BY-SA 4.0,,827,806,0,0,0,1,true,false,false,true,true,true,64,9,true,0.034,0.0028,3960,2016,1,12,Monday,false,false,false,false,false,false,false
22675725,How to find unused packages in package.json?,"Is there a way to determine if you have packages in your package.json file that are no longer needed?
For instance, when trying out a package and later commenting or deleting code, but forgetting to uninstall it, I end up with a couple packages that could be deleted.
What would be an efficient way to determine if a package could safely be deleted?
",https://stackoverflow.com/questions/22675725/how-to-find-unused-packages-in-package-json,733,493771.0,14.0,,,2014-03-27 00:10:45,2024-12-05 13:34:26,2023-05-11 14:52:22,,,node.js;npm;dependencies;package.json,Josh C,8691,965935,registered,true,27362322,,CC BY-SA 4.0,,384,350,1,0,0,4,true,false,false,true,true,true,44,7,true,0.028,0.0015,4622,2014,3,0,Thursday,false,false,false,false,false,false,false
37986800,Node Sass couldn't find a binding for your current environment,"I am having issues building an app because node-sass keeps failing with the error.
ERROR in Missing binding /Users/warren/Sites/random-docs/my-cms/node_modules/node-sass/vendor/darwin-x64-11/binding.node
Node Sass could not find a binding for your current environment: OS X 64-bit with Node 0.10.x
I have tried running
npm rebuild node-sass
which says
Binary is fine; exiting.
When running node -v I get v6.2.2
Which is different to what the sass error says ""Node 0.10.x"". I can't figure out why it is getting the wrong version. I have also tried removing the node_modules folder and running npm update or npm install, both of which did not resolve the issue. Any ideas?
",https://stackoverflow.com/questions/37986800/node-sass-couldnt-find-a-binding-for-your-current-environment,724,541323.0,63.0,,,2016-06-23 08:57:39,2025-02-25 05:27:56,2019-10-13 14:16:13,,,node.js;npm,wazzaday,9674,1349895,registered,true,,,CC BY-SA 4.0,2019-04-08 08:53:53,829,689,2,0,0,2,false,false,false,true,true,true,66,10,false,0.116,0.0013,3803,2016,6,8,Thursday,false,false,false,false,false,false,false
7718313,How to change to an older version of Node.js,"I am running Node.js version v0.5.9-pre on Ubuntu 10.10.
I would like to be using version v0.5.0-pre.
How do I roll back to the older version of node?
",https://stackoverflow.com/questions/7718313/how-to-change-to-an-older-version-of-node-js,724,2107069.0,26.0,,,2011-10-10 20:30:08,2024-11-18 22:37:04,2018-06-11 02:25:01,,,node.js,JD Isaacks,57820,46011,registered,true,7718438,,CC BY-SA 4.0,2022-10-24 14:42:41,201,154,2,0,0,1,true,false,false,true,true,true,44,9,false,0.012,0.0003,5521,2011,10,20,Monday,false,false,false,false,false,false,false
9901082,What is "require" in JavaScript and NodeJS?,"I'm trying to get JavaScript to read/write to a PostgreSQL database. I found this project on GitHub. I was able to get the following sample code to run in Node.
var pg = require('pg'); //native libpq bindings = `var pg = require('pg').native`
var conString = "tcp://postgres:1234@localhost/postgres";
var client = new pg.Client(conString);
client.connect();
//queries are queued and executed one after another once the connection becomes available
client.query("CREATE TEMP TABLE beatles(name varchar(10), height integer, birthday timestamptz)");
client.query("INSERT INTO beatles(name, height, birthday) values($1, $2, $3)", ['Ringo', 67, new Date(1945, 11, 2)]);
client.query("INSERT INTO beatles(name, height, birthday) values($1, $2, $3)", ['John', 68, new Date(1944, 10, 13)]);
//queries can be executed either via text/parameter values passed as individual arguments
//or by passing an options object containing text, (optional) parameter values, and (optional) query name
client.query({
name: 'insert beatle',
text: "INSERT INTO beatles(name, height, birthday) values($1, $2, $3)",
values: ['George', 70, new Date(1946, 02, 14)]
});
//subsequent queries with the same name will be executed without re-parsing the query plan by postgres
client.query({
name: 'insert beatle',
values: ['Paul', 63, new Date(1945, 04, 03)]
});
var query = client.query("SELECT * FROM beatles WHERE name = $1", ['John']);
//can stream row results back 1 at a time
query.on('row', function(row) {
console.log(row);
console.log("Beatle name: %s", row.name); //Beatle name: John
console.log("Beatle birth year: %d", row.birthday.getYear()); //dates are returned as javascript dates
console.log("Beatle height: %d' %d\"", Math.floor(row.height/12), row.height%12); //integers are returned as javascript ints
});
//fired after last row is emitted
query.on('end', function() {
client.end();
});
Next I tried to make it run on a webpage, but nothing seemed to happen. I checked on the JavaScript console and it just says
Uncaught ReferenceError: require is not defined
So what is this "require"? Why does it work in Node but not in a webpage?
Also, before I got it to work in Node, I had to do npm install pg. What's that about? I looked in the directory and didn't find a file pg. Where did it put it, and how does JavaScript find it?
",https://stackoverflow.com/questions/9901082/what-is-require-in-javascript-and-nodejs,724,1111471.0,8.0,,,2012-03-28 04:18:58,2026-06-03 12:46:41,2023-08-18 15:38:20,,,javascript;node.js,neuromancer,56059,209512,registered,true,9901097,,CC BY-SA 4.0,2013-05-02 19:52:10,2617,2449,2,1,0,2,true,false,false,true,true,true,53,7,true,0.007,0.0007,5351,2012,3,4,Wednesday,false,false,true,false,false,false,false
5869216,How to store Node.js deployment settings/configuration files?,"I have been working on a few Node apps, and I've been looking for a good pattern of storing deployment-related settings. In the Django world (where I come from), the common practise would be to have a settings.py file containing the standard settings (timezone, etc), and then a local_settings.py for deployment specific settings, ie. what database to talk to, what memcache socket, e-mail address for the admins and so on.
I have been looking for similar patterns for Node. Just a config file would be nice, so it does not have to be jammed in with everything else in app.js, but I find it important to have a way to have server-specific configuration in a file that is not in source control. The same app could well be deployed across different servers with wildly different settings, and having to deal with merge conflicts and all that is not my idea of fun.
So is there some kind of framework/tool for this, or does everyone just hack something together themselves?
",https://stackoverflow.com/questions/5869216/how-to-store-node-js-deployment-settings-configuration-files,720,620132.0,30.0,,,2011-05-03 12:09:07,2022-11-30 06:06:10,,,,node.js;configuration-files,mikl,24467,66851,registered,true,8563528,,CC BY-SA 3.0,,1033,973,3,0,0,2,true,false,false,true,true,false,61,7,true,0.048,0.0012,5681,2011,5,12,Tuesday,false,false,false,false,false,false,false
10112178,Differences between Socket.IO and websockets,"What are the differences between Socket.IO and websockets in Node.js?
Are they both server push technologies?
The only differences I felt was,
Socket.IO allowed me to send/emit messages by specifying an event name.
In the case of Socket.IO a message from server will reach on all clients, but for the same in websockets I was forced to keep an array of all connections and loop through it to send messages to all clients.
Also, I wonder why web inspectors (like Chrome, Firebug, and Fiddler) are unable to catch these messages (from Socket.IO/websocket) from the server?
Please clarify this.
",https://stackoverflow.com/questions/10112178/differences-between-socket-io-and-websockets,719,367376.0,12.0,,,2012-04-11 18:57:04,2026-01-24 22:25:26,2025-11-26 01:21:48,,,node.js;google-chrome;firebug;websocket;socket.io,Vivek Mohan,8414,1087106,registered,true,10112562,,CC BY-SA 4.0,2016-07-28 08:13:59,743,596,0,1,0,5,true,false,false,true,true,true,44,5,false,0.033,0.002,5337,2012,4,18,Wednesday,false,false,false,false,false,false,false
2387724,Node.js on multi-core machines,"Node.js looks interesting, BUT I must be missing something - isn't Node.js tuned only to run on a single process and thread?
Then how does it scale for multi-core CPUs and multi-CPU servers? After all, it is great to make a single-threaded server as fast as possible, but for high loads I would want to use several CPUs. And the same goes for making applications faster - seems today the way is use multiple CPUs and parallelize the tasks.
How does Node.js fit into this picture? Is its idea to somehow distribute multiple instances or what?
",https://stackoverflow.com/questions/2387724/node-js-on-multi-core-machines,715,280309.0,17.0,,,2010-03-05 15:13:47,2024-06-30 21:09:07,2024-06-29 04:19:56,,,javascript;node.js;node-cluster,zaharpopov,17408,206855,registered,true,,,CC BY-SA 4.0,,648,542,0,1,0,3,false,false,false,true,true,true,30,4,false,0.061,0.0026,6105,2010,3,15,Friday,false,false,true,false,false,false,false
58384179,SyntaxError: Cannot use import statement outside a module,"I've got an ApolloServer project that's giving me trouble, so I thought I might update it and ran into issues when using the latest Babel. My "index.js" is:
require('dotenv').config()
import {startServer} from './server'
startServer()
And when I run it I get the error
SyntaxError: Cannot use import statement outside a module
First I tried doing things to convince TPTB* that this was a module (with no success). So I changed the "import" to a "require" and this worked.
But now I have about two dozen "imports" in other files giving me the same error.
*I'm sure the root of my problem is that I'm not even sure what's complaining about the issue. I sort of assumed it was Babel 7 (since I'm coming from Babel 6 and I had to change the presets) but I'm not 100% sure.
Most of what I've found for solutions don't seem to apply to straight Node. Like this one here:
ES6 module Import giving "Uncaught SyntaxError: Unexpected identifier"
Says it was resolved by adding "type=module" but this would typically go in the HTML, of which I have none. I've also tried using my project's old presets:
"presets": ["es2015", "stage-2"],
"plugins": []
But that gets me another error: "Error: Plugin/Preset files are not allowed to export objects, only functions."
Here are the dependencies I started with:
"dependencies": {
"@babel/polyfill": "^7.6.0",
"apollo-link-error": "^1.1.12",
"apollo-link-http": "^1.5.16",
"apollo-server": "^2.9.6",
"babel-preset-es2015": "^6.24.1",
",https://stackoverflow.com/questions/58384179/syntaxerror-cannot-use-import-statement-outside-a-module,712,1952220.0,33.0,,,2019-10-14 21:17:18,2025-03-12 21:00:49,2023-03-11 20:14:12,,,javascript;node.js;node-modules;package.json;npm-package,user3810626,7809,3810626,registered,true,59399717,,CC BY-SA 4.0,2021-05-25 10:53:02,2174,1700,3,1,0,5,true,false,false,true,true,true,57,8,false,0.017,0.0004,2595,2019,10,21,Monday,false,false,true,false,false,false,false
8088795,Installing a local module using npm?,"I have a downloaded module repo, I want to install it locally, not globally in another directory?
What is an easy way to do this?
",https://stackoverflow.com/questions/8088795/installing-a-local-module-using-npm,708,668761.0,12.0,,,2011-11-11 01:53:29,2024-11-10 10:26:41,2017-01-27 16:47:34,,,javascript;node.js;npm;package;npm-install,fancy,52121,666564,registered,true,8089029,,CC BY-SA 3.0,,146,132,0,0,0,5,true,false,false,true,true,true,36,6,true,0.018,0.0011,5489,2011,11,1,Friday,false,false,true,false,false,false,false
17007997,How to access the GET parameters after "?" in Express?,"I know how to get the params for queries like this:
app.get('/sample/:id', routes.sample);
In this case, I can use req.params.id to get the parameter (e.g. 2 in /sample/2).
However, for url like /sample/2?color=red, how can I access the variable color?
I tried req.params.color but it didn't work.
",https://stackoverflow.com/questions/17007997/how-to-access-the-get-parameters-after-in-express,707,791660.0,10.0,,,2013-06-09 08:51:44,2023-03-25 19:13:54,2015-11-18 10:22:56,,,node.js;express;query-string,Hanfei Sun,47411,1272683,registered,true,17008027,,CC BY-SA 3.0,,433,303,7,0,0,3,true,false,false,true,true,true,64,10,true,0.013,0.0009,4913,2013,6,8,Sunday,true,false,false,false,false,false,false
10183291,How to get the full URL in Express?,"Let's say my sample URL is
and I say I have the following route
app.get('/one/two', function (req, res) {
var url = req.url;
}
The value of url will be /one/two.
How do I get the full URL in Express?
For example, in the case above, I would like to receive http://example.com/one/two.
",https://stackoverflow.com/questions/10183291/how-to-get-the-full-url-in-express,706,841344.0,20.0,,,2012-04-16 23:57:06,2023-06-23 20:53:28,2021-04-02 06:09:53,,,node.js;url;express,Chris Abrams,43110,586131,registered,true,10185427,,CC BY-SA 4.0,,516,318,4,1,0,3,true,false,false,true,true,true,35,8,true,0.024,0.0008,5332,2012,4,23,Monday,false,false,false,false,false,false,false
24330014,bodyParser is deprecated express 4,"I am using express 4.0 and I'm aware that body parser has been taken out of the express core, I am using the recommended replacement, however I am getting
body-parser deprecated bodyParser: use individual json/urlencoded middlewares server.js:15:12
body-parser deprecated urlencoded: explicitly specify ""extended: true"" for extended parsing node_modules/body-parser/index.js:74:29
Where do I find this supposed middlewares? or should I not be getting this error?
var express = require('express');
var server = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var passport = require('./config/passport');
var routes = require('./routes');
mongoose.connect('mongodb://localhost/myapp', function(err) {
if(err) throw err;
});
server.set('view engine', 'jade');
server.set('views', __dirname + '/views');
server.use(bodyParser());
server.use(passport.initialize());
// Application Level Routes
routes(server, passport);
server.use(express.static(__dirname + '/public'));
server.listen(3000);
",https://stackoverflow.com/questions/24330014/bodyparser-is-deprecated-express-4,691,487354.0,13.0,,,2014-06-20 14:48:08,2022-11-10 16:03:46,,,,node.js;express;middleware,Melbourne2991,11827,1650757,registered,true,24330353,,CC BY-SA 3.0,2014-08-22 02:45:38,1122,1064,2,0,0,3,true,false,false,true,true,false,34,5,false,0.027,0.0014,4537,2014,6,14,Friday,false,false,false,false,false,false,false
11944932,How to download a file with Node.js (without using third-party libraries)?,"How do I download a file with Node.js without using third-party libraries?
I don't need anything special. I only want to download a file from a given URL, and then save it to a given directory.
",https://stackoverflow.com/questions/11944932/how-to-download-a-file-with-node-js-without-using-third-party-libraries,683,927418.0,34.0,,,2012-08-14 02:21:44,2025-02-06 17:33:34,2021-01-29 14:27:41,,,javascript;node.js;download;fs,greepow,7373,1478546,registered,true,11944984,,CC BY-SA 4.0,2022-09-05 07:45:51,226,195,0,0,0,4,true,false,false,true,true,true,74,11,true,0.037,0.0007,5212,2012,8,2,Tuesday,false,false,true,false,false,false,false
12478679,npm install vs. update - what's the difference?,"What is the practical difference between npm install and npm update? When should I use which?
",https://stackoverflow.com/questions/12478679/npm-install-vs-update-whats-the-difference,681,324669.0,7.0,,,2012-09-18 14:07:54,2024-11-07 00:04:01,2017-03-08 17:06:45,,,node.js;npm,Borek Bernard,54018,21728,registered,true,19824154,,CC BY-SA 3.0,,127,94,2,0,0,2,true,false,false,true,true,true,51,8,true,0.022,0.0021,5177,2012,9,14,Tuesday,false,false,false,false,false,false,false
2923858,How to print a stack trace in Node.js?,"Does anyone know how to print a stack trace in Node.js?
",https://stackoverflow.com/questions/2923858/how-to-print-a-stack-trace-in-node-js,674,394299.0,13.0,,,2010-05-27 18:35:59,2024-09-21 13:11:13,2017-12-13 04:12:58,,,javascript;node.js;stack-trace,mike.toString,6749,352269,unregistered,true,,,CC BY-SA 3.0,,63,56,0,0,0,3,false,false,false,true,true,true,38,8,true,0.033,0.0017,6022,2010,5,18,Thursday,false,false,true,false,false,false,false
4018154,How do I run a Node.js app as a background service?,"I want my Node.js server to run in the background, i.e.: when I close my terminal I want my server to keep running. I've googled this and came up with this tutorial, however it doesn't work as intended. So instead of using that daemon script, I thought I just used the output redirection (the 2>&1 >> file part), but this too does not exit - I get a blank line in my terminal, like it's waiting for output/errors.
I've also tried to put the process in the background, but as soon as I close my terminal the process is killed as well.
So how can I leave it running when I shut down my local computer?
Top solutions:
- Systemd (Linux)
- Launchd (Mac)
- node-windows (Windows)
- PM2 (Node.js)
",https://stackoverflow.com/questions/4018154/how-do-i-run-a-node-js-app-as-a-background-service,672,903159.0,31.0,,,2010-10-25 19:34:10,2026-08-08 23:07:12,2026-08-08 23:07:12,,,node.js;process;background;server;daemon,Peter Kruithof,10854,339122,registered,true,29042953,,CC BY-SA 4.0,,1168,698,1,5,0,5,true,false,false,true,true,true,51,11,true,0.034,0.0007,5871,2010,10,19,Monday,false,false,false,false,false,false,false
21978658,Invalidating JSON Web Tokens,"For a new node.js project I'm working on, I'm thinking about switching over from a cookie based session approach (by this, I mean, storing an id to a key-value store containing user sessions in a user's browser) to a token-based session approach (no key-value store) using JSON Web Tokens (jwt).
The project is a game that utilizes socket.io - having a token-based session would be useful in such a scenario where there will be multiple communication channels in a single session (web and socket.io)
How would one provide token/session invalidation from the server using the jwt Approach?
I also wanted to understand what common (or uncommon) pitfalls/attacks I should look out for with this sort of paradigm. For example, if this paradigm is vulnerable to the same/different kinds of attacks as the session store/cookie-based approach.
So, say I have the following (adapted from this and this):
Session Store Login:
app.get('/login', function(request, response) {
var user = {username: request.body.username, password: request.body.password };
// Validate somehow
validate(user, function(isValid, profile) {
// Create session token
var token= createSessionToken();
// Add to a key-value database
KeyValueStore.add({token: {userid: profile.id, expiresInMinutes: 60}});
// The client should save this session token in a cookie
response.json({sessionToken: token});
});
}
Token-Based Login:
var jwt = require('jsonwebtoken');
app.get('/login', function(request, response) {
var user = {username: request.body.username, password: request.body.password };
// Validate somehow
validate(user, function(isValid, profile) {
var token = jwt.sign(profile, 'My Super Secret', {expiresInMinutes: 60});
response.json({token: token});
});
}
--
A logout (or invalidate) for the Session Store approach would require an update to the KeyValueStore
database with the specified token.
It seems like such a mechanism would not exist in the token-based approach since the token itself would contain the info that would normally exist in the key-value store.
",https://stackoverflow.com/questions/21978658/invalidating-json-web-tokens,669,510661.0,34.0,,,2014-02-24 04:02:28,2026-01-11 20:16:49,2014-02-25 07:13:34,,,javascript;node.js;session;session-cookies;jwt,funseiki,9577,865883,registered,true,23089839,,CC BY-SA 3.0,,2476,2150,2,2,0,5,true,false,false,true,true,true,28,4,false,0.067,0.0013,4653,2014,2,4,Monday,false,false,true,false,false,false,false
5284340,"What is Node.js' Connect, Express and "middleware"?","Despite knowing JavaScript quite well, I'm confused what exactly these three projects in Node.js ecosystem do. Is it something like Rails' Rack? Can someone please explain?
",https://stackoverflow.com/questions/5284340/what-is-node-js-connect-express-and-middleware,658,156243.0,9.0,,,2011-03-12 17:59:36,2025-06-21 01:12:54,2013-07-25 05:19:22,,,node.js;middleware,tillda,18790,437523,registered,true,5290324,,CC BY-SA 3.0,,189,173,0,0,0,2,true,false,false,true,true,true,65,7,true,0.058,0.0042,5733,2011,3,17,Saturday,true,false,false,false,false,false,false
31173738,TypeScript getting error TS2304: cannot find name ' require',"I am trying to get my first TypeScript and DefinitelyTyped Node.js application up and running, and running into some errors.
I am getting the error ""TS2304: Cannot find name 'require' "" when I attempt to transpile a simple TypeScript Node.js page. I have read through several other occurrences of this error on Stack Overflow, and I do not think I have similar issues.
I am running at the shell prompt the command:
tsc movie.server.model.ts.
The contents of this file are:
'use strict';
/// <reference path=""typings/tsd.d.ts"" />
/* movie.server.model.ts - definition of movie schema */
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var foo = 'test';
The error is thrown on the var mongoose=require('mongoose') line.
The contents of the typings/tsd.d.ts file are:
/// <reference path=""node/node.d.ts"" />
/// <reference path=""requirejs/require.d.ts"" />
The .d.ts file references were placed in the appropriate folders and added to typings/tsd.d.ts by the commands:
tsd install node --save
tsd install require --save
The produced .js file seems to work fine, so I could ignore the error. But I would appreciate knowing why this error occurs and what I am doing wrong.
",https://stackoverflow.com/questions/31173738/typescript-getting-error-ts2304-cannot-find-name-require,654,917683.0,24.0,,,2015-07-02 00:21:40,2023-03-13 11:17:33,2019-10-21 23:31:22,,,node.js;typescript;definitelytyped,JerryKur,7549,587836,registered,true,35961176,,CC BY-SA 4.0,2019-06-20 07:16:24,1383,1225,5,0,0,3,true,false,false,true,true,true,68,9,false,0.026,0.0007,4160,2015,7,0,Thursday,false,false,false,false,false,false,false
17696801,Express.js - app.listen vs server.listen,"This may be a very basic question but I simply don't get it. What is the difference between creating an app using Express.js and starting the app listening on port 1234, for example:
var express = require('express');
var app = express();
//app.configure, app.use etc
app.listen(1234);
and adding an http server:
var express = require('express');
var http = require('http');
var app = express();
var server = http.createServer(app);
//app.configure, app.use etc
server.listen(1234);
What's the difference?
If I navigate to http://localhost:1234, thus I get the same output.
",https://stackoverflow.com/questions/17696801/express-js-app-listen-vs-server-listen,654,194374.0,6.0,,,2013-07-17 10:01:51,2023-07-10 15:10:31,2017-12-10 18:22:19,,,node.js;express;server,Tamas,11274,969460,registered,true,17697134,,CC BY-SA 3.0,,679,584,3,0,0,3,true,false,false,true,true,true,40,5,false,0.031,0.0034,4875,2013,7,10,Wednesday,false,false,false,false,false,false,false
15693192,Heroku + node.js error (Web process failed to bind to $PORT within 60 seconds of launch),"I have my first node.js app (runs fine locally) - but I am unable to deploy it via heroku (first time w/ heroku as well). The code is below. SO doesn't let me write so much code, so I would just say that the running the code locally as well within my network shows no issue.
var http = require('http');
var fs = require('fs');
var path = require('path');
http.createServer(function (request, response) {
console.log('request starting for ');
console.log(request);
var filePath = '.' + request.url;
if (filePath == './')
filePath = './index.html';
console.log(filePath);
var extname = path.extname(filePath);
var contentType = 'text/html';
switch (extname) {
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
break;
}
path.exists(filePath, function(exists) {
if (exists) {
fs.readFile(filePath, function(error, content) {
if (error) {
response.writeHead(500);
response.end();
}
else {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
}
});
}
else {
response.writeHead(404);
response.end();
}
});
}).listen(5000);
console.log('Server running at http://127.0.0.1:5000/');
Any idea ?
",https://stackoverflow.com/questions/15693192/heroku-node-js-error-web-process-failed-to-bind-to-port-within-60-seconds-of,652,399956.0,40.0,,,2013-03-28 22:20:39,2025-07-15 15:45:45,2013-03-28 22:32:44,,,node.js;heroku,user428900,7201,428900,registered,true,15693371,,CC BY-SA 3.0,2021-10-18 18:38:35,1557,1519,1,0,0,2,true,false,false,true,true,true,88,16,false,0.1,0.0016,4986,2013,3,22,Thursday,false,false,false,false,false,false,false
62096269,Unknown file extension ".ts" for a TypeScript file,"When I try to start my app on Heroku I got the following stack trace.
It is just a basic ts.app like you see with ts-node and nodemon.
I am really interested in what the answer is going to be.
2020-05-30T00:03:12.201106+00:00 heroku[web.1]: Starting process with command `npm start`
2020-05-30T00:03:14.405285+00:00 app[web.1]:
2020-05-30T00:03:14.405303+00:00 app[web.1]: > discordtoornamentmanager@1.0.0 start /app
2020-05-30T00:03:14.405303+00:00 app[web.1]: > ts-node src/App.ts
2020-05-30T00:03:14.405304+00:00 app[web.1]:
2020-05-30T00:03:14.833655+00:00 app[web.1]: (node:23) ExperimentalWarning: The ESM module loader is experimental.
2020-05-30T00:03:14.839311+00:00 app[web.1]: TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /app/src/App.ts
2020-05-30T00:03:14.839312+00:00 app[web.1]: at Loader.defaultGetFormat [as _getFormat] (internal/modules/esm/get_format.js:65:15)
2020-05-30T00:03:14.839314+00:00 app[web.1]: at Loader.getFormat (internal/modules/esm/loader.js:113:42)
2020-05-30T00:03:14.839315+00:00 app[web.1]: at Loader.getModuleJob (internal/modules/esm/loader.js:244:31)
2020-05-30T00:03:14.839315+00:00 app[web.1]: at processTicksAndRejections (internal/process/task_queues.js:97:5)
2020-05-30T00:03:14.839316+00:00 app[web.1]: at Loader.import (internal/modules/esm/loader.js:178:17)
2020-05-30T00:03:14.847801+00:00 app[web.1]: npm ERR! code ELIFECYCLE
2020-05-30T00:03:14.847998+00:00 app[web.1]: npm ERR! errno 1
2020-05-30T00:03:14.848957+00:00 app[web.1]: npm ERR! discordtoornamentmanager@1.0.0 start: `ts-node src/App.ts`
2020-05-30T00:03:14.849050+00:00 app[web.1]: npm ERR! Exit status 1
2020-05-30T00:03:14.849172+00:00 app[web.1]: npm ERR!
2020-05-30T00:03:14.849254+00:00 app[web.1]: npm ERR! Failed at the discordtoornamentmanager@1.0.0 start script.
2020-05-30T00:03:14.849337+00:00 app[web.1]: npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
2020-05-30T00:03:14.854859+00:00 app[web.1]:
2020-05-30T00:03:14.854998+00:00 app[web.1]: npm ERR! A complete log of this run can be found in:
2020-05-30T00:03:14.855069+00:00 app[web.1]: npm ERR! /app/.npm/_logs/2020-05-30T00_03_14_850Z-debug.log
2020-05-30T00:03:14.907689+00:00 heroku[web.1]: Process exited with status 1
2020-05-30T00:03:14.943718+00:00 heroku[web.1]: State changed from starting to crashed
This is my package.json:
{
"name": "discordtoornamentmanager",
"version": "1.0.0",
"description": "",
"main": "dist/app.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "nodemon -x ts-node src/App.ts",
"start": "ts-node src/App.ts"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@types/node": "^14.0.5",
"axios": "^0.19.2",
"discord.js": "^12.2.0",
"pg": "^8.2.1",
"reflect-metadata": "^0.1.10",
"typeorm": "0.2.25",
"typescript": "^3.9.3",
"nodemon": "^2.0.4",
"ts-node": "8.10.1"
}
}
And this is my tsconfig:
{
"compilerOptions": {
"lib": [
"es6"
],
"target": "es6",
"module": "commonjs",
"moduleResolution": "node",
"outDir": "dist",
"resolveJsonModule": true,
"emitDecoratorMetadata": true,
"esModuleInterop": true,
"experimentalDecorators": true,
"sourceMap": true
},
"include": ["src/**/*.ts"],
"exclude": ["node_modules", "**/*.spec.ts"]
}
",https://stackoverflow.com/questions/62096269/unknown-file-extension-ts-for-a-typescript-file,651,956304.0,38.0,,,2020-05-30 00:07:13,2025-08-07 13:38:07,2024-08-23 16:24:17,,,node.js;typescript;npm,Elizar Pongracz,6570,12858577,registered,true,62099904,,CC BY-SA 4.0,,4376,4172,5,0,0,3,true,false,false,true,true,true,60,8,false,0.04,0.0007,2366,2020,5,0,Saturday,true,false,false,false,false,false,false
11744975,Enabling HTTPS on express.js,"I'm trying to get HTTPS working on express.js for node, and I can't figure it out.
This is my app.js code.
var express = require('express');
var fs = require('fs');
var privateKey = fs.readFileSync('sslcert/server.key');
var certificate = fs.readFileSync('sslcert/server.crt');
var credentials = {key: privateKey, cert: certificate};
var app = express.createServer(credentials);
app.get('/', function(req,res) {
res.send('hello');
});
app.listen(8000);
When I run it, it seems to only respond to HTTP requests.
I wrote simple vanilla node.js based HTTPS app:
var fs = require("fs"),
http = require("https");
var privateKey = fs.readFileSync('sslcert/server.key').toString();
var certificate = fs.readFileSync('sslcert/server.crt').toString();
var credentials = {key: privateKey, cert: certificate};
var server = http.createServer(credentials,function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
});
server.listen(8000);
And when I run this app, it does respond to HTTPS requests. Note that I don't think the toString() on the fs result matters, as I've used combinations of both and still no es bueno.
EDIT TO ADD:
For production systems, you're probably better off using Nginx or HAProxy to proxy requests to your nodejs app. You can set up nginx to handle the ssl requests and just speak http to your node app.js.
EDIT TO ADD (4/6/2015)
For systems on using AWS, you are better off using EC2 Elastic Load Balancers to handle SSL Termination, and allow regular HTTP traffic to your EC2 web servers. For further security, setup your security group such that only the ELB is allowed to send HTTP traffic to the EC2 instances, which will prevent external unencrypted HTTP traffic from hitting your machines.
",https://stackoverflow.com/questions/11744975/enabling-https-on-express-js,648,708953.0,10.0,,,2012-07-31 16:40:16,2025-03-13 16:02:38,2021-12-08 12:29:04,,,node.js;https;express,Alan,47075,37843,registered,true,11745114,,CC BY-SA 4.0,,1961,1803,4,0,0,3,true,false,false,true,true,true,28,4,false,0.014,0.0009,5226,2012,7,16,Tuesday,false,false,false,false,false,false,false
18391212,Is it not possible to stringify an Error using JSON.stringify?,"Reproducing the problem
I'm running into an issue when trying to pass error messages around using web sockets. I can replicate the issue I am facing using JSON.stringify to cater to a wider audience:
// node v0.10.15
> var error = new Error('simple error message');
undefined
> error
[Error: simple error message]
> Object.getOwnPropertyNames(error);
[ 'stack', 'arguments', 'type', 'message' ]
> JSON.stringify(error);
'{}'
The problem is that I end up with an empty object.
What I've tried
Browsers
I first tried leaving node.js and running it in various browsers. Chrome version 28 gives me the same result, and interestingly enough, Firefox at least makes an attempt but left out the message:
>>> JSON.stringify(error); // Firebug, Firefox 23
{""fileName"":""debug eval code"",""lineNumber"":1,""stack"":""@debug eval code:1\n""}
Replacer function
I then looked at the Error.prototype. It shows that the prototype contains methods such as toString and toSource. Knowing that functions can't be stringified, I included a replacer function when calling JSON.stringify to remove all functions, but then realized that it too had some weird behavior:
var error = new Error('simple error message');
JSON.stringify(error, function(key, value) {
console.log(key === ''); // true (?)
console.log(value === error); // true (?)
});
It doesn't seem to loop over the object as it normally would, and therefore I can't check if the key is a function and ignore it.
The Question
Is there any way to stringify native Error messages with JSON.stringify? If not, why does this behavior occur?
Methods of getting around this
- Stick with simple string-based error messages, or create personal error objects and don't rely on the native Error object.
- Pull properties:
JSON.stringify({ message: error.message, stack: error.stack })
Updates
@Ray Toal Suggested in a comment that I take a look at the property descriptors. It is clear now why it does not work:
var error = new Error('simple error message');
var propertyNames = Object.getOwnPropertyNames(error);
var descriptor;
for (var property, i = 0, len = propertyNames.length; i < len; ++i) {
property = propertyNames[i];
descriptor = Object.getOwnPropertyDescriptor(error, property);
console.log(property, descriptor);
}
Output:
stack { get: [Function],
set: [Function],
enumerable: false,
configurable: true }
arguments { value: undefined,
writable: true,
enumerable: false,
configurable: true }
type { value: undefined,
writable: true,
enumerable: false,
configurable: true }
message { value: 'simple error message',
writable: true,
enumerable: false,
configurable: true }
Key: enumerable: false.
Accepted answer provides a workaround for this problem.
",https://stackoverflow.com/questions/18391212/is-it-not-possible-to-stringify-an-error-using-json-stringify,642,257512.0,15.0,,,2013-08-22 21:34:01,2025-08-28 07:47:07,2017-05-23 10:31:15,,,javascript;json;node.js;error-handling,Jay,20055,586621,registered,true,18391400,,CC BY-SA 3.0,2019-09-18 09:38:33,4419,2797,9,6,0,4,true,false,false,true,true,true,62,10,true,0.058,0.0025,4839,2013,8,21,Thursday,false,false,true,false,false,false,false
25112510,How to set environment variables from within package.json?,"How to set some environment variables from within package.json to be used with npm start like commands?
Here's what I currently have in my package.json:
{
...
""scripts"": {
""help"": ""tagove help"",
""start"": ""tagove start""
}
...
}
I want to set environment variables (like NODE_ENV) in the start script while still being able to start the app with just one command, npm start.
",https://stackoverflow.com/questions/25112510/how-to-set-environment-variables-from-within-package-json,638,1148938.0,23.0,,,2014-08-04 05:55:27,2026-01-09 17:51:15,2021-01-14 10:46:58,,,node.js;npm;package.json;npm-scripts,dev.meghraj,9220,1435800,registered,true,27090755,,CC BY-SA 4.0,2026-01-09 23:53:51,542,393,6,0,0,4,true,false,false,true,true,true,58,8,true,0.02,0.0006,4492,2014,8,5,Monday,false,false,false,false,false,false,false
46677752,The difference between "require(x)" and "import x","I've just started working on a small node project that will interface with a MongoDB. However, I cannot seem to get the relevant node modules to import correctly, even though I have installed them correctly via npm.
For example, the following code throws an error, telling me that ""express has no default export"":
import express from ""express"";
However, this code works:
const express = require(""express"");
So my question is, what is the difference in how the import and variable/require methods function? I'd like to fix whatever is plaguing my imports on the project, as it seems likely to cause additional problems down the road.
",https://stackoverflow.com/questions/46677752/the-difference-between-requirex-and-import-x,638,437720.0,9.0,,,2017-10-11 00:04:37,2024-11-25 07:25:40,2020-02-14 05:11:48,,,node.js;typescript;import;require,austinthemassive,6735,2611688,registered,true,46677972,,CC BY-SA 4.0,2019-12-17 07:57:10,746,640,3,0,0,4,true,false,false,true,true,true,70,7,false,0.021,0.0015,3328,2017,10,0,Wednesday,false,false,false,false,false,false,false
11293857,Fastest way to copy a file in Node.js,"The project that I am working on (Node.js) implies lots of operations with the file system (copying, reading, writing, etc.).
Which methods are the fastest?
",https://stackoverflow.com/questions/11293857/fastest-way-to-copy-a-file-in-node-js,637,554539.0,17.0,,,2012-07-02 12:38:56,2024-06-21 04:53:34,2020-10-27 19:47:53,,,javascript;node.js,bonbonez,6858,1053338,registered,true,11295106,,CC BY-SA 4.0,,171,157,0,0,0,2,true,false,false,true,true,true,37,8,false,0.031,0.0011,5255,2012,7,12,Monday,false,false,true,false,false,false,false
57492546,What is the difference between .js and .mjs files?,"I have started working on an existing project based on Node.js. I was just trying to understand the flow of execution, where I encountered with some *.mjs files. I have searched the web where I found that these are module based JS-files.
I want to know how is it different from *.js files (how does it benefit)?
",https://stackoverflow.com/questions/57492546/what-is-the-difference-between-js-and-mjs-files,628,518757.0,4.0,,,2019-08-14 10:04:31,2024-11-22 16:48:28,2020-10-11 19:48:06,,,javascript;node.js;mjs,Keval Bhogayata,7184,8733427,registered,true,57492606,,CC BY-SA 4.0,,352,312,2,0,0,3,true,false,false,true,true,true,50,9,true,0.008,0.0012,2656,2019,8,10,Wednesday,false,false,true,false,false,false,false
1801160,Can I use jQuery with Node.js?,"Is it possible to use jQuery selectors/DOM manipulation on the server-side using Node.js?
",https://stackoverflow.com/questions/1801160/can-i-use-jquery-with-node-js,620,428774.0,21.0,,,2009-11-26 01:54:20,2023-06-05 12:38:20,2013-10-16 16:47:09,,,javascript;jquery;node.js,John,6217,219069,unregistered,true,,,CC BY-SA 3.0,2020-02-25 00:30:29,97,90,0,0,0,3,false,false,false,true,true,true,30,6,true,0.049,0.0014,6204,2009,11,1,Thursday,false,false,true,false,false,false,false
38558989,Node.js heap out of memory,"Today I ran my script for filesystem indexing to refresh RAID files index and after 4h it crashed with following error:
[md5:] 241613/241627 97.5%
[md5:] 241614/241627 97.5%
[md5:] 241625/241627 98.1%
Creating missing list... (79570 files missing)
Creating new files list... (241627 new files)
<--- Last few GCs --->
11629672 ms: Mark-sweep 1174.6 (1426.5) -> 1172.4 (1418.3) MB, 659.9 / 0 ms [allocation failure] [GC in old space requested].
11630371 ms: Mark-sweep 1172.4 (1418.3) -> 1172.4 (1411.3) MB, 698.9 / 0 ms [allocation failure] [GC in old space requested].
11631105 ms: Mark-sweep 1172.4 (1411.3) -> 1172.4 (1389.3) MB, 733.5 / 0 ms [last resort gc].
11631778 ms: Mark-sweep 1172.4 (1389.3) -> 1172.4 (1368.3) MB, 673.6 / 0 ms [last resort gc].
<--- JS stacktrace --->
==== JS stack trace =========================================
Security context: 0x3d1d329c9e59 <JS Object>
1: SparseJoinWithSeparatorJS(aka SparseJoinWithSeparatorJS) [native array.js:~84] [pc=0x3629ef689ad0] (this=0x3d1d32904189 <undefined>,w=0x2b690ce91071 <JS Array[241627]>,L=241627,M=0x3d1d329b4a11 <JS Function ConvertToString (SharedFunctionInfo 0x3d1d3294ef79)>,N=0x7c953bf4d49 <String[4]\: ,\n >)
2: Join(aka Join) [native array.js:143] [pc=0x3629ef616696] (this=0x3d1d32904189 <undefin...
FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory
1: node::Abort() [/usr/bin/node]
2: 0xe2c5fc [/usr/bin/node]
3: v8::Utils::ReportApiFailure(char const*, char const*) [/usr/bin/node]
4: v8::internal::V8::FatalProcessOutOfMemory(char const*, bool) [/usr/bin/node]
5: v8::internal::Factory::NewRawTwoByteString(int, v8::internal::PretenureFlag) [/usr/bin/node]
6: v8::internal::Runtime_SparseJoinWithSeparator(int, v8::internal::Object**, v8::internal::Isolate*) [/usr/bin/node]
7: 0x3629ef50961b
Server is equipped with 16gb RAM and 24gb SSD swap. I highly doubt my script exceeded 36gb of memory. At least it shouldn't
Script creates index of files stored as Array of Objects with files metadata (modification dates, permissions, etc, no big data)
Here's full script code:
http://pastebin.com/mjaD76c3
I've already experiend weird node issues in the past with this script what forced me eg. split index into multiple files as node was glitching when working on such big files as String. Is there any way to improve nodejs memory management with huge datasets?
",https://stackoverflow.com/questions/38558989/node-js-heap-out-of-memory,619,1238163.0,38.0,,,2016-07-25 02:45:21,2025-08-16 17:10:42,,,,javascript;node.js;crash;out-of-memory;heap-memory,Lapsio,7344,2111737,registered,true,38560292,,CC BY-SA 3.0,2021-08-23 17:49:31,2578,2459,1,1,0,5,true,false,false,true,true,false,26,5,false,0.031,0.0005,3771,2016,7,2,Monday,false,false,true,false,false,false,false
19696240,Proper way to return JSON using node or Express,"So, one can attempt to fetch the following JSON object:
$ curl -i -X GET http://echo.jsontest.com/key/value/anotherKey/anotherValue
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Content-Type: application/json; charset=ISO-8859-1
Date: Wed, 30 Oct 2013 22:19:10 GMT
Server: Google Frontend
Cache-Control: private
Alternate-Protocol: 80:quic,80:quic
Transfer-Encoding: chunked
{
""anotherKey"": ""anotherValue"",
""key"": ""value""
}
$
Is there a way to produce exactly the same body in a response from a server using node or express? Clearly, one can set the headers and indicate that the content-type of the response is going to be ""application/json"", but then there are different ways to write/send the object. The one that I have seen commonly being used is by using a command of the form:
response.write(JSON.stringify(anObject));
However, this has two points where one could argue as if they were ""problems"":
- We are sending a string.
- Moreover, there is no new line character in the end.
Another idea is to use the command:
response.send(anObject);
This appears to be sending a JSON object based on the output of curl similar to the first example above. However, there is no new line character in the end of the body when curl is again being used on a terminal. So, how can one actually write down something like this with a new line character appended in the end using node or node/express?
",https://stackoverflow.com/questions/19696240/proper-way-to-return-json-using-node-or-express,618,1105095.0,12.0,,,2013-10-31 00:16:51,2026-06-08 05:48:34,,,,json;node.js;express;httpresponse,MightyMouse,13938,1355058,registered,true,19696261,,CC BY-SA 3.0,,1542,1408,3,0,0,4,true,false,false,true,true,false,47,9,false,0.011,0.0006,4769,2013,10,0,Thursday,false,false,false,false,false,false,false
4144686,How can I write a test which expects an 'Error' to be thrown in Jasmine?,"I'm trying to write a test for the Jasmine Test Framework which expects an error. At the moment I'm using a Jasmine Node.js integration from GitHub.
In my Node.js module I have the following code:
throw new Error("Parsing is not possible");
Now I try to write a test which expects this error:
describe('my suite...', function() {
[..]
it('should not parse foo', function() {
[..]
expect(parser.parse(raw)).toThrow(new Error("Parsing is not possible"));
});
});
I tried also Error() and some other variants and just can't figure out how to make it work.
",https://stackoverflow.com/questions/4144686/how-can-i-write-a-test-which-expects-an-error-to-be-thrown-in-jasmine,616,340501.0,12.0,,,2010-11-10 12:57:39,2023-06-30 18:02:38,2022-01-08 00:41:34,,,javascript;testing;node.js;jasmine,echox,9870,35915,registered,true,4144803,,CC BY-SA 4.0,,817,599,3,2,0,4,true,false,false,true,true,true,80,15,true,0.035,0.0018,5855,2010,11,12,Wednesday,false,false,true,false,false,false,false
15630770,Node.js check if path is file or directory,"I can't seem to get any search results that explain how to do this.
All I want to do is be able to know if a given path is a file or a directory (folder).
",https://stackoverflow.com/questions/15630770/node-js-check-if-path-is-file-or-directory,609,452525.0,9.0,,,2013-03-26 06:32:14,2024-06-27 08:07:00,2019-02-04 13:22:36,,,node.js;path;directory;filesystems;fs,ThomasReggi,60643,340688,registered,true,15630832,,CC BY-SA 4.0,,170,156,0,0,0,5,true,false,false,true,true,true,42,8,false,0.02,0.0013,4988,2013,3,6,Tuesday,false,false,false,false,false,false,false
5670752,How can I pretty-print JSON using node.js?,"This seems like a solved problem but I am unable to find a solution for it.
Basically, I read a JSON file, change a key, and write back the new JSON to the same file. All works, but I loose the JSON formatting.So, instead of:
{
name:'test',
version:'1.0'
}
I get
{name:'test',version:'1.1'}
Is there a way in Node.js to write well formatted JSON to file ?
",https://stackoverflow.com/questions/5670752/how-can-i-pretty-print-json-using-node-js,603,471915.0,8.0,,,2011-04-14 23:10:50,2025-09-23 06:29:21,2016-01-20 01:12:29,,,json;node.js,Rajat,34348,111683,registered,true,5670892,,CC BY-SA 3.0,2025-09-23 09:26:07,443,367,2,0,0,2,true,false,false,true,true,true,42,7,true,0.017,0.0013,5700,2011,4,23,Thursday,false,false,false,false,false,false,false
18412129,How can I update npm on Windows?,"I tried this:
sudo npm cache clean -f
sudo npm install -g n
sudo n stable
...but it didn't work.
How do I do this on Windows?
",https://stackoverflow.com/questions/18412129/how-can-i-update-npm-on-windows,600,1946975.0,29.0,,,2013-08-23 21:26:57,2026-04-22 11:08:02,2018-01-12 15:28:19,,,windows;node.js;npm;package-managers,Jatin,14269,912703,registered,true,31520672,,CC BY-SA 3.0,2018-05-30 01:54:45,244,130,1,1,0,4,true,false,false,true,true,true,32,7,true,0.015,0.0003,4838,2013,8,21,Friday,false,false,false,false,false,false,false
8131344,What is the difference between __dirname and ./ in node.js?,"When programming in Node.js and referencing files that are located somewhere in relation to your current directory, is there any reason to use the __dirname variable instead of just a regular ./? I've been using ./ thus far in my code and just discovered the existence of __dirname, and essentially want to know whether it would be smart to convert my ./'s to that, and if so, why that would be a smart idea.
",https://stackoverflow.com/questions/8131344/what-is-the-difference-between-dirname-and-in-node-js,600,324837.0,2.0,,,2011-11-15 04:05:04,2018-11-15 01:25:52,2012-03-25 14:19:54,,,node.js,thisissami,16623,798491,registered,true,18283508,,CC BY-SA 3.0,,455,409,3,0,0,1,true,false,false,true,true,true,59,10,true,0.006,0.0018,5485,2011,11,4,Tuesday,false,false,false,false,false,false,false
9755841,How can I change the version of npm using nvm?,"I've been using NVM to install the latest versions of Node.js for my Node.js work. It works totally fine for installing separate versions and switching between them. It also installs the latest version of NPM within each local .../bin folder along with the Node.js binary. However, there doesn't seem to be a way to switch the version of NPM that I'm using (or at least I can't figure it out).
The only solution I can think of myself is to delete the binary that it's defaulting to (which is the NPM that was installed when I first installed node with NVM), and in its place to put the latest NPM binary. However, is there a better way to go about doing this?
",https://stackoverflow.com/questions/9755841/how-can-i-change-the-version-of-npm-using-nvm,592,1053871.0,21.0,,,2012-03-18 03:49:55,2025-09-10 02:27:40,2022-08-09 19:32:15,,,node.js;npm,thisissami,16623,798491,registered,true,33575448,,CC BY-SA 4.0,,674,660,0,0,0,2,true,false,false,true,true,true,46,10,true,0.02,0.0006,5361,2012,3,3,Sunday,true,false,false,false,false,false,false
45854169,How can I use an ES6 import in Node.js?,"I'm trying to get the hang of ES6 imports in Node.js and am trying to use the syntax provided in this example:
Cheatsheet Link
I'm looking through the support table, but I was not able to find what version supports the new import statements (I tried looking for the text import/require). I'm currently running Node.js 8.1.2 and also believe that since the cheatsheet is referring to .js files it should work with .js files.
As I run the code (taken from the cheatsheet's first example):
import { square, diag } from 'lib';
I get the error:
SyntaxError: Unexpected token import.
Reference to library I'm trying to import:
//------ lib.js ------
export const sqrt = Math.sqrt;
export function square(x) {
return x * x;
}
export function diag(x, y) {
return sqrt(square(x) + square(y));
}
What am I missing and how can I get node to recognize my import statement?
",https://stackoverflow.com/questions/45854169/how-can-i-use-an-es6-import-in-node-js,587,749489.0,11.0,,,2017-08-24 06:11:09,2021-12-15 22:14:01,2020-10-12 19:39:52,2019-07-08 16:52:01,Duplicate,node.js;es6-modules,Jonathan002,10488,3859456,registered,true,45854500,,,,1250,873,4,2,0,2,true,true,false,true,true,true,39,9,true,0.015,0.0008,3376,2017,8,6,Thursday,false,false,false,false,false,false,false
12866494,How do you reinstall an app's dependencies using npm?,"Is there a simple way to reinstall all packages that my app depends on (i.e. they are in my apps node_modules folder)?
",https://stackoverflow.com/questions/12866494/how-do-you-reinstall-an-apps-dependencies-using-npm,585,764323.0,10.0,,,2012-10-12 20:18:08,2021-10-26 13:59:51,,,,node.js;npm,trusktr,46177,454780,registered,true,12866545,,CC BY-SA 3.0,,135,119,0,0,0,2,true,false,false,true,true,false,57,9,true,0.013,0.0008,5153,2012,10,20,Friday,false,false,false,false,false,false,false
1972242,How can I auto-reload files in Node.js?,"How could I implement an auto-reload of files in Node.js? I'm tired of restarting the server every time I change a file.
Apparently, Node.js' require() function does not reload files if they have already been 'required', so I need to do something like this:
var http = require('http'),
posix = require('posix'),
json = require('./json');
var script_name = '/some/path/to/app.js';
this.app = require('./app').app;
process.watchFile(script_name, function(curr, prev){
posix.cat(script_name).addCallback(function(content){
process.compile( content, script_name );
});
});
http.createServer(this.app).listen( 8080 );
And in the app.js file I have:
var file = require('./file');
this.app = function(req, res) {
file.serveFile( req, res, 'file.js');
}
But this also isn't working. I get an error in the process.compile() statement, saying that 'require' is not defined. process.compile is eval'ing the app.js, but it doesn’t have any clue about the Node.js globals.
",https://stackoverflow.com/questions/1972242/how-can-i-auto-reload-files-in-node-js,582,545304.0,32.0,,,2009-12-29 00:08:49,2026-01-25 02:18:29,2025-11-26 21:58:14,,,javascript;node.js,disc0dancer,9375,36047,registered,true,14406029,,CC BY-SA 4.0,2022-10-25 12:47:32,1134,1001,5,0,0,2,true,false,false,true,true,true,39,7,true,0.059,0.0011,6171,2009,12,0,Tuesday,false,false,true,false,false,false,false
5778245,How to structure an ExpressJS application?,"I'm using the ExpressJS web framework for NodeJS.
People using ExpressJS put their environments (development, production, test...), their routes etc on the app.js. I think that is not a beautiful way because when you have a big application, app.js is too big!
I would like to have this directory structure:
| my-application
| -- app.js
| -- config/
| -- environment.js
| -- routes.js
Here's my code:
app.js
var express = require('express');
var app = module.exports = express.createServer();
require('./config/environment.js')(app, express);
require('./config/routes.js')(app);
app.listen(3000);
config/environment.js
module.exports = function(app, express){
app.configure(function() {
app.use(express.logger());
});
app.configure('development', function() {
app.use(express.errorHandler({
dumpExceptions: true,
showStack: true
}));
});
app.configure('production', function() {
app.use(express.errorHandler());
});
};
config/routes.js
module.exports = function(app) {
app.get('/', function(req, res) {
res.send('Hello world !');
});
};
My code works well and I think that the structure of the directories is beautiful. However, the code had to be adapted and I'm not sure that it's good/beautiful.
Is it better to use my structure of directories and adapt the code or simply use one file (app.js)?
",https://stackoverflow.com/questions/5778245/how-to-structure-an-expressjs-application,581,216616.0,21.0,,,2011-04-25 12:18:34,2024-04-27 10:16:04,2024-04-27 10:16:04,2024-04-27 09:38:43,Opinion-based,node.js;express,Sandro Munda,41348,259576,registered,true,19623507,,,,1607,1384,5,0,0,2,true,true,false,true,true,true,42,6,true,0.097,0.0027,5689,2011,4,12,Monday,false,false,false,false,false,false,false
48433783,ReferenceError: fetch is not defined,"I have this error when I compile my code in node.js, how can I fix it?
RefernceError: fetch is not defined
This is the function I am doing, it is responsible for recovering information from a specific movie database.
function getMovieTitles(substr){
pageNumber=1;
let url = 'https://jsonmock.hackerrank.com/api/movies/search/?Title=' + substr + ""&page="" + pageNumber;
fetch(url).then((resp) => resp.json()).then(function(data) {
let movies = data.data;
let totPages = data.total_pages;
let sortArray = [];
for(let i=0; i<movies.length;i++){
sortArray.push(data.data[i].Title);
}
for(let i=2; i<=totPages; i++){
let newPage = i;
let url1 = 'https://jsonmock.hackerrank.com/api/movies/search/?Title=' + substr + ""&page="" + newPage;
fetch(url1).then(function(response) {
var contentType = response.headers.get(""content-type"");
if(contentType && contentType.indexOf(""application/json"") !== -1) {
return response.json().then(function(json) {
//console.log(json); //uncomment this console.log to see the JSON data.
for(let i=0; i<json.data.length;i++){
sortArray.push(json.data[i].Title);
}
if(i==totPages)console.log(sortArray.sort());
});
} else {
console.log(""Oops, we haven't got JSON!"");
}
});
}
})
.catch(function(error) {
console.log(error);
});
}
",https://stackoverflow.com/questions/48433783/referenceerror-fetch-is-not-defined,580,1010524.0,28.0,,,2018-01-25 00:22:21,2025-06-20 09:23:07,2019-07-07 15:43:14,,,javascript;node.js,jasa1704,5919,9128799,registered,true,,,CC BY-SA 4.0,,1780,1587,1,1,1,2,false,false,false,true,true,true,36,5,false,0.028,0.0006,3222,2018,1,0,Thursday,false,false,true,false,false,false,false
9177049,Express.js req.body undefined,"I have this as configuration of my Express server
app.use(app.router);
app.use(express.cookieParser());
app.use(express.session({ secret: ""keyboard cat"" }));
app.set('view engine', 'ejs');
app.set(""view options"", { layout: true });
//Handles post requests
app.use(express.bodyParser());
//Handles put requests
app.use(express.methodOverride());
But still when I ask for req.body.something in my routes I get some error pointing out that body is undefined. Here is an example of a route that uses req.body :
app.post('/admin', function(req, res){
console.log(req.body.name);
});
I read that this problem is caused by the lack of app.use(express.bodyParser()); but as you can see I call it before the routes.
Any clue?
",https://stackoverflow.com/questions/9177049/express-js-req-body-undefined,578,777005.0,53.0,,,2012-02-07 13:25:07,2024-05-03 13:03:43,2015-08-03 13:06:02,,,node.js;express,Masiar,21482,617461,registered,true,9211382,,CC BY-SA 3.0,2021-01-25 15:32:48,857,729,6,0,0,2,true,false,false,true,true,true,29,3,false,0.068,0.0007,5401,2012,2,13,Tuesday,false,false,false,false,false,false,false
18052762,Remove directory which is not empty,"In my Node application I need to remove a directory which has some files, but fs.rmdir only works on empty directories. How can I do this?
",https://stackoverflow.com/questions/18052762/remove-directory-which-is-not-empty,574,583963.0,35.0,,,2013-08-05 07:31:11,2025-04-20 11:09:33,2017-09-28 23:11:42,,,node.js;filesystems,sachin,14445,2138629,registered,true,18052969,,CC BY-SA 3.0,2024-04-09 02:24:38,230,139,1,1,0,2,true,false,false,true,true,true,35,6,false,0.06,0.001,4856,2013,8,7,Monday,false,false,false,false,false,false,false
22312671,Setting Environment Variables for Node to retrieve,"I'm trying to follow a tutorial and it says:
There are a few ways to load credentials.
- Loaded from environment variables,
- Loaded from a JSON file on disk,
The keys need to be as follows:
USER_ID, USER_KEY
...This means that if you properly set your environment variables, you
do not need to manage credentials in your application at all.
Based on some Googling, it appears that I need to set the variables in process.env? How and where do I set these credentials? Example Please.
",https://stackoverflow.com/questions/22312671/setting-environment-variables-for-node-to-retrieve,570,1151286.0,21.0,,,2014-03-10 22:25:57,2024-05-18 02:59:30,2019-10-28 08:51:37,,,node.js;environment-variables,user1107173,10824,1107173,registered,true,22312793,,CC BY-SA 4.0,2017-11-26 22:19:26,641,517,2,0,0,2,true,false,false,true,true,true,50,7,false,0.018,0.0005,4639,2014,3,22,Monday,false,false,false,false,false,false,false
27688804,How do I debug "Error: spawn ENOENT" on Node.js?,"When I get the following error:
events.js:72
throw er; // Unhandled 'error' event
^
Error: spawn ENOENT
at errnoException (child_process.js:1000:11)
at Process.ChildProcess._handle.onexit (child_process.js:791:34)
What procedure can I follow to fix it?
Author note: Lots of issues with this error encouraged me to post this question for future references.
Related questions:
- Using spawn function with NODE_ENV=production
- node.js child_process.spawn ENOENT error - only under supervisord
- spawn ENOENT node.js error
- https://stackoverflow.com/questions/27603713/nodejs-spawn-enoent-error-on-travis-calling-global-npm-package
- Node JS - child_process spawn('npm install') in Grunt task results in ENOENT error
- Running "foreman" task Fatal error: spawn ENOENT
- unhandled error event in node js Error: spawn ENOENT at errnoException (child_process.js:975:11)
- Node.js SpookyJS: error executing hello.js
- https://stackoverflow.com/questions/26572214/run-grunt-on-a-directory-nodewebkit
- Run exe file with Child Process NodeJS
- Node: child_process.spawn not working on Java even though it's in the path (ENOENT)
- spawn ENOENT error with NodeJS (PYTHON related)
- https://stackoverflow.com/questions/21346717/image-resizing-is-not-working-in-node-js-partial-js (non-installed dependency)
- npm install error ENOENT (build dependency problem)
- Cannot install node.js - oracle module on Windows 7 (build dependency problem)
- Error installing gulp using nodejs on windows (strange case)
",https://stackoverflow.com/questions/27688804/how-do-i-debug-error-spawn-enoent-on-node-js,561,870342.0,31.0,,,2014-12-29 12:22:00,2025-12-30 15:41:30,2025-12-30 15:41:01,,,node.js;debugging;error-handling;child-process;spawn,laconbass,18070,1894803,registered,true,62551786,,CC BY-SA 4.0,2019-04-24 19:36:28,3578,1517,1,16,0,5,true,false,false,true,true,true,58,9,true,0.036,0.0006,4345,2014,12,12,Monday,false,false,false,false,false,false,false
9898372,How to fix Error: listen EADDRINUSE while using NodeJS?,"If I run a server with the port 80, and I try to use XMLHttpRequest I am getting this error: Error: listen EADDRINUSE
Why is it problem for NodeJS, if I want to do a request, while I run a server on the port 80? For the webbrowsers it is not a problem: I can surf on the internet, while the server is running.
The server is:
net.createServer(function (socket) {
socket.name = socket.remoteAddress + ":" + socket.remotePort;
console.log('connection request from: ' + socket.remoteAddress);
socket.destroy();
}).listen(options.port);
And the request:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
sys.puts("State: " + this.readyState);
if (this.readyState == 4) {
sys.puts("Complete.\nBody length: " + this.responseText.length);
sys.puts("Body:\n" + this.responseText);
}
};
xhr.open("GET", "http://mywebsite.com");
xhr.send();
",https://stackoverflow.com/questions/9898372/how-to-fix-error-listen-eaddrinuse-while-using-nodejs,552,926537.0,45.0,,,2012-03-27 22:00:59,2025-03-29 12:20:28,2021-12-06 17:12:30,,,javascript;node.js,Danny Fox,41199,1091828,registered,true,9898697,,CC BY-SA 4.0,2015-02-10 11:33:28,1128,959,3,1,0,2,true,false,false,true,true,true,55,9,true,0.049,0.0006,5352,2012,3,22,Tuesday,false,false,true,false,false,false,false
46515764,How can I use async/await at the top level?,"I have been going over async/await and after going over several articles, I decided to test things myself. However, I can't seem to wrap my head around why this does not work:
async function main() {
var value = await Promise.resolve('Hey there');
console.log('inside: ' + value);
return value;
}
var text = main();
console.log('outside: ' + text);
The console outputs the following (node v8.6.0) :
> outside: [object Promise]
> inside: Hey there
Why does the log message inside the function execute afterwards? I thought the reason async/await was created was in order to perform synchronous execution using asynchronous tasks.
Is there a way could I use the value returned inside the function without using a .then() after main()?
",https://stackoverflow.com/questions/46515764/how-can-i-use-async-await-at-the-top-level,550,496283.0,16.0,,,2017-10-01 18:55:14,2026-03-31 21:17:32,2020-06-20 09:12:55,,,javascript;node.js;async-await;ecmascript-2017,Felipe,12218,3654061,registered,true,46515787,,CC BY-SA 4.0,,965,759,7,0,0,4,true,false,false,true,true,true,43,9,true,0.032,0.0011,3338,2017,10,18,Sunday,true,false,true,false,false,false,false
21417014,npm command to uninstall or prune unused packages in Node.js,"Is there a way to simply uninstall all unused (undeclared) dependencies from a Node.js project (ones that are no longer defined in my package.json.) When I update my application I like to have the unreferenced packages removed automatically.
",https://stackoverflow.com/questions/21417014/npm-command-to-uninstall-or-prune-unused-packages-in-node-js,545,411755.0,4.0,,,2014-01-28 21:15:53,2023-05-07 20:11:12,2020-02-17 10:16:33,,,node.js;npm;uninstallation,Tarion,17360,86388,registered,true,21417098,,CC BY-SA 4.0,,262,242,1,0,0,3,true,false,false,true,true,true,60,10,false,0.01,0.0013,4680,2014,1,21,Tuesday,false,false,false,false,false,false,false
6456864,Why does Node.js's fs.readFile() return a buffer instead of string?,"I'm trying to read the content of test.txt(which is on the same folder of the Javascript source) and display it using this code:
var fs = require(""fs"");
fs.readFile(""test.txt"", function (err, data) {
if (err) throw err;
console.log(data);
});
The content of the test.txt was created on nano:
Testing Node.js readFile()
And I'm getting this:
Nathan-Camposs-MacBook-Pro:node_test Nathan$ node main.js
<Buffer 54 65 73 74 69 6e 67 20 4e 6f 64 65 2e 6a 73 20 72 65 61 64 46 69 6c 65 28 29>
Nathan-Camposs-MacBook-Pro:node_test Nathan$
",https://stackoverflow.com/questions/6456864/why-does-node-jss-fs-readfile-return-a-buffer-instead-of-string,544,418190.0,9.0,,,2011-06-23 15:44:28,2024-11-04 14:10:40,2023-12-31 06:50:12,,,javascript;file-io;node.js,Nathan Campos,29593,126353,registered,true,6457004,,CC BY-SA 4.0,,698,558,5,0,0,3,true,false,false,true,true,true,71,10,true,0.022,0.0013,5630,2011,6,15,Thursday,false,false,true,false,false,false,false
8107856,How to determine a user's IP address in node,"How can I determine the IP address of a given request from within a controller? For example (in express):
app.post('/get/ip/address', function (req, res) {
// need access to IP address here
})
",https://stackoverflow.com/questions/8107856/how-to-determine-a-users-ip-address-in-node,541,671796.0,34.0,,,2011-11-12 21:56:50,2024-07-08 14:40:32,2021-01-01 20:03:37,,,node.js;ip,Shamoon,44047,239879,registered,true,8107922,,CC BY-SA 4.0,2022-08-19 18:14:28,230,199,1,0,0,2,true,false,false,true,true,true,48,9,false,0.051,0.0008,5488,2011,11,21,Saturday,true,false,false,false,false,false,false
21122342,How to clean node_modules folder of packages that are not in package.json?,"Assume I install project packages with npm install that looks into package.json for modules to be installed. After a while I see that I don't need some specific module and remove its dependency from package.json. Then I remove some other modules from package.json because they are not needed anymore and others are replaced with alternatives.
Now I want to clean node_modules folder so that only modules listed in package.json stay there and the rest must go, something like npm clean. I know I can remove them manually but would like to have some nice ready to use sugar functionality for that.
",https://stackoverflow.com/questions/21122342/how-to-clean-node-modules-folder-of-packages-that-are-not-in-package-json,540,1171531.0,17.0,,,2014-01-14 19:32:52,2025-02-28 10:13:19,2017-01-16 15:39:25,,,node.js;package;npm,Sergei Basharov,54586,135829,registered,true,21122629,,CC BY-SA 3.0,,703,598,7,0,0,3,true,false,false,true,true,true,74,12,true,0.015,0.0005,4694,2014,1,19,Tuesday,false,false,false,false,false,false,false
40294870,module.exports vs. export default in Node.js and ES6,"What is the difference between Node's module.exports and ES6's export default? I'm trying to figure out why I get the ""__ is not a constructor"" error when I try to export default in Node.js 6.2.2.
What works
'use strict'
class SlimShady {
constructor(options) {
this._options = options
}
sayName() {
return 'My name is Slim Shady.'
}
}
// This works
module.exports = SlimShady
What doesn't work
'use strict'
class SlimShady {
constructor(options) {
this._options = options
}
sayName() {
return 'My name is Slim Shady.'
}
}
// This will cause the ""SlimShady is not a constructor"" error
// if in another file I try `let marshall = new SlimShady()`
export default SlimShady
",https://stackoverflow.com/questions/40294870/module-exports-vs-export-default-in-node-js-and-es6,538,581071.0,3.0,,,2016-10-27 21:58:38,2020-09-19 07:36:03,,,,node.js;module;ecmascript-6,Marty Chang,6689,6101554,registered,true,40295288,,CC BY-SA 3.0,,834,713,5,0,0,3,true,false,false,true,true,false,52,8,false,0.005,0.0009,3677,2016,10,21,Thursday,false,false,false,false,false,false,false
12973777,How to run a shell script at startup,"On an Amazon S3 Linux instance, I have two scripts called start_my_app and stop_my_app which start and stop forever (which in turn runs my Node.js application). I use these scripts to manually start and stop my Node.js application. So far so good.
My problem: I also want to set it up such that start_my_app is run whenever the system boots up. I know that I need to add a file inside init.d and I know how to symlink it to the proper directory within rc.d, but I can't figure out what actually needs to go inside the file that I place in init.d. I'm thinking it should be just one line, like, start_my_app, but that hasn't been working for me.
",https://stackoverflow.com/questions/12973777/how-to-run-a-shell-script-at-startup,536,1663477.0,25.0,,,2012-10-19 11:56:39,2024-06-18 09:52:31,2019-12-30 23:46:08,,,linux;node.js;init.d;forever,meetamit,25257,1113023,registered,true,12973826,,CC BY-SA 4.0,2021-03-22 01:50:26,900,646,7,2,0,4,true,false,false,true,true,true,36,8,false,0.015,0.0003,5146,2012,10,11,Friday,false,false,false,false,false,false,false
16748737,Grunt watch error - Waiting...Fatal error: watch ENOSPC,"Why do I get the Waiting...Fatal error: watch ENOSPC when I run the watch task ?
How do I solve this issue?
",https://stackoverflow.com/questions/16748737/grunt-watch-error-waiting-fatal-error-watch-enospc,532,140513.0,7.0,,,2013-05-25 10:42:51,2020-07-06 05:46:50,2017-02-02 14:40:32,,,node.js;gruntjs,kds,28825,1796088,registered,true,17437601,,CC BY-SA 3.0,2014-10-13 17:26:59,129,109,1,0,0,2,true,false,false,true,true,true,55,8,false,0.05,0.0038,4928,2013,5,10,Saturday,true,false,false,false,false,false,false
47008159,How to downgrade to a previous Node version,"I want to downgrade my Node version from the latest to v6.10.3.
But nothing has worked so far. Tried NVM and it gives an error as well by saying that the make command is not found. How can I downgrade Node?
",https://stackoverflow.com/questions/47008159/how-to-downgrade-to-a-previous-node-version,532,1526136.0,24.0,,,2017-10-30 04:29:56,2024-12-26 14:15:18,2023-04-25 13:05:24,,,node.js,Shashika Virajh,9507,5775871,registered,true,50287454,,CC BY-SA 4.0,,247,207,2,0,0,1,true,false,false,true,true,true,43,8,false,0.016,0.0003,3309,2017,10,4,Monday,false,false,false,false,false,false,false
39436322,Node.js - SyntaxError: Unexpected token import,"I don't understand what is wrong.
Node v5.6.0
NPM v3.10.6
The code:
function (exports, require, module, __filename, __dirname) {
import express from 'express'
};
The error:
SyntaxError: Unexpected token import
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:387:25)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Function.Module.runMain (module.js:447:10)
at startup (node.js:140:18)
at node.js:1001:3
",https://stackoverflow.com/questions/39436322/node-js-syntaxerror-unexpected-token-import,531,875377.0,18.0,,,2016-09-11 12:55:44,2023-07-26 09:41:09,2018-11-15 16:09:42,,,javascript;node.js;npm;ecmascript-6,SofDroid,5499,3200461,registered,true,39436580,,CC BY-SA 4.0,,624,555,2,0,0,4,true,false,false,true,true,true,46,6,false,0.021,0.0006,3723,2016,9,12,Sunday,true,false,true,false,false,false,false
21168141,Cannot install packages using node package manager in Ubuntu,"NodeJS interpreter name(node) on Ubuntu has been renamed to nodejs because of a name conflict with another package. Here's what the readme. Debian says:
The upstream name for the Node.js interpreter command is ""node"".
In Debian the interpreter command has been changed to ""nodejs"".
This was done to prevent a namespace collision: other commands use
the same name in their upstream, such as ax25-node from the ""node""
package.
Scripts calling Node.js as a shell command must be changed to instead
use the ""nodejs"" command.
However, using nodejs mucks up installing packages using npm. Package installation fails with the following error:
sh: 1: node: not found
npm WARN This failure might be due to the use of legacy binary ""node""
npm WARN For further explanations, please read /usr/share/doc/nodejs/README.Debian
How do I make npm understand that nodejs is already installed on the system but the interpreter name is different?
",https://stackoverflow.com/questions/21168141/cannot-install-packages-using-node-package-manager-in-ubuntu,525,260489.0,19.0,,,2014-01-16 17:02:54,2022-10-04 13:38:23,2019-01-18 18:38:23,,,node.js;ubuntu;npm,Sayem,6089,1267124,registered,true,21171188,,CC BY-SA 4.0,2017-07-05 01:04:07,1119,964,4,0,0,3,true,false,false,true,true,true,60,9,false,0.073,0.002,4692,2014,1,17,Thursday,false,false,false,false,false,false,false
36172442,How can I get npm start at a different directory?,"I usually cd into the app directory and then run npm start.
It is my feeling that there ought to be some way to run npm start with a path parameter. But, the npm start documentation contains no such feature.
I tried myself only to find npm start ./myapp does not work. Is there a way to do that?
",https://stackoverflow.com/questions/36172442/how-can-i-get-npm-start-at-a-different-directory,525,386651.0,9.0,,,2016-03-23 07:50:26,2025-10-21 09:09:32,2020-02-10 08:32:45,,,node.js,Blaise,22482,863637,registered,true,,,CC BY-SA 4.0,2017-12-18 04:14:49,435,298,4,1,0,1,false,false,false,true,true,true,49,10,true,0.023,0.0014,3895,2016,3,7,Wednesday,false,false,false,false,false,false,false
15806241,How to specify local modules as npm package dependencies,"I have an application which has the usual set of dependencies on third party modules (e.g. "express") specified in the package.json file under dependencies. E.g.
"express" : "3.1.1"
I would like to structure my own code modularly and have a set of local (meaning on the file system I am currently in) modules be installed by the package.json. I know that I can install a local module by running:
npm install path/to/mymodule
However, I don't know how to make this happen via the package.json dependencies structure. Using the --save option in this command is simply putting "mymodule": "0.0.0" into my package.json (doesn't reference the filepath location). If i then remove the installed version from node_modules, and try to re-install from the package.json, it fails (because it looks for "mymodule" in the central registry, and doesn't look locally).
I'm sure the is a way of telling the "dependencies": {} structure that I want it to be installed from a file system path, but don't know how.
Anyone else had this problem?
Thanks.
",https://stackoverflow.com/questions/15806241/how-to-specify-local-modules-as-npm-package-dependencies,520,648251.0,10.0,,,2013-04-04 08:34:35,2024-11-27 19:32:52,2024-03-08 02:44:19,,,node.js;npm,Sam Adams,5925,1584651,registered,true,38417065,,CC BY-SA 4.0,,1333,1107,7,0,0,2,true,false,false,true,true,true,56,9,false,0.015,0.0008,4979,2013,4,8,Thursday,false,false,false,false,false,false,false
19743396,CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true,"I have a setup involving
Frontend server (Node.js, domain: localhost:3000) <---> Backend (Django, Ajax, domain: localhost:8000)
Browser <-- webapp <-- Node.js (Serve the app)
Browser (webapp) --> Ajax --> Django(Serve ajax POST requests)
Now, my problem here is with CORS setup which the webapp uses to make Ajax calls to the backend server. In chrome, I keep getting
Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true.
doesn't work on firefox either.
My Node.js setup is:
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', 'http://localhost:8000/');
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header(""Access-Control-Allow-Headers"", ""Origin, X-Requested-With, Content-Type, Accept"");
next();
};
And in Django I'm using this middleware along with this
The webapp makes requests as such:
$.ajax({
type: ""POST"",
url: 'http://localhost:8000/blah',
data: {},
xhrFields: {
withCredentials: true
},
crossDomain: true,
dataType: 'json',
success: successHandler
});
So, the request headers that the webapp sends looks like:
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: ""Origin, X-Requested-With, Content-Type, Accept""
Access-Control-Allow-Methods: 'GET,PUT,POST,DELETE'
Content-Type: application/json
Accept: */*
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Cookie: csrftoken=***; sessionid=""***""
And here's the response header:
Access-Control-Allow-Headers: Content-Type,*
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST,GET,OPTIONS,PUT,DELETE
Content-Type: application/json
Where am I going wrong?!
Edit 1: I've been using chrome --disable-web-security, but now want things to actually work.
Edit 2: Answer:
So, solution for me django-cors-headers config:
CORS_ORIGIN_ALLOW_ALL = False
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = (
'http://localhost:3000' # Here was the problem indeed and it has to be http://localhost:3000, not http://localhost:3000/
)
",https://stackoverflow.com/questions/19743396/cors-cannot-use-wildcard-in-access-control-allow-origin-when-credentials-flag-i,520,862064.0,12.0,,,2013-11-02 15:18:28,2024-04-24 16:10:37,2015-10-01 12:12:37,,,ajax;django;node.js;cors;django-cors-headers,ixaxaar,6849,2134957,registered,true,19744754,,CC BY-SA 3.0,,2652,2217,7,2,0,5,true,false,false,true,true,true,86,11,false,0.014,0.0006,4767,2013,11,15,Saturday,true,false,false,false,false,false,false
20711240,How to completely remove node.js from Windows,"I uninstalled my previous version of node.js (0.8.11) and downloaded the latest, 0.10.24 from the node.js website and installed it. However, after running node --version, it still indicates that I'm running v0.8.11. Obviously, some stuff was left behind during the uninstall process, and it's causing me to have all sorts of errors when trying to add modules through npm. I've seen solutions to this for OSX and Linux, but couldn't find anything for Windows. I'm running Windows 7 64-bit.
",https://stackoverflow.com/questions/20711240/how-to-completely-remove-node-js-from-windows,515,1242790.0,13.0,,,2013-12-20 20:12:19,2026-02-17 02:11:38,2015-07-23 22:31:22,,,node.js;windows;npm;windows-7-x64,Andrew De Forest,7528,867798,registered,true,20711410,,CC BY-SA 3.0,,509,489,1,0,0,4,true,false,false,true,true,true,45,7,false,0.01,0.0004,4719,2013,12,20,Friday,false,false,false,false,false,false,false
10265798,Determine project root from a running node.js application,"Is there a different way, other than process.cwd(), to get the pathname of the current project's root-directory. Does Node implement something like ruby's property, Rails.root,. I'm looking for something that is constant, and reliable.
",https://stackoverflow.com/questions/10265798/determine-project-root-from-a-running-node-js-application,514,711722.0,34.0,,,2012-04-22 06:39:20,2024-05-18 02:04:27,2021-06-06 15:26:57,,,node.js;working-directory,MrEvil,8133,67707,registered,true,18721515,,CC BY-SA 4.0,,269,236,2,0,0,2,true,false,false,true,true,true,57,8,false,0.048,0.0007,5326,2012,4,6,Sunday,true,false,false,false,false,false,false
7267102,How do I update/upsert a document in Mongoose?,"Perhaps it's the time, perhaps it's me drowning in sparse documentation and not being able to wrap my head around the concept of updating in Mongoose :)
Here's the deal:
I have a contact schema and model (shortened properties):
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var mongooseTypes = require(""mongoose-types""),
useTimestamps = mongooseTypes.useTimestamps;
var ContactSchema = new Schema({
phone: {
type: String,
index: {
unique: true,
dropDups: true
}
},
status: {
type: String,
lowercase: true,
trim: true,
default: 'on'
}
});
ContactSchema.plugin(useTimestamps);
var Contact = mongoose.model('Contact', ContactSchema);
I receive a request from the client, containing the fields I need and use my model thusly:
mongoose.connect(connectionString);
var contact = new Contact({
phone: request.phone,
status: request.status
});
And now we reach the problem:
- If I call
contact.save(function(err){...}) I'll receive an error if the contact with the same phone number already exists (as expected - unique)
- I can't call
update() on contact, since that method does not exist on a document
- If I call update on the model:
Contact.update({phone:request.phone}, contact, {upsert: true}, function(err{...})
I get into an infinite loop of some sorts, since the Mongoose update implementation clearly doesn't want an object as the second parameter.
- If I do the same, but in the second parameter I pass an associative array of the request properties
{status: request.status, phone: request.phone ...} it works - but then I have no reference to the specific contact and cannot find out its createdAt and updatedAt properties.
So the bottom line, after all I tried: given a document contact, how do I update it if it exists, or add it if it doesn't?
Thanks for your time.
",https://stackoverflow.com/questions/7267102/how-do-i-update-upsert-a-document-in-mongoose,512,737575.0,23.0,,,2011-09-01 07:17:00,2022-12-14 06:34:29,2019-05-01 16:42:33,,,javascript;mongodb;node.js;mongoose,Traveling Tech Guy,27927,19856,registered,true,24711713,,CC BY-SA 4.0,2019-02-22 14:10:31,2150,1909,9,0,0,4,true,false,false,true,true,true,46,8,true,0.031,0.0007,5560,2011,9,7,Thursday,false,false,true,false,false,false,false
5878682,node.js hash string?,"I have a string that I want to hash. What's the easiest way to generate the hash in node.js?
The hash is for versioning, not security.
",https://stackoverflow.com/questions/5878682/node-js-hash-string,510,440531.0,14.0,,,2011-05-04 04:47:17,2024-04-13 19:28:41,2018-02-21 17:50:24,,,hash;node.js,Harry,55539,663447,registered,true,5878714,,CC BY-SA 3.0,,150,136,0,0,0,2,true,false,false,true,true,true,20,3,true,0.032,0.0012,5680,2011,5,4,Wednesday,false,false,false,false,false,false,false
38306569,What does body-parser do with express?,"I don't understand why we need body-parser in an Express application, as we can get data without using body-parser.
And what does it do actually and how?
",https://stackoverflow.com/questions/38306569/what-does-body-parser-do-with-express,509,483609.0,11.0,,,2016-07-11 12:08:39,2023-07-26 12:13:27,2017-07-24 16:51:15,,,node.js;express;body-parser,jiten,5221,3459770,registered,true,,,CC BY-SA 3.0,2018-08-19 22:05:58,187,154,2,0,0,3,false,false,false,true,true,true,38,6,true,0.023,0.0011,3785,2016,7,12,Monday,false,false,false,false,false,false,false
34810526,How to properly upgrade node using nvm,"Is it possible to upgrade node right in place, instead of manually installing the latest stable version?
I have installed node.js version 5.0 with nvm, but now I want to update it to 5.4. I'm trying to avoid having to manually reinstall all of my global packages (e.g. by running npm install -g grunt-cli bower yo yoman-angular-generator blabla blablablabla...).
",https://stackoverflow.com/questions/34810526/how-to-properly-upgrade-node-using-nvm,508,564569.0,13.0,,,2016-01-15 11:54:23,2026-01-30 16:54:22,2018-12-26 22:26:32,,,node.js;npm;nvm;package-management,Boris Burkov,14826,1360544,registered,true,34810922,,CC BY-SA 4.0,,572,365,5,2,0,4,true,false,false,true,true,true,38,7,false,0.023,0.0009,3963,2016,1,11,Friday,false,false,false,false,false,false,false
4797050,How to run Node.js as a background process and never die?,"I connect to the linux server via putty SSH. I tried to run it as a background process like this:
$ node server.js &
However, after 2.5 hrs the terminal becomes inactive and the process dies. Is there anyway I can keep the process alive even with the terminal disconnected?
Edit 1
Actually, I tried nohup, but as soon as I close the Putty SSH terminal or unplug my internet, the server process stops right away.
Is there anything I have to do in Putty?
Edit 2 (on Feb, 2012)
There is a node.js module, forever. It will run node.js server as daemon service.
",https://stackoverflow.com/questions/4797050/how-to-run-node-js-as-a-background-process-and-never-die,506,772058.0,14.0,,,2011-01-25 17:53:33,2022-12-24 00:27:16,2018-10-04 11:55:38,,,node.js;linux;background-process,murvinlai,50655,196874,registered,true,4797069,,CC BY-SA 4.0,2015-07-25 01:47:05,785,576,3,1,0,3,true,false,false,true,true,true,57,11,true,0.018,0.0007,5779,2011,1,17,Tuesday,false,false,false,false,false,false,false
1884724,What is Node.js?,"I don't fully get what Node.js is all about. Maybe it's because I am mainly a web based business application developer. What is it and what is the use of it?
My understanding so far is that:
- The programming model is event driven, especially the way it handles I/O.
- It uses JavaScript and the parser is V8.
- It can be easily used to create concurrent server applications.
Are my understandings correct? If yes, then what are the benefits of evented I/O, is it just more for the concurrency stuff? Also, is the direction of Node.js to become a framework like, JavaScript based (V8 based) programming model?
",https://stackoverflow.com/questions/1884724/what-is-node-js,505,488512.0,10.0,,,2009-12-10 23:05:21,2013-06-22 10:22:09,2013-06-22 09:11:06,2012-04-28 14:03:11,not constructive,javascript;node.js;v8;evented-io,Jeff,13205,52752,registered,true,1902991,,,,1001,609,0,4,0,4,true,true,false,true,true,true,16,3,true,0.02,0.001,6190,2009,12,23,Thursday,false,false,true,false,false,false,false
12616153,What is Express.js?,"I am a learner in Node.js.
- What's Express.js?
- What's the purpose of it with Node.js?
- Why do we actually need Express.js? How is it useful for us to use with Node.js?
- What's Redis? Does it come with Express.js?
",https://stackoverflow.com/questions/12616153/what-is-express-js,505,241714.0,10.0,,,2012-09-27 07:24:16,2021-09-29 15:29:29,2020-08-24 15:30:03,2022-05-14 14:53:57,Opinion-based,node.js;express;redis,vinod,8430,1468162,registered,true,12616205,,,,471,212,0,3,0,3,true,true,false,true,true,true,19,3,true,0.041,0.0021,5168,2012,9,7,Thursday,false,false,false,false,false,false,false
40465047,How can I mock an ES6 module import using Jest?,"I want to test that one of my ES6 modules calls another ES6 module in a particular way. With Jasmine this is super easy --
The application code:
// myModule.js
import dependency from './dependency';
export default (x) => {
dependency.doSomething(x * 2);
}
And the test code:
//myModule-test.js
import myModule from '../myModule';
import dependency from '../dependency';
describe('myModule', () => {
it('calls the dependency with double the input', () => {
spyOn(dependency, 'doSomething');
myModule(2);
expect(dependency.doSomething).toHaveBeenCalledWith(4);
});
});
What's the equivalent with Jest? I feel like this is such a simple thing to want to do, but I've been tearing my hair out trying to figure it out.
The closest I've come is by replacing the imports with requires, and moving them inside the tests/functions. Neither of which are things I want to do.
// myModule.js
export default (x) => {
const dependency = require('./dependency'); // Yuck
dependency.doSomething(x * 2);
}
//myModule-test.js
describe('myModule', () => {
it('calls the dependency with double the input', () => {
jest.mock('../dependency');
myModule(2);
const dependency = require('../dependency'); // Also yuck
expect(dependency.doSomething).toBeCalledWith(4);
});
});
For bonus points, I'd love to make the whole thing work when the function inside dependency.js is a default export. However, I know that spying on default exports doesn't work in Jasmine (or at least I could never get it to work), so I'm not holding out hope that it's possible in Jest either.
",https://stackoverflow.com/questions/40465047/how-can-i-mock-an-es6-module-import-using-jest,503,522528.0,11.0,,,2016-11-07 12:19:32,2024-11-27 09:48:32,2020-09-24 21:19:18,,,javascript;node.js;mocking;ecmascript-6;jestjs,Cam Jackson,12365,665488,registered,true,60669731,,CC BY-SA 4.0,,1978,1615,6,2,0,5,true,false,false,true,true,true,47,10,true,0.021,0.001,3666,2016,11,12,Monday,false,false,true,false,false,false,false
42308879,How to solve npm error "npm ERR! code ELIFECYCLE","I'm trying to learn react, so I have this sample code for the full-stack react voting app, and I am trying to get it to work but after running npm install followed by npm start I receive the following error when I run npm start can anyone help me with this issue:
npm ERR! Darwin 16.4.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "run" "server"
npm ERR! node v7.5.0
npm ERR! npm v4.3.0
npm ERR! file sh
npm ERR! code ELIFECYCLE
npm ERR! errno ENOENT
npm ERR! syscall spawn
npm ERR! voting_app@1.1.0 server: `live-server --public --
host=localhost --port=3000 --middleware=./disable-browser-cache.js`
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the voting_app@1.1.0 server script 'live-server --
public --host=localhost --port=3000 --middleware=./disable-browser-
cache.js'.
npm ERR! Make sure you have the latest version of node.js and npm
installed.
npm ERR! If you do, this is most likely a problem with the voting_app
package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! live-server --public --host=localhost --port=3000 --
middleware=./disable-browser-cache.js
npm ERR! You can get information on how to open an issue for this
project with:
npm ERR! npm bugs voting_app
npm ERR! Or if that isn't available, you can get their info via:
npm ERR! npm owner ls voting_app
npm ERR! There is likely additional logging output above.
npm ERR! Please include the following file with any support request:
npm ERR! /Users/ItsMeMrLi/.npm/_logs/2017-02-17T22_48_03_581Z-
debug.log
npm ERR! Darwin 16.4.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "start"
npm ERR! node v7.5.0
npm ERR! npm v4.3.0
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! voting_app@1.1.0 start: `npm run server`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the voting_app@1.1.0 start script 'npm run server'.
npm ERR! Make sure you have the latest version of node.js and npm
installed.
npm ERR! If you do, this is most likely a problem with the voting_app
package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! npm run server
npm ERR! You can get information on how to open an issue for this
project with:
npm ERR! npm bugs voting_app
npm ERR! Or if that isn't available, you can get their info via:
npm ERR! npm owner ls voting_app
npm ERR! There is likely additional logging output above.
npm ERR! Please include the following file with any support request:
npm ERR! /Users/ItsMeMrLi/.npm/_logs/2017-02-17T22_48_03_655Z-
debug.log
Here is my package.json:
{
"name": "voting_app",
"version": "1.1.0",
"author": "Fullstack.io",
"scripts": {
"go": "open http://localhost:3000; npm run server",
"e2e": "nightwatch",
"test": "./node_modules/.bin/concurrently -k 'npm run server' 'npm
run e2e'",
"start": "npm run server",
"server": "live-server public --host=localhost --port=3000 --
middleware=./disable-browser-cache.js"
},
"private": true,
"devDependencies": {
"concurrently": "2.2.0",
"live-server": "git://github.com/acco/live-server.git"
},
"dependencies": {
"semantic-ui": "git://github.com/Semantic-Org/Semantic-
UI.git#27d58a01793b66318478fbc5b6676804d22d065d"
}
}
And finally my log file:
0 info it worked if it ends with ok
1 verbose cli [ '/usr/local/bin/node', '/usr/local/bin/npm', 'start' ]
2 info using npm@4.3.0
3 info using node@v7.5.0
4 verbose run-script [ 'prestart', 'start', 'poststart' ]
5 info lifecycle voting_app@1.1.0~prestart: voting_app@1.1.0
6 silly lifecycle voting_app@1.1.0~prestart: no script for prestart, continuing
7 info lifecycle voting_app@1.1.0~start: voting_app@1.1.0
8 verbose lifecycle voting_app@1.1.0~start: unsafe-perm in lifecycle true
9 verbose lifecycle voting_app@1.1.0~start: PATH: /usr/local/lib/node_modules/npm/bin/node-gyp-bin:/Users/ItsMeMrLi/Downloads/fullstack-react-code/voting_app/node_modules/.bin:/Library/Frameworks/Python.framework/Versions/3.6/bin:/Users/ItsMeMrLi/.rvm/gems/ruby-2.3.1/bin:/Users/ItsMeMrLi/.rvm/gems/ruby-2.3.1@global/bin:/Users/ItsMeMrLi/.rvm/rubies/ruby-2.3.1/bin:/Users/ItsMeMrLi/.cargo/bin:/usr/local/Cellar/smlnj/110.74/libexec/bin:/usr/local/bin:/Users/ItsMeMrLi/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Applications/Postgres.app/Contents/Versions/latest/bin:/Downloads/geckodriver:/usr/local/bin:/Users/ItsMeMrLi/.rvm/bin
10 verbose lifecycle voting_app@1.1.0~start: CWD: /Users/ItsMeMrLi/Downloads/fullstack-react-code/voting_app
11 silly lifecycle voting_app@1.1.0~start: Args: [ '-c', 'npm run server' ]
12 silly lifecycle voting_app@1.1.0~start: Returned: code: 1 signal: null
13 info lifecycle voting_app@1.1.0~start: Failed to exec start script
14 verbose stack Error: voting_app@1.1.0 start: `npm run server`
14 verbose stack Exit status 1
14 verbose stack at EventEmitter.<anonymous> (/usr/local/lib/node_modules/npm/lib/utils/lifecycle.js:279:16)
14 verbose stack at emitTwo (events.js:106:13)
14 verbose stack at EventEmitter.emit (events.js:192:7)
14 verbose stack at ChildProcess.<anonymous> (/usr/local/lib/node_modules/npm/lib/utils/spawn.js:40:14)
14 verbose stack at emitTwo (events.js:106:13)
14 verbose stack at ChildProcess.emit (events.js:192:7)
14 verbose stack at maybeClose (internal/child_process.js:890:16)
14 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:226:5)
15 verbose pkgid voting_app@1.1.0
16 verbose cwd /Users/ItsMeMrLi/Downloads/fullstack-react-code/voting_app
17 error Darwin 16.4.0
18 error argv "/usr/local/bin/node" "/usr/local/bin/npm" "start"
19 error node v7.5.0
20 error npm v4.3.0
21 error code ELIFECYCLE
22 error errno 1
23 error voting_app@1.1.0 start: `npm run server`
23 error Exit status 1
24 error Failed at the voting_app@1.1.0 start script 'npm run server'.
24 error Make sure you have the latest version of node.js and npm installed.
24 error If you do, this is most likely a problem with the voting_app package,
24 error not with npm itself.
24 error Tell the author that this fails on your system:
24 error npm run server
24 error You can get information on how to open an issue for this project with:
24 error npm bugs voting_app
24 error Or if that isn't available, you can get their info via:
24 error npm owner ls voting_app
24 error There is likely additional logging output above.
25 verbose exit [ 1, true ]
",https://stackoverflow.com/questions/42308879/how-to-solve-npm-error-npm-err-code-elifecycle,502,1534013.0,52.0,,,2017-02-17 23:02:25,2025-11-14 12:18:35,2020-08-13 08:38:36,,,node.js;npm;npm-install;npm-start;npm-live-server,user7037425,,,does_not_exist,true,,,CC BY-SA 4.0,2018-08-06 08:02:54,6956,6850,4,0,0,5,false,false,false,true,false,true,59,9,false,0.034,0.0003,3564,2017,2,23,Friday,false,false,false,false,false,false,false
27637609,Understanding passport serialize deserialize,"How would you explain the workflow of Passport's serialize and deserialize methods to a layman.
Where does user.id go after passport.serializeUser has been called?
We are calling passport.deserializeUser right after it where does it fit in the workflow?
// used to serialize the user for the session
passport.serializeUser(function(user, done) {
done(null, user.id);
// where is this user.id going? Are we supposed to access this anywhere?
});
// used to deserialize the user
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
I'm still trying to wrap my head around it. I have a complete working app and am not running into errors of any kind.
I just wanted to understand what exactly is happening here?
Any help is appreciated.
",https://stackoverflow.com/questions/27637609/understanding-passport-serialize-deserialize,491,207526.0,7.0,,,2014-12-24 13:22:56,2024-10-08 22:57:37,2017-11-03 07:09:05,,,node.js;authentication;express;serialization;passport.js,Anubhav,7246,2173853,registered,true,27637668,,CC BY-SA 3.0,,959,823,4,0,0,5,true,false,false,true,true,true,44,4,false,0.034,0.0024,4350,2014,12,13,Wednesday,false,false,false,false,false,false,false
10617070,How do I measure the execution time of JavaScript code with callbacks?,"I have a piece of JavaScript code that I am executing using the node.js interpreter.
for(var i = 1; i < LIMIT; i++) {
var user = {
id: i,
name: ""MongoUser ["" + i + ""]""
};
db.users.save(user, function(err, saved) {
if(err || !saved) {
console.log(""Error"");
} else {
console.log(""Saved"");
}
});
}
How can I measure the time taken by these database insert operations? I could compute the difference of date values after and before this piece of code but that would be incorrect because of the asynchronous nature of the code.
",https://stackoverflow.com/questions/10617070/how-do-i-measure-the-execution-time-of-javascript-code-with-callbacks,488,416948.0,14.0,,,2012-05-16 10:55:35,2024-08-06 09:26:54,2020-01-28 00:45:31,,,javascript;node.js;profiling,Nataraj Mocherla,7249,232694,registered,true,18427652,,CC BY-SA 4.0,,657,569,2,0,0,3,true,false,false,true,true,true,70,12,true,0.034,0.0012,5302,2012,5,10,Wednesday,false,false,true,false,false,false,false
9249830,How can I set NODE_ENV=production on Windows?,"In Ubuntu it's quite simple; I can run the application using:
$ NODE_ENV=production node myapp/app.js
However, this doesn't work on Windows. Is there a configuration file where I can set the attribute?
",https://stackoverflow.com/questions/9249830/how-can-i-set-node-env-production-on-windows,486,651568.0,27.0,,,2012-02-12 15:09:14,2025-01-09 14:39:58,2019-03-08 04:38:37,,,node.js;express,Jack,15900,882993,registered,true,9250168,,CC BY-SA 4.0,2023-04-06 18:34:49,243,205,1,0,0,2,true,false,false,true,true,true,45,7,true,0.041,0.0007,5396,2012,2,15,Sunday,true,false,false,false,false,false,false
19811541,Get file name from absolute path in Nodejs?,"How can I get the file name from an absolute path in Nodejs?
e.g. "foo.txt" from "/var/www/foo.txt"
I know it works with a string operation, like fullpath.replace(/.+\//, ''),
but I want to know is there an explicit way, like file.getName() in Java?
",https://stackoverflow.com/questions/19811541/get-file-name-from-absolute-path-in-nodejs,482,358062.0,12.0,,,2013-11-06 11:57:30,2024-04-17 15:23:05,2022-04-08 08:12:34,,,node.js;path;fs,fxp,7112,220877,registered,true,19811573,,CC BY-SA 4.0,,343,270,4,0,0,3,true,false,false,true,true,true,43,8,true,0.034,0.0013,4763,2013,11,11,Wednesday,false,false,false,false,false,false,false
16995184,NodeJS - What does "socket hang up" actually mean?,"I'm building a web scraper with Node and Cheerio, and for a certain website I'm getting the following error (it only happens on this one website, no others that I try to scrape.
It happens at a different location every time, so sometimes it's url x that throws the error, other times url x is fine and it's a different url entirely:
Error!: Error: socket hang up using [insert random URL, it's different every time]
Error: socket hang up
at createHangUpError (http.js:1445:15)
at Socket.socketOnEnd [as onend] (http.js:1541:23)
at Socket.g (events.js:175:14)
at Socket.EventEmitter.emit (events.js:117:20)
at _stream_readable.js:910:16
at process._tickCallback (node.js:415:13)
This is very tricky to debug, I don't really know where to start. To begin, what IS a socket hang up error? Is it a 404 error or similar? Or does it just mean that the server refused a connection?
I can't find an explanation of this anywhere!
EDIT: Here's a sample of code that is (sometimes) returning errors:
function scrapeNexts(url, oncomplete) {
request(url, function(err, resp, body) {
if (err) {
console.log(""Uh-oh, ScrapeNexts Error!: "" + err + "" using "" + url);
errors.nexts.push(url);
}
$ = cheerio.load(body);
// do stuff with the '$' cheerio content here
});
}
There is no direct call to close the connection, but I'm using Node Request which (as far as I can tell) uses http.get so this is not required, correct me if I'm wrong!
EDIT 2: Here's an actual, in-use bit of code that is causing errors. prodURL and other variables are mostly jquery selectors that are defined earlier. This uses the async library for Node.
function scrapeNexts(url, oncomplete) {
request(url, function (err, resp, body) {
if (err) {
console.log(""Uh-oh, ScrapeNexts Error!: "" + err + "" using "" + url);
errors.nexts.push(url);
}
async.series([
function (callback) {
$ = cheerio.load(body);
callback();
},
function (callback) {
$(prodURL).each(function () {
var theHref = $(this).attr('href');
urls.push(baseURL + theHref);
});
var next = $(next_select).first().attr('href');
oncomplete(next);
}
]);
});
}
",https://stackoverflow.com/questions/16995184/nodejs-what-does-socket-hang-up-actually-mean,482,1130113.0,33.0,,,2013-06-08 01:45:25,2022-09-30 10:45:06,2013-06-08 07:53:35,,,node.js,JVG,21300,556006,registered,true,,,CC BY-SA 3.0,2019-12-17 16:19:38,2866,2481,9,2,0,1,false,false,false,true,true,true,60,9,true,0.029,0.0004,4914,2013,6,1,Saturday,true,false,false,false,false,false,false
4976466,Difference between "process.stdout.write" and "console.log" in node.js?,"What is the difference between ""process.stdout.write"" and ""console.log"" in node.js?
EDIT: Using console.log for a variable showed a lot of unreadable characters while using process.stdout.write showed an object.
Why is that?
",https://stackoverflow.com/questions/4976466/difference-between-process-stdout-write-and-console-log-in-node-js,481,402437.0,12.0,,,2011-02-12 05:09:03,2023-10-27 22:57:00,2011-02-13 22:59:13,,,javascript;node.js,ajsie,80288,206446,registered,true,4984464,,CC BY-SA 2.5,,248,227,0,0,0,2,true,false,false,true,true,true,91,7,true,0.03,0.0012,5761,2011,2,5,Saturday,true,false,true,false,false,false,false
14079833,How to change bower's default components folder?,"I'm making a new project that uses bower from twitter. I created a component.json to maintain all my dependency like jquery. Then I run bower install that installs everything in a folder named components. But I need to install the components in a different folder, e.g. public/components.
I have tried editing my components.json into:
{
""name"": ""test"",
""version"": ""1.0.0"",
""directory"": ""public/"",
""dependencies"": {
""jquery"": ""*""
}
}
or:
{
""name"": ""test"",
""version"": ""1.0.0"",
""componentsDirectory"": ""public/"",
""dependencies"": {
""jquery"": ""*""
}
}
as shown in https://github.com/twitter/bower/pull/94 but it doesn't work.
",https://stackoverflow.com/questions/14079833/how-to-change-bowers-default-components-folder,480,217936.0,6.0,,,2012-12-29 07:55:03,2017-03-06 12:05:27,2013-04-01 20:05:49,,,node.js;bower,Adam Ramadhan,22840,320486,registered,true,14080568,,CC BY-SA 3.0,,854,654,6,1,0,2,true,false,false,true,true,true,52,7,true,0.028,0.0022,5075,2012,12,7,Saturday,true,false,false,false,false,false,false
45801457,Node.js: Python not found exception due to node-sass and node-gyp,"Suddenly in one of my jenkins environment build has started failing, while in local machine it seems to be working fine as i have python installed,
From the logs i was able to detect that the problem is with internal dependency that is node-gyp v3.5.0 from node-sass v3.8.0 when i researched by visiting this about node-gyp and found the prerequisite that Python needs to be installed.
So my question is that what version of node-sass can i install to bypass this or is there a better solution as my build was running fine till this morning on the same environment.
Node v5.10.1
ERROR LOG
gyp verb check python checking for Python executable ""python2"" in the PATH
gyp verb `which` failed Error: not found: python2
gyp verb `which` failed at getNotFoundError (C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\which\which.js:13:12)
gyp verb `which` failed at F (C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\which\which.js:68:19)
gyp verb `which` failed at E (C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\which\which.js:80:29)
gyp verb `which` failed at C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\which\which.js:89:16
gyp verb `which` failed at C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\isexe\index.js:44:5
gyp verb `which` failed at C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\isexe\windows.js:29:5
gyp verb `which` failed at FSReqWrap.oncomplete (fs.js:82:15)
gyp verb `which` failed python2 { [Error: not found: python2] code: 'ENOENT' }
gyp verb check python checking for Python executable ""python"" in the PATH
gyp verb `which` failed Error: not found: python
gyp verb `which` failed at getNotFoundError (C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\which\which.js:13:12)
gyp verb `which` failed at F (C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\which\which.js:68:19)
gyp verb `which` failed at E (C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\which\which.js:80:29)
gyp verb `which` failed at C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\which\which.js:89:16
gyp verb `which` failed at C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\isexe\index.js:44:5
gyp verb `which` failed at C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\isexe\windows.js:29:5
gyp verb `which` failed at FSReqWrap.oncomplete (fs.js:82:15)
gyp verb `which` failed python { [Error: not found: python] code: 'ENOENT' }
gyp verb could not find ""python"". checking python launcher
gyp verb could not find ""python"". guessing location
gyp verb ensuring that file exists: C:\Python27\python.exe
gyp ERR! configure error
gyp ERR! stack Error: Can't find Python executable ""python"", you can set the PYTHON env variable.
gyp ERR! stack at Object.failNoPython (C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\node-gyp\lib\configure.js:454:19)
gyp ERR! stack at Object.<anonymous> (C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\node-gyp\lib\configure.js:480:16)
gyp ERR! stack at C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\graceful-fs\polyfills.js:284:29
gyp ERR! stack at FSReqWrap.oncomplete (fs.js:82:15)
gyp ERR! System Windows_NT 6.3.9600
gyp ERR! command ""C:\\Program Files\\nodejs\\node.exe"" ""C:\\Program Files (x86)\\Jenkins\\jobs\\NdbSite-hot-fix-Manual-PreBuild\\workspace\\src\\NdbSite.UI\\node_modules\\node-gyp\\bin\\node-gyp.js"" ""rebuild"" ""--verbose"" ""--libsass_ext="" ""--libsass_cflags="" ""--libsass_ldflags="" ""--libsass_library=""
gyp ERR! cwd C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\node-sass
gyp ERR! node -v v5.10.1
gyp ERR! node-gyp -v v3.5.0
gyp ERR! not ok
Build failed
Any thoughts are much appreciated, Thanks.
",https://stackoverflow.com/questions/45801457/node-js-python-not-found-exception-due-to-node-sass-and-node-gyp,475,830261.0,38.0,,,2017-08-21 16:02:37,2024-03-20 08:56:24,,,,node.js;node-gyp;node-sass,Vipul Panth,5941,6538763,registered,true,45807410,,CC BY-SA 3.0,2022-05-15 17:28:09,4760,4560,1,1,0,3,true,false,false,true,true,false,65,10,false,0.046,0.0006,3379,2017,8,16,Monday,false,false,false,false,false,false,false
9283472,Command to remove all npm modules globally,"Is there a command to remove all global npm modules? If not, what do you suggest?
",https://stackoverflow.com/questions/9283472/command-to-remove-all-npm-modules-globally,473,649715.0,31.0,,,2012-02-14 20:07:36,2023-09-15 18:26:04,2021-09-17 17:01:40,,,node.js;npm,EhevuTov,20503,183835,registered,true,9283646,,CC BY-SA 4.0,,89,82,0,0,0,2,true,false,false,true,true,true,42,7,false,0.048,0.0007,5394,2012,2,20,Tuesday,false,false,false,false,false,false,false
31714788,Can an AWS Lambda function call another,"I have 2 Lambda functions - one that produces a quote and one that turns a quote into an order.
I'd like the Order lambda function to call the Quote function to regenerate the quote, rather than just receive it from an untrusted client.
I've looked everywhere I can think of - but can't see how I'd go about chaining or calling the functions...surely this exists!
",https://stackoverflow.com/questions/31714788/can-an-aws-lambda-function-call-another,473,342931.0,25.0,,,2015-07-30 03:35:17,2026-03-02 09:37:12,2016-05-06 15:56:44,,,node.js;amazon-web-services;aws-lambda;aws-api-gateway,Silver,5111,1749560,registered,true,31745774,,CC BY-SA 3.0,2018-04-07 09:48:41,379,365,0,0,0,4,true,false,false,true,true,true,39,7,false,0.073,0.0014,4132,2015,7,3,Thursday,false,false,false,false,false,false,false
64557638,How to Polyfill node core modules in webpack 5,"webpack 5 no longer do auto-polyfilling for node core modules.
How to fix it please?
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
",https://stackoverflow.com/questions/64557638/how-to-polyfill-node-core-modules-in-webpack-5,471,718038.0,38.0,,,2020-10-27 15:25:15,2025-02-14 10:57:11,2022-08-25 18:57:01,,,node.js;webpack,Saber,4809,13470423,registered,true,,,CC BY-SA 4.0,2022-08-31 20:06:25,442,275,0,1,1,2,false,false,false,true,true,true,46,9,false,0.053,0.0007,2216,2020,10,15,Tuesday,false,false,false,false,false,false,false
11321635,NodeJS / Express: what is "app.use"?,"In the docs for the NodeJS express module, the example code has app.use(...).
What is the use function and where is it defined?
",https://stackoverflow.com/questions/11321635/nodejs-express-what-is-app-use,467,391719.0,33.0,,,2012-07-04 02:20:29,2024-04-24 13:47:48,2015-10-21 11:23:14,,,node.js;express,Alexander Bird,41208,10608,registered,true,11321828,,CC BY-SA 3.0,2021-07-28 14:31:42,246,130,3,1,0,2,true,false,false,true,true,true,46,6,true,0.084,0.0012,5253,2012,7,2,Wednesday,false,false,false,false,false,false,false
17245881,How do I debug error ECONNRESET in Node.js?,"I'm running an Express.js application using Socket.io for a chat webapp
and I get the following error randomly around 5 times during 24h.
The node process is wrapped in forever and it restarts itself immediately.
The problem is that restarting Express kicks my users out of their rooms
and nobody wants that.
The web server is proxied by HAProxy. There are no socket stability issues,
just using websockets and flashsockets transports.
I cannot reproduce this on purpose.
This is the error with Node v0.10.11:
events.js:72
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET //alternatively it s a 'write'
at errnoException (net.js:900:11)
at TCP.onread (net.js:555:19)
error: Forever detected script exited with code: 8
error: Forever restarting script for 2 time
EDIT (2013-07-22)
Added both socket.io client error handler and the uncaught exception handler.
Seems that this one catches the error:
process.on('uncaughtException', function (err) {
console.error(err.stack);
console.log(""Node NOT Exiting..."");
});
So I suspect it's not a Socket.io issue but an HTTP request to another server
that I do or a MySQL/Redis connection. The problem is that the error stack
doesn't help me identify my code issue. Here is the log output:
Error: read ECONNRESET
at errnoException (net.js:900:11)
at TCP.onread (net.js:555:19)
How do I know what causes this? How do I get more out of the error?
Ok, not very verbose but here's the stacktrace with Longjohn:
Exception caught: Error ECONNRESET
{ [Error: read ECONNRESET]
code: 'ECONNRESET',
errno: 'ECONNRESET',
syscall: 'read',
__cached_trace__:
[ { receiver: [Object],
fun: [Function: errnoException],
pos: 22930 },
{ receiver: [Object], fun: [Function: onread], pos: 14545 },
{},
{ receiver: [Object],
fun: [Function: fireErrorCallbacks],
pos: 11672 },
{ receiver: [Object], fun: [Function], pos: 12329 },
{ receiver: [Object], fun: [Function: onread], pos: 14536 } ],
__previous__:
{ [Error]
id: 1061835,
location: 'fireErrorCallbacks (net.js:439)',
__location__: 'process.nextTick',
__previous__: null,
__trace_count__: 1,
__cached_trace__: [ [Object], [Object], [Object] ] } }
Here I serve the flash socket policy file:
net = require(""net"")
net.createServer( (socket) =>
socket.write(""<?xml version=\""1.0\""?>\n"")
socket.write(""<!DOCTYPE cross-domain-policy SYSTEM \""http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd\"">\n"")
socket.write(""<cross-domain-policy>\n"")
socket.write(""<allow-access-from domain=\""*\"" to-ports=\""*\""/>\n"")
socket.write(""</cross-domain-policy>\n"")
socket.end()
).listen(843)
Can this be the cause?
",https://stackoverflow.com/questions/17245881/how-do-i-debug-error-econnreset-in-node-js,467,1370956.0,19.0,,,2013-06-21 23:49:22,2023-06-15 10:50:21,2020-01-28 00:28:08,,,node.js;sockets;tcp;express,Samson,2831,971459,registered,true,17805277,,CC BY-SA 4.0,2022-12-31 15:04:20,3219,2992,6,0,0,4,true,false,false,true,true,true,43,8,true,0.014,0.0003,4901,2013,6,23,Friday,false,false,false,false,false,false,false
46653833,Is there a way to force npm to generate package-lock.json?,"I deleted it by accident and have made many changes to package.json since. An npm install or npm update do not generate package-lock.json anymore. I tried clearing my npm cache and my nvm cache, but nothing seems to be working. I tried it on several versions of Node.js (6.10.3 Node.js - 3.10.10 npm is what I would like it to work on), and it doesn't work on any.
Is there a way to force npm to generate the package-lock.json file?
",https://stackoverflow.com/questions/46653833/is-there-a-way-to-force-npm-to-generate-package-lock-json,466,511519.0,7.0,,,2017-10-09 19:39:25,2022-03-16 19:55:48,2020-06-10 18:41:45,,,node.js;npm;package-lock.json,Big Money,10398,2548010,registered,true,54910009,,CC BY-SA 4.0,,513,434,5,0,0,3,true,false,false,true,true,true,58,10,true,0.014,0.0009,3330,2017,10,19,Monday,false,false,false,false,false,false,false
43127863,Node update a specific package,"I want to update my Browser-sync without updating all my node packages. How can I achieve this? My current version of Browser-sync does not have the Browser-sync GUI :(
├─┬ browser-sync@1.9.2
│ ├── browser-sync-client@1.0.2
",https://stackoverflow.com/questions/43127863/node-update-a-specific-package,466,627284.0,6.0,,,2017-03-30 20:37:33,2025-10-06 10:30:25,,,,javascript;node.js;npm;gulp;browser-sync,Samuel,6288,2303073,registered,true,43127994,,CC BY-SA 3.0,,274,226,1,0,0,5,true,false,false,true,true,false,30,5,false,0.01,0.0007,3523,2017,3,20,Thursday,false,false,true,false,false,false,false
14031763,Doing a cleanup action just before Node.js exits,"I want to tell Node.js to always do something just before it exits, for whatever reason — Ctrl+C, an exception, or any other reason.
I tried this:
process.on('exit', function (){
console.log('Goodbye!');
});
I started the process, killed it, and nothing happened. I started it again, pressed Ctrl+C, and still nothing happened...
",https://stackoverflow.com/questions/14031763/doing-a-cleanup-action-just-before-node-js-exits,464,289223.0,13.0,,,2012-12-25 15:07:26,2023-09-18 10:10:54,2019-12-14 23:06:56,,,node.js,Erel Segal-Halevi,37617,827927,registered,true,14032965,,CC BY-SA 4.0,,464,338,1,0,0,1,true,false,false,true,true,true,48,8,false,0.045,0.0016,5079,2012,12,15,Tuesday,false,false,false,false,false,false,false
15393821,npm ERR cb() never called,"I have a Node.js app hosted on Heroku. Every time I do a git push heroku I get the following error:
Counting objects: 14, done.
Delta compression using up to 6 threads.
Compressing objects: 100% (12/12), done.
Writing objects: 100% (12/12), 1.20 KiB, done.
Total 12 (delta 8), reused 0 (delta 0)
-----> Node.js app detected
-----> Resolving engine versions
Using Node.js version: 0.6.20
Using npm version: 1.2.12
-----> Fetching Node.js binaries
-----> Vendoring node into slug
-----> Installing dependencies with npm
npm http GET https://registry.npmjs.org/pg/0.6.15
npm http GET https://registry.npmjs.org/socket.io
npm http 200 https://registry.npmjs.org/pg/0.6.15
npm http GET https://registry.npmjs.org/pg/-/pg-0.6.15.tgz
npm http 200 https://registry.npmjs.org/socket.io
npm http GET https://registry.npmjs.org/socket.io/-/socket.io-0.9.13.tgz
npm http 200 https://registry.npmjs.org/pg/-/pg-0.6.15.tgz
npm http 200 https://registry.npmjs.org/socket.io/-/socket.io-0.9.13.tgz
npm http GET https://registry.npmjs.org/socket.io-client/0.9.11
npm http GET https://registry.npmjs.org/policyfile/0.0.4
npm http GET https://registry.npmjs.org/base64id/0.1.0
npm http GET https://registry.npmjs.org/redis/0.7.3
npm http GET https://registry.npmjs.org/generic-pool/1.0.9
npm http 200 https://registry.npmjs.org/policyfile/0.0.4
npm http GET https://registry.npmjs.org/policyfile/-/policyfile-0.0.4.tgz
npm http 200 https://registry.npmjs.org/base64id/0.1.0
npm http GET https://registry.npmjs.org/base64id/-/base64id-0.1.0.tgz
npm http 200 https://registry.npmjs.org/generic-pool/1.0.9
npm http GET https://registry.npmjs.org/generic-pool/-/generic-pool-1.0.9
.tgz
npm http 200 https://registry.npmjs.org/socket.io-client/0.9.11
npm http GET https://registry.npmjs.org/socket.io-client/-/socket.io-clie
nt-0.9.11.tgz
npm http 200 https://registry.npmjs.org/redis/0.7.3
npm http GET https://registry.npmjs.org/redis/-/redis-0.7.3.tgz
npm http 200 https://registry.npmjs.org/policyfile/-/policyfile-0.0.4.tgz
npm http 200 https://registry.npmjs.org/base64id/-/base64id-0.1.0.tgz
npm http 200 https://registry.npmjs.org/generic-pool/-/generic-pool-1.0.9
.tgz
npm http 200 https://registry.npmjs.org/socket.io-client/-/socket.io-clie
nt-0.9.11.tgz
npm http 200 https://registry.npmjs.org/redis/-/redis-0.7.3.tgz
> pg@0.6.15 install /tmp/build_36us8733h7kkr/node_modules/pg
> node-waf configure build || (exit 0)
Checking for program g++ or c++ : /usr/bin/g++
Checking for program cpp : /usr/bin/cpp
Checking for program ar : /usr/bin/ar
Checking for program ranlib : /usr/bin/ranlib
Checking for g++ : ok
Checking for node path : not found
Checking for node prefix : ok /tmp/node-node-nNUw
Checking for program pg_config : /usr/bin/pg_config
'configure' finished successfully (0.058s)
Waf: Entering directory `/tmp/build_36us8733h7kkr/node_modules/pg/build'
[1/2] cxx: src/binding.cc -> build/Release/src/binding_1.o
[2/2] cxx_link: build/Release/src/binding_1.o -> build/Release/binding.no
de
Waf: Leaving directory `/tmp/build_36us8733h7kkr/node_modules/pg/build'
'build' finished successfully (0.492s)
npm http GET https://registry.npmjs.org/uglify-js/1.2.5
npm http GET https://registry.npmjs.org/ws
npm http GET https://registry.npmjs.org/xmlhttprequest/1.4.2
npm http GET https://registry.npmjs.org/active-x-obfuscator/0.0.1
npm http 200 https://registry.npmjs.org/active-x-obfuscator/0.0.1
npm http GET https://registry.npmjs.org/active-x-obfuscator/-/active-x-ob
fuscator-0.0.1.tgz
npm http 200 https://registry.npmjs.org/uglify-js/1.2.5
npm http GET https://registry.npmjs.org/uglify-js/-/uglify-js-1.2.5.tgz
npm http 200 https://registry.npmjs.org/xmlhttprequest/1.4.2
npm http GET https://registry.npmjs.org/xmlhttprequest/-/xmlhttprequest-1
.4.2.tgz
npm http 200 https://registry.npmjs.org/ws
npm http GET https://registry.npmjs.org/ws/-/ws-0.4.25.tgz
npm http 200 https://registry.npmjs.org/active-x-obfuscator/-/active-x-ob
fuscator-0.0.1.tgz
npm http 200 https://registry.npmjs.org/uglify-js/-/uglify-js-1.2.5.tgz
npm http 200 https://registry.npmjs.org/xmlhttprequest/-/xmlhttprequest-1
.4.2.tgz
npm http 200 https://registry.npmjs.org/ws/-/ws-0.4.25.tgz
npm http GET https://registry.npmjs.org/zeparser/0.0.5
npm http GET https://registry.npmjs.org/commander
npm http GET https://registry.npmjs.org/tinycolor
npm http GET https://registry.npmjs.org/options
npm http 200 https://registry.npmjs.org/zeparser/0.0.5
npm http GET https://registry.npmjs.org/zeparser/-/zeparser-0.0.5.tgz
npm http 200 https://registry.npmjs.org/options
npm http GET https://registry.npmjs.org/options/-/options-0.0.3.tgz
npm http 200 https://registry.npmjs.org/tinycolor
npm http GET https://registry.npmjs.org/tinycolor/-/tinycolor-0.0.1.tgz
npm http 200 https://registry.npmjs.org/commander
npm http GET https://registry.npmjs.org/commander/-/commander-0.6.1.tgz
npm http 200 https://registry.npmjs.org/zeparser/-/zeparser-0.0.5.tgz
npm http 200 https://registry.npmjs.org/options/-/options-0.0.3.tgz
npm http 200 https://registry.npmjs.org/tinycolor/-/tinycolor-0.0.1.tgz
npm http 200 https://registry.npmjs.org/commander/-/commander-0.6.1.tgz
> ws@0.4.25 install /tmp/build_36us8733h7kkr/node_modules/socket.io/node_
modules/socket.io-client/node_modules/ws
> (node-gyp rebuild 2> builderror.log) || (exit 0)
make: Entering directory `/tmp/build_36us8733h7kkr/node_modules/socket.io
/node_modules/socket.io-client/node_modules/ws/build'
CXX(target) Release/obj.target/bufferutil/src/bufferutil.o
SOLINK_MODULE(target) Release/obj.target/bufferutil.node
SOLINK_MODULE(target) Release/obj.target/bufferutil.node: Finished
COPY Release/bufferutil.node
CXX(target) Release/obj.target/validation/src/validation.o
SOLINK_MODULE(target) Release/obj.target/validation.node
SOLINK_MODULE(target) Release/obj.target/validation.node: Finished
COPY Release/validation.node
make: Leaving directory `/tmp/build_36us8733h7kkr/node_modules/socket.io/
node_modules/socket.io-client/node_modules/ws/build'
npm ERR! cb() never called!
npm ERR! not ok code undefined
npm ERR! cb() never called!
npm ERR! not ok code 1
! Failed to install --production dependencies with npm
! Heroku push rejected, failed to compile Node.js app
To git@heroku.com:still-chamber-1286.git
! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'git@heroku.com:still-chamber-1286.git'
The error is in the last few lines:
npm ERR! cb() never called!
npm ERR! not ok code undefined
npm ERR! cb() never called!
npm ERR! not ok code 1
! Failed to install --production dependencies with npm
! Heroku push rejected, failed to compile Node.js app
To git@heroku.com:still-chamber-1286.git
! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'git@heroku.com:still-chamber-1286.git'
I have had no problems with pushing my code to Heroku before; only since Monday have I had this error.
I have seen similar posts on the web referring to slightly different er",https://stackoverflow.com/questions/15393821/npm-err-cb-never-called,461,711237.0,63.0,,,2013-03-13 18:44:28,2024-08-08 15:08:18,2021-04-12 04:23:13,,,node.js;heroku;npm,Louise K,4813,1562347,registered,true,,,CC BY-SA 4.0,2018-05-26 04:10:16,8125,8023,4,0,0,3,false,false,false,true,true,true,25,5,false,0.089,0.0006,5001,2013,3,18,Wednesday,false,false,false,false,false,false,false
7288814,Download a file from NodeJS Server using Express,"
How can I download a file that is in my server to my machine accessing a page in a nodeJS server?
I'm using the ExpressJS and I've been trying this:
app.get('/download', function(req, res){
var file = fs.readFileSync(__dirname + '/upload-folder/dramaticpenguin.MOV', 'binary');
res.setHeader('Content-Length', file.length);
res.write(file, 'binary');
res.end();
});
But I can't get the file name and the file type ( or extension ). Can anyone help me with that?
",https://stackoverflow.com/questions/7288814/download-a-file-from-nodejs-server-using-express,461,669019.0,7.0,,,2011-09-02 20:18:57,2023-02-28 10:27:08,2017-11-10 07:20:22,,,javascript;node.js;file;express;download,Thiago Miranda de Oliveira,5960,626978,registered,true,7288883,,CC BY-SA 3.0,2015-08-31 16:24:30,521,476,1,0,0,5,true,false,false,true,true,true,48,8,false,0.01,0.0007,5559,2011,9,20,Friday,false,false,true,false,false,false,false
6554039,How do I URl encode something in Node.js?,"I want to URL encode this:
SELECT name FROM user WHERE uid = me()
Do I have to download a module for this? I already have the request module.
",https://stackoverflow.com/questions/6554039/how-do-i-url-encode-something-in-node-js,460,469205.0,6.0,,,2011-07-01 23:09:55,2022-10-20 19:08:17,,,,javascript;url;node.js,TIMEX,275634,179736,registered,true,6554045,,CC BY-SA 3.0,2018-08-10 06:46:19,184,146,1,0,0,3,true,false,false,true,true,false,41,8,true,0.013,0.001,5622,2011,7,23,Friday,false,false,true,false,false,false,false
11949419,npm - how to show the latest version of a package,"How do I use npm to show the latest version of a module? I am expecting something like npm --latest express to print out v3.0.0.
",https://stackoverflow.com/questions/11949419/npm-how-to-show-the-latest-version-of-a-package,458,307697.0,10.0,,,2012-08-14 09:27:16,2023-12-06 19:15:19,2019-11-04 09:01:28,,,node.js;npm;versioning,Trantor Liu,9266,911164,registered,true,11949502,,CC BY-SA 4.0,,162,129,2,0,0,3,true,false,false,true,true,true,49,11,false,0.032,0.0015,5212,2012,8,9,Tuesday,false,false,false,false,false,false,false
16392260,Which websocket library to use with Node.js?,"Currently there is a plethora of websocket libraries for node.js, the most popular seem to be:
- https://github.com/Worlize/WebSocket-Node
- https://github.com/einaros/ws
- https://github.com/LearnBoost/engine.io
- https://github.com/learnboost/socket.io
- https://github.com/sockjs
However I can't find any solid concrete comparisons between any of them...
Apparently Socket.io was awesome, but has become quite dated and has failing builds. Both ws and websocket-node claim they are the fastest. And engine.io seems new, but a lot heavier than the lighter aletarntives.
It would be amazing if we or someone could put together an answer that serves as a guide on which socket library to use and when, as well as a comparison between them.
",https://stackoverflow.com/questions/16392260/which-websocket-library-to-use-with-node-js,458,252356.0,3.0,,,2013-05-06 05:06:28,2021-04-21 18:43:04,2015-04-18 22:20:38,2017-02-07 09:07:15,Not suitable for this site,node.js;websocket;socket.io;sockjs;engine.io,balupton,49209,130638,registered,true,16393046,,,2014-10-20 07:20:01,1107,735,0,6,0,5,true,true,false,true,true,true,44,7,true,0.012,0.0018,4947,2013,5,5,Monday,false,false,false,false,false,false,false
3653065,Get local IP address in Node.js,"I have a simple Node.js program running on my machine and I want to get the local IP address of a PC on which my program is running. How do I get it with Node.js?
",https://stackoverflow.com/questions/3653065/get-local-ip-address-in-node-js,457,639163.0,46.0,,,2010-09-06 16:51:13,2024-10-30 05:30:04,2020-12-21 18:30:31,,,javascript;node.js;ip,yojimbo87,68985,217288,registered,true,8440736,,CC BY-SA 4.0,,170,163,0,0,0,3,true,false,false,true,true,true,31,6,false,0.072,0.0007,5920,2010,9,16,Monday,false,false,true,false,false,false,false
9961502,Is there a way to automatically build the package.json file for Node.js projects,"Is package.json supposed to be manually edited? Couldn't a program like NPM just look through the files, see the require statements, and then use that to put the necessary entries in the package.json file? Are there any programs like that?
",https://stackoverflow.com/questions/9961502/is-there-a-way-to-automatically-build-the-package-json-file-for-node-js-projects,457,388178.0,13.0,,,2012-04-01 02:45:56,2024-09-09 19:07:08,2024-09-09 19:06:02,,,json;node.js;npm,neuromancer,56059,209512,registered,true,13728837,,CC BY-SA 4.0,,286,240,3,0,0,3,true,false,false,true,true,true,80,13,false,0.033,0.0012,5347,2012,4,2,Sunday,true,false,false,false,false,false,false
43431550,How can I invoke asynchronous code within a constructor?,"At the moment, I'm attempting to use async/await within a class constructor function. This is so that I can get a custom e-mail tag for an Electron project I'm working on.
customElements.define('e-mail', class extends HTMLElement {
async constructor() {
super()
let uid = this.getAttribute('data-uid')
let message = await grabUID(uid)
const shadowRoot = this.attachShadow({mode: 'open'})
shadowRoot.innerHTML = `
<div id="email">A random email message has appeared. ${message}</div>
`
}
})
At the moment however, the project does not work, with the following error:
Class constructor may not be an async method
Is there a way to circumvent this so that I can use async/await within this? Instead of requiring callbacks or .then()?
",https://stackoverflow.com/questions/43431550/how-can-i-invoke-asynchronous-code-within-a-constructor,456,458162.0,22.0,,,2017-04-15 21:41:26,2025-01-13 04:19:41,2024-04-25 09:41:12,,,javascript;node.js;async-await,Alexander Craggs,9027,3832377,registered,true,43433773,,CC BY-SA 4.0,2024-04-25 10:36:58,936,794,6,0,0,3,true,false,false,true,true,true,56,9,true,0.048,0.001,3507,2017,4,21,Saturday,true,false,true,false,false,false,false
16631064,Declare multiple module.exports in Node.js,"What I'm trying to achieve is to create one module that contains multiple functions in it.
module.js:
module.exports = function(firstParam) { console.log(""You did it""); },
module.exports = function(secondParam) { console.log(""Yes you did it""); },
// This may contain more functions
main.js:
var foo = require('module.js')(firstParam);
var bar = require('module.js')(secondParam);
The problem I have is that the firstParam is an object type and the secondParam is a URL string, but when I have that it always complains that the type is wrong.
How can I declare multiple module.exports in this case?
",https://stackoverflow.com/questions/16631064/declare-multiple-module-exports-in-node-js,455,544071.0,20.0,,,2013-05-19 03:07:46,2023-06-14 16:26:48,2015-04-01 16:25:32,,,node.js;module,Ali,10559,775119,registered,true,16631079,,CC BY-SA 3.0,,729,607,5,0,0,2,true,false,false,true,true,true,42,5,false,0.037,0.0008,4934,2013,5,3,Sunday,true,false,false,false,false,false,false
9874382,What's the difference between process.cwd() vs __dirname?,"What's the difference between
console.log(process.cwd())
and
console.log(__dirname);
I've seen both used in similar contexts.
",https://stackoverflow.com/questions/9874382/whats-the-difference-between-process-cwd-vs-dirname,454,216357.0,4.0,,,2012-03-26 14:48:29,2022-03-08 12:55:01,2013-06-27 09:00:46,,,node.js,helpermethod,63090,1178669,registered,true,9874415,,CC BY-SA 3.0,,201,132,2,0,0,1,true,false,false,true,true,true,61,7,true,0.018,0.0021,5353,2012,3,14,Monday,false,false,false,false,false,false,false
31579509,Can pm2 run an 'npm start' script,"Is there a way for pm2 to run an npm start script or do you just have to run pm2 start app.js
So in development
npm start
Then in production with pm2 you would run something like
pm2 start 'npm start'
There is an equivalent way to do this in forever:
forever start -c "npm start" ./
",https://stackoverflow.com/questions/31579509/can-pm2-run-an-npm-start-script,452,692616.0,24.0,,,2015-07-23 06:18:02,2025-07-24 07:45:14,2020-06-25 14:03:20,,,node.js;shell;npm;pm2,svnm,24666,3709775,registered,true,37775318,,CC BY-SA 4.0,,422,296,5,0,0,4,true,false,false,true,true,true,41,7,false,0.035,0.0007,4139,2015,7,6,Thursday,false,false,false,false,false,false,false
12495891,What is the "__v" field in Mongoose,"I'm using Mongoose version 3 with MongoDB version 2.2. I've noticed a __v field has started appearing in my MongoDB documents. Is it something to do with versioning? How is it used?
",https://stackoverflow.com/questions/12495891/what-is-the-v-field-in-mongoose,452,274344.0,10.0,,,2012-09-19 13:35:18,2024-09-03 15:38:52,2018-06-02 15:06:34,,,node.js;mongodb;mongoose,Simon Lomax,9042,179064,registered,true,12495922,,CC BY-SA 4.0,,241,182,4,0,0,3,true,false,false,true,true,true,45,7,false,0.036,0.0016,5176,2012,9,13,Wednesday,false,false,false,false,false,false,false
20089582,How to get a URL parameter in Express?,"I am facing an issue on getting the value of tagid from my URL: localhost:8888/p?tagid=1234.
Help me out to correct my controller code. I am not able to get the tagid value.
My code is as follows:
app.js:
var express = require('express'),
http = require('http'),
path = require('path');
var app = express();
var controller = require('./controller')({
app: app
});
// all environments
app.configure(function() {
app.set('port', process.env.PORT || 8888);
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
app.set('view engine', 'jade');
app.set('views', __dirname + '/views');
app.use(app.router);
app.get('/', function(req, res) {
res.render('index');
});
});
http.createServer(app).listen(app.get('port'), function() {
console.log('Express server listening on port ' + app.get('port'));
});
Controller/index.js:
function controller(params) {
var app = params.app;
//var query_string = request.query.query_string;
app.get('/p?tagId=/', function(request, response) {
// userId is a parameter in the url request
response.writeHead(200); // return 200 HTTP OK status
response.end('You are looking for tagId' + request.route.query.tagId);
});
}
module.exports = controller;
routes/index.js:
require('./controllers');
/*
* GET home page.
*/
exports.index = function(req, res) {
res.render('index', {
title: 'Express'
});
};
",https://stackoverflow.com/questions/20089582/how-to-get-a-url-parameter-in-express,450,704723.0,4.0,,,2013-11-20 07:09:12,2025-04-09 18:41:40,2018-04-24 14:06:29,,,javascript;node.js;express;url-parameters;query-string,user2834795,4543,2834795,registered,true,20089634,,CC BY-SA 3.0,,1709,1517,9,0,0,5,true,false,false,true,true,true,38,8,true,0.006,0.0006,4749,2013,11,7,Wednesday,false,false,true,false,false,false,false
10888610,Ignore invalid self-signed ssl certificate in node.js with https.request?,"I'm working on a little app that logs into my local wireless router (Linksys) but I'm running into a problem with the router's self-signed ssl certificate.
I ran wget 192.168.1.1 and get:
ERROR: cannot verify 192.168.1.1's certificate, issued by `/C=US/ST=California/L=Irvine/O=Cisco-Linksys, LLC/OU=Division/CN=Linksys/emailAddress=support@linksys.com':
Self-signed certificate encountered.
ERROR: certificate common name `Linksys' doesn't match requested host name `192.168.1.1'.
To connect to 192.168.1.1 insecurely, use `--no-check-certificate'.
In node, the error being caught is:
{ [Error: socket hang up] code: 'ECONNRESET' }
My current sample code is:
var req = https.request({
host: '192.168.1.1',
port: 443,
path: '/',
method: 'GET'
}, function(res){
var body = [];
res.on('data', function(data){
body.push(data);
});
res.on('end', function(){
console.log( body.join('') );
});
});
req.end();
req.on('error', function(err){
console.log(err);
});
How can I go about getting node.js to do the equivalent of ""--no-check-certificate""?
",https://stackoverflow.com/questions/10888610/ignore-invalid-self-signed-ssl-certificate-in-node-js-with-https-request,448,743340.0,14.0,,,2012-06-04 21:26:40,2024-05-11 07:20:02,,,,node.js;https;ssl-certificate,Geuis,42591,68788,registered,true,21961005,,CC BY-SA 3.0,,1221,1114,3,0,0,3,true,false,false,true,true,false,73,9,true,0.019,0.0006,5283,2012,6,21,Monday,false,false,false,false,false,false,false
23097928,Node.js throws "btoa is not defined" error,"In my node.js application I did an npm install btoa-atob so that I could use the btoa() and atob() functions which are native in client-side javascript but for some reason weren't included in node. The new directory showed up in my node_modules folder, which itself is in root alongside app.js. Then I made sure to add btoa-atob as a dependency in my package.json file which is in root.
However, for some reason, it still will not work.
console.log(btoa("Hello World!"));
^ should output "SGVsbG8gV29ybGQh" to the console, but instead, I get the error:
btoa is not defined.
Did I not do the install properly? What did I overlook?
",https://stackoverflow.com/questions/23097928/node-js-throws-btoa-is-not-defined-error,447,374004.0,12.0,,,2014-04-16 02:27:12,2024-07-08 15:40:30,2020-08-07 10:00:49,,,node.js,Joey,11065,1202123,registered,true,23097961,,CC BY-SA 4.0,,832,653,7,0,0,1,true,false,false,true,true,true,52,7,false,0.032,0.0012,4602,2014,4,2,Wednesday,false,false,false,false,false,false,false
5050265,"JavaScript, Node.js: is Array.forEach asynchronous?","I have a question regarding the native Array.forEach implementation of JavaScript: Does it behave asynchronously?
For example, if I call:
[many many elements].forEach(function () {lots of work to do})
Will this be non-blocking?
",https://stackoverflow.com/questions/5050265/javascript-node-js-is-array-foreach-asynchronous,446,376208.0,12.0,,,2011-02-19 10:36:48,2021-07-12 06:39:50,2014-12-29 10:36:53,,,javascript;arrays;asynchronous;foreach;node.js,R. Gr.,4501,624291,unregistered,true,5050317,,CC BY-SA 3.0,,282,231,2,0,0,5,true,false,false,true,true,true,51,5,true,0.032,0.0012,5754,2011,2,10,Saturday,true,false,true,false,false,false,false
9626990,receiving error: 'Error: SSL Error: SELF_SIGNED_CERT_IN_CHAIN' while using npm,"I am using npm v1.0.104/node 0.6.12 on ubuntu - I am receiving the error copied below while attempting to install any new modules via npm (I tested socket.io earlier using http, not https though & am wondering if that could have resulted in the issue with npm/unsigned certs). The error pops up once npm tries to resolve the 'https://registry.npmjs.org' URL. Is there anyway I can ignore the error or perhaps locate/add the cert to a trusted store in order to continue using npm.
Any insight on what needs to be done to resolve the issue will be appreciated (I would prefer to resolve the issue through configuration as opposed to re-installing if possible).
Error: ""Error: SSL Error: SELF_SIGNED_CERT_IN_CHAIN""
Full Message:
npm ERR! Error: SSL Error: SELF_SIGNED_CERT_IN_CHAIN
npm ERR! at ClientRequest.<anonymous> (/usr/lib/node_modules/npm/node_modules/request/main.js:252:28)
npm ERR! at ClientRequest.emit (events.js:67:17)
npm ERR! at HTTPParser.onIncoming (http.js:1261:11)
npm ERR! at HTTPParser.onHeadersComplete (http.js:102:31)
npm ERR! at CleartextStream.ondata (http.js:1150:24)
npm ERR! at CleartextStream._push (tls.js:375:27)
npm ERR! at SecurePair.cycle (tls.js:734:20)
npm ERR! at EncryptedStream.write (tls.js:130:13)
npm ERR! at Socket.ondata (stream.js:38:26)
npm ERR! at Socket.emit (events.js:67:17)
npm ERR! Report this *entire* log at:
npm ERR! <http://github.com/isaacs/npm/issues>
npm ERR! or email it to:
npm ERR! <npm-@googlegroups.com>
npm ERR!
npm ERR! System Linux 2.6.38-13-generic
npm ERR! command ""node"" ""/usr/bin/npm"" ""install"" ""jed""
npm ERR! node -v v0.6.12
npm ERR! npm -v 1.0.104
",https://stackoverflow.com/questions/9626990/receiving-error-error-ssl-error-self-signed-cert-in-chain-while-using-npm,443,772108.0,22.0,,,2012-03-09 00:01:23,2026-07-23 14:09:09,2017-12-15 11:24:09,,,node.js;ssl-certificate;npm,ali haider,20619,941357,registered,true,9631045,,CC BY-SA 3.0,2014-03-03 00:58:19,1838,1703,1,1,0,3,true,false,false,true,true,true,86,9,false,0.028,0.0006,5370,2012,3,0,Friday,false,false,false,false,false,false,false
46745014,Alternative for __dirname in Node.js when using ES6 modules,"I use the flag --experimental-modules when running my Node application in order to use ES6 modules.
However when I use this flag the metavariable __dirname is not available. Is there an alternative way to get the same string that is stored in __dirname that is compatible with this mode?
",https://stackoverflow.com/questions/46745014/alternative-for-dirname-in-node-js-when-using-es6-modules,443,262981.0,26.0,,,2017-10-14 13:17:55,2024-07-18 08:14:00,2021-12-24 12:04:38,,,node.js;ecmascript-6;es6-modules,Amygdaloideum,5293,6769954,registered,true,50052194,,CC BY-SA 4.0,,341,288,3,0,0,3,true,false,false,true,true,true,59,9,false,0.099,0.0017,3325,2017,10,13,Saturday,true,false,false,false,false,false,false
41415945,How to list all versions of an npm module?,"In order to see all the versions of a node module [webpack], I have executed below command in windows command prompt
npm view webpack versions
This command only displays first 100 versions and later displays ""331 more"" text.
How will I be able to list all versions?
",https://stackoverflow.com/questions/41415945/how-to-list-all-versions-of-an-npm-module,443,417598.0,5.0,,,2017-01-01 13:48:26,2023-03-16 17:40:35,2017-12-04 16:44:09,,,node.js;npm,refactor,15384,2693545,registered,true,41416032,,CC BY-SA 3.0,,315,270,1,0,0,2,true,false,false,true,true,true,42,9,true,0.012,0.0011,3611,2017,1,13,Sunday,true,false,false,false,false,false,false
31976722,Start script missing error when running npm start,"I'm receiving this error when trying to debug my node application using the npm start command.
Error:
npm ERR! Windows_NT 6.3.9600
npm ERR! argv "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "start"
npm ERR! node v0.12.7
npm ERR! npm v2.11.3
npm ERR! missing script: start
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR! <https://github.com/npm/npm/issues>npm ERR! Please include the following file with any support request:
npm ERR! C:\Users\andrmoll.NORTHAMERICA\Documents\GitHub\SVIChallenge\npm-debug.log
From the debug file:
Error: missing script: start
at run (C:\Program Files\nodejs\node_modules\npm\lib\run-script.js:142:19)
at C:\Program Files\nodejs\node_modules\npm\lib\run-script.js:58:5
at C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:345:5
at checkBinReferences_ (C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:309:45)
at final (C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:343:3)
at then (C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:113:5)
at C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:300:12
at evalmachine.<anonymous>:334:14
at C:\Program Files\nodejs\node_modules\npm\node_modules\graceful-fs\graceful-fs.js:102:5
at FSReqWrap.oncomplete (evalmachine.<anonymous>:95:15)
",https://stackoverflow.com/questions/31976722/start-script-missing-error-when-running-npm-start,442,1632707.0,34.0,,,2015-08-12 22:51:54,2025-05-31 01:51:33,2025-05-31 01:51:33,,,javascript;node.js;express;package.json;npm-scripts,Andrew Moll,5053,4951010,registered,true,31976870,,CC BY-SA 4.0,2019-02-21 03:46:01,1769,1605,3,0,0,5,true,false,false,true,true,true,49,8,false,0.021,0.0003,4119,2015,8,22,Wednesday,false,false,true,false,false,false,false
9198310,How to set NODE_ENV to production/development in OS X,"For use in express.js environments. Any suggestions?
",https://stackoverflow.com/questions/9198310/how-to-set-node-env-to-production-development-in-os-x,441,806754.0,17.0,,,2012-02-08 17:23:18,2022-12-01 21:21:39,2018-03-15 17:25:46,,,javascript;node.js;macos;environment-variables,Mark Nguyen,7498,999032,registered,true,9204973,,CC BY-SA 3.0,2023-04-06 18:43:36,60,53,0,0,0,4,true,false,false,true,true,true,53,9,false,0.021,0.0005,5400,2012,2,17,Wednesday,false,false,true,false,false,false,false
10005939,How do I consume the JSON POST data in an Express application,"I'm sending the following JSON string to my server.
(
{
id = 1;
name = foo;
},
{
id = 2;
name = bar;
}
)
On the server I have this.
app.post('/', function(request, response) {
console.log(""Got response: "" + response.statusCode);
response.on('data', function(chunk) {
queryResponse+=chunk;
console.log('data');
});
response.on('end', function(){
console.log('end');
});
});
When I send the string, it shows that I got a 200 response, but those other two methods never run. Why is that?
",https://stackoverflow.com/questions/10005939/how-do-i-consume-the-json-post-data-in-an-express-application,440,717057.0,9.0,,,2012-04-04 06:27:34,2025-07-09 07:52:14,2017-01-22 16:54:45,,,json;node.js;express,neuromancer,56059,209512,registered,true,10007542,,CC BY-SA 3.0,,663,594,2,0,0,3,true,false,false,true,true,true,61,12,false,0.013,0.0006,5344,2012,4,6,Wednesday,false,false,false,false,false,false,false
32811510,Mongoose: findOneAndUpdate doesn't return updated document,"Below is my code
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var Cat = mongoose.model('Cat', {
name: String,
age: {type: Number, default: 20},
create: {type: Date, default: Date.now}
});
Cat.findOneAndUpdate({age: 17}, {$set:{name:""Naomi""}},function(err, doc){
if(err){
console.log(""Something wrong when updating data!"");
}
console.log(doc);
});
I already have some record in my mongo database and I would like to run this code to update name for which age is 17 and then print result out in the end of code.
However, why I still get same result from console(not the modified name) but when I go to mongo db command line and type ""db.cats.find();"". The result came with modified name.
Then I go back to run this code again and the result is modified.
My question is: If the data was modified, then why I still got original data at first time when console.log it.
",https://stackoverflow.com/questions/32811510/mongoose-findoneandupdate-doesnt-return-updated-document,439,479487.0,17.0,,,2015-09-27 18:41:34,2024-07-10 04:15:54,2018-10-30 17:07:28,,,node.js;mongodb;mongoose,Dreams,8546,2567859,registered,true,32811548,,CC BY-SA 4.0,,1016,944,2,0,0,3,true,false,false,true,true,true,62,6,false,0.035,0.0009,4073,2015,9,18,Sunday,true,false,false,false,false,false,false
8683895,How do I determine the current operating system with Node.js,"I'm writing a couple of node shell scripts for use when developing on a platform. We have both Mac and Windows developers. Is there a variable I can check for in Node to run a .sh file in one instance and .bat in another?
",https://stackoverflow.com/questions/8683895/how-do-i-determine-the-current-operating-system-with-node-js,439,303609.0,10.0,,,2011-12-30 20:42:31,2024-09-23 15:33:55,2015-03-07 00:29:55,,,node.js,Mauvis Ledford,42744,704703,registered,true,8684009,,CC BY-SA 3.0,,229,222,0,0,0,1,true,false,false,true,true,true,60,10,false,0.033,0.0014,5440,2011,12,20,Friday,false,false,false,false,false,false,false
24543847,req.body empty on posts,"All of a sudden this has been happening to all my projects.
Whenever I make a post in nodejs using express and body-parser req.body is an empty object.
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded())
// parse application/json
app.use(bodyParser.json())
app.listen(2000);
app.post(""/"", function (req, res) {
console.log(req.body) // populated!
res.send(200, req.body);
});
Via ajax and postman it's always empty.
However via curl
$ curl -H ""Content-Type: application/json"" -d '{""username"":""xyz"",""password"":""xyz""}' http://localhost:2000/
it works as intended.
I tried manually setting Content-type : application/json in the former but I then always get 400 bad request
This has been driving me crazy.
I thought it was that something updated in body-parser but I downgraded and it didn't help.
Any help appreciated, thanks.
",https://stackoverflow.com/questions/24543847/req-body-empty-on-posts,438,539257.0,32.0,,,2014-07-03 02:03:56,2024-08-28 17:45:00,2023-01-15 03:29:41,,,node.js;express;postman,Joseph Dailey,4933,1787322,registered,true,24557561,,CC BY-SA 4.0,2021-10-21 10:54:25,1117,967,5,0,0,3,true,false,false,true,true,true,23,4,false,0.059,0.0008,4524,2014,7,2,Thursday,false,false,false,false,false,false,false
18112204,Get all directories within directory nodejs,"I was hoping this would be a simple thing, but I cannot find anything out there to do so.
I just want to get all folders/directories within a given folder/directory.
So for example:
<MyFolder>
|- SomeFolder
|- SomeOtherFolder
|- SomeFile.txt
|- SomeOtherFile.txt
|- x-directory
I would expect to get an array of:
[""SomeFolder"", ""SomeOtherFolder"", ""x-directory""]
Or the above with the path if that was how it was served...
So does anything already exist to do the above?
",https://stackoverflow.com/questions/18112204/get-all-directories-within-directory-nodejs,435,333520.0,21.0,,,2013-08-07 19:32:49,2024-04-20 09:33:20,,,,node.js;directory,Grofit,18663,476660,registered,true,24594123,,CC BY-SA 3.0,2024-06-03 02:03:54,575,485,2,0,0,2,true,false,false,true,true,false,43,6,false,0.063,0.0013,4854,2013,8,19,Wednesday,false,false,false,false,false,false,false
39322089,Node.js Port 3000 already in use but it actually isn't?,"I have been working with a node.js project for a few weeks and it has been working great. Usually, I use npm start to run my app and view it in a browser on localhost, port 3000.
Today, I started to get the following error while using npm start:
Server started on port 3000
Port 3000 is already in use
I have checked the resource monitor and I have no other process running on port 3000. Why would I be getting this error message?
In my app.js I have the following code to set the port...is this incorrect? It worked fine before so I'm not sure what I am doing wrong.
// Set Port
app.set('port', (process.env.PORT || 3000));
app.listen(app.get('port'), function() {
console.log('Server started on port '+app.get('port'));
});
Thanks for the help!
EDIT:
I have tried running netstat and TCPView to check what process is using the port, but there is nothing using that port. I also tried restarting my laptop but I still get the same error.
",https://stackoverflow.com/questions/39322089/node-js-port-3000-already-in-use-but-it-actually-isnt,434,982051.0,47.0,,,2016-09-04 22:38:24,2024-07-19 17:56:27,2020-04-25 13:15:01,,,javascript;node.js;npm;port,user2573690,6151,2573690,registered,true,,,CC BY-SA 4.0,2020-04-16 09:20:18,1298,1143,3,0,0,4,false,false,false,true,true,true,59,10,true,0.048,0.0004,3730,2016,9,22,Sunday,true,false,true,false,false,false,false
11928013,""NODE_ENV" is not recognized as an internal or external command, operable command or batch file","I'm trying to setup an environment for a Node.js app. but I'm getting this error every time.
""NODE_ENV"" is not recognized as an internal or external command,
operable command or batch file.
What does this mean and how can I solve this problem?
I'm using Windows and also tried set NODE_ENV=development but had no luck.
",https://stackoverflow.com/questions/11928013/node-env-is-not-recognized-as-an-internal-or-external-command-operable-comman,431,418171.0,29.0,,,2012-08-13 03:55:25,2025-09-05 12:36:26,2019-05-14 08:58:09,,,windows;node.js,krozero,6515,1534398,registered,true,11928210,,CC BY-SA 4.0,2022-09-04 00:42:13,395,329,1,0,0,2,true,false,false,true,true,true,105,15,false,0.069,0.001,5213,2012,8,3,Monday,false,false,false,false,false,false,false
10849687,How to get remote client address in Express.js,"I don't completely understand how I should get a remote user IP address.
Let's say I have a simple request route such as:
app.get(/, function (req, res){
var forwardedIpsStr = req.header('x-forwarded-for');
var IP = '';
if (forwardedIpsStr) {
IP = forwardedIps = forwardedIpsStr.split(',')[0];
}
});
Is the above approach correct to get the real user IP address or is there a better way?
And what about proxies?
",https://stackoverflow.com/questions/10849687/how-to-get-remote-client-address-in-express-js,431,548860.0,17.0,,,2012-06-01 11:49:01,2025-10-24 06:31:26,2025-10-23 09:54:12,,,node.js;express;ip;ip-address,Erik,14898,1006884,registered,true,10849772,,CC BY-SA 4.0,,482,437,1,0,0,4,true,false,false,true,true,true,46,8,false,0.031,0.0008,5286,2012,6,11,Friday,false,false,false,false,false,false,false
20764881,Why does npm install say I have unmet dependencies?,"I have a node package. When I run npm install from the package root, it installs a bunch of things, but then prints several error messages that look like this:
npm WARN unmet dependency /Users/seanmackesey/google_drive/code/explore/generator/node_modules/findup-sync/node_modules/glob requires graceful-fs@'~1.2.0' but will load
I must be confused about what exactly npm install does. If it detects a dependency, shouldn't it install it? Under what conditions does it give me error messages like this, and how can I resolve the dependencies?
",https://stackoverflow.com/questions/20764881/why-does-npm-install-say-i-have-unmet-dependencies,431,328780.0,17.0,,,2013-12-24 17:49:30,2019-10-03 09:43:07,2015-08-19 16:24:27,,,node.js;dependencies;npm,Sean Mackesey,11059,1244455,registered,true,20765400,,CC BY-SA 3.0,2022-11-14 22:40:07,620,548,2,0,0,3,true,false,false,true,true,true,51,9,true,0.052,0.0013,4715,2013,12,17,Tuesday,false,false,false,false,false,false,false
32106155,Can you force Vue.js to reload/re-render?,"Just a quick question.
Can you force Vue.js to reload/recalculate everything? If so, how?
",https://stackoverflow.com/questions/32106155/can-you-force-vue-js-to-reload-re-render,426,770297.0,26.0,,,2015-08-19 21:43:52,2026-03-26 13:03:22,2022-04-27 00:05:06,,,javascript;node.js;vue.js;reload;rerender,Dave,12507,150094,registered,true,40586872,,CC BY-SA 4.0,,153,92,1,0,0,5,true,false,false,true,true,true,41,6,true,0.034,0.0006,4112,2015,8,21,Wednesday,false,false,true,false,false,false,false
5998694,How to create an HTTPS server in Node.js?,"Given an SSL key and certificate, how does one create an HTTPS service?
",https://stackoverflow.com/questions/5998694/how-to-create-an-https-server-in-node-js,426,595122.0,9.0,,,2011-05-13 23:19:08,2026-01-16 15:35:28,2018-05-01 10:57:04,,,javascript;node.js;ssl;https;webserver,murvinlai,50655,196874,registered,true,5998795,,CC BY-SA 3.0,2020-09-03 21:18:06,79,72,0,0,0,5,true,false,false,true,true,true,41,8,true,0.015,0.0007,5671,2011,5,23,Friday,false,false,true,false,false,false,false
13147693,How to extract request http headers from a request using NodeJS connect,"I'd like to get the ""Host"" header of a request made using Node JS's connect library bundle. My code looks like:
var app = connect()
.use(connect.logger('dev'))
.use(connect.static('public'))
.use(function(req, res){
var host = req.???
})
.listen(3000);
The documentation for connect is here but I don't see anything detailing the API of the req object in the above code. http://www.senchalabs.org/connect/
Edit: Note a successful answer must point to the documentation (I need this to verify which version provided the API I'm looking for).
",https://stackoverflow.com/questions/13147693/how-to-extract-request-http-headers-from-a-request-using-nodejs-connect,425,744412.0,7.0,,,2012-10-30 21:15:13,2025-01-30 10:49:55,2012-10-30 21:30:46,,,node.js,Alex Spurling,56152,12149,registered,true,,,CC BY-SA 3.0,2018-08-16 16:32:43,702,561,2,1,0,1,false,false,false,true,true,true,71,12,false,0.009,0.0006,5135,2012,10,21,Tuesday,false,false,false,false,false,false,false
60248452,Is there a compatibility list for Angular / Angular-CLI and Node.js?,"I periodically run into the problem, having to spin up old Angular projects with deprecated dependencies of Angular.
Because I unsually run the latest Node.js version (at least lates LTS version) I often had the problem, that I wasn't able to get the old projects running.
I solved this by using a node version manager, but still I often have the problem that I'm not sure what is the best Node.js version to use for Angular Version X.
Sadly the official release notes handle this topic shabbily and are not a true help, especially if you like to know as of which Angular Version you can't use a specific Node.js version anymore...
Is there a complete compatibility list to check which Angular version is compatible with which Node.js version?
",https://stackoverflow.com/questions/60248452/is-there-a-compatibility-list-for-angular-angular-cli-and-node-js,421,669821.0,5.0,,,2020-02-16 12:28:52,2025-08-09 13:56:46,2020-05-07 06:52:19,,,node.js;angular;angular-cli,jowey,8441,6191996,registered,true,60258560,,CC BY-SA 4.0,2025-01-24 17:43:37,870,747,0,1,0,3,true,false,false,true,true,true,68,11,true,0.007,0.0006,2470,2020,2,12,Sunday,true,false,false,false,false,false,false
17690803,Node.js getaddrinfo ENOTFOUND,"When using Node.js to try and get the html content of the following web page:
eternagame.wikia.com/wiki/EteRNA_Dictionary
I get the following error:
events.js:72
throw er; // Unhandled 'error' event
^
Error: getaddrinfo ENOTFOUND
at errnoException (dns.js:37:11)
at Object.onanswer [as oncomplete] (dns.js:124:16)
I did already look up this error on stackoverflow, and realized that this is because node.js cannot find the server from DNS (I think). However, I am not sure why this would be, as my code works perfectly on www.google.com.
Here is my code (practically copied and pasted from a very similar question, except with the host changed):
var http = require(""http"");
var options = {
host: 'eternagame.wikia.com/wiki/EteRNA_Dictionary'
};
http.get(options, function (http_res) {
// initialize the container for our data
var data = """";
// this event fires many times, each time collecting another piece of the response
http_res.on(""data"", function (chunk) {
// append this chunk to our growing `data` var
data += chunk;
});
// this event fires *one* time, after all the `data` events/chunks have been gathered
http_res.on(""end"", function () {
// you can use res.send instead of console.log to output via express
console.log(data);
});
});
Here is the source where I copied and pasted from : How to make web service calls in Expressjs?
I am not using any modules with node.js.
Thanks for reading.
",https://stackoverflow.com/questions/17690803/node-js-getaddrinfo-enotfound,421,1267872.0,21.0,,,2013-07-17 03:54:18,2024-06-02 19:57:49,2019-08-28 15:23:00,,,node.js,Vineet Kosaraju,5870,1700618,registered,true,17691556,,CC BY-SA 4.0,2018-08-14 19:36:06,1737,1506,4,1,0,1,true,false,false,true,true,true,29,3,false,0.017,0.0003,4875,2013,7,3,Wednesday,false,false,false,false,false,false,false
9768444,possible EventEmitter memory leak detected,"I am getting following warning:
(node) warning: possible EventEmitter memory leak detected. 11 listeners added. Use emitter.setMaxListeners() to increase limit.
Trace:
at EventEmitter.<anonymous> (events.js:139:15)
at EventEmitter.<anonymous> (node.js:385:29)
at Server.<anonymous> (server.js:20:17)
at Server.emit (events.js:70:17)
at HTTPParser.onIncoming (http.js:1514:12)
at HTTPParser.onHeadersComplete (http.js:102:31)
at Socket.ondata (http.js:1410:22)
at TCP.onread (net.js:354:27)
I wrote code like this in server.js:
http.createServer(
function (req, res) { ... }).listen(3013);
How to fix this ?
",https://stackoverflow.com/questions/9768444/possible-eventemitter-memory-leak-detected,418,751051.0,25.0,,,2012-03-19 10:20:59,2023-12-13 09:41:10,2016-12-11 04:06:05,,,node.js;memory-leaks;eventemitter,Riz,10334,486348,registered,true,9768586,,CC BY-SA 3.0,2017-09-11 16:33:26,777,669,2,0,0,3,true,false,false,true,true,true,42,5,false,0.033,0.0006,5360,2012,3,10,Monday,false,false,false,false,false,false,false
20992723,"'npm' is not recognized as internal or external command, operable program or batch file","I am completely new to nodejs. I am trying to get nodejs to work on my Windows 2008 box in order to install Karma which I would use for TDDing my AngularJs code. I have done the following steps so far
- Install using Chocolatey ==> npm is not recognised
- Install using 64-bit nodejs installer from nodejs.org ==> npm is not recognised
- At this stage, running
where npm gives me c:\User\<Username>\AppData\Roaming\npm which has nothing in it
- I figure out that nodejs is installed in
C:\Program Files\nodejs. Opening a command prompt in this directory makes npm work fine.
- So I added
C:\Program Files\nodejs to PATH only to get the same error again that npm is not recognized
- One of the github issues on nodejs repository says that I need to restart the machine and it would fix. But that has not helped so far
- I do see a
Node.js icon in my Start -> Programms mennu which takes me to nodejs console but not sure what to do with that.
Have I missed any important step in the process?
Edit
I figured out that if I open ""Nodejs command prompt"" from program files, then npm is recognized. How do I make it work on a normal command prompt?
Edit
After node I started facing a similar problem with another application. I posted this question on superuser and as rightly pointed out by the accepted answer, I had an additional quote in my PATH which was causing issues with all the paths added after the quote. I have a feeling that some Chocolatey install adds this troubling quote but I am just not sure which one.
",https://stackoverflow.com/questions/20992723/npm-is-not-recognized-as-internal-or-external-command-operable-program-or-bat,417,2469713.0,44.0,,,2014-01-08 10:18:44,2024-06-25 08:27:36,2018-03-07 13:10:13,,,windows;node.js,Suhas,8518,209834,registered,true,21923238,,CC BY-SA 3.0,2017-11-22 07:43:40,1913,1522,11,1,0,2,true,false,false,true,true,true,95,14,false,0.018,0.0002,4700,2014,1,10,Wednesday,false,false,false,false,false,false,false
22475849,Node.js: what is ENOSPC error and how to solve?,"I have a problem with Node.js and uploading files to server. For uploading files to server I use this plugin. When starting file upload to the server, Node.js process crashed and show error:
Error: ENOSPC.
The server code doesn't run.
$ df -h
Filesystem Size Used Avail Use% Mounted on
/dev/xvda1 7.9G 4.1G 3.5G 55% /
udev 288M 8.0K 288M 1% /dev
tmpfs 119M 168K 118M 1% /run
none 5.0M 0 5.0M 0% /run/lock
none 296M 0 296M 0% /run/shm
/dev/xvdf 9.9G 3.0G 6.5G 32% /vol
overflow 1.0M 1.0M 0 100% /tmp
",https://stackoverflow.com/questions/22475849/node-js-what-is-enospc-error-and-how-to-solve,413,373300.0,20.0,,,2014-03-18 09:59:44,2025-03-14 14:12:28,2018-10-10 14:48:28,,,node.js,Giffo,4261,1901571,registered,true,32600959,,CC BY-SA 4.0,2018-10-20 11:29:38,762,607,1,1,0,1,true,false,false,true,true,true,47,9,true,0.054,0.0011,4631,2014,3,9,Tuesday,false,false,false,false,false,false,false
22824546,How to run Gulp tasks sequentially one after the other,"in the snippet like this:
gulp.task ""coffee"", ->
gulp.src(""src/server/**/*.coffee"")
.pipe(coffee {bare: true}).on(""error"",gutil.log)
.pipe(gulp.dest ""bin"")
gulp.task ""clean"",->
gulp.src(""bin"", {read:false})
.pipe clean
force:true
gulp.task 'develop',['clean','coffee'], ->
console.log ""run something else""
In develop task I want to run clean and after it's done, run coffee and when that's done, run something else. But I can't figure that out. This piece doesn't work. Please advise.
",https://stackoverflow.com/questions/22824546/how-to-run-gulp-tasks-sequentially-one-after-the-other,411,258205.0,15.0,,,2014-04-02 22:45:35,2021-04-03 12:29:55,2016-08-22 20:24:39,,,javascript;node.js;coffeescript;gulp,iLemming,36934,116395,registered,true,31329150,,CC BY-SA 3.0,,626,549,4,0,0,4,true,false,false,true,true,true,54,10,false,0.058,0.0016,4616,2014,4,22,Wednesday,false,false,true,false,false,false,false
6398196,Detect if called through require or directly by command line,"How can I detect whether my Node.JS file was called using SH:node path-to-file or JS:require('path-to-file')?
This is the Node.JS equivalent to my previous question in Perl: How can I run my Perl script only if it wasn't loaded with require?
",https://stackoverflow.com/questions/6398196/detect-if-called-through-require-or-directly-by-command-line,409,71959.0,9.0,,,2011-06-18 18:56:07,2026-01-11 16:45:49,2019-10-22 23:09:21,,,node.js;require,700 Software,88369,463304,registered,true,6398335,,CC BY-SA 4.0,,411,247,2,1,0,2,true,false,false,true,true,true,60,10,false,0.125,0.0057,5635,2011,6,18,Saturday,true,false,false,false,false,false,false
5827612,Node.js fs.readdir recursive directory search,"Any ideas on an async directory search using fs.readdir? I realize that we could introduce recursion and call the read directory function with the next directory to read, but I'm a little worried about it not being async...
Any ideas? I've looked at node-walk which is great, but doesn't give me just the files in an array, like readdir does. Although
Looking for output like...
['file1.txt', 'file2.txt', 'dir/file3.txt']
",https://stackoverflow.com/questions/5827612/node-js-fs-readdir-recursive-directory-search,408,458359.0,50.0,,,2011-04-29 03:44:22,2025-01-22 07:32:44,2020-12-22 20:18:21,,,node.js;readdir,crawf,9698,731814,registered,true,5827895,,CC BY-SA 4.0,2017-07-21 17:09:55,538,424,1,1,0,2,true,false,false,true,true,true,45,5,false,0.109,0.0009,5685,2011,4,3,Friday,false,false,false,false,false,false,false
17699599,Node.js check if file exists,"How do I check for the existence of a file?
",https://stackoverflow.com/questions/17699599/node-js-check-if-file-exists,408,558392.0,28.0,,,2013-07-17 12:18:59,2026-01-19 19:45:23,2022-06-19 22:34:03,,,node.js;fs,RomanGor,4553,2332416,registered,true,17699926,,CC BY-SA 4.0,2018-08-03 07:31:49,51,44,0,0,0,2,true,false,false,true,true,true,28,5,false,0.05,0.0007,4875,2013,7,12,Wednesday,false,false,false,false,false,false,false
11459475,Should I check in folder "node_modules" to Git when creating a Node.js app on Heroku?,"I followed the basic getting started instructions for Node.js on Heroku here:
https://devcenter.heroku.com/categories/nodejs
These instructions don't tell you to create a .gitignore node_modules, and therefore imply that folder node_modules should be checked into Git. When I included node_modules in the Git repository, my getting started application ran correctly.
When I followed the more advanced example at:
- Building a Real-time, Polyglot Application with Node.js, Ruby, MongoDB and Socket.IO
- https://github.com/mongolab/tractorpush-server (source)
It instructed me to add folder node_modules to file .gitignore. So I removed folder node_modules from Git, added it to file .gitignore, and then redeployed. This time the deployment failed like so:
-----> Heroku receiving push
-----> Node.js app detected
-----> Resolving engine versions
Using Node.js version: 0.8.2
Using npm version: 1.0.106
-----> Fetching Node.js binaries
-----> Vendoring node into slug
-----> Installing dependencies with npm
Error: npm doesn't work with node v0.8.2
Required: node@0.4 || 0.5 || 0.6
at /tmp/node-npm-5iGk/bin/npm-cli.js:57:23
at Object.<anonymous> (/tmp/node-npm-5iGk/bin/npm-cli.js:77:3)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:362:17)
at require (module.js:378:17)
at Object.<anonymous> (/tmp/node-npm-5iGk/cli.js:2:1)
at Module._compile (module.js:449:26)
Error: npm doesn't work with node v0.8.2
Required: node@0.4 || 0.5 || 0.6
at /tmp/node-npm-5iGk/bin/npm-cli.js:57:23
at Object.<anonymous> (/tmp/node-npm-5iGk/bin/npm-cli.js:77:3)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:362:17)
at require (module.js:378:17)
at Object.<anonymous> (/tmp/node-npm-5iGk/cli.js:2:1)
at Module._compile (module.js:449:26)
Dependencies installed
-----> Discovering process types
Procfile declares types -> mongod, redis, web
-----> Compiled slug size is 5.0MB
-----> Launching... done, v9
Running "heroku ps" confirms the crash. OK, no problem, so I rolled back the change, added folder node_module back to the Git repository and removed it from file .gitignore. However, even after reverting, I still get the same error message on deployment, but now the application is running correctly again. Running "heroku ps" tells me the application is running.
What's the right way to do this? Include folder node_modules or not? And why would I still be getting the error message when I roll back? My guess is the Git repository is in a bad state on the Heroku side.
",https://stackoverflow.com/questions/11459475/should-i-check-in-folder-node-modules-to-git-when-creating-a-node-js-app-on-he,406,203224.0,12.0,,,2012-07-12 19:45:23,2024-03-31 13:09:58,2024-03-31 13:09:58,,,git;node.js;heroku;npm;gitignore,Jason Griffin,4113,1072179,registered,true,19416403,,CC BY-SA 4.0,,3622,3110,1,3,0,5,true,false,false,true,true,true,95,15,true,0.059,0.002,5245,2012,7,19,Thursday,false,false,false,false,false,false,false
9164915,Node.js EACCES error when listening on most ports,"I'm testing out an app (hopefully to run on heroku, but am having issues locally as well). It's giving me an EACCES error when it runs http.Server.listen() - but it only occurs on some ports.
So, locally I'm running:
joe@joebuntu:~$ node
> var h = require('http').createServer();
> h.listen(900);
Error: EACCES, Permission denied
at Server._doListen (net.js:1062:5)
at net.js:1033:14
at Object.lookup (dns.js:132:45)
at Server.listen (net.js:1027:20)
at [object Context]:1:3
at Interface.<anonymous> (repl.js:150:22)
at Interface.emit (events.js:42:17)
at Interface._onLine (readline.js:132:10)
at Interface._line (readline.js:387:8)
at Interface._ttyWrite (readline.js:564:14)
I don't have anything running on port 900 (or any of the other 20 ports I've tried), so this should work. The weird part is that it does work on some ports. For instance, port 3000 works perfectly.
What would cause this?
Update 1:
I figured out that on my local computer, the EACCES error is coming because I have to run node as root in order to bind to those certain ports. I don't know why this happens, but using sudo fixes it. However, this doesn't explain how I would fix it on Heroku. There is no way to run as root on Heroku, so how can I listen on port 80?
",https://stackoverflow.com/questions/9164915/node-js-eacces-error-when-listening-on-most-ports,405,566749.0,38.0,,,2012-02-06 18:06:48,2025-06-27 06:29:32,2012-02-06 18:13:30,,,http;node.js;permission-denied,jwegner,7503,489230,registered,true,9166332,,CC BY-SA 3.0,2022-07-07 11:50:30,1395,1310,1,0,0,3,true,false,false,true,true,true,49,8,false,0.067,0.0007,5402,2012,2,18,Monday,false,false,false,false,false,false,false
28305120,Differences between express.Router and app.get?,"I'm starting with NodeJS and Express 4, and I'm a bit confused. I have been reading the Express website, but can't see when to use a route handler or when to use express.Router.
As I could see if I want to show a page or something when the user hits /show for example I should use:
var express = require('express')
var app = express()
app.get("/show", someFunction)
In the beginning, I thought this was old (for Express 3). Is that right or this is the way for Express 4 too?
If this is the way to do it in Express 4, what is express.Router used for?
I read almost the same example as above but using express.Router:
var express = require('express');
var router = express.Router();
router.get("/show", someFunction)
So, what's the difference between both examples?
Which one should I use if I just want to do a simple testing website?
",https://stackoverflow.com/questions/28305120/differences-between-express-router-and-app-get,405,132348.0,9.0,,,2015-02-03 17:31:20,2024-03-29 15:56:35,2024-03-29 15:56:35,,,node.js;express,nelson687,4533,2649573,registered,true,33261362,,CC BY-SA 4.0,,1025,867,6,0,0,2,true,false,false,true,true,true,47,5,true,0.068,0.0031,4309,2015,2,17,Tuesday,false,false,false,false,false,false,false
10462223,Call a "local" function within module.exports from another function in module.exports?,"How do you call a function from within another function in a module.exports declaration?
app.js
var bla = require('./bla.js');
console.log(bla.bar());
bla.js
module.exports = {
foo: function (req, res, next) {
return ('foo');
},
bar: function(req, res, next) {
this.foo();
}
}
I'm trying to access the function foo from within the function bar, and I'm getting:
TypeError: Object # has no method 'foo'
If I change this.foo() to just foo() I get:
ReferenceError: foo is not defined
",https://stackoverflow.com/questions/10462223/call-a-local-function-within-module-exports-from-another-function-in-module-ex,404,292405.0,10.0,,,2012-05-05 13:15:00,2022-12-23 05:30:58,2019-12-15 03:48:48,,,node.js;express,k00k,17653,191713,registered,true,10462275,,CC BY-SA 4.0,,717,519,7,0,0,2,true,false,false,true,true,true,96,11,true,0.034,0.0014,5313,2012,5,13,Saturday,true,false,false,false,false,false,false
14573001,NodeJS: How to decode base64 encoded string back to binary?,"I was implementing password hashing with salt, so I generated salt as binary, hashed the password, base64 encoded the password and salt then stored them into database.
Now when I am checking password, I am supposed to decode the salt back into binary data, use it to hash the supplied password, base64 encode the result and check if the result matches the one in database.
The problem is, I cannot find a method to decode the salt back into binary data. I encoded them using the Buffer.toString method but there doesn't seem to be reverse function.
",https://stackoverflow.com/questions/14573001/nodejs-how-to-decode-base64-encoded-string-back-to-binary,404,531262.0,1.0,,,2013-01-28 23:13:16,2018-10-05 13:03:34,,2015-04-19 07:31:34,Duplicate,node.js;encoding;base64;decoding,Xavier_Ex,8816,1264587,registered,true,14573049,,,,572,551,0,0,0,4,true,true,false,true,true,false,59,10,true,0.002,0.0008,5045,2013,1,23,Monday,false,false,false,false,false,false,false
47675478,NPM Install Error:Unexpected end of JSON input while parsing near '...nt-webpack-plugin":"0',"When creating a new Angular 5 project:
node version: 8.9.2
npm version: 5.5.1
My Command is:
npm install -g @angular/cli
The Error is:
npm ERR! **Unexpected end of JSON input while parsing near '...nt-webpack-plugin":"0'**
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Aashitec\AppData\Roaming\npm-cache\_logs\2017-12-06T13_10_10_729Z-debug.log
",https://stackoverflow.com/questions/47675478/npm-install-errorunexpected-end-of-json-input-while-parsing-near-nt-webpack,402,533516.0,38.0,,,2017-12-06 13:26:29,2024-04-09 15:41:58,2021-07-12 08:43:15,,,node.js;angular;npm;npm-install,kathir,4285,8024633,registered,true,47896884,,CC BY-SA 4.0,2019-04-08 06:15:59,627,408,2,1,0,4,true,false,false,true,true,true,110,11,false,0.071,0.0008,3272,2017,12,13,Wednesday,false,false,false,false,false,false,false
9831594,Apache and Node.js on the Same Server,"I want to use Node because it's swift, uses the same language I am using on the client side, and it's non-blocking by definition. But the guy who I hired to write the program for file handling (saving, editing, renaming, downloading, uploading files, etc.), he wants to use apache. So, I must:
Convince him to use Node (he's giving up little ground on that)
Figure out how to upload, download, rename, save, etc. files in node or
I must install apache and node on the same server.
Which is the most favorable situation, and how do I implement that?
",https://stackoverflow.com/questions/9831594/apache-and-node-js-on-the-same-server,402,307879.0,10.0,,,2012-03-22 22:37:41,2024-08-05 10:11:50,2015-10-08 16:20:25,,,apache;node.js,Matt,5663,1024501,registered,true,18604082,,CC BY-SA 3.0,,626,555,0,0,0,2,true,false,false,true,true,true,37,7,false,0.032,0.0013,5357,2012,3,22,Thursday,false,false,false,false,false,false,false
35207380,How to install npm peer dependencies automatically?,"For example, when I install Angular2:
npm install --save angular2
temp@1.0.0 /Users/doug/Projects/dougludlow/temp
├── angular2@2.0.0-beta.3
├── UNMET PEER DEPENDENCY es6-promise@^3.0.2
├── UNMET PEER DEPENDENCY es6-shim@^0.33.3
├── UNMET PEER DEPENDENCY reflect-metadata@0.1.2
├── UNMET PEER DEPENDENCY rxjs@5.0.0-beta.0
└── UNMET PEER DEPENDENCY zone.js@0.5.11
npm WARN angular2@2.0.0-beta.3 requires a peer of es6-promise@^3.0.2 but none was installed.
npm WARN angular2@2.0.0-beta.3 requires a peer of es6-shim@^0.33.3 but none was installed.
npm WARN angular2@2.0.0-beta.3 requires a peer of reflect-metadata@0.1.2 but none was installed.
npm WARN angular2@2.0.0-beta.3 requires a peer of rxjs@5.0.0-beta.0 but none was installed.
npm WARN angular2@2.0.0-beta.3 requires a peer of zone.js@0.5.11 but none was installed.
Is there a magic flag that I can pass to npm that will install the peer dependencies as well? I haven't been able to find one... It's tedious to manually copy and paste the peer dependencies and make sure I have the correct versions.
In other words, I'd rather not have to do:
npm install --save angular2@2.0.0-beta.3 es6-promise@^3.0.2 es6-shim@^0.33.3 reflect-metadata@0.1.2 rxjs@5.0.0-beta.0 zone.js@0.5.11
What is the better way?
",https://stackoverflow.com/questions/35207380/how-to-install-npm-peer-dependencies-automatically,402,695475.0,9.0,,,2016-02-04 17:15:12,2024-05-14 08:34:41,,,,node.js;npm,Douglas Ludlow,10949,1110395,registered,true,35207983,,CC BY-SA 3.0,,1343,1267,2,0,0,2,true,false,false,true,true,false,51,7,true,0.013,0.0006,3943,2016,2,17,Thursday,false,false,false,false,false,false,false
5178334,Folder structure for a Node.js project,"I notice that Node.js projects often include folders like these:
/libs, /vendor, /support, /spec, /tests
What exactly do these mean? What's the different between them, and where should I include referenced code?
",https://stackoverflow.com/questions/5178334/folder-structure-for-a-node-js-project,401,331660.0,7.0,,,2011-03-03 08:37:03,2022-04-20 06:27:23,2014-12-29 10:35:40,,,node.js,guilin 桂林,17520,443966,registered,true,5193206,,CC BY-SA 3.0,,264,218,0,0,0,1,true,false,false,true,true,true,38,6,false,0.021,0.0012,5742,2011,3,8,Thursday,false,false,false,false,false,false,false
9210542,node.js require() cache - possible to invalidate?,"From the node.js documentation:
Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.
Is there a way to invalidate this cache? i.e. for unit testing, I'd like each test to be working on a fresh object.
",https://stackoverflow.com/questions/9210542/node-js-require-cache-possible-to-invalidate,400,202250.0,18.0,,,2012-02-09 12:07:16,2024-12-17 10:12:46,,,,node.js,William,13682,120820,registered,true,11477602,,CC BY-SA 3.0,,404,358,0,0,0,1,true,false,false,true,true,false,49,7,true,0.089,0.002,5399,2012,2,12,Thursday,false,false,false,false,false,false,false
34700610,npm install won't install devDependencies,"On windows for some reason when I run npm install it won't install devDependencies. AFAIK it should. If I run npm install --dev devDependencies are installed. I don't understand why npm install doesn't install devDependencies too, but installs only dependencies. What could be the reason? How can I fix it?
Maybe something is wrong with my package.json? It is listed below if it may be helpful:
{
"name": "try-brunch",
"version": "0.1.0",
"private": "true",
"devDependencies": {
"brunch": "^2.0.4",
"cssnano-brunch": "^1.1.5",
"javascript-brunch": "^1.8.0",
"sass-brunch": "^1.9.2",
"uglify-js-brunch": "^1.7.8"
},
"dependencies": {
"jquery": "^2.1.4"
}
}
",https://stackoverflow.com/questions/34700610/npm-install-wont-install-devdependencies,399,563311.0,14.0,,,2016-01-10 00:26:35,2024-04-25 13:25:37,2024-03-15 03:25:03,,,node.js;npm,tristantzara,6017,4806797,registered,true,34719468,,CC BY-SA 4.0,,1071,895,4,0,0,2,true,false,false,true,true,true,45,5,false,0.025,0.0007,3968,2016,1,0,Sunday,true,false,false,false,false,false,false
27441803,Why does JSHint throw a warning if I am using const?,"This is the error I get when using const:
<error line=""2"" column=""1"" severity=""warning"" message=""'const' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz)."" source=""jshint.W104"" />
My code looks like this:
const Suites = {
Spade: 1,
Heart: 2,
Diamond: 3,
Club: 4
};
The code works fine only JSHint is warning me every time.
",https://stackoverflow.com/questions/27441803/why-does-jshint-throw-a-warning-if-i-am-using-const,397,309326.0,19.0,,,2014-12-12 10:39:01,2022-01-27 01:56:03,2016-09-10 20:25:13,,,javascript;node.js;constants;jslint;jshint,Andre Schlesinger,3985,2775842,registered,true,27442276,,CC BY-SA 3.0,,464,395,2,0,0,5,true,false,false,true,true,true,52,11,true,0.061,0.0013,4362,2014,12,10,Friday,false,false,true,false,false,false,false
35048686,What's the difference between path.resolve and path.join?,"Is there some difference between the following invocations?
path.join(__dirname, 'app')
vs.
path.resolve(__dirname, 'app')
Which one should be preferred?
",https://stackoverflow.com/questions/35048686/whats-the-difference-between-path-resolve-and-path-join,397,202231.0,5.0,,,2016-01-27 21:46:33,2023-11-12 17:16:32,2020-08-25 10:15:02,,,node.js,helpermethod,63090,1178669,registered,true,39836259,,CC BY-SA 4.0,,229,160,2,0,0,1,true,false,false,true,true,true,61,7,true,0.025,0.002,3951,2016,1,21,Wednesday,false,false,false,false,false,false,false
31472755,sudo: npm: command not found,"I'm trying to upgrade to the latest version of node. I'm following the instructions at http://davidwalsh.name/upgrade-nodejs
But when I do:
sudo npm install -g n
I get the error:
sudo: npm: command not found
npm works without sudo. When I do:
whereis node
I see:
node: /usr/bin/node /usr/lib/node /usr/bin/X11/node /usr/local/node
Running:
which npm
Shows:
/usr/local/node/bin/npm
I tried the solution at https://stackoverflow.com/a/5062718/1246159
But I'm still getting the same error. I also looked at the /etc/sudoers file and the relevant line is:
Defaults secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
This looks fine to me. How can I possibly get NPM working with sudo command?
",https://stackoverflow.com/questions/31472755/sudo-npm-command-not-found,396,1618239.0,31.0,,,2015-07-17 09:36:44,2025-01-23 08:28:47,2022-11-22 21:27:20,,,node.js;linux;unix;npm,Mark,5198,1246159,registered,true,31734090,,CC BY-SA 4.0,2017-06-11 07:47:27,1115,737,8,2,0,4,true,false,false,true,true,true,28,5,false,0.019,0.0002,4145,2015,7,9,Friday,false,false,false,false,false,false,false
60573595,`npm install` fails on node-gyp rebuild with `gyp: No Xcode or CLT version detected!`,"Every time I try npm install. I get the following error. How do I fix it?
gyp: No Xcode or CLT version detected!
I am on node -v → v8.8.0 & npm -v → v6.11.3
I tried to run it on VSCode terminal and iTerm, but both ended up getting the same error. (both are updated to the latest version). The only new thing I did is updating my macOS to the latest version (Catalina 10.15.3 today).
$ npm install Fri Mar 6 17:22:40 2020
> fsevents@1.2.11 install /Users/synapse/Documents/synapsefi-dev-ui/node_modules/watchpack/node_modules/fsevents
> node-gyp rebuild
No receipt for 'com.apple.pkg.CLTools_Executables' found at '/'.
No receipt for 'com.apple.pkg.DeveloperToolsCLILeo' found at '/'.
No receipt for 'com.apple.pkg.DeveloperToolsCLI' found at '/'.
gyp: No Xcode or CLT version detected!
gyp ERR! configure error
gyp ERR! stack Error: `gyp` failed with exit code: 1
gyp ERR! stack at ChildProcess.onCpExit (/Users/synapse/.nvm/versions/node/v8.8.0/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:344:16)
gyp ERR! stack at emitTwo (events.js:125:13)
gyp ERR! stack at ChildProcess.emit (events.js:213:7)
gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/child_process.js:200:12)
gyp ERR! System Darwin 19.3.0
gyp ERR! command "/Users/synapse/.nvm/versions/node/v8.8.0/bin/node" "/Users/synapse/.nvm/versions/node/v8.8.0/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /Users/synapse/Documents/synapsefi-dev-ui/node_modules/watchpack/node_modules/fsevents
gyp ERR! node -v v8.8.0
gyp ERR! node-gyp -v v5.0.3
gyp ERR! not ok
npm WARN synapsefi-dev-ui@2.0.20 No repository field.
npm WARN The package country-data is included as both a dev and production dependency.
npm WARN The package react-dropzone is included as both a dev and production dependency.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.11 (node_modules/watchpack/node_modules/fsevents):
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.11 install: `node-gyp rebuild`
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: Exit status 1
",https://stackoverflow.com/questions/60573595/npm-install-fails-on-node-gyp-rebuild-with-gyp-no-xcode-or-clt-version-detec,396,178909.0,24.0,,,2020-03-07 01:31:19,2022-11-15 11:13:07,2020-11-02 20:44:49,,,node.js;npm;terminal;macos-catalina;node-gyp,Jeena,4295,12310205,registered,true,60982835,,CC BY-SA 4.0,,2258,2150,5,0,0,5,true,false,false,true,true,true,85,14,false,0.134,0.0022,2450,2020,3,1,Saturday,true,false,false,false,false,false,false
10386310,How to install a private NPM module without my own registry?,"I've taken some shared code and put it in an NPM module, one I don't want to upload to the central registry. The question is, how do I install it from other projects?
The obvious way is probably to set up my own NPM registry, but according to the documentation, that involves a lot of hassle.
Can I just install an NPM module that sits on the local filesystem, or perhaps even from git?
npm install --from-git git@server:project
",https://stackoverflow.com/questions/10386310/how-to-install-a-private-npm-module-without-my-own-registry,394,297108.0,16.0,,,2012-04-30 15:33:17,2024-03-16 13:41:43,2016-08-04 10:27:00,,,node.js;npm;package;npm-private-modules,futlib,8438,606036,registered,true,10388874,,CC BY-SA 3.0,,478,433,1,0,0,4,true,false,false,true,true,true,60,11,true,0.054,0.0013,5318,2012,4,15,Monday,false,false,false,false,false,false,false
5364928,node.js require all files in a folder?,"How do I require all files in a folder in node.js?
need something like:
files.forEach(function (v,k){
// require routes
require('./routes/'+v);
}};
",https://stackoverflow.com/questions/5364928/node-js-require-all-files-in-a-folder,394,377451.0,15.0,,,2011-03-19 21:09:23,2023-12-17 12:22:54,2022-05-05 15:32:17,,,node.js,Harry,55539,663447,registered,true,5365577,,CC BY-SA 4.0,,193,155,1,0,0,1,true,false,false,true,true,true,38,7,true,0.04,0.001,5726,2011,3,21,Saturday,true,false,false,false,false,false,false
21237105,Const in JavaScript: when to use it and is it necessary?,"I've recently come across the const keyword in JavaScript. From what I can tell, it is used to create immutable variables, and I've tested to ensure that it cannot be redefined (in Node.js):
const x = 'const';
const x = 'not-const';
// Will give an error: 'constant 'x' has already been defined'
I realise that it is not yet standardized across all browsers - but I'm only interested in the context of Node.js V8, and I've noticed that certain developers / projects seem to favor it heavily when the var keyword could be used to the same effect.
- When is it appropriate to use
const in place of var?
- Should it be used every time a variable which is not going to be
re-assigned is declared?
- Does it actually make any difference if
var is used in place of
const or vice-versa?
",https://stackoverflow.com/questions/21237105/const-in-javascript-when-to-use-it-and-is-it-necessary,393,247246.0,19.0,,,2014-01-20 14:56:15,2024-07-26 09:28:29,2021-03-23 04:13:03,,,javascript;node.js;constants;immutability,axdg,4075,2095244,registered,true,21237365,,CC BY-SA 4.0,2017-11-06 09:11:28,1336,778,7,4,0,4,true,false,false,true,true,true,56,11,true,0.077,0.0016,4688,2014,1,14,Monday,false,false,true,false,false,false,false
15349733,setImmediate vs. nextTick,"Node.js version 0.10 was released today and introduced setImmediate. The API changes documentation suggests using it when doing recursive nextTick calls.
From what MDN says it seems very similar to process.nextTick.
When should I use nextTick and when should I use setImmediate?
",https://stackoverflow.com/questions/15349733/setimmediate-vs-nexttick,392,131506.0,8.0,,,2013-03-11 22:14:20,2023-05-17 21:38:39,2017-03-28 16:14:28,,,javascript;node.js;setimmediate,Benjamin Gruenbaum,277974,1348195,registered,true,15349865,,CC BY-SA 3.0,,570,282,5,2,0,3,true,false,false,true,true,true,25,3,false,0.061,0.003,5003,2013,3,22,Monday,false,false,true,false,false,false,false
34215526,Eslint: How to disable "unexpected console statement" in Node.js?,"I'm using eslint with Sublime Text 3 and I am writing gulpfile.js.
/*eslint-env node*/
var gulp = require('gulp');
gulp.task('default', function(){
console.log('default task');
});
But eslint keeps showing error : ""Error: Unexpected console statement. (no-console)""
![]()
I found official document here, but I still don't know how to disable it.
/*eslint-env node*/
var gulp = require('gulp');
/*eslint no-console: 2*/
gulp.task('default', function(){
console.log('default task');
});
doesn't work, either.
My Sublime Text 3 plugins: SublimeLinter and SublimeLinter-contrib-eslint.
Here's my .eslintrc.js file:
module.exports = {
""rules"": {
""no-console"":0,
""indent"": [
2,
""tab""
],
""quotes"": [
2,
""single""
],
""linebreak-style"": [
2,
""unix""
],
""semi"": [
2,
""always""
]
},
""env"": {
""browser"": true,
""node"": true
},
""extends"": ""eslint:recommended""
};
",https://stackoverflow.com/questions/34215526/eslint-how-to-disable-unexpected-console-statement-in-node-js,391,439252.0,21.0,,,2015-12-11 03:15:27,2024-08-24 09:52:35,2019-02-20 09:09:51,,,javascript;node.js;sublimetext3;sublime-text-plugin;eslint,Jean Y.C. Yang,4594,1951139,registered,true,34215651,,CC BY-SA 4.0,,1407,1066,5,2,1,5,true,false,false,true,true,true,75,9,true,0.048,0.0009,3998,2015,12,3,Friday,false,false,true,false,false,false,false
56617209,The engine "node" is incompatible with this module,"I am getting below yarn error when deploying to AWS:
error fs-extra@7.0.1: The engine "node" is incompatible with this module. Expected version ">=6 <7 || >=8". Got "7.0.0"
Any idea how will this be resolved?
Will this work out if I specify engine in package.json:
{
"engines" : {
"node" : ">=8.0.0"
}
}
",https://stackoverflow.com/questions/56617209/the-engine-node-is-incompatible-with-this-module,390,625335.0,27.0,,,2019-06-16 08:16:58,2025-01-09 16:05:19,2024-03-15 10:40:16,,,node.js;npm;dependencies;yarnpkg,JN_newbie,6192,455964,registered,true,,,CC BY-SA 4.0,,575,389,5,0,0,4,false,false,false,true,true,true,60,8,false,0.043,0.0006,2715,2019,6,8,Sunday,true,false,false,false,false,false,false
18130164,nodejs vs node on ubuntu 12.04,"I installed nodejs on ubuntu from instructions given here
When I write node --version in the terminal I see this :
-bash: /usr/sbin/node: No such file or directory
I can see node in the /usr/sbin/ directory, though.
Writing npm --version shows 1.3.5
Writing nodejs --version shows v0.10.15
Also, I can see node in the /usr/bin/ directory.
So, how do I get node working?
Also, If I use zsh instead of bash, then node command works.
",https://stackoverflow.com/questions/18130164/nodejs-vs-node-on-ubuntu-12-04,390,242998.0,22.0,,,2013-08-08 15:33:33,2023-06-06 07:51:07,2016-12-19 18:07:53,,,javascript;node.js;ubuntu;serverside-javascript,Jatin,14269,912703,registered,true,18130296,,CC BY-SA 3.0,2023-06-06 06:55:35,736,439,10,1,0,4,true,false,false,true,true,true,30,6,false,0.091,0.0016,4853,2013,8,15,Thursday,false,false,true,false,false,false,false
10695629,What is the parameter "next" used for in Express?,"Suppose you have a simple block of code like this:
app.get('/', function(req, res){
res.send('Hello World');
});
This function has two parameters, req and res, which represent the request and response objects respectively.
On the other hand, there are other functions with a third parameter called next. For example, lets have a look at the following code:
app.get('/users/:id?', function(req, res, next){ // Why do we need next?
var id = req.params.id;
if (id) {
// do something
} else {
next(); // What is this doing?
}
});
I can't understand what the point of next() is or why its being used. In that example, if id doesn't exist, what is next actually doing?
",https://stackoverflow.com/questions/10695629/what-is-the-parameter-next-used-for-in-express,390,234921.0,6.0,,,2012-05-22 04:11:38,2022-11-04 18:21:19,2015-11-18 10:38:51,,,node.js;express,Menztrual,41717,1258398,registered,true,10695714,,CC BY-SA 3.0,2019-09-23 10:34:43,847,706,7,0,0,2,true,false,false,true,true,true,59,9,true,0.026,0.0017,5296,2012,5,4,Tuesday,false,false,false,false,false,false,false
23327010,How to generate unique ID with node.js,"function generate(count) {
var founded = false,
_sym = 'abcdefghijklmnopqrstuvwxyz1234567890',
str = '';
while(!founded) {
for(var i = 0; i < count; i++) {
str += _sym[parseInt(Math.random() * (_sym.length))];
}
base.getID(string, function(err, res) {
if(!res.length) {
founded = true; // How to do it?
}
});
}
return str;
}
How to set a variable value with database query callback? How I can do it?
",https://stackoverflow.com/questions/23327010/how-to-generate-unique-id-with-node-js,388,609047.0,25.0,,,2014-04-27 18:04:41,2025-03-22 19:58:48,2018-12-03 18:30:27,,,javascript;node.js;express,owl,4529,3213853,registered,true,23328916,,CC BY-SA 4.0,2025-03-22 23:17:09,552,521,1,0,0,3,true,false,false,true,true,true,38,7,false,0.041,0.0006,4591,2014,4,18,Sunday,true,false,true,false,false,false,false
31778413,Run JavaScript in Visual Studio Code,"Is there a way to execute JavaScript and display the results using Visual Studio Code?
For example, a script file containing:
console.log('hello world');
I assume that Node.js would be needed but can't work out how to do it?
By Visual Studio Code I mean the new Code Editor from Microsoft -
Not code written using Visual Studio.
",https://stackoverflow.com/questions/31778413/run-javascript-in-visual-studio-code,388,1110536.0,24.0,,,2015-08-03 01:55:20,2026-02-18 23:20:17,2022-04-26 11:15:30,,,javascript;node.js;vs-code,Nick Le Page,4429,301736,registered,true,33850390,,CC BY-SA 4.0,2021-09-15 21:09:20,513,340,1,1,0,3,true,false,false,true,true,true,36,6,false,0.022,0.0003,4128,2015,8,1,Monday,false,false,true,false,false,false,false
5818312,MySQL with Node.js,"I've just started getting into Node.js. I come from a PHP background, so I'm fairly used to using MySQL for all my database needs.
How can I use MySQL with Node.js?
",https://stackoverflow.com/questions/5818312/mysql-with-node-js,387,327089.0,9.0,,,2011-04-28 12:05:33,2020-06-12 19:52:20,2015-11-21 12:49:23,,,mysql;node.js,crawf,9698,731814,registered,true,5818884,,CC BY-SA 3.0,2014-03-13 20:27:55,180,166,0,0,0,2,true,false,false,true,true,true,18,3,false,0.028,0.0012,5686,2011,4,12,Thursday,false,false,false,false,false,false,false
8855687,Secure random token in Node.js,"In this question Erik needs to generate a secure random token in Node.js. There's the method crypto.randomBytes that generates a random Buffer. However, the base64 encoding in node is not url-safe, it includes / and + instead of - and _. Therefore, the easiest way to generate such token I've found is
require('crypto').randomBytes(48, function(ex, buf) {
token = buf.toString('base64').replace(/\//g,'_').replace(/\+/g,'-');
});
Is there a more elegant way?
",https://stackoverflow.com/questions/8855687/secure-random-token-in-node-js,384,369997.0,16.0,,,2012-01-13 18:55:14,2025-04-21 05:20:24,2017-05-23 12:10:09,,,javascript;node.js;base64;securestring,Hubert OG,19564,876409,registered,true,8856177,,CC BY-SA 3.0,2025-03-22 23:16:57,677,466,6,1,0,4,true,false,false,true,true,true,30,5,false,0.043,0.001,5426,2012,1,18,Friday,false,false,true,false,false,false,false
6737824,How to run a hello.js file in Node.js on windows?,"I am trying to run a hello world program written in javascript in a separate file named hello.js
Currently running windows version of node.js.
The code runs perfectly in console window but how do I reference the path in windows environment.
C:\abc\zyx\hello.js
in Unix I guess it is showing $ node hello.js
I'm absolutely new to Node.js Please correct me if I am doing something wrong.
I tried
> node C:\abc\zyx\hello.js ----didn't work
> C:\abc\zyx\hello.js --didn't work
UPDATE1:
Added node.exe to the folder where hello.js file is sitting.
Added path point to the folder c:\abc\zyx\ and I get an error that says
ReferenceError: hello is not defined
see contents of hello.js
setTimeout(function() {
console.log('World!');
}, 2000);
console.log('Hello');
UPDATE 2:
So far I have tried all these version and none of them seems to work. May be I am doing something completely wrong.
>node hello.js
>$ node hello.js
>node.exe hello.js
>node /hello.js
>node \hello.js
> \node \hello.js
> /node /hello.js
> C:\abc\xyz\node.exe C:\abc\xyz\hello.js
> C:\abc\xyz\node.exe C:/abc/xyz/hello.js
> hello.js
> /hello.js
> \hello.js
>node hello
Refer to my file structure
.
├── hello.js
├── node.exe
└── paths.txt
RESOLVED:
Instead of running node.exe, try running in command prompt with the following option and it worked.
c:\>node c:\abc\hello.js
Hello
World! (after 2 secs)
",https://stackoverflow.com/questions/6737824/how-to-run-a-hello-js-file-in-node-js-on-windows,382,1234913.0,17.0,,,2011-07-18 18:52:25,2022-06-23 20:44:42,2020-04-06 15:13:32,,,windows;node.js,Mitul,9874,581922,registered,true,6738741,,CC BY-SA 4.0,2019-01-09 23:52:54,1807,1443,7,0,0,2,true,false,false,true,true,true,49,10,true,0.014,0.0003,5605,2011,7,18,Monday,false,false,false,false,false,false,false
16633246,Code coverage with Mocha,"I am using Mocha for testing my NodeJS application. I am not able to figure out how to use its code coverage feature. I tried googling it but did not find any proper tutorial. Please help.
",https://stackoverflow.com/questions/16633246/code-coverage-with-mocha,381,212606.0,4.0,,,2013-05-19 09:35:19,2024-02-15 08:48:08,2017-04-16 18:42:45,,,node.js;unit-testing;code-coverage;mocha.js,tusharmath,11020,1040006,registered,true,16634823,,CC BY-SA 3.0,,196,189,0,0,0,4,true,false,false,true,true,true,24,4,false,0.019,0.0018,4934,2013,5,9,Sunday,true,false,false,false,false,false,false
40182121,What's the cause of the error 'getaddrinfo EAI_AGAIN'?,"My server threw this today, which is a Node.js error I've never seen before:
Error: getaddrinfo EAI_AGAIN my-store.myshopify.com:443
at Object.exports._errnoException (util.js:870:11)
at errnoException (dns.js:32:15)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:78:26)
I'm wondering if this is related to the DynDns DDOS attack which affected Shopify and many other services today. Here's an article about that.
My main question is what does dns.js do? What part of node is it a part of? How can I recreate this error with a different domain?
",https://stackoverflow.com/questions/40182121/whats-the-cause-of-the-error-getaddrinfo-eai-again,380,714769.0,16.0,,,2016-10-21 17:11:27,2025-03-11 15:22:19,2022-01-28 10:01:03,,,javascript;node.js;error-handling;dns;shopify,ThomasReggi,60643,340688,registered,true,40182520,,CC BY-SA 4.0,2018-12-20 01:51:55,750,569,2,1,0,5,true,false,false,true,true,true,66,8,true,0.022,0.0005,3683,2016,10,17,Friday,false,false,true,false,false,false,false
23023650,Is it possible to pass a flag to Gulp to have it run tasks in different ways?,"Normally in Gulp tasks look like this:
gulp.task('my-task', function() {
return gulp.src(options.SCSS_SOURCE)
.pipe(sass({style:'nested'}))
.pipe(autoprefixer('last 10 version'))
.pipe(concat('style.css'))
.pipe(gulp.dest(options.SCSS_DEST));
});
Is it possible to pass a command line flag to gulp (that's not a task) and have it run tasks conditionally based on that? For instance
$ gulp my-task -a 1
And then in my gulpfile.js:
gulp.task('my-task', function() {
if (a == 1) {
var source = options.SCSS_SOURCE;
} else {
var source = options.OTHER_SOURCE;
}
return gulp.src(source)
.pipe(sass({style:'nested'}))
.pipe(autoprefixer('last 10 version'))
.pipe(concat('style.css'))
.pipe(gulp.dest(options.SCSS_DEST));
});
",https://stackoverflow.com/questions/23023650/is-it-possible-to-pass-a-flag-to-gulp-to-have-it-run-tasks-in-different-ways,379,158662.0,11.0,,,2014-04-11 22:30:11,2023-02-16 21:32:34,2016-08-24 09:16:38,,,javascript;node.js;gulp,Aron Solberg,6938,1316464,registered,true,23038290,,CC BY-SA 3.0,,960,867,3,0,0,3,true,false,false,true,true,true,77,17,true,0.069,0.0024,4607,2014,4,22,Friday,false,false,true,false,false,false,false
37377731,Extend Express Request object using Typescript,"I’m trying to add a property to express request object from a middleware using typescript. However I can’t figure out how to add extra properties to the object. I’d prefer to not use bracket notation if possible.
I’m looking for a solution that would allow me to write something similar to this (if possible):
app.use((req, res, next) => {
req.property = setProperty();
next();
});
",https://stackoverflow.com/questions/37377731/extend-express-request-object-using-typescript,378,300481.0,35.0,,,2016-05-22 18:01:10,2025-05-13 15:29:04,2016-12-29 13:58:39,,,node.js;express;typescript,Isak Ågren,3977,3741080,registered,true,40762463,,CC BY-SA 3.0,2022-01-08 18:44:36,440,398,1,0,0,3,true,false,false,true,true,true,46,6,false,0.116,0.0013,3835,2016,5,18,Sunday,true,false,false,false,false,false,false
18310394,No 'Access-Control-Allow-Origin' - Node / Apache Port Issue,"i've created a small API using Node/Express and trying to pull data using Angularjs but as my html page is running under apache on localhost:8888 and node API is listen on port 3000, i am getting the No 'Access-Control-Allow-Origin'. I tried using node-http-proxy and Vhosts Apache but not having much succes, please see full error and code below.
XMLHttpRequest cannot load localhost:3000. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost:8888' is therefore not allowed access.""
// Api Using Node/Express
var express = require('express');
var app = express();
var contractors = [
{
""id"": ""1"",
""name"": ""Joe Blogg"",
""Weeks"": 3,
""Photo"": ""1.png""
}
];
app.use(express.bodyParser());
app.get('/', function(req, res) {
res.json(contractors);
});
app.listen(process.env.PORT || 3000);
console.log('Server is running on Port 3000')
Angular code
angular.module('contractorsApp', [])
.controller('ContractorsCtrl', function($scope, $http,$routeParams) {
$http.get('localhost:3000').then(function(response) {
var data = response.data;
$scope.contractors = data;
})
HTML
<body ng-app=""contractorsApp"">
<div ng-controller=""ContractorsCtrl"">
<ul>
<li ng-repeat=""person in contractors"">{{person.name}}</li>
</ul>
</div>
</body>
",https://stackoverflow.com/questions/18310394/no-access-control-allow-origin-node-apache-port-issue,378,576849.0,17.0,,,2013-08-19 09:22:50,2023-10-10 09:03:31,2019-11-21 23:55:46,,,node.js;angularjs;rest;express;cors,user1336103,3897,1336103,registered,true,18311469,,CC BY-SA 4.0,2019-01-11 09:09:33,1577,1435,4,0,0,5,true,false,false,true,true,true,67,8,false,0.029,0.0007,4842,2013,8,9,Monday,false,false,false,false,false,false,false
28175200,How to Delete node_modules - Deep Nested Folder in Windows,"Upon trying to remove the node_modules directory created by npm install:
The source file name(s) are larger than is supported by the file
system. Try moving to a location which has a shorter path name, or try
renaming to shorter name(s) before attempting this operation
I also tried shift + delete and still having the same issue.
",https://stackoverflow.com/questions/28175200/how-to-delete-node-modules-deep-nested-folder-in-windows,377,633203.0,39.0,,,2015-01-27 16:26:25,2025-03-04 16:33:11,2019-02-28 04:59:44,,,node.js;windows-7;npm,leoh,10628,892669,registered,true,29685530,,CC BY-SA 4.0,2020-11-17 20:50:14,442,344,1,0,0,3,true,false,false,true,true,true,58,10,false,0.062,0.0006,4316,2015,1,16,Tuesday,false,false,false,false,false,false,false
24430220,E11000 duplicate key error index dup key { : null },"Following is my user schema in user.js model -
var userSchema = new mongoose.Schema({
local: {
name: { type: String },
email : { type: String, require: true, unique: true },
password: { type: String, require:true },
},
facebook: {
id : { type: String },
token : { type: String },
email : { type: String },
name : { type: String }
}
});
var User = mongoose.model('User',userSchema);
module.exports = User;
This is how I am using it in my controller -
var user = require('./../models/user.js');
This is how I am saving it in the db -
user({'local.email' : req.body.email, 'local.password' : req.body.password}).save(function(err, result){
if(err)
res.send(err);
else {
console.log(result);
req.session.user = result;
res.send({"code":200,"message":"Record inserted successfully"});
}
});
The error thrown is:
{"name":"MongoError","code":11000,"err":"insertDocument :: caused by :: 11000 E11000 duplicate key error index: mydb.users.$email_1 dup key: { : null }"}
I checked the db collection and no such duplicate entry exists.
FYI - req.body.email and req.body.password are fetching values.
I also checked Getting "err" : "E11000 duplicate key error when inserting into mongo using the Java driver but it didn't help.
If I removed completely then it inserts the document, otherwise it throws error "Duplicate" error even I have an entry in the local.email. What is happening?
",https://stackoverflow.com/questions/24430220/e11000-duplicate-key-error-index-dup-key-null,377,652635.0,25.0,,,2014-06-26 12:12:30,2026-04-09 19:24:56,2026-04-09 19:24:56,,,node.js;mongodb;mongoose,Trialcoder,6054,1594368,registered,true,24430345,,CC BY-SA 4.0,2018-08-04 07:59:33,1920,1636,8,1,0,3,true,false,false,true,true,true,51,11,false,0.038,0.0006,4531,2014,6,12,Thursday,false,false,false,false,false,false,false
49432579,await is only valid in async function,"I wrote this code in lib/helper.js:
var myfunction = async function(x,y) {
....
return [variableA, variableB]
}
exports.myfunction = myfunction;
Then I tried to use it in another file:
var helper = require('./helper.js');
var start = function(a,b){
....
const result = await helper.myfunction('test','test');
}
exports.start = start;
I got an error:
await is only valid in async function
What is the issue?
",https://stackoverflow.com/questions/49432579/await-is-only-valid-in-async-function,377,864126.0,15.0,,,2018-03-22 15:29:02,2024-09-09 20:08:12,2023-06-05 05:26:54,,,javascript;node.js,j.doe,4939,8759895,registered,true,49432604,,CC BY-SA 4.0,2021-09-08 20:08:55,625,430,3,0,0,2,true,false,false,true,true,true,37,7,false,0.017,0.0004,3166,2018,3,15,Thursday,false,false,true,false,false,false,false
10522532,Stop node.js program from command line,"I have a simple TCP server that listens on a port.
var net = require("net");
var server = net.createServer(function(socket) {
socket.end("Hello!\n");
});
server.listen(7777);
I start it with node server.js and then close it with Ctrl+Z on Mac. When I try to run it again with node server.js I get this error message:
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: listen EADDRINUSE
at errnoException (net.js:670:11)
at Array.0 (net.js:771:26)
at EventEmitter._tickCallback (node.js:192:41)
Am I closing the program the wrong way? How can I prevent this from happening?
",https://stackoverflow.com/questions/10522532/stop-node-js-program-from-command-line,374,848179.0,20.0,,,2012-05-09 19:05:40,2024-08-27 16:17:17,2024-02-03 23:49:45,,,node.js;command,Eleeist,7041,1136542,registered,true,10522688,,CC BY-SA 4.0,2014-12-07 15:36:18,773,656,4,0,0,2,true,false,false,true,true,true,38,6,false,0.024,0.0004,5309,2012,5,19,Wednesday,false,false,false,false,false,false,false
26320901,Cannot install NodeJs: /usr/bin/env: node: No such file or directory,"I'm trying to install nodeJs into my Ubuntu 14.04 in order to use GruntJs.
I've read about Ubuntu different way of doing it (issues?), so this is what I've done in order to install it:
sudo apt-get install npm
sudo npm install -g grunt-cli
Typing grunt after that I've got the error:
/usr/bin/env: node: No such file or directory
So, I've tried:
curl -sL https://deb.nodesource.com/setup | sudo bash -
sudo apt-get install -y nodejs
sudo apt-get update
And trying again, and still getting the error, I've tried:
sudo add-apt-repository https://launchpad.net/~chris-lea/+archive/node.js/
sudo apt-get install -y nodejs
I've got this message:
nodejs is already the newest version.
0 to upgrade, 0 to newly install, 0 to remove and 3 not to upgrade.
I did try a cleanup just in case:
sudo apt-get autoremove
But nope, the error is still there: when I type grunt I still get /usr/bin/env: node: No such file or directory
What should I do?
",https://stackoverflow.com/questions/26320901/cannot-install-nodejs-usr-bin-env-node-no-such-file-or-directory,373,408341.0,22.0,,,2014-10-12 01:17:44,2024-03-14 09:30:11,2018-09-18 09:31:39,,,node.js;ubuntu;gruntjs;npm-install;node-modules,Rosamunda,15016,892490,registered,true,26320915,,CC BY-SA 4.0,,1367,959,7,2,0,5,true,false,false,true,true,true,68,10,false,0.054,0.0009,4423,2014,10,1,Sunday,true,false,false,false,false,false,false
42706584,ESLint: "error Parsing error: The keyword 'const' is reserved","I am getting this error from ESLint:
error Parsing error: The keyword 'const' is reserved
from this code:
const express = require('express');
const app = express();
const _ = require('underscore');
I've tried removing node_modules and reinstalling all npm packages (as suggested here), but to no avail.
",https://stackoverflow.com/questions/42706584/eslint-error-parsing-error-the-keyword-const-is-reserved,373,253046.0,11.0,,,2017-03-09 22:19:27,2024-09-12 15:56:07,2023-04-18 15:55:59,,,javascript;node.js;ecmascript-6;eslint,opike,7625,549226,registered,true,42706706,,CC BY-SA 4.0,,538,310,3,1,0,4,true,false,false,true,true,true,80,9,false,0.043,0.0015,3544,2017,3,22,Thursday,false,false,true,false,false,false,false
10058814,Get data from fs.readFile,"var content;
fs.readFile('./Index.html', function read(err, data) {
if (err) {
throw err;
}
content = data;
});
console.log(content);
Logs undefined, why?
",https://stackoverflow.com/questions/10058814/get-data-from-fs-readfile,371,799641.0,17.0,,,2012-04-07 22:12:09,2023-02-10 15:55:27,2014-11-27 09:11:26,2023-02-18 13:55:22,Duplicate,javascript;node.js,karaxuna,26903,1265753,registered,true,10058879,,,,221,177,2,0,0,2,true,true,false,true,true,true,25,4,false,0.021,0.0005,5341,2012,4,22,Saturday,true,false,true,false,false,false,false
7163061,is there a require for json in node.js,"I would like to include a couple of JSON files in my JavaScript code that are in the same directory as my JavaScript source file.
If I wanted to include another JavaScript file I could simply use require.
Now I'm using readFileSync and __dirname to get the JSON, which I think is an ugly way to do it.
Is there something similar for require that enables me to load a JSON file?
",https://stackoverflow.com/questions/7163061/is-there-a-require-for-json-in-node-js,371,449780.0,11.0,,,2011-08-23 14:56:23,2025-07-29 06:27:25,2017-01-17 16:34:25,,,json;node.js;require,Corno,5466,832074,registered,true,7165572,,CC BY-SA 3.0,,440,380,3,0,0,3,true,false,false,true,true,true,38,8,false,0.024,0.0008,5569,2011,8,14,Tuesday,false,false,false,false,false,false,false
4981891,node.js equivalent of python's if __name__ == '__main__',"I'd like to check if my module is being included or run directly. How can I do this in node.js?
",https://stackoverflow.com/questions/4981891/node-js-equivalent-of-pythons-if-name-main,369,89748.0,2.0,,,2011-02-13 01:40:00,2025-08-01 16:32:36,,2017-07-03 23:16:27,Duplicate,node.js,nornagon,15911,216728,registered,true,6090287,,,,103,96,0,0,0,1,true,true,false,true,true,false,68,8,false,0.022,0.0041,5760,2011,2,1,Sunday,true,false,false,false,false,false,false
7559648,Is there a way to make npm install (the command) to work behind proxy?,"Is there a way to make npm install work behind a proxy? I tried changing the proxy variable in the .npmrc file but it didn't work. I'm trying to avoid doing a manual download.
",https://stackoverflow.com/questions/7559648/is-there-a-way-to-make-npm-install-the-command-to-work-behind-proxy,368,802594.0,33.0,,,2011-09-26 18:37:16,2024-06-06 11:14:31,2023-12-02 23:31:18,,,node.js;npm;proxy,Ben,5029,762638,unregistered,true,,,CC BY-SA 4.0,2018-11-01 18:24:45,210,177,2,0,0,3,false,false,false,true,true,true,70,14,true,0.041,0.0005,5535,2011,9,18,Monday,false,false,false,false,false,false,false
8303900,mongodb/mongoose findMany - find all documents with IDs listed in array,"I have an array of _ids and I want to get all docs accordingly, what's the best way to do it ?
Something like ...
// doesn't work ... of course ...
model.find({
'_id' : [
'4ed3ede8844f0f351100000c',
'4ed3f117a844e0471100000d',
'4ed3f18132f50c491100000e'
]
}, function(err, docs){
console.log(docs);
});
The array might contain hundreds of _ids.
",https://stackoverflow.com/questions/8303900/mongodb-mongoose-findmany-find-all-documents-with-ids-listed-in-array,366,347544.0,10.0,,,2011-11-28 23:31:11,2025-01-20 18:17:01,2020-08-24 20:45:28,,,node.js;mongodb;mongoose;filtering,ezmilhouse,9151,690253,registered,true,8304213,,CC BY-SA 4.0,,432,387,1,0,0,4,true,false,false,true,true,true,71,11,false,0.029,0.0011,5472,2011,11,23,Monday,false,false,false,false,false,false,false
12913141,"message failed to fetch from registry" while trying to install any module,"I can't install any node module from the npm.
npm install socket.io
The above command resulted to below output, it is not able to install socket.io
npm http GET https://registry.npmjs.org/socket.io
npm ERR! Error: failed to fetch from registry: socket.io
npm ERR! at /opt/node0610/lib/node_modules/npm/lib/utils/npm-registry-client/get.js:139:12
npm ERR! at cb (/opt/node0610/lib/node_modules/npm/lib/utils/npm-registry-client/request.js:32:9)
npm ERR! at Request._callback (/opt/node0610/lib/node_modules/npm/lib/utils/npm-registry-client/request.js:137:18)
npm ERR! at Request.callback (/opt/node0610/lib/node_modules/npm/node_modules/request/main.js:109:22)
npm ERR! at Request.<anonymous> (/opt/node0610/lib/node_modules/npm/node_modules/request/main.js:198:58)
npm ERR! at Request.emit (events.js:88:20)
npm ERR! at ClientRequest.<anonymous> (/opt/node0610/lib/node_modules/npm/node_modules/request/main.js:195:10)
npm ERR! at ClientRequest.emit (events.js:67:17)
npm ERR! at CleartextStream.<anonymous> (http.js:1134:11)
npm ERR! at CleartextStream.emit (events.js:67:17)
npm ERR! You may report this log at:
npm ERR! <http://github.com/isaacs/npm/issues>
npm ERR! or email it to:
npm ERR! <npm-@googlegroups.com>
npm ERR!
npm ERR! System Linux 2.6.18-194.el5
npm ERR! command ""node"" ""/opt/node0610/bin/npm"" ""install"" ""socket.io""
npm ERR! cwd /opt/node0610/lib/node_modules
npm ERR! node -v v0.6.10
npm ERR! npm -v 1.1.0-3
npm ERR! message failed to fetch from registry: socket.io
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! /opt/node0610/lib/node_modules/npm-debug.log
npm not ok
My NPM Version is :
[applmgr@dev node_modules]$ npm --version
1.1.0-3
My NodeJS Version is :
[applmgr@dev node_modules]$ node --version
v0.6.10
",https://stackoverflow.com/questions/12913141/message-failed-to-fetch-from-registry-while-trying-to-install-any-module,365,229675.0,15.0,,,2012-10-16 10:56:08,2022-12-29 14:44:41,2014-12-20 20:22:24,,,node.js;npm,Dexter,12230,1328276,registered,true,13119867,,CC BY-SA 3.0,2014-07-09 16:48:56,1978,1854,4,0,0,2,true,false,false,true,true,true,84,12,false,0.065,0.0016,5149,2012,10,10,Tuesday,false,false,false,false,false,false,false
30782693,Run function in script from command line (Node JS),"I'm writing a web app in Node. If I've got some JS file db.js with a function init in it how could I call that function from the command line?
",https://stackoverflow.com/questions/30782693/run-function-in-script-from-command-line-node-js,365,362976.0,17.0,,,2015-06-11 13:48:41,2024-04-22 13:27:40,,,,javascript;node.js;command-line,winhowes,8125,4525938,registered,true,36480927,,CC BY-SA 3.0,,176,143,2,0,0,3,true,false,false,true,true,false,50,9,false,0.047,0.001,4181,2015,6,13,Thursday,false,false,true,false,false,false,false
48387040,How do I determine the correct "max-old-space-size" for Node.js?,"I'm having some trouble to understand how Node.js acts based on the parameter max-old-space-size.
In my case, for example, I'm running two t2.small AWS instances (2GB of RAM).
Not sure why, but I did set max-old-space-size=4096 (4GB). What does node do in this case? Could this configuration lead to a possible memory allocation failure?
How do I determine the correct value of max-old-space-size based on the server resources?
My application is constantly growing the memory usage and I'm trying to understand everything about node internals.
",https://stackoverflow.com/questions/48387040/how-do-i-determine-the-correct-max-old-space-size-for-node-js,365,589475.0,8.0,,,2018-01-22 17:24:35,2025-08-20 23:22:01,2022-12-28 12:47:07,,,node.js;memory;v8,Borjante,10717,4289649,registered,true,48392705,,CC BY-SA 4.0,,631,544,4,0,0,3,true,false,false,true,true,true,74,9,true,0.014,0.0006,3225,2018,1,17,Monday,false,false,false,false,false,false,false
14469515,How to npm install to a specified directory?,"Is it possible to specify a target directory when running npm install <package>?
",https://stackoverflow.com/questions/14469515/how-to-npm-install-to-a-specified-directory,363,471638.0,6.0,,,2013-01-22 22:49:30,2025-06-12 10:40:45,,,,node.js;npm,coudy,14228,797320,registered,true,14469516,,CC BY-SA 3.0,,107,87,1,0,0,2,true,false,false,true,true,false,44,8,true,0.013,0.0008,5051,2013,1,22,Tuesday,false,false,false,false,false,false,false
27464168,How to include scripts located inside the node_modules folder?,"I have a question concerning best practice for including node_modules into a HTML website.
Imagine I have Bootstrap inside my node_modules folder. Now for the production version of the website, how would I include the Bootstrap script and CSS files located inside the node_modules folder? Does it make sense to leave Bootstrap inside that folder and do something like the following?
<script src=""./node_modules/bootstrap/dist/bootstrap.min.js""></script>
Or would I have to add rules to my gulp file which then copy those files into my dist folder? Or would it be best to let gulp somehow completely remove the local bootstrap from my HTML file and replace it with the CDN version?
",https://stackoverflow.com/questions/27464168/how-to-include-scripts-located-inside-the-node-modules-folder,363,281879.0,12.0,,,2014-12-13 22:12:09,2023-10-14 08:18:46,2019-10-25 15:51:14,,,node.js;twitter-bootstrap;npm;node-modules,Chris,6273,1032472,registered,true,27464258,,CC BY-SA 4.0,,781,697,4,0,0,4,true,false,false,true,true,true,62,9,true,0.043,0.0013,4361,2014,12,22,Saturday,true,false,false,false,false,false,false
5924072,"Express-js can't GET my static files, why?","I've reduced my code to the simplest express-js app I could make:
var express = require(""express""),
app = express.createServer();
app.use(express.static(__dirname + '/styles'));
app.listen(3001);
My directory look like this:
static_file.js
/styles
default.css
Yet when I access http://localhost:3001/styles/default.css I get the following error:
Cannot GET / styles /
default.css
I'm using express 2.3.3 and node 0.4.7. What am I doing wrong?
",https://stackoverflow.com/questions/5924072/express-js-cant-get-my-static-files-why,362,389125.0,27.0,,,2011-05-07 21:21:23,2024-08-22 11:08:58,2011-06-05 04:24:12,,,node.js;express,Kit Sunde,37345,29347,registered,true,5924732,,CC BY-SA 3.0,2023-07-12 21:54:51,597,458,6,0,0,2,true,false,false,true,true,true,46,7,true,0.069,0.0009,5677,2011,5,21,Saturday,true,false,false,false,false,false,false
19035373,How do I redirect in expressjs while passing some context?,"I am using express to make a web app in node.js. This is a simplification of what I have:
var express = require('express');
var jade = require('jade');
var http = require(""http"");
var app = express();
var server = http.createServer(app);
app.get('/', function(req, res) {
// Prepare the context
res.render('home.jade', context);
});
app.post('/category', function(req, res) {
// Process the data received in req.body
res.redirect('/');
});
My problem is the following:
If I find that the data sent in /category doesn't validate, I would like pass some additional context to the / page. How could I do this? Redirect doesn't seem to allow any kind of extra parameter.
",https://stackoverflow.com/questions/19035373/how-do-i-redirect-in-expressjs-while-passing-some-context,362,632142.0,10.0,,,2013-09-26 18:00:41,2022-12-13 08:13:35,2015-02-25 13:19:24,,,node.js;express,Enrique Moreno Tent,25591,392684,registered,true,19038048,,CC BY-SA 3.0,,762,691,3,0,0,2,true,false,false,true,true,true,58,10,true,0.016,0.0006,4804,2013,9,18,Thursday,false,false,false,false,false,false,false
10645994,How to format a UTC date as a `YYYY-MM-DD hh:mm:ss` string using NodeJS?,"Using NodeJS, I want to format a Date into the following string format:
var ts_hms = new Date(UTC);
ts_hms.format(""%Y-%m-%d %H:%M:%S"");
How do I do that?
",https://stackoverflow.com/questions/10645994/how-to-format-a-utc-date-as-a-yyyy-mm-dd-hhmmss-string-using-nodejs,361,815198.0,26.0,,,2012-05-18 02:27:30,2024-01-22 04:07:29,2018-09-12 20:20:00,,,javascript;node.js;date,Tampa,78968,1203556,registered,true,13219636,,CC BY-SA 4.0,,208,157,2,0,0,3,true,false,false,true,true,true,72,13,true,0.032,0.0004,5300,2012,5,2,Friday,false,false,true,false,false,false,false
11625519,How to access the request body when POSTing using Node.js and Express?,"I have the following Node.js code:
var express = require('express');
var app = express.createServer(express.logger());
app.use(express.bodyParser());
app.post('/', function(request, response) {
response.write(request.body.user);
response.end();
});
Now if I POST something like:
curl -d user=Someone -H Accept:application/json --url http://localhost:5000
I get Someone as expected. Now, what if I want to get the full request body? I tried doing response.write(request.body) but Node.js throws an exception saying ""first argument must be a string or Buffer"" then goes to an ""infinite loop"" with an exception that says ""Can't set headers after they are sent.""; this also true even if I did var reqBody = request.body; and then writing response.write(reqBody).
What's the issue here?
Also, can I just get the raw request without using express.bodyParser()?
",https://stackoverflow.com/questions/11625519/how-to-access-the-request-body-when-posting-using-node-js-and-express,361,812864.0,18.0,,,2012-07-24 06:47:28,2024-09-30 19:11:47,2015-06-24 05:27:23,,,javascript;node.js;express,TheBlueSky,6008,121097,registered,true,11631664,,CC BY-SA 3.0,,1038,872,7,0,0,3,true,false,false,true,true,true,70,12,true,0.022,0.0004,5233,2012,7,6,Tuesday,false,false,true,false,false,false,false
10656574,How do I manage MongoDB connections in a Node.js web application?,"I'm using the node-mongodb-native driver with MongoDB to write a website.
I have some questions about how to manage connections:
Is it enough using only one MongoDB connection for all requests? Are there any performance issues? If not, can I setup a global connection to use in the whole application?
If not, is it good if I open a new connection when request arrives, and close it when handled the request? Is it expensive to open and close a connection?
Should I use a global connection pool? I hear the driver has a native connection pool. Is it a good choice?
If I use a connection pool, how many connections should be used?
Are there other things I should notice?
",https://stackoverflow.com/questions/10656574/how-do-i-manage-mongodb-connections-in-a-node-js-web-application,361,162803.0,13.0,,,2012-05-18 16:42:34,2023-01-21 06:51:41,2017-01-15 09:47:15,,,node.js;mongodb;database-connection;connection-pooling,Freewind,199358,342235,registered,true,14464750,,CC BY-SA 3.0,2019-02-22 14:11:42,854,673,0,1,0,4,true,false,false,true,true,true,65,11,true,0.08,0.0022,5300,2012,5,16,Friday,false,false,false,false,false,false,false
46415343,Downgrade npm to an older version,"I tried updating npm to see if it would solve some dependency problems we were having, and now I want to downgrade to the version the rest of the development team is using. How can I install an older version?
I updated npm according to the instructions on the About npm CLI versions:
The latest release of npm
The latest release of npm is the most recent stable version. When you install Node.js, npm is automatically installed. However, npm is released more frequently than Node.js, so to install the latest stable version of npm, on the command line, run:
npm install npm@latest -g
",https://stackoverflow.com/questions/46415343/downgrade-npm-to-an-older-version,359,702928.0,6.0,,,2017-09-25 22:54:08,2023-10-21 18:21:26,2022-08-12 14:09:14,,,node.js;npm;installation;downgrade,Don Kirkby,56926,4794,registered,true,46415344,,CC BY-SA 4.0,,838,586,9,1,0,4,true,false,false,true,true,true,33,6,false,0.009,0.0005,3344,2017,9,22,Monday,false,false,false,false,false,false,false
23450534,How to call a Python function from Node.js,"I have an Express Node.js application, but I also have a machine learning algorithm to use in Python. Is there a way I can call Python functions from my Node.js application to make use of the power of machine learning libraries?
",https://stackoverflow.com/questions/23450534/how-to-call-a-python-function-from-node-js,358,373533.0,14.0,,,2014-05-03 22:35:13,2023-12-20 14:43:28,2018-06-03 14:55:08,,,python;node.js;express,Genjuro,7815,978769,registered,true,,,CC BY-SA 4.0,2022-12-07 08:57:06,236,229,0,0,0,3,false,false,false,true,true,true,42,8,false,0.037,0.001,4585,2014,5,22,Saturday,true,true,false,false,false,false,false
32633678,Is there any way to configure multiple registries in a single npmrc file,"Here is my problem. We have a private NPM registry which only works in VPN. I would like to have a fallback registry https://registry.npmjs.org so that when I am out of VPN it works seamlessly.
P.S. Currently I am using npmrc which does a good job in switching between .npmrc files as a workaround
",https://stackoverflow.com/questions/32633678/is-there-any-way-to-configure-multiple-registries-in-a-single-npmrc-file,358,380000.0,14.0,,,2015-09-17 15:01:29,2023-04-17 23:12:48,2022-07-05 08:30:57,,,node.js;npm,Abhijit Mazumder,9724,1614870,registered,true,,,CC BY-SA 4.0,,467,298,1,2,0,2,false,false,false,true,true,true,72,13,false,0.037,0.0009,4083,2015,9,15,Thursday,false,false,false,false,false,false,false
43002444,Make Axios send cookies in its requests automatically,"I am sending requests from the client to my Express.js server using Axios.
I set a cookie on the client and I want to read that cookie from all Axios requests without adding them manually to request by hand.
This is my clientside request example:
axios.get(`some api url`).then(response => ...
I tried to access headers or cookies by using these properties in my Express.js server:
req.headers
req.cookies
Neither of them contained any cookies. I am using cookie parser middleware:
app.use(cookieParser())
How do I make Axios send cookies in requests automatically?
Edit:
I set cookie on the client like this:
import cookieClient from 'react-cookie'
...
let cookie = cookieClient.load('cookie-name')
if(cookie === undefined){
axios.get('path/to/my/cookie/api').then(response => {
if(response.status == 200){
cookieClient.save('cookie-name', response.data, {path:'/'})
}
})
}
...
While it's also using Axios, it is not relevant to the question. I simply want to embed cookies into all my requests once a cookie is set.
",https://stackoverflow.com/questions/43002444/make-axios-send-cookies-in-its-requests-automatically,356,785189.0,25.0,,,2017-03-24 14:44:09,2025-09-15 15:54:07,2017-04-08 10:14:05,,,javascript;node.js;express;cookies;axios,Kunok,8907,5426743,registered,true,43178070,,CC BY-SA 3.0,,1246,1087,4,0,0,5,true,false,false,true,true,true,53,8,false,0.032,0.0005,3529,2017,3,14,Friday,false,false,true,false,false,false,false
33870520,Npm install cannot find module 'semver',"I can't use npm install using the command prompt in NodeJS. I'm getting these errors when running npm install:
module.js:339
throw err;
^
Error: Cannot find module 'semver'
at Function.Module._resolveFilename (module.js:337:15)
at Function.Module._load (module.js:287:25)
at Module.require (module.js:366:17)
at require (module.js:385:17)
at Object.<anonymous> (C:\Users\admin\AppData\Roaming\npm\node_modules\npm\l
ib\config\defaults.js:6:14)
at Module._compile (module.js:435:26)
at Object.Module._extensions..js (module.js:442:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:311:12)
at Module.require (module.js:366:17)
",https://stackoverflow.com/questions/33870520/npm-install-cannot-find-module-semver,353,451059.0,42.0,,,2015-11-23 11:55:03,2024-06-28 22:20:32,2020-05-09 10:54:53,,,javascript;node.js;mean-stack,user2447562,3671,2447562,registered,true,,,CC BY-SA 4.0,2017-01-26 14:29:10,762,705,3,0,0,3,false,false,false,true,true,true,47,6,false,0.093,0.0008,4016,2015,11,11,Monday,false,false,true,false,false,false,false
27465850,TypeError: Router.use() requires middleware function but got a Object,"There have been some middleware changes on the new version of express and I have made some changes in my code around some of the other posts on this issue but I can't get anything to stick.
We had it working before hand but I can't remember what the change was.
throw new TypeError('Router.use() requires middleware function but got a
^
TypeError: Router.use() requires middleware function but got a Object
node ./bin/www
js-bson: Failed to load c++ bson extension, using pure JS version
js-bson: Failed to load c++ bson extension, using pure JS version
/Users/datis/Documents/bb-dashboard/node_modules/express/lib/router/index.js:438
throw new TypeError('Router.use() requires middleware function but got a
^
TypeError: Router.use() requires middleware function but got a Object
at /Users/datis/Documents/bb-dashboard/node_modules/express/lib/router/index.js:438:13
at Array.forEach (native)
at Function.use (/Users/datis/Documents/bb-dashboard/node_modules/express/lib/router/index.js:436:13)
at /Users/datis/Documents/bb-dashboard/node_modules/express/lib/application.js:188:21
at Array.forEach (native)
at Function.use (/Users/datis/Documents/bb-dashboard/node_modules/express/lib/application.js:185:7)
at Object.<anonymous> (/Users/datis/Documents/bb-dashboard/app.js:46:5)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var session = require('express-session');
var MongoClient = require('mongodb').MongoClient;
var routes = require('./routes/index');
var users = require('./routes/users');
var Users = require('./models/user');
var Items = require('./models/item');
var Store = require('./models/store');
var StoreItem = require('./models/storeitem');
var app = express();
//set mongo db connection
var db = mongoose.connection;
MongoClient.connect(""mongodb://localhost:27017/test"", function(err, db) {
if(!err) {
console.log(""We are connected"");
}
});
// var MONGOHQ_URL=""mongodb://localhost:27017/test""
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
secret: 'something',
resave: true,
saveUninitialized: true
}));
app.use('/', routes);
app.use('/users', users);
app.use(express.static(path.join(__dirname, 'public')));
// catch 404 and forward to error handler
// app.use(function(req, res, next) {
// var err = new Error('Not Found');
// err.status = 404;
// next(err);
// });
// Make our db accessible to our router
app.use(function(req, res, next){
req.db = db;
next();
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
It appears the answer to this question has changed for versioning reasons. Thanks to Nik
",https://stackoverflow.com/questions/27465850/typeerror-router-use-requires-middleware-function-but-got-a-object,352,605513.0,18.0,,,2014-12-14 02:45:42,2024-01-09 03:07:36,2016-05-10 12:10:34,,,javascript;node.js;express,Datise,3983,4358503,registered,true,27466117,,CC BY-SA 3.0,2017-05-29 16:04:56,4110,3814,4,1,0,3,true,false,false,true,true,true,69,9,false,0.03,0.0006,4360,2014,12,2,Sunday,true,false,true,false,false,false,false
36856232,Write / add data in JSON file using Node.js,"I am trying to write JSON file using node from loop data, e.g.:
let jsonFile = require('jsonfile');
for (i = 0; i < 11; i++) {
jsonFile.writeFile('loop.json', ""id :"" + i + "" square :"" + i * i);
}
outPut in loop.json is:
id :1 square : 1
but I want output file like this (below) and also if I run that code again it should add that new output as elements in same existing JSON file:
{
""table"":[
{
""Id "":1,
""square "":1
},
{
""Id "":2,
""square "":3
},
{
""Id "":3,
""square "":9
},
{
""Id "":4,
""square "":16
},
{
""Id "":5,
""square "":25
},
{
""Id "":6,
""square "":36
},
{
""Id "":7,
""square "":49
},
{
""Id "":8,
""square "":64
},
{
""Id "":9,
""square "":81
},
{
""Id "":10,
""square "":100
}
]
}
I want to use same file that I created 1st time but whenever I run that code new elements should add in that same file
const fs = require('fs');
let obj = {
table: []
};
fs.exists('myjsonfile.json', function(exists) {
if (exists) {
console.log(""yes file exists"");
fs.readFile('myjsonfile.json', function readFileCallback(err, data) {
if (err) {
console.log(err);
} else {
obj = JSON.parse(data);
for (i = 0; i < 5; i++) {
obj.table.push({
id: i,
square: i * i
});
}
let json = JSON.stringify(obj);
fs.writeFile('myjsonfile.json', json);
}
});
} else {
console.log(""file not exists"");
for (i = 0; i < 5; i++) {
obj.table.push({
id: i,
square: i * i
});
}
let json = JSON.stringify(obj);
fs.writeFile('myjsonfile.json', json);
}
});
",https://stackoverflow.com/questions/36856232/write-add-data-in-json-file-using-node-js,351,870067.0,9.0,,,2016-04-26 05:48:29,2022-10-05 11:25:02,2019-09-24 14:06:12,,,javascript;json;node.js;fs,Isoftmaster,3565,6254448,registered,true,36856787,,CC BY-SA 4.0,,2332,2095,4,0,0,4,true,false,false,true,true,true,43,9,false,0.01,0.0004,3861,2016,4,5,Tuesday,false,false,true,false,false,false,false
14795145,How the single threaded nonblocking I/O model works in Node.js,"I'm not a Node.js programmer, but I'm interested in how the single-threaded nonblocking I/O model works.
After I read the article understanding-the-node-js-event-loop, I'm really confused about it.
It gave an example for the model:
c.query(
'SELECT SLEEP(20);',
function (err, results, fields) {
if (err) {
throw err;
}
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<html><head><title>Hello</title></head><body><h1>Return from async DB query</h1></body></html>');
c.end();
}
);
When there are two requests A (comes first) and B since there is only a single thread, the server-side program will handle the request A firstly: doing SQL querying is asleep statement standing for I/O wait.
And the program is stuck at the I/O waiting, and cannot execute the code which renders the web page behind. Will the program switch to request B during the waiting?
In my opinion, because of the single thread model, there isn’t any way to switch one request from another. But the title of the example code says that everything runs in parallel except your code.
P.S.: I'm not sure if I misunderstand the code or not, since I have
never used Node.js. How does Node.js switch A to B during the waiting? And can you explain the single-threaded nonblocking I/O model of Node.js in a simple way?
",https://stackoverflow.com/questions/14795145/how-the-single-threaded-nonblocking-i-o-model-works-in-node-js,351,117659.0,9.0,,,2013-02-10 05:54:17,2026-03-05 04:46:45,2026-03-05 04:36:18,,,node.js,Wenhao Ji,5171,1122665,registered,true,14797359,,CC BY-SA 4.0,,1628,1394,1,1,0,1,true,false,false,true,true,true,62,10,false,0.076,0.003,5032,2013,2,5,Sunday,true,false,false,false,false,false,false
5809788,How do I remove documents using Node.js Mongoose?,"FBFriendModel.find({
id: 333
}, function (err, docs) {
docs.remove(); //Remove all the documents that match!
});
The above doesn't seem to work. The records are still there.
Can someone fix?
",https://stackoverflow.com/questions/5809788/how-do-i-remove-documents-using-node-js-mongoose,350,586675.0,24.0,,,2011-04-27 19:57:27,2023-01-30 08:59:47,2017-12-06 10:46:04,,,javascript;node.js;mongodb;express;authentication,TIMEX,275634,179736,registered,true,,,CC BY-SA 3.0,,241,203,1,0,0,5,false,false,false,true,true,true,49,8,true,0.041,0.0006,5687,2011,4,19,Wednesday,false,false,true,false,false,false,false
19135867,What is pip's equivalent of `npm install package --save-dev`?,"In nodejs, I can do npm install package --save-dev to save the installed package into the package.
How do I achieve the same thing in Python package manager pip? I would like to save the package name and its version into, say, requirements.pip just after installing the package using something like pip install package --save-dev requirements.pip.
",https://stackoverflow.com/questions/19135867/what-is-pips-equivalent-of-npm-install-package-save-dev,350,169404.0,10.0,,,2013-10-02 11:28:54,2024-12-01 22:49:45,,,,python;node.js;pip,hllau,10621,952901,registered,true,,,CC BY-SA 3.0,,415,349,4,0,0,3,false,false,false,true,true,false,65,9,true,0.059,0.0021,4798,2013,10,11,Wednesday,false,true,false,false,false,false,false
48033841,Test process.env with Jest,"I have an application that depends on environmental variables like:
const APP_PORT = process.env.APP_PORT || 8080;
And I would like to test that for example:
- APP_PORT can be set by a Node.js environment variable.
- or that an Express.js application is running on the port set with
process.env.APP_PORT
How can I achieve this with Jest? Can I set these process.env variables before each test or should I mock it somehow maybe?
",https://stackoverflow.com/questions/48033841/test-process-env-with-jest,347,454568.0,17.0,,,2017-12-30 12:14:21,2023-07-21 18:46:19,2021-01-29 14:00:13,,,node.js;testing;environment-variables;jestjs,Tomasz Mularczyk,36474,4443323,registered,true,48042799,,CC BY-SA 4.0,,634,427,3,1,0,4,true,false,false,true,true,true,26,4,false,0.037,0.0008,3248,2017,12,12,Saturday,true,false,false,false,false,false,false
14040562,How to search in array of object in mongodb,"Suppose the mongodb document(table) 'users' is
{
_id: 1,
name: {
first: 'John',
last: 'Backus'
},
birth: new Date('Dec 03, 1924'),
death: new Date('Mar 17, 2007'),
contribs: ['Fortran', 'ALGOL', 'Backus-Naur Form', 'FP'],
awards: [
{
award: 'National Medal',
year: 1975,
by: 'NSF'
},
{
award: 'Turing Award',
year: 1977,
by: 'ACM'
}
]
}
// ...and other object(person)s
I want to find the person who has the award 'National Medal' and must be awarded in year 1975
There could be other persons who have this award in different years.
How can I find this person using award type and year. So I can get exact person.
",https://stackoverflow.com/questions/14040562/how-to-search-in-array-of-object-in-mongodb,347,350392.0,4.0,,,2012-12-26 12:27:05,2023-02-12 04:06:36,2020-12-17 13:40:50,,,javascript;arrays;node.js;mongodb;express,vcxz,4188,1307971,registered,true,14042310,,CC BY-SA 4.0,,811,766,1,0,0,5,true,false,false,true,true,true,43,9,false,0.011,0.001,5078,2012,12,12,Wednesday,false,false,true,false,false,false,false
21587122,Mocha / Chai expect.to.throw not catching thrown errors,"I'm having issues getting Chai's expect.to.throw to work in a test for my node.js app. The test keeps failing on the thrown error, but If I wrap the test case in try and catch and assert on the caught error, it works.
Does expect.to.throw not work like I think it should or something?
it('should throw an error if you try to get an undefined property', function (done) {
var params = { a: 'test', b: 'test', c: 'test' };
var model = new TestModel(MOCK_REQUEST, params);
// neither of these work
expect(model.get('z')).to.throw('Property does not exist in model schema.');
expect(model.get('z')).to.throw(new Error('Property does not exist in model schema.'));
// this works
try {
model.get('z');
}
catch(err) {
expect(err).to.eql(new Error('Property does not exist in model schema.'));
}
done();
});
The failure:
19 passing (25ms)
1 failing
1) Model Base should throw an error if you try to get an undefined property:
Error: Property does not exist in model schema.
",https://stackoverflow.com/questions/21587122/mocha-chai-expect-to-throw-not-catching-thrown-errors,346,276839.0,7.0,,,2014-02-05 19:52:49,2020-05-24 17:43:52,2015-06-29 12:04:36,,,javascript;node.js;mocha.js;chai,doremi,15439,361833,registered,true,21587239,,CC BY-SA 3.0,,1152,1018,4,0,0,4,true,false,false,true,true,true,55,8,false,0.025,0.0012,4672,2014,2,19,Wednesday,false,false,true,false,false,false,false
6007353,Which ORM should I use for Node.js and MySQL?,"I'm rewriting a project to use Node.js. I'd like to keep using MySQL as the DB (even though I don't mind rewriting the schema).
I'm looking for a simple-to-use, reasonable-performance ORM, which supports caching, many-to-one and many-to-many relations.
From the MySQL ORMs I could find, persistencejs and sequelize seem the most mature.
Do you have experience with either? What are the relevant pros and cons I should be aware of in my decision?
",https://stackoverflow.com/questions/6007353/which-orm-should-i-use-for-node-js-and-mysql,343,236375.0,4.0,,,2011-05-15 08:34:15,2018-11-14 18:14:21,2015-04-25 07:17:42,2012-05-06 12:43:37,not constructive,mysql;orm;node.js,Near Privman,3780,579103,registered,true,7646459,,,,548,447,0,2,0,3,true,true,false,true,true,true,45,9,true,0.017,0.0015,5669,2011,5,8,Sunday,true,false,false,false,false,false,false
8817423,Why is __dirname not defined in node REPL?,"From the node manual I see that I can get the directory of a file with __dirname, but from the REPL this seems to be undefined. Is this a misunderstanding on my side or where is the error?
$ node
> console.log(__dirname)
ReferenceError: __dirname is not defined
at repl:1:14
at REPLServer.eval (repl.js:80:21)
at Interface.<anonymous> (repl.js:182:12)
at Interface.emit (events.js:67:17)
at Interface._onLine (readline.js:162:10)
at Interface._line (readline.js:426:8)
at Interface._ttyWrite (readline.js:603:14)
at ReadStream.<anonymous> (readline.js:82:12)
at ReadStream.emit (events.js:88:20)
at ReadStream._emitKey (tty.js:320:10)
",https://stackoverflow.com/questions/8817423/why-is-dirname-not-defined-in-node-repl,342,365471.0,15.0,,,2012-01-11 10:05:46,2024-04-09 06:34:30,2020-08-25 10:39:27,,,node.js,topskip,17775,317915,registered,true,8817507,,CC BY-SA 4.0,2023-02-26 16:58:29,736,692,2,0,0,1,true,false,false,true,true,true,42,8,true,0.041,0.0009,5428,2012,1,10,Wednesday,false,false,false,false,false,false,false
17254008,Stop Mongoose from creating _id property for sub-document array items,"If you have subdocument arrays, Mongoose automatically creates ids for each one. Example:
{
_id: ""mainId""
subDocArray: [
{
_id: ""unwantedId"",
field: ""value""
},
{
_id: ""unwantedId"",
field: ""value""
}
]
}
Is there a way to tell Mongoose to not create ids for objects within an array?
",https://stackoverflow.com/questions/17254008/stop-mongoose-from-creating-id-property-for-sub-document-array-items,342,150696.0,8.0,,,2013-06-22 18:28:35,2024-01-21 11:07:53,2019-03-19 15:17:29,,,node.js;mongodb;mongoose;subdocument,Atlas,3523,2355787,registered,true,17254148,,CC BY-SA 4.0,,390,352,1,0,0,4,true,false,false,true,true,true,69,10,false,0.053,0.0023,4900,2013,6,18,Saturday,true,false,false,false,false,false,false
15604140,Replace multiple strings with multiple other strings,"I'm trying to replace multiple words in a string with multiple other words. The string is ""I have a cat, a dog, and a goat.""
However, this does not produce ""I have a dog, a goat, and a cat"", but instead it produces ""I have a cat, a cat, and a cat"". Is it possible to replace multiple strings with multiple other strings at the same time in JavaScript, so that the correct result will be produced?
var str = ""I have a cat, a dog, and a goat."";
str = str.replace(/cat/gi, ""dog"");
str = str.replace(/dog/gi, ""goat"");
str = str.replace(/goat/gi, ""cat"");
//this produces ""I have a cat, a cat, and a cat""
//but I wanted to produce the string ""I have a dog, a goat, and a cat"".
",https://stackoverflow.com/questions/15604140/replace-multiple-strings-with-multiple-other-strings,341,504318.0,28.0,,,2013-03-24 21:19:55,2023-08-09 14:42:40,2018-09-17 06:42:44,,,javascript;node.js;regex;string;replace,Anderson Green,32190,975097,registered,true,67374697,,CC BY-SA 4.0,2023-08-10 09:20:23,713,675,1,0,0,5,true,false,false,true,true,true,52,7,false,0.056,0.0007,4990,2013,3,21,Sunday,true,false,true,false,false,false,false
27350634,How to yum install Node.js on Amazon Linux,"I've seen the write-up on using yum to install the dependencies, and then installing Node.js and NPM from source. While this does work, I feel like Node.js and NPM should both be in a public repository somewhere.
How can I install Node.js and NPM in one command on AWS Amazon Linux?
",https://stackoverflow.com/questions/27350634/how-to-yum-install-node-js-on-amazon-linux,340,264187.0,21.0,,,2014-12-08 02:46:50,2024-04-26 05:38:39,2024-04-26 01:06:48,,,node.js;amazon-web-services;npm;yum;amazon-linux,Tim Fulmer,20758,752693,registered,true,27350635,,CC BY-SA 4.0,2016-04-13 09:19:14,298,284,0,0,0,5,true,false,false,true,true,true,42,8,false,0.079,0.0013,4366,2014,12,2,Monday,false,false,false,false,false,false,false
51634361,How to force tsc to ignore node_modules folder?,"I'm using tsc build tasks. Unfortunately I'm always getting the same errors from the node modules folder
Executing task: .\node_modules\.bin\tsc.cmd --watch -p .\tsconfig.json <
node_modules/@types/node/index.d.ts(6208,55): error TS2304: Cannot find name 'Map'.
node_modules/@types/node/index.d.ts(6215,55): error TS2304: Cannot find name 'Set'.
node_modules/@types/node/index.d.ts(6219,64): error TS2304: Cannot find name 'Symbol'.
node_modules/@types/node/index.d.ts(6225,59): error TS2304: Cannot find name 'WeakMap'.
node_modules/@types/node/index.d.ts(6226,59): error TS2304: Cannot find name 'WeakSet'.
10:13:18 - Compilation complete. Watching for file changes.
I already added the directory to the ignore at tsconfig.json
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"sourceMap": true,
"strict": false,
"noImplicitAny": false,
"strictPropertyInitialization": false,
"esModuleInterop": true,
},
"include": [
"src/*"
],
"exclude": [
"node_modules",
"./node_modules",
"./node_modules/*",
"./node_modules/@types/node/index.d.ts",
]
}
What I'm doing wrong? What should I do in order to ignore those errors?
I'm using VSCode and tsc Version 2.9.2.
",https://stackoverflow.com/questions/51634361/how-to-force-tsc-to-ignore-node-modules-folder,340,299801.0,18.0,,,2018-08-01 13:18:28,2026-01-19 08:48:03,2024-04-24 03:08:14,,,node.js;typescript;tsc;tsconfig,Daniel Santos,16696,888469,registered,true,,,CC BY-SA 4.0,2024-04-24 02:53:43,1569,1402,3,0,0,4,false,false,false,true,true,true,47,8,true,0.06,0.0011,3034,2018,8,13,Wednesday,false,false,false,false,false,false,false
8367031,How do I install package.json dependencies in the current directory using npm,"I have a web app: fooapp. I have a package.json in the root. I want to install all the dependencies in a specific node_modules directory. How do I do this?
What I want
Lets say I have two widget dependencies. I want to end up with a directory structure like this:
node_modules/
widgetA
widgetB
fooapp/
package.js
lib
..
What I get
when I run npm install fooapp/ I get this:
node_modules/
fooapp/
node_modules/
widgetA
widgetB
package.js
lib/
..
fooapp/
package.js
lib/
..
npm makes a copy of my app directory in the node_modules dir and installs the packages inside another node_modules directory.
I understand this makes sense for installing a package. But I don't require() my web app inside of something else, I run it directly. I'm looking for a simple way to install my dependencies into a specific node_modules directory.
",https://stackoverflow.com/questions/8367031/how-do-i-install-package-json-dependencies-in-the-current-directory-using-npm,338,682670.0,4.0,,,2011-12-03 10:26:09,2022-12-27 08:45:00,2012-09-13 00:51:01,,,deployment;node.js;dependencies;npm,Daniel Beardsley,20508,13216,registered,true,8374526,,CC BY-SA 3.0,,1080,888,7,0,0,4,true,false,false,true,true,true,77,12,false,0.006,0.0005,5467,2011,12,10,Saturday,true,false,false,false,false,false,false
16383795,Difference between "module.exports" and "exports" in the CommonJs Module System,"On this page (http://docs.nodejitsu.com/articles/getting-started/what-is-require), it states that "If you want to set the exports object to a function or a new object, you have to use the module.exports object."
My question is why.
// right
module.exports = function () {
console.log("hello world")
}
// wrong
exports = function () {
console.log("hello world")
}
I console.logged the result (result=require(example.js)) and the first one is [Function] the second one is {}.
Could you please explain the reason behind it? I read the post here: module.exports vs exports in Node.js . It is helpful, but does not explain the reason why it is designed in that way. Will there be a problem if the reference of exports be returned directly?
",https://stackoverflow.com/questions/16383795/difference-between-module-exports-and-exports-in-the-commonjs-module-system,337,167492.0,9.0,,,2013-05-05 10:59:26,2025-12-04 17:48:30,2020-09-03 04:26:58,,,javascript;node.js;commonjs,Peng Xiao,12017,529187,registered,true,16383925,,CC BY-SA 4.0,,1096,770,4,2,0,3,true,false,false,true,true,true,99,10,false,0.054,0.002,4948,2013,5,10,Sunday,true,false,true,false,false,false,false
10865347,Node.js get file extension,"Im creating a file upload function in node.js with express 3.
I would like to grab the file extension of the image. so i can rename the file and then append the file extension to it.
app.post('/upload', function(req, res, next) {
var is = fs.createReadStream(req.files.upload.path),
fileExt = '', // I want to get the extension of the image here
os = fs.createWriteStream('public/images/users/' + req.session.adress + '.' + fileExt);
});
How can i get the extension of the image in node.js?
",https://stackoverflow.com/questions/10865347/node-js-get-file-extension,336,368428.0,16.0,,,2012-06-02 19:37:10,2023-05-18 07:06:55,2019-06-21 07:48:15,,,javascript;node.js;file-type,georgesamper,5189,416443,registered,true,15778396,,CC BY-SA 4.0,,560,515,1,0,0,3,true,false,false,true,true,true,26,4,false,0.043,0.0009,5285,2012,6,19,Saturday,true,false,true,false,false,false,false
23199392,Difference between MEAN.js and MEAN.io,"I wanted to use the MEAN JavaScript Stack, but I noticed that there are two different stacks with either their own website and installation methods: mean.js and mean.io. So I came up asking myself this question: ""Which one do I use?"".
So in order to answer this question I ask the community if you could explain what are the differences between these two? And if possible pros and cons? Because they look very similar to me.
",https://stackoverflow.com/questions/23199392/difference-between-mean-js-and-mean-io,336,111115.0,5.0,,,2014-04-21 14:26:01,2017-08-22 15:41:04,2014-07-21 13:05:59,,,javascript;node.js;angularjs;web-applications;mean-stack,CMPSoares,4205,3555155,registered,true,23206972,,CC BY-SA 3.0,2014-12-14 14:50:44,440,426,0,0,0,5,true,false,false,true,true,true,38,5,false,0.045,0.003,4597,2014,4,14,Monday,false,false,true,false,false,false,false
53645882,Pandas Merging 101,"
- How can I perform a (
INNER| (LEFT|RIGHT|FULL) OUTER) JOIN with pandas?
- How do I add NaNs for missing rows after a merge?
- How do I get rid of NaNs after merging?
- Can I merge on the index?
- How do I merge multiple DataFrames?
- Cross join with pandas
merge? join? concat? update? Who? What? Why?!
... and more. I've seen these recurring questions asking about various facets of the pandas merge functionality. Most of the information regarding merge and its various use cases today is fragmented across dozens of badly worded, unsearchable posts. The aim here is to collate some of the more important points for posterity.
This Q&A is meant to be the next installment in a series of helpful user guides on common pandas idioms (see this post on pivoting, and this post on concatenation, which I will be touching on, later).
Please note that this post is not meant to be a replacement for the documentation, so please read that as well! Some of the examples are taken from there.
Table of Contents
For ease of access.
Merging basics - basic types of joins (read this first)
-
-
-
",https://stackoverflow.com/questions/53645882/pandas-merging-101,954,470274.0,8.0,,,2018-12-06 06:41:15,2026-01-26 21:08:02,2021-07-31 17:38:31,,,python;pandas;join;merge;concatenation,coldspeed95,407735,4909087,registered,true,53645883,,CC BY-SA 4.0,2020-01-14 17:14:09,2037,1146,10,7,0,5,true,false,false,true,true,true,18,3,false,0.017,0.002,2907,2018,12,6,Thursday,false,true,false,false,false,false,false
13784192,"Creating an empty Pandas DataFrame, and then filling it","I'm starting from the pandas DataFrame documentation here: Introduction to data structures
I'd like to iteratively fill the DataFrame with values in a time series kind of calculation. I'd like to initialize the DataFrame with columns A, B, and timestamp rows, all 0 or all NaN.
I'd then add initial values and go over this data calculating the new row from the row before, say row[A][t] = row[A][t-1]+1 or so.
I'm currently using the code as below, but I feel it's kind of ugly and there must be a way to do this with a DataFrame directly or just a better way in general.
import pandas as pd
import datetime as dt
import scipy as s
base = dt.datetime.today().date()
dates = [ base - dt.timedelta(days=x) for x in range(9, -1, -1) ]
valdict = {}
symbols = ['A','B', 'C']
for symb in symbols:
valdict[symb] = pd.Series( s.zeros(len(dates)), dates )
for thedate in dates:
if thedate > dates[0]:
for symb in valdict:
valdict[symb][thedate] = 1 + valdict[symb][thedate - dt.timedelta(days=1)]
",https://stackoverflow.com/questions/13784192/creating-an-empty-pandas-dataframe-and-then-filling-it,929,2657482.0,8.0,,,2012-12-09 02:50:38,2024-04-26 21:35:43,2024-04-26 20:50:02,,,python;pandas;dataframe,Matthias Kauer,10647,1707931,registered,true,13786327,,CC BY-SA 4.0,2018-05-17 07:29:25,1222,1023,2,1,0,3,true,false,false,true,true,true,55,9,false,0.003,0.0003,5095,2012,12,2,Sunday,true,true,false,false,false,false,false
11350770,Filter pandas DataFrame by substring criteria,"I have a pandas DataFrame with a column of string values. I need to select rows based on partial string matches.
Something like this idiom:
re.search(pattern, cell_in_question)
returning a boolean. I am familiar with the syntax of df[df['A'] == "hello world"] but can't seem to find a way to do the same with a partial string match, say 'hello'.
",https://stackoverflow.com/questions/11350770/filter-pandas-dataframe-by-substring-criteria,928,1613462.0,18.0,,,2012-07-05 18:57:34,2023-11-22 19:38:00,2023-11-22 19:38:00,,,python;pandas;regex;string;dataframe,euforia,9355,1170342,registered,true,,,CC BY-SA 4.0,2019-06-14 19:15:11,466,358,3,0,0,5,false,false,false,true,true,true,45,6,false,0.011,0.0006,5252,2012,7,18,Thursday,false,true,false,false,false,false,false
36921951,"Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()","I want to filter my dataframe with an or condition to keep rows with a particular column's values that are outside the range [-0.25, 0.25]. I tried:
df = df[(df['col'] < -0.25) or (df['col'] > 0.25)]
But I get the error:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
",https://stackoverflow.com/questions/36921951/truth-value-of-a-series-is-ambiguous-use-a-empty-a-bool-a-item-a-any-o,907,2644974.0,15.0,,,2016-04-28 17:46:30,2025-06-18 17:28:11,2025-06-18 17:28:11,,,python;pandas;filter;conditional-statements;valueerror,obabs,9361,6267003,registered,true,36922103,,CC BY-SA 4.0,2019-07-03 22:12:38,433,337,3,0,0,5,true,false,false,true,true,true,89,14,false,0.006,0.0003,3859,2016,4,17,Thursday,false,true,false,false,false,false,false
29576430,Shuffle DataFrame rows,"I have the following DataFrame:
Col1 Col2 Col3 Type
0 1 2 3 1
1 4 5 6 1
...
20 7 8 9 2
21 10 11 12 2
...
45 13 14 15 3
46 16 17 18 3
...
The DataFrame is read from a CSV file. All rows which have Type 1 are on top, followed by the rows with Type 2, followed by the rows with Type 3, etc.
I would like to shuffle the order of the DataFrame's rows so that all Type's are mixed. A possible result could be:
Col1 Col2 Col3 Type
0 7 8 9 2
1 13 14 15 3
...
20 1 2 3 1
21 10 11 12 2
...
45 4 5 6 1
46 16 17 18 3
...
How can I achieve this?
",https://stackoverflow.com/questions/29576430/shuffle-dataframe-rows,905,981739.0,15.0,,,2015-04-11 09:47:57,2024-09-16 13:16:27,2022-03-12 07:04:50,,,python;pandas;dataframe;permutation;shuffle,JNevens,12162,1833854,registered,true,34879805,,CC BY-SA 4.0,,855,727,6,0,0,5,true,false,false,true,true,true,22,3,false,0.015,0.0009,4242,2015,4,9,Saturday,true,true,false,false,false,false,false
19960077,How to filter Pandas dataframe using 'in' and 'not in' like in SQL,"How can I achieve the equivalents of SQL's IN and NOT IN?
I have a list with the required values. Here's the scenario:
df = pd.DataFrame({'country': ['US', 'UK', 'Germany', 'China']})
countries_to_keep = ['UK', 'China']
# pseudo-code:
df[df['country'] not in countries_to_keep]
My current way of doing this is as follows:
df = pd.DataFrame({'country': ['US', 'UK', 'Germany', 'China']})
df2 = pd.DataFrame({'country': ['UK', 'China'], 'matched': True})
# IN
df.merge(df2, how='inner', on='country')
# NOT IN
not_in = df.merge(df2, how='left', on='country')
not_in = not_in[pd.isnull(not_in['matched'])]
But this seems like a horrible kludge. Can anyone improve on it?
",https://stackoverflow.com/questions/19960077/how-to-filter-pandas-dataframe-using-in-and-not-in-like-in-sql,898,1400728.0,12.0,,,2013-11-13 17:11:07,2025-03-21 21:09:49,2025-03-21 21:09:49,,,python;pandas;dataframe;indexing;filter,LondonRob,79945,2071807,registered,true,19960116,,CC BY-SA 4.0,2020-12-21 18:01:26,849,673,4,0,0,5,true,false,false,true,true,true,82,13,false,0.009,0.0006,4756,2013,11,17,Wednesday,false,true,false,false,false,false,false
17839973,"Constructing DataFrame from values in variables yields "ValueError: If using all scalar values, you must pass an index"","I have two variables as follows.
a = 2
b = 3
I want to construct a DataFrame from this:
df2 = pd.DataFrame({'A':a, 'B':b})
This generates an error:
ValueError: If using all scalar values, you must pass an index
I tried this also:
df2 = (pd.DataFrame({'a':a, 'b':b})).reset_index()
This gives the same error message. How do I do what I want?
",https://stackoverflow.com/questions/17839973/constructing-dataframe-from-values-in-variables-yields-valueerror-if-using-all,871,1588122.0,24.0,,,2013-07-24 16:40:24,2025-04-16 04:15:56,2025-04-16 04:15:56,,,python;pandas;dataframe;constructor;valueerror,Nilani Algiriyage,36166,461436,registered,true,17840195,,CC BY-SA 4.0,,626,345,4,0,0,5,true,false,false,true,true,true,129,18,false,0.015,0.0005,4868,2013,7,16,Wednesday,false,true,false,false,false,false,false
20461165,How to convert index of a pandas dataframe into a column,"How to convert an index of a dataframe into a column?
For example:
gi ptt_loc
0 384444683 593
1 384444684 594
2 384444686 596
to
index1 gi ptt_loc
0 0 384444683 593
1 1 384444684 594
2 2 384444686 596
",https://stackoverflow.com/questions/20461165/how-to-convert-index-of-a-pandas-dataframe-into-a-column,862,1387470.0,11.0,,,2013-12-09 00:34:16,2025-04-19 03:48:04,2025-04-19 03:48:04,,,python;pandas;dataframe;join;indexing,msakya,9891,1090629,registered,true,20461206,,CC BY-SA 4.0,2024-01-31 19:50:47,441,294,2,0,0,5,true,false,false,true,true,true,56,11,false,0.008,0.0006,4730,2013,12,0,Monday,false,true,false,false,false,false,false
26266362,How do I count the NaN values in a column in pandas DataFrame?,"I want to find the number of NaN in each column of my data.
",https://stackoverflow.com/questions/26266362/how-do-i-count-the-nan-values-in-a-column-in-pandas-dataframe,826,1638092.0,33.0,,,2014-10-08 21:00:19,2024-08-02 07:31:41,2022-07-17 06:40:47,,,python;pandas;dataframe,user3799307,8269,3799307,registered,true,,,CC BY-SA 4.0,2022-02-22 18:44:00,80,60,1,0,0,3,false,false,false,true,true,true,62,13,true,0.02,0.0005,4427,2014,10,21,Wednesday,false,true,false,false,false,false,false
19384532,"Get statistics for each group (such as count, mean, etc) using pandas GroupBy?","I have a dataframe df and I use several columns from it to groupby:
df[['col1','col2','col3','col4']].groupby(['col1','col2']).mean()
In the above way, I almost get the table (dataframe) that I need. What is missing is an additional column that contains number of rows in each group. In other words, I have mean but I also would like to know how many were used to get these means. For example in the first group there are 8 values and in the second one 10 and so on.
In short: How do I get group-wise statistics for a dataframe?
",https://stackoverflow.com/questions/19384532/get-statistics-for-each-group-such-as-count-mean-etc-using-pandas-groupby,822,1763549.0,13.0,,,2013-10-15 15:00:12,2025-09-25 14:47:01,2025-09-25 14:45:01,,,python;pandas;dataframe;group-by;statistics,Roman,132560,245549,registered,true,19385591,,CC BY-SA 4.0,2019-06-08 22:55:35,655,530,3,0,0,5,true,false,false,true,true,true,78,13,true,0.007,0.0005,4785,2013,10,15,Tuesday,false,true,false,false,false,false,false
13842088,Set value for particular cell in pandas DataFrame using index,"I have created a Pandas DataFrame
df = DataFrame(index=['A','B','C'], columns=['x','y'])
Now, I would like to assign a value to particular cell, for example to row C and column x. In other words, I would like to perform the following transformation:
x y x y
A NaN NaN A NaN NaN
B NaN NaN ⟶ B NaN NaN
C NaN NaN C 10 NaN
with this code:
df.xs('C')['x'] = 10
However, the contents of df has not changed. The dataframe contains yet again only NaNs. How do I what I want?
",https://stackoverflow.com/questions/13842088/set-value-for-particular-cell-in-pandas-dataframe-using-index,804,1855468.0,25.0,,,2012-12-12 14:40:45,2023-09-27 19:47:19,2023-09-27 19:47:19,,,python;pandas;dataframe;cell;nan,Mitkp,8117,1675248,registered,true,13842286,,CC BY-SA 4.0,2018-10-16 07:36:15,789,524,7,0,0,5,true,false,false,true,true,true,61,10,false,0.013,0.0004,5092,2012,12,14,Wednesday,false,true,false,false,false,false,false
20906474,Import multiple CSV files into pandas and concatenate into one DataFrame,"I would like to read several CSV files from a directory into pandas and concatenate them into one big DataFrame. I have not been able to figure it out though. Here is what I have so far:
import glob
import pandas as pd
# Get data file names
path = r'C:\DRO\DCL_rawdata_files'
filenames = glob.glob(path + "/*.csv")
dfs = []
for filename in filenames:
dfs.append(pd.read_csv(filename))
# Concatenate all data into one DataFrame
big_frame = pd.concat(dfs, ignore_index=True)
I guess I need some help within the for loop?
",https://stackoverflow.com/questions/20906474/import-multiple-csv-files-into-pandas-and-concatenate-into-one-dataframe,781,1047671.0,20.0,,,2014-01-03 15:00:46,2023-02-16 19:13:06,2022-09-04 23:16:36,,,python;pandas;csv;dataframe;concatenation,jonas,14049,2219369,registered,true,21232849,,CC BY-SA 4.0,2017-03-17 19:19:38,584,537,1,0,0,5,true,false,false,true,true,true,72,11,false,0.019,0.0007,4705,2014,1,15,Friday,false,true,false,false,false,false,false
20845213,How to avoid pandas creating an index in a saved csv,"I am trying to save a csv to a folder after making some edits to the file.
Every time I use pd.to_csv('C:/Path of file.csv') the csv file has a separate column of indexes. I want to avoid printing the index to csv.
I tried:
pd.read_csv('C:/Path to file to edit.csv', index_col = False)
And to save the file...
pd.to_csv('C:/Path to save edited file.csv', index_col = False)
However, I still got the unwanted index column. How can I avoid this when I save my files?
",https://stackoverflow.com/questions/20845213/how-to-avoid-pandas-creating-an-index-in-a-saved-csv,781,917504.0,6.0,,,2013-12-30 18:24:25,2022-09-08 22:11:05,2022-09-08 22:11:05,,,python;csv;indexing;pandas,Alexis,9251,3137488,registered,true,,,CC BY-SA 4.0,2019-11-23 05:35:50,571,475,3,0,0,4,false,false,false,true,true,true,52,11,false,0.007,0.0009,4709,2013,12,18,Monday,false,true,false,false,false,false,false
13331698,How to apply a function to two columns of Pandas dataframe,"Suppose I have a function and a dataframe defined as below:
def get_sublist(sta, end):
return mylist[sta:end+1]
df = pd.DataFrame({'ID':['1','2','3'], 'col_1': [0,2,3], 'col_2':[1,4,5]})
mylist = ['a','b','c','d','e','f']
Now I want to apply get_sublist to df's two columns 'col_1', 'col_2' to element-wise calculate a new column 'col_3' to get an output that looks like:
ID col_1 col_2 col_3
0 1 0 1 ['a', 'b']
1 2 2 4 ['c', 'd', 'e']
2 3 3 5 ['d', 'e', 'f']
I tried:
df['col_3'] = df[['col_1','col_2']].apply(get_sublist, axis=1)
but this results in the following: error:
TypeError: get_sublist() missing 1 required positional argument:
How do I do this?
",https://stackoverflow.com/questions/13331698/how-to-apply-a-function-to-two-columns-of-pandas-dataframe,768,1250035.0,16.0,,,2012-11-11 13:48:53,2024-08-21 19:15:15,2024-08-21 19:15:15,,,python;pandas;dataframe;function;typeerror,bigbug,60024,1072888,registered,true,,,CC BY-SA 4.0,2019-07-20 09:41:08,1027,723,7,0,0,5,false,false,false,true,true,true,58,11,false,0.013,0.0006,5123,2012,11,13,Sunday,true,true,false,false,false,false,false
19798153,"Difference between map, applymap and apply methods in Pandas","Can you tell me when to use these vectorization methods with basic examples?
I see that map is a Series method whereas the rest are DataFrame methods. I got confused about apply and applymap methods though. Why do we have two methods for applying a function to a DataFrame? Again, simple examples which illustrate the usage would be great!
",https://stackoverflow.com/questions/19798153/difference-between-map-applymap-and-apply-methods-in-pandas,759,579712.0,12.0,,,2013-11-05 20:20:14,2023-11-16 08:03:04,2019-01-20 17:07:45,,,python;pandas;dataframe;vectorization,marillion,11280,1505259,registered,true,56300992,,CC BY-SA 4.0,2019-05-29 00:40:36,421,342,5,0,0,4,true,false,false,true,true,true,60,9,false,0.021,0.0013,4764,2013,11,20,Tuesday,false,true,false,false,false,false,false
16729574,How can I get a value from a cell of a dataframe?,"I have constructed a condition that extracts exactly one row from my dataframe:
d2 = df[(df['l_ext']==l_ext) & (df['item']==item) & (df['wn']==wn) & (df['wd']==1)]
Now I would like to take a value from a particular column:
val = d2['col_name']
But as a result, I get a dataframe that contains one row and one column (i.e., one cell). It is not what I need. I need one value (one float number). How can I do it in pandas?
",https://stackoverflow.com/questions/16729574/how-can-i-get-a-value-from-a-cell-of-a-dataframe,756,2811979.0,19.0,,,2013-05-24 07:17:06,2025-01-10 22:54:16,2025-01-10 22:54:16,,,python;pandas;dataframe;indexing;filter,Roman,132560,245549,registered,true,16729808,,CC BY-SA 4.0,,578,435,2,0,0,5,true,false,false,true,true,true,49,12,true,0.007,0.0003,4929,2013,5,7,Friday,false,true,false,false,false,false,false
29530232,How to check if any value is NaN in a Pandas DataFrame,"How do I check whether a pandas DataFrame has NaN values?
I know about pd.isnan but it returns a DataFrame of booleans. I also found this post but it doesn't exactly answer my question either.
",https://stackoverflow.com/questions/29530232/how-to-check-if-any-value-is-nan-in-a-pandas-dataframe,754,1700643.0,30.0,,,2015-04-09 05:09:39,2024-11-24 17:38:42,2023-12-07 23:18:47,,,python;pandas;dataframe;nan,hlin117,22608,2014591,registered,true,29530601,,CC BY-SA 4.0,,306,193,1,1,0,4,true,false,false,true,true,true,54,12,false,0.018,0.0004,4244,2015,4,5,Thursday,false,true,false,false,false,false,false
19828822,How do I check if a pandas DataFrame is empty?,"How do I check if a pandas DataFrame is empty? I'd like to print some message in the terminal if the DataFrame is empty.
",https://stackoverflow.com/questions/19828822/how-do-i-check-if-a-pandas-dataframe-is-empty,721,1104050.0,6.0,,,2013-11-07 05:45:35,2025-04-25 04:34:41,2025-04-25 04:34:41,,,python;pandas;dataframe;membership;any,Nilani Algiriyage,36166,461436,registered,true,19828967,,CC BY-SA 4.0,,154,121,2,0,0,5,true,false,false,true,true,true,46,10,true,0.005,0.0007,4762,2013,11,5,Thursday,false,true,false,false,false,false,false
18171739,UnicodeDecodeError when reading CSV file in Pandas,"I'm running a program which is processing 30,000 similar files. A random number of them are stopping and producing this error...
File "C:\Importer\src\dfman\importer.py", line 26, in import_chr
data = pd.read_csv(filepath, names=fields)
File "C:\Python33\lib\site-packages\pandas\io\parsers.py", line 400, in parser_f
return _read(filepath_or_buffer, kwds)
File "C:\Python33\lib\site-packages\pandas\io\parsers.py", line 205, in _read
return parser.read()
File "C:\Python33\lib\site-packages\pandas\io\parsers.py", line 608, in read
ret = self._engine.read(nrows)
File "C:\Python33\lib\site-packages\pandas\io\parsers.py", line 1028, in read
data = self._reader.read(nrows)
File "parser.pyx", line 706, in pandas.parser.TextReader.read (pandas\parser.c:6745)
File "parser.pyx", line 728, in pandas.parser.TextReader._read_low_memory (pandas\parser.c:6964)
File "parser.pyx", line 804, in pandas.parser.TextReader._read_rows (pandas\parser.c:7780)
File "parser.pyx", line 890, in pandas.parser.TextReader._convert_column_data (pandas\parser.c:8793)
File "parser.pyx", line 950, in pandas.parser.TextReader._convert_tokens (pandas\parser.c:9484)
File "parser.pyx", line 1026, in pandas.parser.TextReader._convert_with_dtype (pandas\parser.c:10642)
File "parser.pyx", line 1046, in pandas.parser.TextReader._string_convert (pandas\parser.c:10853)
File "parser.pyx", line 1278, in pandas.parser._string_box_utf8 (pandas\parser.c:15657)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xda in position 6: invalid continuation byte
The source/creation of these files all come from the same place. What's the best way to correct this to proceed with the import?
",https://stackoverflow.com/questions/18171739/unicodedecodeerror-when-reading-csv-file-in-pandas,718,1128222.0,27.0,,,2013-08-11 12:06:25,2026-01-21 14:31:58,2023-04-05 04:04:33,,,python;pandas;csv;dataframe;unicode,TravisVOX,21781,867549,registered,true,18172249,,CC BY-SA 4.0,2019-10-08 04:33:06,1916,1839,1,0,0,5,true,false,false,true,true,true,50,7,false,0.024,0.0006,4850,2013,8,12,Sunday,true,true,false,false,false,false,false
18039057,pandas.parser.CParserError: Error tokenizing data,"I'm trying to use pandas to manipulate a .csv file but I get this error:
pandas.parser.CParserError: Error tokenizing data. C error: Expected 2 fields in line 3, saw 12
I have tried to read the pandas docs, but found nothing.
My code is simple:
path = 'GOOG Key Ratios.csv'
#print(open(path).read())
data = pd.read_csv(path)
How can I resolve this? Should I use the csv module or another language?
",https://stackoverflow.com/questions/18039057/pandas-parser-cparsererror-error-tokenizing-data,717,2288723.0,51.0,,,2013-08-04 01:54:45,2024-11-07 03:08:41,2023-10-15 02:10:01,,,python;csv;pandas,abuteau,7501,2649671,registered,true,18129082,,CC BY-SA 4.0,2019-01-08 13:26:12,499,402,2,0,0,3,true,false,false,true,true,true,49,4,false,0.022,0.0003,4857,2013,8,1,Sunday,true,true,false,false,false,false,false
13187778,Convert Pandas dataframe to NumPy array,"How do I convert a Pandas dataframe into a NumPy array?
import numpy as np
import pandas as pd
df = pd.DataFrame(
{
'A': [np.nan, np.nan, np.nan, 0.1, 0.1, 0.1, 0.1],
'B': [0.2, np.nan, 0.2, 0.2, 0.2, np.nan, np.nan],
'C': [np.nan, 0.5, 0.5, np.nan, 0.5, 0.5, np.nan],
},
index=[1, 2, 3, 4, 5, 6, 7],
).rename_axis('ID')
That gives this DataFrame:
A B C
ID
1 NaN 0.2 NaN
2 NaN NaN 0.5
3 NaN 0.2 0.5
4 0.1 0.2 NaN
5 0.1 0.2 0.5
6 0.1 NaN 0.5
7 0.1 NaN NaN
I would like to convert this to a NumPy array, like so:
array([[ nan, 0.2, nan],
[ nan, nan, 0.5],
[ nan, 0.2, 0.5],
[ 0.1, 0.2, nan],
[ 0.1, 0.2, 0.5],
[ 0.1, nan, 0.5],
[ 0.1, nan, nan]])
Also, is it possible to preserve the dtypes, like this?
array([[ 1, nan, 0.2, nan],
[ 2, nan, nan, 0.5],
[ 3, nan, 0.2, 0.5],
[ 4, 0.1, 0.2, nan],
[ 5, 0.1, 0.2, 0.5],
[ 6, 0.1, nan, 0.5],
[ 7, 0.1, nan, nan]],
dtype=[('ID', '<i4'), ('A', '<f8'), ('B', '<f8'), ('B', '<f8')])
",https://stackoverflow.com/questions/13187778/convert-pandas-dataframe-to-numpy-array,717,1732844.0,17.0,,,2012-11-02 00:57:33,2024-12-28 23:42:35,2024-12-28 23:42:35,,,python;arrays;pandas;numpy;dataframe,Mister Nobody,7187,1792954,registered,true,,,CC BY-SA 4.0,2018-04-22 04:06:13,1449,1165,4,0,0,5,false,false,false,true,true,true,39,6,false,0.01,0.0004,5132,2012,11,0,Friday,false,true,false,false,false,false,false
37787698,How to sort pandas dataframe by one column,"I have a dataframe like this:
0 1 2
0 354.7 April 4.0
1 55.4 August 8.0
2 176.5 December 12.0
3 95.5 February 2.0
4 85.6 January 1.0
5 152 July 7.0
6 238.7 June 6.0
7 104.8 March 3.0
8 283.5 May 5.0
9 278.8 November 11.0
10 249.6 October 10.0
11 212.7 September 9.0
As you can see, months are not in calendar order. So I created a second column to get the month number corresponding to each month (1-12). From there, how can I sort this dataframe according to calendar months' order?
",https://stackoverflow.com/questions/37787698/how-to-sort-pandas-dataframe-by-one-column,717,1463839.0,15.0,,,2016-06-13 10:44:09,2025-03-18 18:13:57,2023-11-09 00:15:05,,,python;pandas;dataframe;sorting;datetime,Sachila Ranawaka,41651,6428638,registered,true,37787724,,CC BY-SA 4.0,,678,601,1,0,0,5,true,false,false,true,true,true,42,8,false,0.01,0.0005,3813,2016,6,10,Monday,false,true,false,false,false,false,false
13851535,How to delete rows from a pandas DataFrame based on a conditional expression,"I have a pandas DataFrame and I want to delete rows from it where the length of the string in a particular column is greater than 2.
I expect to be able to do this (per this answer):
df[(len(df['column name']) < 2)]
but I just get the error:
KeyError: u'no item named False'
What am I doing wrong?
(Note: I know I can use df.dropna() to get rid of rows that contain any NaN, but I didn't see how to remove rows based on a conditional expression.)
",https://stackoverflow.com/questions/13851535/how-to-delete-rows-from-a-pandas-dataframe-based-on-a-conditional-expression,704,1824380.0,6.0,,,2012-12-13 01:28:24,2021-10-15 22:01:30,2020-12-21 04:40:49,2020-07-04 11:21:59,Duplicate,python;pandas,sjs,9390,1080717,registered,true,13851602,,,2019-07-03 22:12:20,656,458,4,1,0,2,true,true,false,true,true,true,76,13,false,0.003,0.0004,5091,2012,12,1,Thursday,false,true,false,false,false,false,false
10373660,Converting a Pandas GroupBy multiindex output from Series back to DataFrame,"I have a dataframe:
City Name
0 Seattle Alice
1 Seattle Bob
2 Portland Mallory
3 Seattle Mallory
4 Seattle Bob
5 Portland Mallory
I perform the following grouping:
g1 = df1.groupby(["Name", "City"]).count()
which when printed looks like:
City Name
Name City
Alice Seattle 1 1
Bob Seattle 2 2
Mallory Portland 2 2
Seattle 1 1
But what I want eventually is another DataFrame object that contains all the rows in the GroupBy object. In other words I want to get the following result:
City Name
Name City
Alice Seattle 1 1
Bob Seattle 2 2
Mallory Portland 2 2
Mallory Seattle 1 1
How do I do it?
",https://stackoverflow.com/questions/10373660/converting-a-pandas-groupby-multiindex-output-from-series-back-to-dataframe,696,1165283.0,13.0,,,2012-04-29 16:10:35,2023-11-18 00:38:40,2023-11-18 00:38:40,,,python;pandas;dataframe;group-by;multi-index,saveenr,8669,468604,registered,true,10374456,,CC BY-SA 4.0,2016-06-10 10:12:54,1068,783,4,0,0,5,true,false,false,true,true,true,75,11,false,0.011,0.0006,5319,2012,4,16,Sunday,true,true,false,false,false,false,false
13295735,How to replace NaN values in a dataframe column,"I have a Pandas Dataframe as below:
itm Date Amount
67 420 2012-09-30 00:00:00 65211
68 421 2012-09-09 00:00:00 29424
69 421 2012-09-16 00:00:00 29877
70 421 2012-09-23 00:00:00 30990
71 421 2012-09-30 00:00:00 61303
72 485 2012-09-09 00:00:00 71781
73 485 2012-09-16 00:00:00 NaN
74 485 2012-09-23 00:00:00 11072
75 485 2012-09-30 00:00:00 113702
76 489 2012-09-09 00:00:00 64731
77 489 2012-09-16 00:00:00 NaN
When I try to apply a function to the Amount column, I get the following error:
ValueError: cannot convert float NaN to integer
I have tried applying a function using math.isnan, pandas' .replace method, .sparse data attribute from pandas 0.9, if NaN == NaN statement in a function; I have also looked at this Q/A; none of them works.
How do I do it?
",https://stackoverflow.com/questions/13295735/how-to-replace-nan-values-in-a-dataframe-column,680,1413659.0,16.0,,,2012-11-08 18:50:39,2024-11-28 04:29:51,2023-10-24 00:42:23,,,python;pandas;dataframe;nan;fillna,George Thompson,7127,1733061,registered,true,13295801,,CC BY-SA 4.0,2018-07-07 12:34:31,1154,847,6,1,0,5,true,false,false,true,true,true,47,9,false,0.011,0.0005,5126,2012,11,18,Thursday,false,true,false,false,false,false,false
24870306,How to check if a column exists in Pandas,"How do I check if a column exists in a Pandas DataFrame df?
A B C
0 3 40 100
1 6 30 200
How would I check if the column "A" exists in the above DataFrame so that I can compute:
df['sum'] = df['A'] + df['C']
And if "A" doesn't exist:
df['sum'] = df['B'] + df['C']
",https://stackoverflow.com/questions/24870306/how-to-check-if-a-column-exists-in-pandas,668,754775.0,6.0,,,2014-07-21 16:43:02,2025-04-03 22:23:20,2025-04-03 22:23:20,,,python;pandas;dataframe;membership;any,npires,6863,3321229,registered,true,24870404,,CC BY-SA 4.0,,545,300,6,0,0,5,true,false,false,true,true,true,41,9,false,0.008,0.0009,4506,2014,7,16,Monday,false,true,false,false,false,false,false
26886653,"Create new column based on values from other columns / apply a function of multiple columns, row-wise in Pandas","I want to apply my custom function (it uses an if-else ladder) to these six columns (ERI_Hispanic, ERI_AmerInd_AKNatv, ERI_Asian, ERI_Black_Afr.Amer, ERI_HI_PacIsl, ERI_White) in each row of my dataframe.
I've tried different methods from other questions but still can't seem to find the right answer for my problem. The critical piece of this is that if the person is counted as Hispanic they can't be counted as anything else. Even if they have a "1" in another ethnicity column they still are counted as Hispanic not two or more races. Similarly, if the sum of all the ERI columns is greater than 1 they are counted as two or more races and can't be counted as a unique ethnicity(except for Hispanic).
It's almost like doing a for loop through each row and if each record meets a criterion they are added to one list and eliminated from the original.
From the dataframe below I need to calculate a new column based on the following spec in SQL:
CRITERIA
IF [ERI_Hispanic] = 1 THEN RETURN “Hispanic”
ELSE IF SUM([ERI_AmerInd_AKNatv] + [ERI_Asian] + [ERI_Black_Afr.Amer] + [ERI_HI_PacIsl] + [ERI_White]) > 1 THEN RETURN “Two or More”
ELSE IF [ERI_AmerInd_AKNatv] = 1 THEN RETURN “A/I AK Native”
ELSE IF [ERI_Asian] = 1 THEN RETURN “Asian”
ELSE IF [ERI_Black_Afr.Amer] = 1 THEN RETURN “Black/AA”
ELSE IF [ERI_HI_PacIsl] = 1 THEN RETURN “Haw/Pac Isl.”
ELSE IF [ERI_White] = 1 THEN RETURN “White”
Comment: If the ERI Flag for Hispanic is True (1), the employee is classified as “Hispanic”
Comment: If more than 1 non-Hispanic ERI Flag is true, return “Two or More”
DATAFRAME
lname fname rno_cd eri_afr_amer eri_asian eri_hawaiian eri_hispanic eri_nat_amer eri_white rno_defined
0 MOST JEFF E 0 0 0 0 0 1 White
1 CRUISE TOM E 0 0 0 1 0 0 White
2 DEPP JOHNNY 0 0 0 0 0 1 Unknown
3 DICAP LEO 0 0 0 0 0 1 Unknown
4 BRANDO MARLON E 0 0 0 0 0 0 White
5 HANKS TOM 0 0 0 0 0 1 Unknown
6 DENIRO ROBERT E 0 1 0 0 0 1 White
7 PACINO AL E 0 0 0 0 0 1 White
8 WILLIAMS ROBIN E 0 0 1 0 0 0 White
9 EASTWOOD CLINT E 0 0 0 0 0 1 White
",https://stackoverflow.com/questions/26886653/create-new-column-based-on-values-from-other-columns-apply-a-function-of-multi,653,1428015.0,8.0,,,2014-11-12 12:08:12,2025-04-09 17:33:50,2025-04-09 17:11:22,,,python;pandas;dataframe;conditional-statements;switch-statement,Dave,7500,2201603,registered,true,26887820,,CC BY-SA 4.0,2022-07-28 14:05:32,3293,3077,8,0,0,5,true,false,false,true,true,true,111,19,false,0.006,0.0005,4392,2014,11,12,Wednesday,false,true,false,false,false,false,false
47152691,How can I pivot a dataframe?,"How do I pivot the pandas dataframe below such that the col values become columns, row values become the index, and mean of val0 becomes the values? (In some cases this is called transforming from long-format to wide-format.)
Consider a dataframe df with columns 'key', 'row', 'item', 'col', and random float values 'val0', 'val1'. I conspicuously named the columns and relevant column values to correspond with how I want to pivot them. (Setup code at bottom.)
key row item col val0 val1
0 key0 row3 item1 col3 0.81 0.04
1 key1 row2 item1 col2 0.44 0.07
2 key1 row0 item1 col0 0.77 0.01
3 key0 row4 item0 col2 0.15 0.59
4 key1 row0 item2 col1 0.81 0.64
5 key1 row2 item2 col4 0.13 0.88
6 key2 row4 item1 col3 0.88 0.39
7 key1 row4 item1 col1 0.10 0.07
8 key1 row0 item2 col4 0.65 0.02
9 key1 row2 item0 col2 0.35 0.61
10 key2 row0 item2 col1 0.40 0.85
11 key2 row4 item1 col2 0.64 0.25
12 key0 row2 item2 col3 0.50 0.44
13 key0 row4 item1 col4 0.24 0.46
14 key1 row3 item2 col3 0.28 0.11
15 key0 row3 item1 col1 0.31 0.23
16 key0 row0 item2 col3 0.86 0.01
17 key0 row4 item0 col3 0.64 0.21
18 key2 row2 item2 col0 0.13 0.45
19 key0 row2 item0 col4 0.37 0.70
Subquestions
How to avoid getting ValueError: Index contains duplicate entries, cannot reshape?
How do I pivot df such that the col values become columns, row values become the index, and mean of val0 are the values?
col col0 col1 col2 col3 col4
row
row0 0.77 0.605 NaN 0.860 0.65
row2 0.13 NaN 0.395 0.500 0.25
row3 NaN 0.310 NaN 0.545 NaN
row4 NaN 0.100 0.395 0.760 0.24
How do I pivot...
... so that missing values are 0?
col col0 col1 col2 col3 col4
row
row0 0.77 0.605 0.000 0.860 0.65
row2 0.13 0.000 0.395 0.500 0.25
row3 0.00 0.310 0.000 0.545 0.00
row4 0.00 0.100 0.395 0.760 0.24
... to do an aggregate function other than mean, like sum?
col col0 col1 col2 col3 col4
row
row0 0.77 1.21 0.00 0.86 0.65
row2 0.13 0.00 0.79 0.50 0.50
row3 0.00 0.31 0.00 1.09 0.00
row4 0.00 0.10 0.79 1.52 0.24
... to do more that one aggregation at a time?
sum mean
col col0 col1 col2 col3 col4 col0 col1 col2 col3 col4
row
row0 0.77 1.21 0.00 0.86 0.65 0.77 0.605 0.000 0.860 0.65
row2 0.13 0.00 0.79 0.50 0.50 0.13 0.000 0.395 0.500 0.25
row3 0.00 0.31 0.00 1.09 0.00 0.00 0.310 0.000 0.545 0.00
row4 0.00 0.10 0.79 1.52 0.24 0.00 0.100 0.395 0.760 0.24
... to aggregate over multiple 'value' columns?
val0 val1
col col0 col1 col2 col3 col4 col0 col1 col2 col3 col4
row
row0 0.77 0.605 0.000 0.860 0.65 0.01 0.745 0.00 0.010 0.02
row2 0.13 0.000 0.395 0.500 0.25 0.45 0.000 0.34 0.440 0.79
row3 0.00 0.310 0.000 0.545 0.00 0.00 0.230 0.00 0.075 0.00
row4 0.00 0.100 0.395 0.760 0.24 0.00 0.070 0.42 0.300 0.46
... to subdivide by multiple columns? (item0,item1,item2..., col0,col1,col2...)
item item0 item1 item2
col col2 col3 col4 col0 col1 col2 col3 col4 col0 col1 col3 col4
row
row0 0.00 0.00 0.00 0.77 0.00 0.00 0.00 0.00 0.00 0.605 0.86 0.65
row2 0.35 0.00 0.37 0.00 0.00 0.44 0.00 0.00 0.13 0.000 0.50 0.13
row3 0.00 0.00 0.00 0.00 0.31 0.00 0.81 0.00 0.00 0.000 0.28 0.00
row4 0.15 0.64 0.00 0.00 0.10 0.64 0.88 0.24 0.00 0.000 0.00 0.00
... to subdivide by multiple rows: (key0,key1... row0,row1,row2...)
item item0 item1 item2
col col2 col3 col4 col0 col1 col2 col3 col4 col0 col1 col3 col4
key row
key0 row0 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.86 0.00
row2 0.00 0.00 0.37 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.50 0.00
row3 0.00 0.00 0.00 0.00 0.31 0.00 0.81 0.00 0.00 0.00 0.00 0.00
row4 0.15 0.64 0.00 0.00 0.00 0.00 0.00 0.24 0.00 0.00 0.00 0.00
key1 row0 0.00 0.00 0.00 0.77 0.00 0.00 0.00 0.00 0.00 0.81 0.00 0.65
row2 0.35 0.00 0.00 0.00 0.00 0.44 0.00 0.00 0.00 0.00 0.00 0.13
row3 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.28 0.00
row4 0.00 0.00 0.00 0.00 0.10 0.00 0.00 0.00 0.00 0.00 0.00 0.00
key2 row0 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.40 0.00 0.00
row2 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.13 0.00 0.00 0.00
row4 0.00 0.00 0.00 0.00 0.00 0.64 0.88 0.00 0.00 0.00 0.00 0.00
... to aggregate the frequency in which the column and rows occur together, aka "cross tabulation"?
col col0 col1 col2 col3 col4
row
row0 1 2 0 1 1
row2 1 0 2 1 2
row3 0 1 0 2 0
row4 0 1 2 2 1
... to convert a DataFrame from long-to-wide by pivoting on ONLY two columns? Given:
np.random.seed([3, 1415])
df2 = pd.DataFrame({'A': list('aaaabbbc'), 'B': np.random.choice(15, 8)})
df2
A B
0 a 0
1 a 11
2 a 2
3 a 11
4 b 10
5 b 10
6 b 14
7 c 7
The expected should look something like
a b c
0 0.0 10.0 7.0
1 11.0 10.0 NaN
2 2.0 14.0 NaN
3 11.0 NaN NaN
How do I flatten the multi-index to single index after pivot?
From:
1 2
1 1 2
a 2 1 1
b 2 1 0
c 1 0 0
To:
1|1 2|1 2|2
a 2 1 1
b 2 1 0
c 1 0 0
Setup
import numpy as np
import pandas as pd
from numpy.core.defchararray import add
np.random.seed([3,1415])
n = 20
cols = np.array(['key', 'row', 'item', 'col'])
arr1 = (np.random.randint(5, size=(n, 4)) // [2, 1, 2, 1]).astype(str)
df = pd.DataFrame(
add(cols, arr1), columns=cols
).join(
pd.DataFrame(np.random.rand(n, 2).round(2)).add_prefix('val')
)
print(df)
Why is this question not a duplicate? and more useful than the following autosuggestions:
How to pivot a dataframe in Pandas? only covers the specific case of 'Country' to row-index, values of 'Indicator' for 'Year' to multiple columns and no aggregation of values.
When pivoting a Pandas dataframe, how do I make the column names the same as in R? (flat, label in column names)
asks how to pivot in pandas like in R, i.e. autogenerate an individual column for each value of strength...
pandas pivoting a dataframe, duplicate rows asks about the syntax for pivoting multiple columns, without needing to list them all.
None of the existing questions and answers are comprehensive",https://stackoverflow.com/questions/47152691/how-can-i-pivot-a-dataframe,631,80727.0,5.0,,,2017-11-07 08:00:28,2025-10-09 13:12:57,2025-10-09 13:12:57,2025-03-03 11:05:25,Needs more focus,python;pandas;group-by;pivot;pivot-table,piRSquared,296006,2336654,registered,true,47152692,,,2019-12-18 22:43:35,8229,6810,27,5,0,5,true,true,false,true,true,true,28,6,true,0.062,0.0078,3301,2017,11,8,Tuesday,false,true,false,false,false,false,false
20250771,"Remap values in pandas column with a dict, preserve NaNs","
I have a dictionary which looks like this: di = {1: "A", 2: "B"}
I would like to apply it to the col1 column of a dataframe similar to:
col1 col2
0 w a
1 1 2
2 2 NaN
to get:
col1 col2
0 w a
1 A 2
2 B NaN
How can I best do this?
",https://stackoverflow.com/questions/20250771/remap-values-in-pandas-column-with-a-dict-preserve-nans,620,837550.0,12.0,,,2013-11-27 18:56:58,2025-04-03 04:48:04,2025-04-03 04:48:04,,,python;pandas;dataframe;dictionary;replace,TheChymera,18166,1893275,registered,true,20250996,,CC BY-SA 4.0,2017-07-06 18:09:33,506,326,4,0,0,5,true,false,false,true,true,true,56,10,false,0.014,0.0007,4742,2013,11,18,Wednesday,false,true,false,false,false,false,false
18837262,Convert Python dict into a dataframe,"I have a Python dictionary:
{u'2012-07-01': 391,
u'2012-07-02': 392,
u'2012-07-03': 392,
u'2012-07-04': 392,
u'2012-07-05': 392,
u'2012-07-06': 392}
I would like to convert this into a pandas dataframe by having the dates and their corresponding values as two separate columns; the expected result looks like:
Date DateValue
0 2012-07-01 391
1 2012-07-02 392
2 2012-07-03 392
. 2012-07-04 392
. ... ...
Is there a direct way to do this?
",https://stackoverflow.com/questions/18837262/convert-python-dict-into-a-dataframe,614,1769611.0,19.0,,,2013-09-16 21:02:22,2024-04-20 17:11:12,2023-09-18 22:57:29,,,python;pandas;dataframe;dictionary,anonuser0428,12493,1009091,registered,true,18837389,,CC BY-SA 4.0,2018-05-17 07:28:30,639,494,2,0,0,4,true,false,false,true,true,true,36,6,false,0.011,0.0003,4814,2013,9,21,Monday,false,true,false,false,false,false,false
6541123,Improve subplot size/spacing with many subplots,"I need to generate a whole bunch of vertically-stacked plots in matplotlib. The result will be saved using savefig and viewed on a webpage, so I don't care how tall the final image is, as long as the subplots are spaced so they don't overlap.
No matter how big I allow the figure to be, the subplots always seem to overlap.
My code currently looks like
import matplotlib.pyplot as plt
import my_other_module
titles, x_lists, y_lists = my_other_module.get_data()
fig = plt.figure(figsize=(10,60))
for i, y_list in enumerate(y_lists):
plt.subplot(len(titles), 1, i)
plt.xlabel("Some X label")
plt.ylabel("Some Y label")
plt.title(titles[i])
plt.plot(x_lists[i],y_list)
fig.savefig('out.png', dpi=100)
",https://stackoverflow.com/questions/6541123/improve-subplot-size-spacing-with-many-subplots,603,1014962.0,12.0,,,2011-06-30 21:09:11,2025-03-19 17:03:33,2022-08-26 20:28:39,,,python;pandas;matplotlib;seaborn;subplot,mcstrother,7607,222515,registered,true,9827848,,CC BY-SA 4.0,2022-08-26 16:50:08,800,742,2,0,0,5,true,false,false,true,true,true,47,6,false,0.012,0.0006,5623,2011,6,21,Thursday,false,true,false,false,false,false,false
24251219,Pandas read_csv: low_memory and dtype options,"df = pd.read_csv('somefile.csv')
...gives an error:
.../site-packages/pandas/io/parsers.py:1130:
DtypeWarning: Columns (4,5,7,16) have mixed types. Specify dtype
option on import or set low_memory=False.
Why is the dtype option related to low_memory, and why might low_memory=False help?
",https://stackoverflow.com/questions/24251219/pandas-read-csv-low-memory-and-dtype-options,599,845903.0,14.0,,,2014-06-16 19:56:47,2025-02-04 07:04:07,2022-06-20 01:52:24,,,python;parsing;numpy;pandas;dataframe,Josh,12951,1732769,registered,true,27232309,,CC BY-SA 4.0,,401,292,4,0,0,5,true,false,false,true,true,true,45,6,false,0.017,0.0007,4541,2014,6,19,Monday,false,true,false,false,false,false,false
12065885,Filter dataframe rows if value in column is in a set list of values,"I have a Python pandas DataFrame rpt:
rpt
<class 'pandas.core.frame.DataFrame'>
MultiIndex: 47518 entries, ('000002', '20120331') to ('603366', '20091231')
Data columns:
STK_ID 47518 non-null values
STK_Name 47518 non-null values
RPT_Date 47518 non-null values
sales 47518 non-null values
I can filter the rows whose stock id is '600809' like this: rpt[rpt['STK_ID'] == '600809']
<class 'pandas.core.frame.DataFrame'>
MultiIndex: 25 entries, ('600809', '20120331') to ('600809', '20060331')
Data columns:
STK_ID 25 non-null values
STK_Name 25 non-null values
RPT_Date 25 non-null values
sales 25 non-null values
and I want to get all the rows of some stocks together, such as ['600809','600141','600329']. That means I want a syntax like this:
stk_list = ['600809','600141','600329']
rst = rpt[rpt['STK_ID'] in stk_list] # this does not works in pandas
Since pandas not accept above command, how to achieve the target?
",https://stackoverflow.com/questions/12065885/filter-dataframe-rows-if-value-in-column-is-in-a-set-list-of-values,595,580693.0,7.0,,,2012-08-22 03:16:56,2020-12-26 10:54:14,2017-04-27 13:28:09,2018-12-26 18:23:37,Duplicate,python;pandas;dataframe,bigbug,60024,1072888,registered,true,12065904,,,2019-06-08 22:55:58,1250,1098,7,0,0,3,true,true,false,true,true,true,67,14,false,0.012,0.001,5204,2012,8,3,Wednesday,false,true,false,false,false,false,false
22341271,Get list from pandas dataframe column or row?,"I have a dataframe df imported from an Excel document like this:
cluster load_date budget actual fixed_price
A 1/1/2014 1000 4000 Y
A 2/1/2014 12000 10000 Y
A 3/1/2014 36000 2000 Y
B 4/1/2014 15000 10000 N
B 4/1/2014 12000 11500 N
B 4/1/2014 90000 11000 N
C 7/1/2014 22000 18000 N
C 8/1/2014 30000 28960 N
C 9/1/2014 53000 51200 N
I want to be able to return the contents of column 1 df['cluster'] as a list, so I can run a for-loop over it, and create an Excel worksheet for every cluster.
Is it also possible to return the contents of a whole column or row to a list? e.g.
list = [], list[column1] or list[df.ix(row1)]
",https://stackoverflow.com/questions/22341271/get-list-from-pandas-dataframe-column-or-row,595,1944313.0,11.0,,,2014-03-12 03:12:33,2025-04-04 16:47:48,2025-04-04 16:47:48,,,python;pandas;dataframe;list;type-conversion,yoshiserry,21645,3098818,registered,true,22341390,,CC BY-SA 4.0,,882,711,4,0,0,5,true,false,false,true,true,true,45,8,true,0.006,0.0003,4637,2014,3,3,Wednesday,false,true,false,false,false,false,false
22219004,How to group dataframe rows into list in pandas groupby,"Given a dataframe, I want to groupby the first column and get second column as lists in rows, so that a dataframe like:
a b
A 1
A 2
B 5
B 5
B 4
C 6
becomes
A [1,2]
B [5,5,4]
C [6]
How do I do this?
",https://stackoverflow.com/questions/22219004/how-to-group-dataframe-rows-into-list-in-pandas-groupby,594,679135.0,16.0,,,2014-03-06 08:31:09,2023-10-31 17:08:14,2023-10-31 17:08:14,,,python;pandas;list;group-by;aggregate,Abhishek Thakur,17075,1296816,registered,true,22221675,,CC BY-SA 4.0,,269,200,2,0,0,5,true,false,false,true,true,true,55,10,false,0.024,0.0009,4643,2014,3,8,Thursday,false,true,false,false,false,false,false
20490274,How to reset index in a pandas dataframe?,"I have a dataframe from which I remove some rows. As a result, I get a dataframe in which index is something like [1,5,6,10,11] and I would like to reset it to [0,1,2,3,4]. How can I do it?
The following seems to work:
df = df.reset_index()
del df['index']
The following does not work:
df = df.reindex()
",https://stackoverflow.com/questions/20490274/how-to-reset-index-in-a-pandas-dataframe,590,1151357.0,4.0,,,2013-12-10 09:12:55,2024-01-11 20:28:42,2024-01-11 20:28:42,,,python;indexing;pandas;dataframe,Roman,132560,245549,registered,true,20491748,,CC BY-SA 4.0,,482,307,4,0,0,4,true,false,false,true,true,true,41,8,true,0.003,0.0005,4729,2013,12,9,Tuesday,false,true,false,false,false,false,false
29763620,How to select all columns except one in pandas?,"I have a dataframe that look like this:
a b c d
0 0.418762 0.042369 0.869203 0.972314
1 0.991058 0.510228 0.594784 0.534366
2 0.407472 0.259811 0.396664 0.894202
3 0.726168 0.139531 0.324932 0.906575
How I can get all columns except b?
",https://stackoverflow.com/questions/29763620/how-to-select-all-columns-except-one-in-pandas,589,898540.0,14.0,,,2015-04-21 05:24:59,2025-03-20 17:09:07,2025-03-20 17:09:07,,,python;pandas;dataframe;select;filter,markov zain,13095,4744765,registered,true,29763653,,CC BY-SA 4.0,2018-04-21 13:20:56,377,287,2,0,0,5,true,false,false,true,true,true,47,9,true,0.016,0.0007,4232,2015,4,5,Tuesday,false,true,false,false,false,false,false
34962104,How can I use the apply() function for a single column?,"I have a pandas dataframe with multiple columns. I want to change the values of the only the first column without affecting the other columns. How can I do that using apply() in pandas?
",https://stackoverflow.com/questions/34962104/how-can-i-use-the-apply-function-for-a-single-column,589,1008545.0,8.0,,,2016-01-23 10:04:27,2023-08-19 09:57:46,2023-08-19 09:57:46,,,python;pandas;dataframe;numpy;apply,Amani,18723,852063,registered,true,34962199,,CC BY-SA 4.0,2019-07-03 22:15:32,307,186,1,1,0,5,true,false,false,true,true,true,55,11,true,0.008,0.0006,3955,2016,1,10,Saturday,true,true,false,false,false,false,false
16096627,Selecting a row of pandas series/dataframe by integer index,"I am curious as to why df[2] is not supported, while df.ix[2] and df[2:3] both work.
In [26]: df.ix[2]
Out[26]:
A 1.027680
B 1.514210
C -1.466963
D -0.162339
Name: 2000-01-03 00:00:00
In [27]: df[2:3]
Out[27]:
A B C D
2000-01-03 1.02768 1.51421 -1.466963 -0.162339
I would expect df[2] to work the same way as df[2:3] to be consistent with Python indexing convention. Is there a design reason for not supporting indexing row by single integer?
",https://stackoverflow.com/questions/16096627/selecting-a-row-of-pandas-series-dataframe-by-integer-index,589,1390785.0,8.0,,,2013-04-19 03:14:00,2025-04-01 03:05:20,2025-04-01 03:05:20,,,python;pandas;dataframe;indexing;filter,user1642513,,,does_not_exist,true,16104482,,CC BY-SA 4.0,2016-05-23 06:58:02,607,504,6,0,0,5,true,false,false,true,false,true,59,9,false,0.006,0.0004,4964,2013,4,3,Friday,false,true,false,false,false,false,false
14507794,How to flatten a hierarchical index in columns,"I have a data frame with a hierarchical index in axis 1 (columns) (from a groupby.agg operation):
USAF WBAN year month day s_PC s_CL s_CD s_CNT tempf
sum sum sum sum amax amin
0 702730 26451 1993 1 1 1 0 12 13 30.92 24.98
1 702730 26451 1993 1 2 0 0 13 13 32.00 24.98
2 702730 26451 1993 1 3 1 10 2 13 23.00 6.98
3 702730 26451 1993 1 4 1 0 12 13 10.04 3.92
4 702730 26451 1993 1 5 3 0 10 13 19.94 10.94
I want to flatten it, so that it looks like this (names aren't critical - I could rename):
USAF WBAN year month day s_PC s_CL s_CD s_CNT tempf_amax tmpf_amin
0 702730 26451 1993 1 1 1 0 12 13 30.92 24.98
1 702730 26451 1993 1 2 0 0 13 13 32.00 24.98
2 702730 26451 1993 1 3 1 10 2 13 23.00 6.98
3 702730 26451 1993 1 4 1 0 12 13 10.04 3.92
4 702730 26451 1993 1 5 3 0 10 13 19.94 10.94
How do I do this? (I've tried a lot, to no avail.)
Per a suggestion, here is the head in dict form
{('USAF', ''): {0: '702730',
1: '702730',
2: '702730',
3: '702730',
4: '702730'},
('WBAN', ''): {0: '26451', 1: '26451', 2: '26451', 3: '26451', 4: '26451'},
('day', ''): {0: 1, 1: 2, 2: 3, 3: 4, 4: 5},
('month', ''): {0: 1, 1: 1, 2: 1, 3: 1, 4: 1},
('s_CD', 'sum'): {0: 12.0, 1: 13.0, 2: 2.0, 3: 12.0, 4: 10.0},
('s_CL', 'sum'): {0: 0.0, 1: 0.0, 2: 10.0, 3: 0.0, 4: 0.0},
('s_CNT', 'sum'): {0: 13.0, 1: 13.0, 2: 13.0, 3: 13.0, 4: 13.0},
('s_PC', 'sum'): {0: 1.0, 1: 0.0, 2: 1.0, 3: 1.0, 4: 3.0},
('tempf', 'amax'): {0: 30.920000000000002,
1: 32.0,
2: 23.0,
3: 10.039999999999999,
4: 19.939999999999998},
('tempf', 'amin'): {0: 24.98,
1: 24.98,
2: 6.9799999999999969,
3: 3.9199999999999982,
4: 10.940000000000001},
('year', ''): {0: 1993, 1: 1993, 2: 1993, 3: 1993, 4: 1993}}
",https://stackoverflow.com/questions/14507794/how-to-flatten-a-hierarchical-index-in-columns,578,572930.0,21.0,,,2013-01-24 18:03:11,2025-01-16 20:01:27,2022-07-11 19:36:58,,,python;pandas;dataframe;multi-index,Ross R,9513,1400991,registered,true,14508355,,CC BY-SA 4.0,2017-08-25 09:57:31,2233,2120,4,0,0,4,true,false,false,true,true,true,46,8,false,0.037,0.001,5049,2013,1,18,Thursday,false,true,false,false,false,false,false
24147278,How do I create test and train samples from one dataframe with pandas?,"I have a fairly large dataset in the form of a dataframe and I was wondering how I would be able to split the dataframe into two random samples (80% and 20%) for training and testing.
Thanks!
",https://stackoverflow.com/questions/24147278/how-do-i-create-test-and-train-samples-from-one-dataframe-with-pandas,567,872370.0,30.0,,,2014-06-10 17:24:57,2023-10-30 15:36:06,,,,python;python-2.7;pandas;dataframe,tooty44,7149,3712008,registered,true,24147363,,CC BY-SA 3.0,2019-07-03 22:10:21,207,193,0,0,0,4,true,false,false,true,true,false,70,13,true,0.034,0.0006,4547,2014,6,17,Tuesday,false,true,false,false,false,false,false
21800169,Python Pandas: Get index of rows where column matches certain value,"Given a DataFrame with a column "BoolCol", we want to find the indexes of the DataFrame in which the values for "BoolCol" == True
I currently have the iterating way to do it, which works perfectly:
for i in range(100,3000):
if df.iloc[i]['BoolCol']== True:
print i,df.iloc[i]['BoolCol']
But this is not the correct pandas way to do it. After some research, I am currently using this code:
df[df['BoolCol'] == True].index.tolist()
This one gives me a list of indexes, but they don't match, when I check them by doing:
df.iloc[i]['BoolCol']
The result is actually False!!
Which would be the correct pandas way to do this?
",https://stackoverflow.com/questions/21800169/python-pandas-get-index-of-rows-where-column-matches-certain-value,564,2029298.0,8.0,,,2014-02-15 16:18:11,2022-09-10 16:37:16,2022-09-10 16:35:25,,,python;pandas;dataframe;indexing,I want badges,6565,2138906,registered,true,21800319,,CC BY-SA 4.0,2019-07-03 22:14:06,881,656,3,0,0,4,true,false,false,true,true,true,67,11,false,0.004,0.0003,4662,2014,2,16,Saturday,true,true,false,false,false,false,false
25254016,Pandas: Get first row value of a given column,"This seems like a ridiculously easy question... but I'm not seeing the easy answer I was expecting.
So, how do I get the value at an nth row of a given column in Pandas? (I am particularly interested in the first row, but would be interested in a more general practice as well).
For example, let's say I want to pull the 1.2 value in Btime as a variable.
Whats the right way to do this?
>>> df_test
ATime X Y Z Btime C D E
0 1.2 2 15 2 1.2 12 25 12
1 1.4 3 12 1 1.3 13 22 11
2 1.5 1 10 6 1.4 11 20 16
3 1.6 2 9 10 1.7 12 29 12
4 1.9 1 1 9 1.9 11 21 19
5 2.0 0 0 0 2.0 8 10 11
6 2.4 0 0 0 2.4 10 12 15
",https://stackoverflow.com/questions/25254016/pandas-get-first-row-value-of-a-given-column,557,1407272.0,10.0,,,2014-08-11 23:30:16,2024-07-12 12:43:00,2024-07-12 12:43:00,,,python;pandas;indexing,Ahmed Haque,7614,2860565,registered,true,25254087,,CC BY-SA 4.0,,825,723,2,0,0,3,true,false,false,true,true,true,45,9,false,0.007,0.0004,4485,2014,8,23,Monday,false,true,false,false,false,false,false
14940743,Selecting/excluding sets of columns in pandas,"I would like to create views or dataframes from an existing dataframe based on column selections.
For example, I would like to create a dataframe df2 from a dataframe df1 that holds all columns from it except two of them. I tried doing the following, but it didn't work:
import numpy as np
import pandas as pd
# Create a dataframe with columns A,B,C and D
df = pd.DataFrame(np.random.randn(100, 4), columns=list('ABCD'))
# Try to create a second dataframe df2 from df with all columns except 'B' and D
my_cols = set(df.columns)
my_cols.remove('B').remove('D')
# This returns an error (""unhashable type: set"")
df2 = df[my_cols]
What am I doing wrong? Perhaps more generally, what mechanisms does pandas have to support the picking and exclusions of arbitrary sets of columns from a dataframe?
",https://stackoverflow.com/questions/14940743/selecting-excluding-sets-of-columns-in-pandas,536,1079975.0,9.0,,,2013-02-18 16:22:38,2021-01-13 17:51:36,2019-01-22 15:36:18,2019-01-22 08:12:13,Duplicate,python;pandas;dataframe,Amelio Vazquez-Reina,97532,283296,registered,true,29319200,,,,887,799,3,0,0,3,true,true,false,true,true,true,45,6,false,0.008,0.0005,5024,2013,2,16,Monday,false,true,false,false,false,false,false
16327055,How to add an empty column to a dataframe?,"What's the easiest way to add an empty column to a pandas DataFrame object? The best I've stumbled upon is something like
df['foo'] = df.apply(lambda _: '', axis=1)
Is there a less perverse method?
",https://stackoverflow.com/questions/16327055/how-to-add-an-empty-column-to-a-dataframe,532,1228451.0,16.0,,,2013-05-01 21:46:47,2023-11-09 18:20:55,2023-11-09 18:20:55,,,python;pandas;dataframe;variable-assignment,kjo,35881,559827,registered,true,16327135,,CC BY-SA 4.0,,275,200,1,0,0,4,true,false,false,true,true,true,42,9,true,0.013,0.0004,4952,2013,5,21,Wednesday,false,true,false,false,false,false,false
17141558,How to sort a pandas dataFrame by two or more columns?,"Suppose I have a dataframe with columns a, b and c. I want to sort the dataframe by column b in ascending order, and by column c in descending order. How do I do this?
",https://stackoverflow.com/questions/17141558/how-to-sort-a-pandas-dataframe-by-two-or-more-columns,532,659940.0,5.0,,,2013-06-17 06:28:47,2026-03-15 06:40:33,2026-03-15 06:40:33,,,python;pandas;dataframe;sorting;data-analysis,Rakesh Adhikesavan,13056,4168397,registered,true,17141755,,CC BY-SA 4.0,,240,168,5,0,0,5,true,false,false,true,true,true,54,11,true,0.008,0.0008,4905,2013,6,6,Monday,false,true,false,false,false,false,false
11067027,Sorting columns in pandas dataframe based on column name,"I have a dataframe with over 200 columns. The issue is as they were generated the order is
['Q1.3','Q6.1','Q1.2','Q1.1',......]
I need to sort the columns as follows:
['Q1.1','Q1.2','Q1.3',.....'Q6.1',......]
Is there some way for me to do this within Python?
",https://stackoverflow.com/questions/11067027/sorting-columns-in-pandas-dataframe-based-on-column-name,527,667455.0,11.0,,,2012-06-16 21:05:01,2024-12-15 14:40:30,2023-05-31 01:52:09,,,python;pandas;dataframe,pythOnometrist,6889,1419123,registered,true,11067072,,CC BY-SA 4.0,,353,262,3,0,0,3,true,false,false,true,true,true,56,9,false,0.016,0.0008,5271,2012,6,21,Saturday,true,true,false,false,false,false,false
22391433,Count the frequency that a value occurs in a dataframe column,"I have a dataset
category
cat a
cat b
cat a
I'd like to return something like the following which shows the unique values and their frequencies
category freq
cat a 2
cat b 1
",https://stackoverflow.com/questions/22391433/count-the-frequency-that-a-value-occurs-in-a-dataframe-column,522,1282524.0,16.0,,,2014-03-13 21:34:41,2025-04-27 06:12:23,2025-04-27 06:12:23,,,python;pandas;group-by;count;frequency,yoshiserry,21645,3098818,registered,true,22391554,,CC BY-SA 4.0,2019-06-28 15:34:33,331,191,2,0,0,5,true,false,false,true,true,true,61,11,false,0.012,0.0004,4636,2014,3,21,Thursday,false,true,false,false,false,false,false
27236275,What does `ValueError: cannot reindex from a duplicate axis` mean?,"I am getting a ValueError: cannot reindex from a duplicate axis when I am trying to set an index to a certain value. I tried to reproduce this with a simple example, but I could not do it.
Here is my session inside of ipdb trace. I have a DataFrame with string index, and integer columns, float values. However when I try to create sum index for sum of all columns I am getting ValueError: cannot reindex from a duplicate axis error. I created a small DataFrame with the same characteristics, but was not able to reproduce the problem, what could I be missing?
I don't really understand what ValueError: cannot reindex from a duplicate axismeans, what does this error message mean? Maybe this will help me diagnose the problem, and this is most answerable part of my question.
ipdb> type(affinity_matrix)
<class 'pandas.core.frame.DataFrame'>
ipdb> affinity_matrix.shape
(333, 10)
ipdb> affinity_matrix.columns
Int64Index([9315684, 9315597, 9316591, 9320520, 9321163, 9320615, 9321187, 9319487, 9319467, 9320484], dtype='int64')
ipdb> affinity_matrix.index
Index([u'001', u'002', u'003', u'004', u'005', u'008', u'009', u'010', u'011', u'014', u'015', u'016', u'018', u'020', u'021', u'022', u'024', u'025', u'026', u'027', u'028', u'029', u'030', u'032', u'033', u'034', u'035', u'036', u'039', u'040', u'041', u'042', u'043', u'044', u'045', u'047', u'047', u'048', u'050', u'053', u'054', u'055', u'056', u'057', u'058', u'059', u'060', u'061', u'062', u'063', u'065', u'067', u'068', u'069', u'070', u'071', u'072', u'073', u'074', u'075', u'076', u'077', u'078', u'080', u'082', u'083', u'084', u'085', u'086', u'089', u'090', u'091', u'092', u'093', u'094', u'095', u'096', u'097', u'098', u'100', u'101', u'103', u'104', u'105', u'106', u'107', u'108', u'109', u'110', u'111', u'112', u'113', u'114', u'115', u'116', u'117', u'118', u'119', u'121', u'122', ...], dtype='object')
ipdb> affinity_matrix.values.dtype
dtype('float64')
ipdb> 'sums' in affinity_matrix.index
False
Here is the error:
ipdb> affinity_matrix.loc['sums'] = affinity_matrix.sum(axis=0)
*** ValueError: cannot reindex from a duplicate axis
I tried to reproduce this with a simple example, but I failed
In [32]: import pandas as pd
In [33]: import numpy as np
In [34]: a = np.arange(35).reshape(5,7)
In [35]: df = pd.DataFrame(a, ['x', 'y', 'u', 'z', 'w'], range(10, 17))
In [36]: df.values.dtype
Out[36]: dtype('int64')
In [37]: df.loc['sums'] = df.sum(axis=0)
In [38]: df
Out[38]:
10 11 12 13 14 15 16
x 0 1 2 3 4 5 6
y 7 8 9 10 11 12 13
u 14 15 16 17 18 19 20
z 21 22 23 24 25 26 27
w 28 29 30 31 32 33 34
sums 70 75 80 85 90 95 100
",https://stackoverflow.com/questions/27236275/what-does-valueerror-cannot-reindex-from-a-duplicate-axis-mean,521,915269.0,18.0,,,2014-12-01 20:00:51,2025-03-11 12:29:21,2016-01-19 17:54:09,,,python;pandas,Akavall,87022,1078084,registered,true,27242735,,CC BY-SA 3.0,,2915,2743,8,0,0,2,true,false,false,true,true,true,66,10,true,0.02,0.0006,4373,2014,12,20,Monday,false,true,false,false,false,false,false
15705630,Get the row(s) which have the max value in groups using groupby,"How do I find all rows in a pandas DataFrame which have the max value for count column, after grouping by ['Sp','Mt'] columns?
Example 1: the following DataFrame:
Sp Mt Value count
0 MM1 S1 a **3**
1 MM1 S1 n 2
2 MM1 S3 cb **5**
3 MM2 S3 mk **8**
4 MM2 S4 bg **10**
5 MM2 S4 dgd 1
6 MM4 S2 rd 2
7 MM4 S2 cb 2
8 MM4 S2 uyi **7**
Expected output is to get the result rows whose count is max in each group, like this:
Sp Mt Value count
0 MM1 S1 a **3**
2 MM1 S3 cb **5**
3 MM2 S3 mk **8**
4 MM2 S4 bg **10**
8 MM4 S2 uyi **7**
Example 2:
Sp Mt Value count
4 MM2 S4 bg 10
5 MM2 S4 dgd 1
6 MM4 S2 rd 2
7 MM4 S2 cb 8
8 MM4 S2 uyi 8
Expected output:
Sp Mt Value count
4 MM2 S4 bg 10
7 MM4 S2 cb 8
8 MM4 S2 uyi 8
",https://stackoverflow.com/questions/15705630/get-the-rows-which-have-the-max-value-in-groups-using-groupby,515,707122.0,16.0,,,2013-03-29 14:48:13,2024-04-21 15:34:21,2023-02-18 21:02:25,,,python;pandas;dataframe;group-by;max,jojo12,5253,2216109,registered,true,15705958,,CC BY-SA 4.0,2019-07-16 16:23:02,1104,913,6,0,0,5,true,false,false,true,true,true,63,12,false,0.023,0.0007,4985,2013,3,14,Friday,false,true,false,false,false,false,false
19913659,How do I create a new column where the values are selected based on an existing column?,"How do I add a color column to the following dataframe so that color='green' if Set == 'Z', and color='red' otherwise?
Type Set
1 A Z
2 B Z
3 B X
4 C Y
",https://stackoverflow.com/questions/19913659/how-do-i-create-a-new-column-where-the-values-are-selected-based-on-an-existing,510,873324.0,15.0,,,2013-11-11 18:52:06,2024-10-24 05:33:22,2024-06-08 18:26:10,,,python;pandas;dataframe;numpy,user7289,34698,213216,registered,true,19913845,,CC BY-SA 4.0,2019-07-03 22:11:44,279,196,5,0,0,4,true,false,false,true,true,true,87,17,true,0.017,0.0006,4758,2013,11,18,Monday,false,true,false,false,false,false,false
22604564,Create Pandas DataFrame from a string,"In order to test some functionality I would like to create a DataFrame from a string. Let's say my test data looks like:
TESTDATA=""""""col1;col2;col3
1;4.4;99
2;4.5;200
3;4.7;65
4;3.2;140
""""""
What is the simplest way to read that data into a Pandas DataFrame?
",https://stackoverflow.com/questions/22604564/create-pandas-dataframe-from-a-string,510,492978.0,7.0,,,2014-03-24 08:43:29,2023-07-01 14:48:46,2018-10-02 00:25:49,,,python;string;pandas;csv;csv-import,Emil L,21301,355499,registered,true,22605281,,CC BY-SA 4.0,,325,261,3,0,0,5,true,false,false,true,true,true,37,6,false,0.014,0.001,4625,2014,3,8,Monday,false,true,false,false,false,false,false
24988448,How to draw vertical lines on a given plot,"Given a plot of a signal in time representation, how can I draw lines marking the corresponding time index?
Specifically, given a signal plot with a time index ranging from 0 to 2.6 (seconds), I want to draw vertical red lines indicating the corresponding time index for the list [0.22058956, 0.33088437, 2.20589566]. How can I do it?
",https://stackoverflow.com/questions/24988448/how-to-draw-vertical-lines-on-a-given-plot,504,964878.0,6.0,,,2014-07-28 04:29:41,2023-04-22 04:18:38,2022-07-11 09:58:01,,,python;pandas;matplotlib;seaborn,Francis,6776,3882995,registered,true,24988486,,CC BY-SA 4.0,2019-07-11 20:19:27,362,335,1,0,0,4,true,false,false,true,true,true,42,9,false,0.006,0.0005,4499,2014,7,4,Monday,false,true,false,false,false,false,false
26763344,Convert Pandas Column to DateTime,"I have one field in a pandas DataFrame that was imported as string format.
It should be a datetime variable. How do I convert it to a datetime column, and then filter based on date?
Example:
raw_data = pd.DataFrame({'Mycol': ['05SEP2014:00:00:00.000']})
",https://stackoverflow.com/questions/26763344/convert-pandas-column-to-datetime,504,1287812.0,7.0,,,2014-11-05 17:24:34,2024-07-10 00:30:14,2024-07-10 00:30:14,,,python;pandas;dataframe;datetime;type-conversion,Chris,13890,3971910,registered,true,26763793,,CC BY-SA 4.0,2018-12-02 08:30:59,337,255,1,0,0,5,true,false,false,true,true,true,33,5,false,0.005,0.0004,4399,2014,11,17,Wednesday,false,true,false,false,false,false,false
26414913,Normalize columns of a dataframe,"I have a dataframe in pandas where each column has different value range. For example:
df:
A B C
1000 10 0.5
765 5 0.35
800 7 0.09
Any idea how I can normalize the columns of this dataframe where each value is between 0 and 1?
My desired output is:
A B C
1 1 1
0.765 0.5 0.7
0.8 0.7 0.18(which is 0.09/0.5)
",https://stackoverflow.com/questions/26414913/normalize-columns-of-a-dataframe,493,1136960.0,25.0,,,2014-10-16 22:24:42,2024-05-14 09:34:40,2022-08-01 16:14:43,,,python;pandas;dataframe;normalize,ahajib,13688,2827771,registered,true,26415620,,CC BY-SA 4.0,2018-04-14 02:51:32,424,348,2,0,0,4,true,false,false,true,true,true,32,5,false,0.022,0.0004,4419,2014,10,22,Thursday,false,true,false,false,false,false,false
13035764,Remove pandas rows with duplicate indices,"How to remove rows with duplicate index values?
In the weather DataFrame below, sometimes a scientist goes back and corrects observations -- not by editing the erroneous rows, but by appending a duplicate row to the end of a file.
I'm reading some automated weather data from the web (observations occur every 5 minutes, and compiled into monthly files for each weather station.) After parsing a file, the DataFrame looks like:
Sta Precip1hr Precip5min Temp DewPnt WindSpd WindDir AtmPress
Date
2001-01-01 00:00:00 KPDX 0 0 4 3 0 0 30.31
2001-01-01 00:05:00 KPDX 0 0 4 3 0 0 30.30
2001-01-01 00:10:00 KPDX 0 0 4 3 4 80 30.30
2001-01-01 00:15:00 KPDX 0 0 3 2 5 90 30.30
2001-01-01 00:20:00 KPDX 0 0 3 2 10 110 30.28
Example of a duplicate case:
import pandas as pd
import datetime
startdate = datetime.datetime(2001, 1, 1, 0, 0)
enddate = datetime.datetime(2001, 1, 1, 5, 0)
index = pd.date_range(start=startdate, end=enddate, freq='H')
data1 = {'A' : range(6), 'B' : range(6)}
data2 = {'A' : [20, -30, 40], 'B' : [-50, 60, -70]}
df1 = pd.DataFrame(data=data1, index=index)
df2 = pd.DataFrame(data=data2, index=index[:3])
df3 = df2.append(df1)
df3
A B
2001-01-01 00:00:00 20 -50
2001-01-01 01:00:00 -30 60
2001-01-01 02:00:00 40 -70
2001-01-01 03:00:00 3 3
2001-01-01 04:00:00 4 4
2001-01-01 05:00:00 5 5
2001-01-01 00:00:00 0 0
2001-01-01 01:00:00 1 1
2001-01-01 02:00:00 2 2
And so I need df3 to eventually become:
A B
2001-01-01 00:00:00 0 0
2001-01-01 01:00:00 1 1
2001-01-01 02:00:00 2 2
2001-01-01 03:00:00 3 3
2001-01-01 04:00:00 4 4
2001-01-01 05:00:00 5 5
I thought that adding a column of row numbers (df3['rownum'] = range(df3.shape[0])) would help me select the bottom-most row for any value of the DatetimeIndex, but I am stuck on figuring out the group_by or pivot (or ???) statements to make that work.
",https://stackoverflow.com/questions/13035764/remove-pandas-rows-with-duplicate-indices,491,533791.0,8.0,,,2012-10-23 17:11:04,2025-07-23 17:41:19,2023-02-22 22:19:14,,,python;pandas;dataframe;duplicates,Paul H,68875,1552748,registered,true,34297689,,CC BY-SA 4.0,,2467,2288,8,0,0,4,true,false,false,true,true,true,41,6,false,0.015,0.0009,5142,2012,10,17,Tuesday,false,true,false,false,false,false,false
17134716,Convert DataFrame column type from string to datetime,"How can I convert a DataFrame column of strings (in dd/mm/yyyy format) to datetime dtype?
",https://stackoverflow.com/questions/17134716/convert-dataframe-column-type-from-string-to-datetime,491,809418.0,7.0,,,2013-06-16 15:14:58,2024-07-10 00:31:46,2024-07-10 00:31:46,,,python;pandas;dataframe;datetime;type-conversion,perigee,9988,857130,registered,true,17134750,,CC BY-SA 4.0,,123,90,0,0,0,5,true,false,false,true,true,true,53,8,false,0.009,0.0006,4906,2013,6,15,Sunday,true,true,false,false,false,false,false
17098654,How to reversibly store and load a Pandas dataframe to/from disk,"Right now I'm importing a fairly large CSV as a dataframe every time I run the script. Is there a good solution for keeping that dataframe constantly available in between runs so I don't have to spend all that time waiting for the script to run?
",https://stackoverflow.com/questions/17098654/how-to-reversibly-store-and-load-a-pandas-dataframe-to-from-disk,490,561427.0,14.0,,,2013-06-13 23:05:36,2024-04-05 15:33:46,2021-06-01 12:44:59,,,python;pandas;dataframe,jeffstern,5096,972381,registered,true,17098736,,CC BY-SA 4.0,2018-05-17 07:28:09,266,246,1,0,0,3,true,false,false,true,true,true,64,11,false,0.025,0.0009,4909,2013,6,23,Thursday,false,true,false,false,false,false,false
13703720,"Converting between datetime, Timestamp and datetime64","How do I convert a numpy.datetime64 object to a datetime.datetime (or Timestamp)?
In the following code, I create a datetime, timestamp and datetime64 objects.
import datetime
import numpy as np
import pandas as pd
dt = datetime.datetime(2012, 5, 1)
# A strange way to extract a Timestamp object, there's surely a better way?
ts = pd.DatetimeIndex([dt])[0]
dt64 = np.datetime64(dt)
In [7]: dt
Out[7]: datetime.datetime(2012, 5, 1, 0, 0)
In [8]: ts
Out[8]: <Timestamp: 2012-05-01 00:00:00>
In [9]: dt64
Out[9]: numpy.datetime64('2012-05-01T01:00:00.000000+0100')
Note: it's easy to get the datetime from the Timestamp:
In [10]: ts.to_datetime()
Out[10]: datetime.datetime(2012, 5, 1, 0, 0)
But how do we extract the datetime or Timestamp from a numpy.datetime64 (dt64)?
.
Update: a somewhat nasty example in my dataset (perhaps the motivating example) seems to be:
dt64 = numpy.datetime64('2002-06-28T01:00:00.000000000+0100')
which should be datetime.datetime(2002, 6, 28, 1, 0), and not a long (!) (1025222400000000000L)...
",https://stackoverflow.com/questions/13703720/converting-between-datetime-timestamp-and-datetime64,484,922233.0,14.0,,,2012-12-04 13:08:29,2021-12-13 11:31:04,2019-01-22 21:33:33,,,python;datetime;numpy;pandas,Andy Hayden,378871,1240268,registered,true,13704307,,CC BY-SA 4.0,2022-07-14 20:09:25,1293,1046,12,0,0,4,true,false,false,true,true,true,53,6,false,0.015,0.0005,5100,2012,12,13,Tuesday,false,true,false,false,false,false,false
17530542,How to add pandas data to an existing csv file?,"I want to know if it is possible to use the pandas to_csv() function to add a dataframe to an existing csv file. The csv file has the same structure as the loaded data.
",https://stackoverflow.com/questions/17530542/how-to-add-pandas-data-to-an-existing-csv-file,481,588382.0,7.0,,,2013-07-08 15:33:46,2022-01-20 14:28:53,2019-03-06 21:50:55,,,python;pandas;csv;dataframe,Ayoub Ennassiri,4936,2355050,registered,true,17975690,,CC BY-SA 4.0,2019-07-03 22:15:01,190,170,1,0,0,4,true,false,false,true,true,true,47,10,true,0.012,0.0008,4884,2013,7,15,Monday,false,true,false,false,false,false,false
26521266,Using Pandas to pd.read_excel() for multiple (but not all) worksheets of the same workbook without reloading the whole file,"I have a large spreadsheet file (.xlsx) that I'm processing using python pandas. It happens that I need data from two tabs (sheets) in that large file. One of the tabs has a ton of data and the other is just a few square cells.
When I use pd.read_excel() on any worksheet, it looks to me like the whole file is loaded (not just the worksheet I'm interested in). So when I use the method twice (once for each sheet), I effectively have to suffer the whole workbook being read in twice (even though we're only using the specified sheet).
How do I only load specific sheet(s) with pd.read_excel()?
",https://stackoverflow.com/questions/26521266/using-pandas-to-pd-read-excel-for-multiple-but-not-all-worksheets-of-the-sam,455,1122921.0,14.0,,,2014-10-23 04:21:45,2024-11-28 13:55:45,2024-08-21 21:43:50,,,python;excel;pandas;dataframe;xlsx,HaPsantran,6327,3127764,registered,true,26521726,,CC BY-SA 4.0,2021-08-10 07:25:30,768,595,2,1,0,5,true,false,false,true,true,true,123,19,false,0.012,0.0004,4412,2014,10,4,Thursday,false,true,false,false,false,false,false
26716616,Convert a Pandas DataFrame to a dictionary,"I have a DataFrame with four columns. I want to convert this DataFrame to a python dictionary. I want the elements of first column be keys and the elements of other columns in the same row be values.
DataFrame:
ID A B C
0 p 1 3 2
1 q 4 3 2
2 r 4 0 9
Output should be like this:
{'p': [1,3,2], 'q': [4,3,2], 'r': [4,0,9]}
",https://stackoverflow.com/questions/26716616/convert-a-pandas-dataframe-to-a-dictionary,453,909013.0,12.0,,,2014-11-03 14:47:53,2023-03-22 20:19:20,2023-03-22 20:19:13,,,python;pandas;dictionary;dataframe,Prince Bhatti,5091,3676196,registered,true,26716774,,CC BY-SA 4.0,2019-07-16 16:24:49,530,361,4,0,0,4,true,false,false,true,true,true,42,7,false,0.013,0.0005,4401,2014,11,14,Monday,false,true,false,false,false,false,false
2051744,How to invert the x or y axis,"I have a scatter plot graph with a bunch of random x, y coordinates. Currently the Y-Axis starts at 0 and goes up to the max value. I would like the Y-Axis to start at the max value and go up to 0.
points = [(10,5), (5,11), (24,13), (7,8)]
x_arr = []
y_arr = []
for x,y in points:
x_arr.append(x)
y_arr.append(y)
plt.scatter(x_arr,y_arr)
",https://stackoverflow.com/questions/2051744/how-to-invert-the-x-or-y-axis,451,711341.0,11.0,,,2010-01-12 19:31:47,2024-04-09 13:12:59,2022-06-29 23:06:09,,,python;pandas;matplotlib;seaborn,DarkAnt,4521,139423,registered,true,8280500,,CC BY-SA 4.0,,383,352,1,0,0,4,true,false,false,true,true,true,29,8,false,0.015,0.0006,6157,2010,1,19,Tuesday,false,true,false,false,false,false,false
11869910,pandas: filter rows of DataFrame with operator chaining,"Most operations in pandas can be accomplished with operator chaining (groupby, aggregate, apply, etc), but the only way I've found to filter rows is via normal bracket indexing
df_filtered = df[df['column'] == value]
This is unappealing as it requires I assign df to a variable before being able to filter on its values. Is there something more like the following?
df_filtered = df.mask(lambda x: x['column'] == value)
",https://stackoverflow.com/questions/11869910/pandas-filter-rows-of-dataframe-with-operator-chaining,445,875953.0,15.0,,,2012-08-08 17:25:37,2023-12-12 21:42:01,2019-01-22 03:44:32,2026-04-20 13:58:04,Duplicate,python;pandas;dataframe,duckworthd,15447,128580,registered,true,11872393,,,2018-04-16 17:50:05,552,425,7,0,0,3,true,true,false,true,true,true,55,8,false,0.017,0.0005,5218,2012,8,17,Wednesday,false,true,false,false,false,false,false
28901683,pandas get rows which are NOT in other dataframe,"I've two pandas data frames that have some rows in common.
Suppose dataframe2 is a subset of dataframe1.
How can I get the rows of dataframe1 which are not in dataframe2?
df1 = pandas.DataFrame(data = {'col1' : [1, 2, 3, 4, 5], 'col2' : [10, 11, 12, 13, 14]})
df2 = pandas.DataFrame(data = {'col1' : [1, 2, 3], 'col2' : [10, 11, 12]})
df1
col1 col2
0 1 10
1 2 11
2 3 12
3 4 13
4 5 14
df2
col1 col2
0 1 10
1 2 11
2 3 12
Expected result:
col1 col2
3 4 13
4 5 14
",https://stackoverflow.com/questions/28901683/pandas-get-rows-which-are-not-in-other-dataframe,444,551474.0,18.0,,,2015-03-06 15:10:28,2024-08-08 07:47:26,2021-01-17 16:49:28,,,python;pandas;dataframe,think nice things,4715,3965770,registered,true,28902170,,CC BY-SA 4.0,2019-07-03 22:16:03,702,547,4,0,0,3,true,false,false,true,true,true,48,9,false,0.033,0.0008,4278,2015,3,15,Friday,false,true,false,false,false,false,false
20763012,Creating a Pandas DataFrame from a Numpy array: How do I specify the index column and column headers?,"I have a Numpy array consisting of a list of lists, representing a two-dimensional array with row labels and column names as shown below:
data = np.array([['','Col1','Col2'],['Row1',1,2],['Row2',3,4]])
I'd like the resulting DataFrame to have Row1 and Row2 as index values, and Col1, Col2 as header values.
I can specify the index as follows:
df = pd.DataFrame(data, index=data[:,0])
However, I am unsure how to best assign column headers.
",https://stackoverflow.com/questions/20763012/creating-a-pandas-dataframe-from-a-numpy-array-how-do-i-specify-the-index-colum,444,1403830.0,10.0,,,2013-12-24 15:09:07,2023-08-19 10:18:27,2023-03-21 18:05:59,,,python;pandas;dataframe;list;numpy,user3132783,5505,3132783,registered,true,20763459,,CC BY-SA 4.0,,644,442,6,0,0,5,true,false,false,true,true,true,101,18,true,0.007,0.0003,4715,2013,12,15,Tuesday,false,true,false,false,false,false,false
29815129,Pandas DataFrame to List of Dictionaries,"I have the following DataFrame:
customer item1 item2 item3
1 apple milk tomato
2 water orange potato
3 juice mango chips
which I want to translate it to list of dictionaries per row
rows = [
{
'customer': 1,
'item1': 'apple',
'item2': 'milk',
'item3': 'tomato'
}, {
'customer': 2,
'item1':
'water',
'item2': 'orange',
'item3': 'potato'
}, {
'customer': 3,
'item1': 'juice',
'item2': 'mango',
'item3': 'chips'
}
]
",https://stackoverflow.com/questions/29815129/pandas-dataframe-to-list-of-dictionaries,440,358856.0,6.0,,,2015-04-23 06:12:18,2025-06-08 12:01:21,2025-06-08 12:01:21,,,python;pandas;dataframe,Mohamad Ibrahim,5695,1057443,registered,true,29816143,,CC BY-SA 4.0,,650,601,1,0,0,3,true,false,false,true,true,true,40,6,false,0.017,0.0012,4230,2015,4,6,Thursday,false,true,false,false,false,false,false
18022845,How to get/set a pandas index column title or name?,"How do I get the index column name in Python's pandas? Here's an example dataframe:
Column 1
Index Title
Apples 1
Oranges 2
Puppies 3
Ducks 4
What I'm trying to do is get/set the dataframe's index title. Here is what I tried:
import pandas as pd
data = {'Column 1' : [1., 2., 3., 4.],
'Index Title': ["Apples", "Oranges", "Puppies", "Ducks"]}
df = pd.DataFrame(data)
df.index = df["Index Title"]
del df["Index Title"]
Anyone know how to do this?
",https://stackoverflow.com/questions/18022845/how-to-get-set-a-pandas-index-column-title-or-name,440,1138204.0,10.0,,,2013-08-02 17:30:53,2025-04-20 23:52:24,2025-04-20 23:52:24,,,python;pandas;dataframe;indexing;rename,Radical Edward,5584,1754273,registered,true,18023468,,CC BY-SA 4.0,,741,596,2,0,0,5,true,false,false,true,true,true,51,10,true,0.009,0.0004,4859,2013,8,17,Friday,false,true,false,false,false,false,false
22149584,What does axis in pandas mean?,"Here is my code to generate a dataframe:
import pandas as pd
import numpy as np
dff = pd.DataFrame(np.random.randn(1, 2), columns=list('AB'))
then I got the dataframe:
A B
0 0.626386 1.52325
When I type the command dff.mean(axis=1), I get:
0 1.074821
dtype: float64
According to the reference of pandas, axis=1 stands for columns and I expect the result of the command to be
A 0.626386
B 1.523255
dtype: float64
So what does axis in pandas mean?
",https://stackoverflow.com/questions/22149584/what-does-axis-in-pandas-mean,436,545928.0,30.0,,,2014-03-03 14:41:04,2026-09-11 13:33:28,2024-12-27 16:38:42,,,python;pandas;dataframe,jerry_sjtu,5496,636467,registered,true,22149930,,CC BY-SA 4.0,2019-05-01 12:36:40,636,479,6,0,0,3,true,false,false,true,true,true,30,6,true,0.055,0.0008,4646,2014,3,14,Monday,false,true,false,false,false,false,false
14529838,Apply multiple functions to multiple groupby columns,"The docs show how to apply multiple functions on a groupby object at a time using a dict with the output column names as the keys:
In [563]: grouped['D'].agg({'result1' : np.sum,
.....: 'result2' : np.mean})
.....:
Out[563]:
result2 result1
A
bar -0.579846 -1.739537
foo -0.280588 -1.402938
However, this only works on a Series groupby object. And when a dict is similarly passed to a groupby DataFrame, it expects the keys to be the column names that the function will be applied to.
What I want to do is apply multiple functions to several columns (but certain columns will be operated on multiple times). Also, some functions will depend on other columns in the groupby object (like sumif functions). My current solution is to go column by column, and doing something like the code above, using lambdas for functions that depend on other rows. But this is taking a long time, (I think it takes a long time to iterate through a groupby object). I'll have to change it so that I iterate through the whole groupby object in a single run, but I'm wondering if there's a built in way in pandas to do this somewhat cleanly.
For example, I've tried something like
grouped.agg({'C_sum' : lambda x: x['C'].sum(),
'C_std': lambda x: x['C'].std(),
'D_sum' : lambda x: x['D'].sum()},
'D_sumifC3': lambda x: x['D'][x['C'] == 3].sum(), ...)
but as expected I get a KeyError (since the keys have to be a column if agg is called from a DataFrame).
Is there any built in way to do what I'd like to do, or a possibility that this functionality may be added, or will I just need to iterate through the groupby manually?
",https://stackoverflow.com/questions/14529838/apply-multiple-functions-to-multiple-groupby-columns,433,548019.0,10.0,,,2013-01-25 20:26:45,2024-05-23 09:40:45,2021-10-31 13:43:49,,,python;group-by;aggregate-functions;pandas,beardc,21233,386279,registered,true,47103408,,CC BY-SA 4.0,,1933,1700,3,1,0,4,true,false,false,true,true,true,52,7,false,0.018,0.0008,5048,2013,1,20,Friday,false,true,false,false,false,false,false
16176996,Keep only date part when using pandas.to_datetime,"I use pandas.to_datetime to parse the dates in my data. Pandas by default represents the dates with datetime64[ns] even though the dates are all daily only.
I wonder whether there is an elegant/clever way to convert the dates to datetime.date or datetime64[D] so that, when I write the data to CSV, the dates are not appended with 00:00:00. I know I can convert the type manually element-by-element:
[dt.to_datetime().date() for dt in df.dates]
But this is really slow since I have many rows and it sort of defeats the purpose of using pandas.to_datetime. Is there a way to convert the dtype of the entire column at once? Or alternatively, does pandas.to_datetime support a precision specification so that I can get rid of the time part while working with daily data?
",https://stackoverflow.com/questions/16176996/keep-only-date-part-when-using-pandas-to-datetime,430,926069.0,13.0,,,2013-04-23 18:50:36,2023-03-10 17:02:08,2019-10-22 16:12:29,,,python;pandas;csv;datetime;series,user1642513,,,does_not_exist,true,,,CC BY-SA 4.0,,913,771,9,0,0,5,false,false,false,true,false,true,49,7,false,0.014,0.0005,4960,2013,4,18,Tuesday,false,true,false,false,false,false,false
18674064,how do I insert a column at a specific column index in pandas?,"Can I insert a column at a specific column index in pandas?
import pandas as pd
df = pd.DataFrame({'l':['a','b','c','d'], 'v':[1,2,1,2]})
df['n'] = 0
This will put column n as the last column of df, but isn't there a way to tell df to put n at the beginning?
",https://stackoverflow.com/questions/18674064/how-do-i-insert-a-column-at-a-specific-column-index-in-pandas,427,652228.0,6.0,,,2013-09-07 13:59:01,2024-01-07 22:36:34,,,,python;indexing;pandas,HappyPy,10863,2635863,registered,true,18674915,,CC BY-SA 3.0,,353,263,5,0,0,3,true,false,false,true,true,false,62,13,true,0.009,0.0007,4823,2013,9,13,Saturday,true,true,false,false,false,false,false
18062135,Combining two Series into a DataFrame in pandas,"I have two Series s1 and s2 with the same (non-consecutive) indices. How do I combine s1 and s2 to being two columns in a DataFrame and keep one of the indices as a third column?
",https://stackoverflow.com/questions/18062135/combining-two-series-into-a-dataframe-in-pandas,427,638084.0,10.0,,,2013-08-05 15:37:39,2025-08-26 14:31:44,2015-12-29 20:10:51,,,python;pandas;series;dataframe,user7289,34698,213216,registered,true,18062521,,CC BY-SA 3.0,,238,179,4,0,0,4,true,false,false,true,true,true,47,8,false,0.016,0.0007,4856,2013,8,15,Monday,false,true,false,false,false,false,false
13021654,Get column index from column name in python pandas,"In R when you need to retrieve a column index based on the name of the column you could do
idx <- which(names(my_data)==my_colum_name)
Is there a way to do the same with pandas dataframes?
",https://stackoverflow.com/questions/13021654/get-column-index-from-column-name-in-python-pandas,423,751924.0,9.0,,,2012-10-22 23:48:58,2023-01-11 12:36:29,2017-12-19 02:56:13,,,python;pandas;dataframe;indexing,ak3nat0n,6388,55299,registered,true,13021797,,CC BY-SA 3.0,,233,195,1,0,0,4,true,false,false,true,true,true,50,9,false,0.012,0.0006,5143,2012,10,23,Monday,false,true,false,false,false,false,false
15411158,Pandas 'count(distinct)' equivalent,"I am using Pandas as a database substitute as I have multiple databases (Oracle, SQL Server, etc.), and I am unable to make a sequence of commands to a SQL equivalent.
I have a table loaded in a DataFrame with some columns:
YEARMONTH, CLIENTCODE, SIZE, etc., etc.
In SQL, to count the amount of different clients per year would be:
SELECT count(distinct CLIENTCODE) FROM table GROUP BY YEARMONTH;
And the result would be
201301 5000
201302 13245
How can I do that in Pandas?
",https://stackoverflow.com/questions/15411158/pandas-countdistinct-equivalent,421,774842.0,12.0,,,2013-03-14 13:50:03,2025-05-16 17:16:06,2025-05-16 17:16:06,,,python;pandas;group-by;count;duplicates,Adriano Almeida,5386,1879940,registered,true,15411596,,CC BY-SA 4.0,2019-07-03 22:13:24,866,484,3,2,0,5,true,false,false,true,true,true,43,3,false,0.015,0.0005,5000,2013,3,13,Thursday,false,true,false,false,false,false,false
26837998,Pandas Replace NaN with blank/empty string,"I have a Pandas Dataframe as shown below:
1 2 3
0 a NaN read
1 b l unread
2 c NaN read
I want to remove the NaN values with an empty string so that it looks like so:
1 2 3
0 a """" read
1 b l unread
2 c """" read
",https://stackoverflow.com/questions/26837998/pandas-replace-nan-with-blank-empty-string,420,732270.0,8.0,,,2014-11-10 06:29:26,2023-05-10 08:28:06,2018-10-20 20:38:59,,,python;pandas;dataframe;nan,user1452759,9548,1452759,registered,true,26838140,,CC BY-SA 4.0,2019-07-03 22:17:10,340,278,2,0,0,4,true,false,false,true,true,true,42,6,false,0.011,0.0006,4394,2014,11,6,Monday,false,true,false,false,false,false,false
22233488,Pandas: drop a level from a multi-level column index?,"If I've got a multi-level column index:
>>> cols = pd.MultiIndex.from_tuples([(""a"", ""b""), (""a"", ""c"")])
>>> pd.DataFrame([[1,2], [3,4]], columns=cols)
a
---+--
b | c
--+---+--
0 | 1 | 2
1 | 3 | 4
How can I drop the ""a"" level of that index, so I end up with:
b | c
--+---+--
0 | 1 | 2
1 | 3 | 4
",https://stackoverflow.com/questions/22233488/pandas-drop-a-level-from-a-multi-level-column-index,419,515149.0,8.0,,,2014-03-06 18:58:06,2024-10-29 14:59:43,,,,python;pandas,David Wolever,156308,71522,registered,true,,,CC BY-SA 3.0,,395,335,1,0,0,2,false,false,false,true,true,false,53,9,true,0.016,0.0008,4643,2014,3,18,Thursday,false,true,false,false,false,false,false
25146121,Extracting just Month and Year separately from Pandas Datetime column,"I have a Dataframe, df, with the following column:
ArrivalDate
936 2012-12-31
938 2012-12-29
965 2012-12-31
966 2012-12-31
967 2012-12-31
968 2012-12-31
969 2012-12-31
970 2012-12-29
971 2012-12-31
972 2012-12-29
973 2012-12-29
The elements of the column are pandas.tslib.Timestamp type. I want to extract the year and month.
Here's what I've tried:
df['ArrivalDate'].resample('M', how = 'mean')
which throws the following error:
Only valid with DatetimeIndex or PeriodIndex
Then I tried:
df['ArrivalDate'].apply(lambda(x):x[:-2])
which throws the following error:
'Timestamp' object has no attribute '__getitem__'
My current solution is
df.index = df['ArrivalDate']
Then, I can resample another column using the index.
But I'd still like a method for reconfiguring the entire column. Any ideas?
",https://stackoverflow.com/questions/25146121/extracting-just-month-and-year-separately-from-pandas-datetime-column,416,1328411.0,11.0,,,2014-08-05 18:44:30,2023-10-07 06:43:52,2023-10-07 06:43:52,,,python;pandas;datetime,monkeybiz7,5188,3494704,registered,true,25149272,,CC BY-SA 4.0,2018-03-15 08:50:22,1293,832,8,0,0,3,true,false,false,true,true,true,69,10,false,0.008,0.0003,4491,2014,8,18,Tuesday,false,true,false,false,false,false,false
23199796,Detect and exclude outliers in a pandas DataFrame,"I have a pandas dataframe with few columns.
Now I know that certain rows are outliers based on a certain column value.
For instance
column Vol has all values around 12xx and one value is 4000 (outlier).
I would like to exclude those rows that have Vol column like this.
So, essentially I need to put a filter on the data frame such that we select all rows where the values of a certain column are within, say, 3 standard deviations from mean.
What is an elegant way to achieve this?
",https://stackoverflow.com/questions/23199796/detect-and-exclude-outliers-in-a-pandas-dataframe,416,693687.0,18.0,,,2014-04-21 14:51:37,2023-10-16 01:02:28,2023-10-16 00:50:44,,,python;pandas;filtering;dataframe;outliers,AMM,18250,11212,registered,true,,,CC BY-SA 4.0,2018-11-25 19:57:14,530,483,2,0,0,5,false,false,false,true,true,true,49,8,false,0.026,0.0006,4597,2014,4,14,Monday,false,true,false,false,false,false,false
29517072,Add column to dataframe with constant value,"I have an existing dataframe which I need to add an additional column to which will contain the same value for every row.
Existing df:
Date, Open, High, Low, Close
01-01-2015, 565, 600, 400, 450
New df:
Name, Date, Open, High, Low, Close
abc, 01-01-2015, 565, 600, 400, 450
I know how to append an existing series / dataframe column. But this is a different situation, because all I need is to add the 'Name' column and set every row to the same value, in this case 'abc'.
",https://stackoverflow.com/questions/29517072/add-column-to-dataframe-with-constant-value,413,863349.0,10.0,,,2015-04-08 14:09:22,2024-11-22 17:59:07,2020-07-04 12:22:08,,,python;pandas;dataframe,darkpool,14751,4169229,registered,true,29517089,,CC BY-SA 4.0,,556,480,2,0,0,3,true,false,false,true,true,true,43,7,false,0.012,0.0005,4245,2015,4,14,Wednesday,false,true,false,false,false,false,false
38231591,Split / Explode a column of dictionaries into separate columns with pandas,"I have data saved in a postgreSQL database. I am querying this data using Python2.7 and turning it into a Pandas DataFrame. However, the last column of this dataframe has a dictionary of values inside it. The DataFrame df looks like this:
Station ID Pollutants
8809 {"a": "46", "b": "3", "c": "12"}
8810 {"a": "36", "b": "5", "c": "8"}
8811 {"b": "2", "c": "7"}
8812 {"c": "11"}
8813 {"a": "82", "c": "15"}
I need to split this column into separate columns, so that the DataFrame `df2 looks like this:
Station ID a b c
8809 46 3 12
8810 36 5 8
8811 NaN 2 7
8812 NaN NaN 11
8813 82 NaN 15
The major issue I'm having is that the lists are not the same lengths. But all of the lists only contain up to the same 3 values: 'a', 'b', and 'c'. And they always appear in the same order ('a' first, 'b' second, 'c' third).
The following code USED to work and return exactly what I wanted (df2).
objs = [df, pandas.DataFrame(df['Pollutant Levels'].tolist()).iloc[:, :3]]
df2 = pandas.concat(objs, axis=1).drop('Pollutant Levels', axis=1)
print(df2)
I was running this code just last week and it was working fine. But now my code is broken and I get this error from line [4]:
IndexError: out-of-bounds on slice (end)
I made no changes to the code but am now getting the error. I feel this is due to my method not being robust or proper.
Any suggestions or guidance on how to split this column of lists into separate columns would be super appreciated!
EDIT: I think the .tolist() and .apply methods are not working on my code because it is one Unicode string, i.e.:
#My data format
u{'a': '1', 'b': '2', 'c': '3'}
#and not
{u'a': '1', u'b': '2', u'c': '3'}
The data is imported from the postgreSQL database in this format. Any help or ideas with this issue? is there a way to convert the Unicode?
",https://stackoverflow.com/questions/38231591/split-explode-a-column-of-dictionaries-into-separate-columns-with-pandas,410,389747.0,14.0,,,2016-07-06 18:47:56,2025-05-19 19:18:03,2021-03-03 22:32:59,,,python;json;pandas;dictionary;json-normalize,llaffin,4141,6157698,registered,true,,,CC BY-SA 4.0,2021-05-25 14:31:03,2429,2177,9,0,0,5,false,false,false,true,true,true,74,12,false,0.036,0.0011,3790,2016,7,18,Wednesday,false,true,false,false,false,false,false
7837722,What is the most efficient way to loop through dataframes with pandas?,"I want to perform my own complex operations on financial data in dataframes in a sequential manner.
For example I am using the following MSFT CSV file taken from Yahoo Finance:
Date,Open,High,Low,Close,Volume,Adj Close
2011-10-19,27.37,27.47,27.01,27.13,42880000,27.13
2011-10-18,26.94,27.40,26.80,27.31,52487900,27.31
2011-10-17,27.11,27.42,26.85,26.98,39433400,26.98
2011-10-14,27.31,27.50,27.02,27.27,50947700,27.27
....
I then do the following:
#!/usr/bin/env python
from pandas import *
df = read_csv('table.csv')
for i, row in enumerate(df.values):
date = df.index[i]
open, high, low, close, adjclose = row
#now perform analysis on open/close based on date, etc..
Is that the most efficient way? Given the focus on speed in pandas, I would assume there must be some special function to iterate through the values in a manner that one also retrieves the index (possibly through a generator to be memory efficient)? df.iteritems unfortunately only iterates column by column.
",https://stackoverflow.com/questions/7837722/what-is-the-most-efficient-way-to-loop-through-dataframes-with-pandas,409,686904.0,13.0,,,2011-10-20 14:46:14,2024-09-09 17:21:11,2020-12-23 22:50:15,2026-03-23 02:03:23,Duplicate,python;pandas;performance;dataframe;for-loop,Muppet,6045,1005409,registered,true,11617194,,,,1142,1002,3,1,0,5,true,true,false,true,true,true,70,12,true,0.019,0.0006,5511,2011,10,14,Thursday,false,true,false,false,false,false,false
29370057,Select DataFrame rows between two dates,"I am creating a DataFrame from a csv as follows:
stock = pd.read_csv('data_in/' + filename + '.csv', skipinitialspace=True)
The DataFrame has a date column. Is there a way to create a new DataFrame (or just overwrite the existing one) which only contains rows with date values that fall within a specified date range or between two specified date values?
",https://stackoverflow.com/questions/29370057/select-dataframe-rows-between-two-dates,408,983278.0,14.0,,,2015-03-31 13:38:06,2025-08-09 09:51:29,2023-12-22 06:19:53,,,python;pandas;dataframe;date;datetime,darkpool,14751,4169229,registered,true,29370182,,CC BY-SA 4.0,2019-07-03 22:18:00,431,356,1,0,0,5,true,false,false,true,true,true,39,6,false,0.014,0.0004,4253,2015,3,13,Tuesday,false,true,false,false,false,false,false
14745022,How to split a dataframe string column into two columns?,"I have a data frame with one (string) column and I'd like to split it into two (string) columns, with one column header as 'fips' and the other 'row'
My dataframe df looks like this:
row
0 00000 UNITED STATES
1 01000 ALABAMA
2 01001 Autauga County, AL
3 01003 Baldwin County, AL
4 01005 Barbour County, AL
I do not know how to use df.row.str[:] to achieve my goal of splitting the row cell. I can use df['fips'] = hello to add a new column and populate it with hello. Any ideas?
fips row
0 00000 UNITED STATES
1 01000 ALABAMA
2 01001 Autauga County, AL
3 01003 Baldwin County, AL
4 01005 Barbour County, AL
",https://stackoverflow.com/questions/14745022/how-to-split-a-dataframe-string-column-into-two-columns,406,963776.0,12.0,,,2013-02-07 06:30:11,2023-09-28 00:58:51,2020-10-29 20:11:52,,,python;dataframe;pandas,a k,4073,2049102,registered,true,14745484,,CC BY-SA 4.0,2019-07-03 22:18:25,812,665,8,0,0,3,true,false,false,true,true,true,56,10,true,0.012,0.0004,5035,2013,2,6,Thursday,false,true,false,false,false,false,false
49188960,How to show all columns' names on a large pandas dataframe?,"I have a dataframe that consist of hundreds of columns, and I need to see all column names.
What I did:
In[37]:
data_all2.columns
The output is:
Out[37]:
Index(['customer_id', 'incoming', 'outgoing', 'awan', 'bank', 'family', 'food',
'government', 'internet', 'isipulsa',
...
'overdue_3months_feature78', 'overdue_3months_feature79',
'overdue_3months_feature80', 'overdue_3months_feature81',
'overdue_3months_feature82', 'overdue_3months_feature83',
'overdue_3months_feature84', 'overdue_3months_feature85',
'overdue_3months_feature86', 'loan_overdue_3months_total_y'],
dtype='object', length=102)
How do I show all columns, instead of a truncated list?
",https://stackoverflow.com/questions/49188960/how-to-show-all-columns-names-on-a-large-pandas-dataframe,405,1134555.0,23.0,,,2018-03-09 07:49:04,2026-04-13 16:56:48,2022-07-16 15:02:32,,,python;pandas;dataframe,Nabih Bawazir,7465,7585973,registered,true,49189503,,CC BY-SA 4.0,2023-02-23 20:50:52,801,716,2,0,0,3,true,false,false,true,true,true,63,11,true,0.02,0.0004,3179,2018,3,7,Friday,false,true,false,false,false,false,false
29287224,Pandas read in table without headers,"Using pandas, how do I read in only a subset of the columns (say 4th and 7th columns) of a .csv file with no headers? I cannot seem to be able to do so using usecols.
",https://stackoverflow.com/questions/29287224/pandas-read-in-table-without-headers,403,757341.0,5.0,,,2015-03-26 19:27:49,2025-04-11 06:06:58,2025-04-11 06:06:58,,,python;pandas;dataframe;csv;file-io,user308827,22551,308827,registered,true,51612800,,CC BY-SA 4.0,,187,167,1,0,0,5,true,false,false,true,true,true,36,6,false,0.007,0.0005,4258,2015,3,19,Thursday,false,true,false,false,false,false,false
17477979,Dropping infinite values from dataframes in pandas?,"How do I drop nan, inf, and -inf values from a DataFrame without resetting mode.use_inf_as_null?
Can I tell dropna to include inf in its definition of missing values so that the following works?
df.dropna(subset=["col1", "col2"], how="all")
",https://stackoverflow.com/questions/17477979/dropping-infinite-values-from-dataframes-in-pandas,402,591235.0,10.0,,,2013-07-04 20:55:20,2024-06-05 17:03:55,2022-06-20 01:23:32,,,python;pandas;numpy,user248237,,,does_not_exist,true,17478495,,CC BY-SA 4.0,,401,272,8,0,0,3,true,false,false,true,false,true,51,7,true,0.017,0.0007,4888,2013,7,20,Thursday,false,true,false,false,false,false,false
39922986,How do I use Pandas group-by to get the sum?,"I am using this dataframe:
Fruit Date Name Number
Apples 10/6/2016 Bob 7
Apples 10/6/2016 Bob 8
Apples 10/6/2016 Mike 9
Apples 10/7/2016 Steve 10
Apples 10/7/2016 Bob 1
Oranges 10/7/2016 Bob 2
Oranges 10/6/2016 Tom 15
Oranges 10/6/2016 Mike 57
Oranges 10/6/2016 Bob 65
Oranges 10/7/2016 Tony 1
Grapes 10/7/2016 Bob 1
Grapes 10/7/2016 Tom 87
Grapes 10/7/2016 Bob 22
Grapes 10/7/2016 Bob 12
Grapes 10/7/2016 Tony 15
I would like to aggregate this by Name and then by Fruit to get a total number of Fruit per Name. For example:
Bob,Apples,16
I tried grouping by Name and Fruit but how do I get the total number of Fruit?
",https://stackoverflow.com/questions/39922986/how-do-i-use-pandas-group-by-to-get-the-sum,401,973330.0,11.0,,,2016-10-07 17:36:25,2024-08-29 15:29:05,2024-08-29 15:29:05,,,python;pandas;dataframe;group-by;aggregate,Trying_hard,9641,1027427,registered,true,39923012,,CC BY-SA 4.0,,829,669,9,0,0,5,true,false,false,true,true,true,44,10,true,0.011,0.0004,3697,2016,10,17,Friday,false,true,false,false,false,false,false
21287624,Convert Pandas column containing NaNs to dtype `int`,"I read data from a .csv file to a Pandas dataframe as below. For one of the columns, namely id, I want to specify the column type as int. The problem is the id series has missing/empty values.
When I try to cast the id column to integer while reading the .csv, I get:
df= pd.read_csv(""data.csv"", dtype={'id': int})
error: Integer column has NA values
Alternatively, I tried to convert the column type after reading as below, but this time I get:
df= pd.read_csv(""data.csv"")
df[['id']] = df[['id']].astype(int)
error: Cannot convert NA to integer
How can I tackle this?
",https://stackoverflow.com/questions/21287624/convert-pandas-column-containing-nans-to-dtype-int,401,514874.0,31.0,,,2014-01-22 15:51:28,2024-03-07 17:05:32,2022-08-25 14:23:13,,,python;pandas;dataframe;nan;dtype,Zhubarb,12016,988125,registered,true,21290084,,CC BY-SA 4.0,,706,578,6,0,0,5,true,false,false,true,true,true,52,8,false,0.06,0.0008,4686,2014,1,15,Wednesday,false,true,false,false,false,false,false
21291259,Convert floats to ints in Pandas?,"I've been working with data imported from a CSV. Pandas changed some columns to float, so now the numbers in these columns get displayed as floating points! However, I need them to be displayed as integers or without comma. Is there a way to convert them to integers or not display the comma?
",https://stackoverflow.com/questions/21291259/convert-floats-to-ints-in-pandas,401,1101810.0,11.0,,,2014-01-22 18:42:15,2025-11-03 16:51:02,2022-12-19 18:15:07,,,python;pandas;dataframe;floating-point;integer,MJP,5707,2961929,registered,true,21291622,,CC BY-SA 4.0,2019-07-03 22:15:45,300,293,0,0,0,5,true,false,false,true,true,true,33,6,true,0.01,0.0004,4686,2014,1,18,Wednesday,false,true,false,false,false,false,false
35491274,Split a Pandas column of lists into multiple columns,"I have a Pandas DataFrame with one column:
import pandas as pd
df = pd.DataFrame({"teams": [["SF", "NYG"] for _ in range(7)]})
teams
0 [SF, NYG]
1 [SF, NYG]
2 [SF, NYG]
3 [SF, NYG]
4 [SF, NYG]
5 [SF, NYG]
6 [SF, NYG]
How can split this column of lists into two columns?
Desired result:
team1 team2
0 SF NYG
1 SF NYG
2 SF NYG
3 SF NYG
4 SF NYG
5 SF NYG
6 SF NYG
",https://stackoverflow.com/questions/35491274/split-a-pandas-column-of-lists-into-multiple-columns,399,513694.0,13.0,,,2016-02-18 20:01:07,2023-08-04 08:58:55,2022-08-05 15:46:28,,,python;pandas;list;dataframe;split,bgame2498,4927,2938093,registered,true,35491399,,CC BY-SA 4.0,,515,446,2,0,0,5,true,false,false,true,true,true,52,9,false,0.025,0.0008,3929,2016,2,20,Thursday,false,true,false,false,false,false,false
22005911,Convert columns to string in Pandas,"I have the following DataFrame from a SQL query:
(Pdb) pp total_rows
ColumnID RespondentCount
0 -1 2
1 3030096843 1
2 3030096845 1
and I pivot it like this:
total_data = total_rows.pivot_table(cols=['ColumnID'])
which produces
(Pdb) pp total_data
ColumnID -1 3030096843 3030096845
RespondentCount 2 1 1
[1 rows x 3 columns]
When I convert this dataframe into a dictionary (using total_data.to_dict('records')[0]), I get
{3030096843: 1, 3030096845: 1, -1: 2}
but I want to make sure the 303 columns are cast as strings instead of integers so that I get this:
{'3030096843': 1, '3030096845': 1, -1: 2}
",https://stackoverflow.com/questions/22005911/convert-columns-to-string-in-pandas,396,1430738.0,10.0,,,2014-02-25 06:03:30,2023-08-04 00:15:30,2023-02-22 05:21:56,,,python;pandas;string;dataframe;type-conversion,sontek,12591,17176,registered,true,22006514,,CC BY-SA 4.0,,1079,722,6,0,0,5,true,false,false,true,true,true,35,6,false,0.007,0.0003,4652,2014,2,6,Tuesday,false,true,false,false,false,false,false
16236684,Apply pandas function to column to create multiple new columns?,"How to do this in pandas:
I have a function extract_text_features on a single text column, returning multiple output columns. Specifically, the function returns 6 values.
The function works, however there doesn't seem to be any proper return type (pandas DataFrame/ numpy array/ Python list) such that the output can get correctly assigned df.ix[: ,10:16] = df.textcol.map(extract_text_features)
So I think I need to drop back to iterating with df.iterrows(), as per this?
UPDATE:
Iterating with df.iterrows() is at least 20x slower, so I surrendered and split out the function into six distinct .map(lambda ...) calls.
UPDATE 2: this question was asked back around v0.11.0, before the useability of df.apply was improved or df.assign() was added in v0.16. Hence much of the question and answers are not too relevant since then.
",https://stackoverflow.com/questions/16236684/apply-pandas-function-to-column-to-create-multiple-new-columns,393,390705.0,17.0,,,2013-04-26 12:38:33,2024-09-05 08:19:43,2024-09-05 08:19:43,,,python;pandas;merge;multiple-columns;return-type,smci,34291,202229,registered,true,16245109,,CC BY-SA 4.0,,1406,829,7,4,0,5,true,false,false,true,true,true,63,10,true,0.044,0.001,4957,2013,4,12,Friday,false,true,false,false,false,false,false
29432629,Plot correlation matrix using pandas,"I have a data set with huge number of features, so analysing the correlation matrix has become very difficult. I want to plot a correlation matrix which we get using dataframe.corr() function from pandas library. Is there any built-in function provided by the pandas library to plot this matrix?
",https://stackoverflow.com/questions/29432629/plot-correlation-matrix-using-pandas,391,1053331.0,20.0,,,2015-04-03 12:57:22,2025-06-25 10:51:46,2019-03-27 16:30:52,,,python;pandas;matplotlib;data-visualization;information-visualization,Gaurav Singh,13577,1983512,registered,true,29432741,,CC BY-SA 4.0,,316,296,1,0,0,5,true,false,false,true,true,true,36,5,false,0.019,0.0004,4250,2015,4,12,Friday,false,true,false,false,false,false,false
18603270,Progress indicator during pandas operations,"I regularly perform pandas operations on data frames in excess of 15 million or so rows and I'd love to have access to a progress indicator for particular operations.
Does a text based progress indicator for pandas split-apply-combine operations exist?
For example, in something like:
df_users.groupby(['userID', 'requestDate']).apply(feature_rollup)
where feature_rollup is a somewhat involved function that take many DF columns and creates new user columns through various methods. These operations can take a while for large data frames so I'd like to know if it is possible to have text based output in an iPython notebook that updates me on the progress.
So far, I've tried canonical loop progress indicators for Python but they don't interact with pandas in any meaningful way.
I'm hoping there's something I've overlooked in the pandas library/documentation that allows one to know the progress of a split-apply-combine. A simple implementation would maybe look at the total number of data frame subsets upon which the apply function is working and report progress as the completed fraction of those subsets.
Is this perhaps something that needs to be added to the library?
",https://stackoverflow.com/questions/18603270/progress-indicator-during-pandas-operations,390,287997.0,10.0,,,2013-09-03 23:55:02,2023-08-29 21:22:45,2019-06-19 03:54:23,,,python;pandas;ipython,cwharland,6823,1968405,registered,true,34365537,,CC BY-SA 4.0,,1290,1191,3,0,0,3,true,false,false,true,true,true,43,5,false,0.035,0.0014,4827,2013,9,23,Tuesday,false,true,false,false,false,false,false
33382619,Plot a horizontal line on a given plot,"How do I add a horizontal line to an existing plot?
",https://stackoverflow.com/questions/33382619/plot-a-horizontal-line-on-a-given-plot,382,864237.0,7.0,,,2015-10-28 03:53:32,2022-07-12 13:29:04,2022-06-16 20:48:18,,,python;pandas;matplotlib;seaborn,Ibe,6205,1801769,registered,true,33382692,,CC BY-SA 4.0,,59,52,0,0,0,4,true,false,false,true,true,true,38,8,false,0.008,0.0004,4042,2015,10,3,Wednesday,false,true,false,false,false,false,false
34682828,Extracting specific selected columns to new DataFrame as a copy,"I have a pandas DataFrame with 4 columns and I want to create a new DataFrame that only has three of the columns. This question is similar to: Extracting specific columns from a data frame but for pandas not R. The following code does not work, raises an error, and is certainly not the pandas way to do it.
import pandas as pd
old = pd.DataFrame({'A' : [4,5], 'B' : [10,20], 'C' : [100,50], 'D' : [-30,-50]})
new = pd.DataFrame(zip(old.A, old.C, old.D))
# raises TypeError: data argument can't be an iterator
What is the pandas way to do it?
",https://stackoverflow.com/questions/34682828/extracting-specific-selected-columns-to-new-dataframe-as-a-copy,382,1172941.0,10.0,,,2016-01-08 17:34:45,2026-04-08 15:53:14,2023-03-16 07:47:53,,,python;pandas;dataframe;chained-assignment,SpeedCoder5,9258,1134881,registered,true,34683105,,CC BY-SA 4.0,2019-07-03 22:20:55,761,547,1,1,0,4,true,false,false,true,true,true,63,10,false,0.009,0.0003,3970,2016,1,17,Friday,false,true,false,false,false,false,false
16424493,Pandas: Setting no. of max rows,"I have a problem viewing the following DataFrame:
n = 100
foo = DataFrame(index=range(n))
foo['floats'] = np.random.randn(n)
foo
The problem is that it does not print all rows per default in ipython notebook, but I have to slice to view the resulting rows. Even the following option does not change the output:
pd.set_option('display.max_rows', 500)
Does anyone know how to display the whole array?
",https://stackoverflow.com/questions/16424493/pandas-setting-no-of-max-rows,381,791384.0,10.0,,,2013-05-07 16:52:02,2023-07-12 19:15:01,2017-01-05 14:49:23,,,python;formatting;pandas;jupyter-notebook,Andy,10181,2331506,registered,true,16433953,,CC BY-SA 3.0,2025-02-25 21:28:10,488,406,3,0,0,4,true,false,false,true,true,true,31,6,false,0.013,0.0005,4946,2013,5,16,Tuesday,false,true,false,false,false,false,false
41815079,pandas: merge (join) two data frames on multiple columns,"I am trying to join two pandas dataframes using two columns:
new_df = pd.merge(A_df, B_df, how='left', left_on='[A_c1,c2]', right_on = '[B_c1,c2]')
but got the following error:
pandas/index.pyx in pandas.index.IndexEngine.get_loc (pandas/index.c:4164)()
pandas/index.pyx in pandas.index.IndexEngine.get_loc (pandas/index.c:4028)()
pandas/src/hashtable_class_helper.pxi in pandas.hashtable.PyObjectHashTable.get_item (pandas/hashtable.c:13166)()
pandas/src/hashtable_class_helper.pxi in pandas.hashtable.PyObjectHashTable.get_item (pandas/hashtable.c:13120)()
KeyError: '[B_1, c2]'
Any idea what should be the right way to do this?
",https://stackoverflow.com/questions/41815079/pandas-merge-join-two-data-frames-on-multiple-columns,381,1141171.0,6.0,,,2017-01-23 20:32:09,2024-07-27 16:03:50,2023-01-20 22:33:09,,,python;python-3.x;pandas;join;pandas-merge,Edamame,25668,3993270,registered,true,41815118,,CC BY-SA 4.0,,783,638,2,0,0,5,true,false,false,true,true,true,56,9,false,0.005,0.0003,3589,2017,1,20,Monday,false,true,false,false,false,false,false
15998188,How can I obtain the element-wise logical NOT of a pandas Series?,"I have a pandas Series object containing boolean values. How can I get a series containing the logical NOT of each value?
For example, consider a series containing:
True
True
True
False
The series I'd like to get would contain:
False
False
False
True
This seems like it should be reasonably simple, but apparently I've misplaced my mojo =(
",https://stackoverflow.com/questions/15998188/how-can-i-obtain-the-element-wise-logical-not-of-a-pandas-series,380,281495.0,7.0,,,2013-04-14 10:44:28,2023-10-10 20:11:50,2022-02-12 00:48:01,,,python;pandas;operators;boolean-logic,Louis Thibault,21640,1156707,registered,true,15998993,,CC BY-SA 4.0,,449,347,4,0,0,4,true,false,false,true,true,true,65,12,true,0.025,0.0013,4969,2013,4,10,Sunday,true,true,false,false,false,false,false
23330654,Update a dataframe in pandas while iterating row by row,"I have a pandas data frame that looks like this (its a pretty big one)
date exer exp ifor mat
1092 2014-03-17 American M 528.205 2014-04-19
1093 2014-03-17 American M 528.205 2014-04-19
1094 2014-03-17 American M 528.205 2014-04-19
1095 2014-03-17 American M 528.205 2014-04-19
1096 2014-03-17 American M 528.205 2014-05-17
now I would like to iterate row by row and as I go through each row, the value of ifor
in each row can change depending on some conditions and I need to lookup another dataframe.
Now, how do I update this as I iterate.
Tried a few things none of them worked.
for i, row in df.iterrows():
if <something>:
row['ifor'] = x
else:
row['ifor'] = y
df.ix[i]['ifor'] = x
None of these approaches seem to work. I don't see the values updated in the dataframe.
",https://stackoverflow.com/questions/23330654/update-a-dataframe-in-pandas-while-iterating-row-by-row,378,575081.0,10.0,,,2014-04-28 00:19:49,2025-09-15 08:52:27,2015-04-23 10:42:59,,,python;pandas;updates;dataframe,AMM,18250,11212,registered,true,,,CC BY-SA 3.0,2019-07-03 22:17:44,974,885,3,0,0,4,false,false,false,true,true,true,55,10,false,0.017,0.0007,4590,2014,4,0,Monday,false,true,false,false,false,false,false
12680754,Split (explode) pandas dataframe string entry to separate rows,"I have a pandas dataframe in which one column of text strings contains comma-separated values. I want to split each CSV field and create a new row per entry (assume that CSV are clean and need only be split on ','). For example, a should become b:
In [7]: a
Out[7]:
var1 var2
0 a,b,c 1
1 d,e,f 2
In [8]: b
Out[8]:
var1 var2
0 a 1
1 b 1
2 c 1
3 d 2
4 e 2
5 f 2
So far, I have tried various simple functions, but the .apply method seems to only accept one row as return value when it is used on an axis, and I can't get .transform to work.
Example data:
from pandas import DataFrame
import numpy as np
a = DataFrame([{'var1': 'a,b,c', 'var2': 1},
{'var1': 'd,e,f', 'var2': 2}])
b = DataFrame([{'var1': 'a', 'var2': 1},
{'var1': 'b', 'var2': 1},
{'var1': 'c', 'var2': 1},
{'var1': 'd', 'var2': 2},
{'var1': 'e', 'var2': 2},
{'var1': 'f', 'var2': 2}])
I know this won't work because we lose DataFrame meta-data by going through numpy, but it should give you a sense of what I tried to do:
def fun(row):
letters = row['var1']
letters = letters.split(',')
out = np.array([row] * len(letters))
out['var1'] = letters
a['idx'] = range(a.shape[0])
z = a.groupby('idx')
z.transform(fun)
",https://stackoverflow.com/questions/12680754/split-explode-pandas-dataframe-string-entry-to-separate-rows,376,449890.0,27.0,,,2012-10-01 20:42:16,2025-09-26 16:57:13,2025-09-26 16:57:13,,,python;pandas;numpy;dataframe,Vincent,18458,342331,registered,true,12681217,,CC BY-SA 4.0,2019-07-03 22:16:50,1502,1350,7,0,0,4,true,false,false,true,true,true,62,9,false,0.06,0.0008,5164,2012,10,20,Monday,false,true,false,false,false,false,false
26873127,Show DataFrame as table in iPython Notebook,"I am using iPython notebook. When I do this:
df
I get a beautiful table with cells. However, if i do this:
df1
df2
it doesn't print the first beautiful table. If I try this:
print df1
print df2
It prints out the table in a different format that spills columns over and makes the output very tall.
Is there a way to force it to print out the beautiful tables for both datasets?
",https://stackoverflow.com/questions/26873127/show-dataframe-as-table-in-ipython-notebook,376,514404.0,10.0,,,2014-11-11 19:40:53,2025-08-25 19:06:23,2025-08-25 19:06:23,,,python;pandas;jupyter-notebook;printing;display,Chris,13890,3971910,registered,true,29665452,,CC BY-SA 4.0,,500,393,3,0,0,5,true,false,false,true,true,true,43,7,false,0.019,0.0007,4393,2014,11,19,Tuesday,false,true,false,false,false,false,false
15315452,Selecting with complex criteria from pandas.DataFrame,"For example I have simple DF:
import pandas as pd
from random import randint
df = pd.DataFrame({'A': [randint(1, 9) for x in range(10)],
'B': [randint(1, 9)*10 for x in range(10)],
'C': [randint(1, 9)*100 for x in range(10)]})
Can I select values from 'A' for which corresponding values for 'B' will be greater than 50, and for 'C' - not equal to 900, using methods and idioms of Pandas?
",https://stackoverflow.com/questions/15315452/selecting-with-complex-criteria-from-pandas-dataframe,374,977811.0,5.0,,,2013-03-09 20:17:49,2026-06-01 17:12:08,2025-04-28 17:45:50,,,python;pandas;select;filter;conditional-statements,Gill Bates,15655,1818608,registered,true,15315507,,CC BY-SA 4.0,,466,428,1,0,0,5,true,false,false,true,true,true,53,6,false,0.005,0.0004,5005,2013,3,20,Saturday,true,true,false,false,false,false,false
27673231,why should I make a copy of a data frame in pandas,"When selecting a sub dataframe from a parent dataframe, I noticed that some programmers make a copy of the data frame using the .copy() method. For example,
X = my_dataframe[features_list].copy()
...instead of just
X = my_dataframe[features_list]
Why are they making a copy of the data frame? What will happen if I don't make a copy?
",https://stackoverflow.com/questions/27673231/why-should-i-make-a-copy-of-a-data-frame-in-pandas,371,382454.0,8.0,,,2014-12-28 02:22:27,2023-12-14 22:47:47,2023-12-14 22:47:47,,,python;pandas;copy;chained-assignment,Elizabeth Susan Joseph,6535,4273266,registered,true,27680109,,CC BY-SA 4.0,,492,336,3,0,0,4,true,false,false,true,true,true,50,12,false,0.021,0.001,4346,2014,12,2,Sunday,true,true,false,false,false,false,false
10202570,Find row where values for column is maximal in a pandas DataFrame,"How can I find the row for which the value of a specific column is maximal?
df.max() will give me the maximal value for each column, I don't know how to get the corresponding row.
",https://stackoverflow.com/questions/10202570/find-row-where-values-for-column-is-maximal-in-a-pandas-dataframe,370,533108.0,15.0,,,2012-04-18 03:59:55,2024-08-12 09:16:03,2021-05-23 07:20:13,,,python;pandas;dataframe;row;argmax,Miki Tebeka,14090,7650,registered,true,10202789,,CC BY-SA 4.0,,225,181,1,0,0,5,true,false,false,true,true,true,65,12,false,0.028,0.0007,5330,2012,4,3,Wednesday,false,true,false,false,false,false,false
22898824,Filtering Pandas DataFrames on dates,"I have a Pandas DataFrame with a 'date' column. Now I need to filter out all rows in the DataFrame that have dates outside of the next two months. Essentially, I only need to retain the rows that are within the next two months.
What is the best way to achieve this?
",https://stackoverflow.com/questions/22898824/filtering-pandas-dataframes-on-dates,368,1009862.0,18.0,,,2014-04-06 19:24:42,2024-11-17 01:13:01,2018-06-18 06:33:23,,,python;datetime;pandas;filtering;dataframe,AMM,18250,11212,registered,true,,,CC BY-SA 4.0,,282,268,0,0,0,5,false,false,false,true,true,true,36,5,false,0.018,0.0004,4612,2014,4,19,Sunday,true,true,false,false,false,false,false
14661701,How to drop a list of rows from Pandas dataframe?,"I have a dataframe df :
>>> df
sales discount net_sales cogs
STK_ID RPT_Date
600141 20060331 2.709 NaN 2.709 2.245
20060630 6.590 NaN 6.590 5.291
20060930 10.103 NaN 10.103 7.981
20061231 15.915 NaN 15.915 12.686
20070331 3.196 NaN 3.196 2.710
20070630 7.907 NaN 7.907 6.459
Then I want to drop rows with certain sequence numbers which indicated in a list, suppose here is [1,2,4], then left:
sales discount net_sales cogs
STK_ID RPT_Date
600141 20060331 2.709 NaN 2.709 2.245
20061231 15.915 NaN 15.915 12.686
20070630 7.907 NaN 7.907 6.459
How or what function can do that ?
",https://stackoverflow.com/questions/14661701/how-to-drop-a-list-of-rows-from-pandas-dataframe,367,816672.0,15.0,,,2013-02-02 12:03:46,2024-10-28 06:59:05,2013-02-02 12:25:47,,,python;pandas,bigbug,60024,1072888,registered,true,14661768,,CC BY-SA 3.0,,970,888,3,0,0,2,true,false,false,true,true,true,49,10,true,0.018,0.0004,5040,2013,2,12,Saturday,true,true,false,false,false,false,false
44513738,Pandas create empty DataFrame with only column names,"I have a dynamic DataFrame which works fine, but when there are no data to be added into the DataFrame I get an error. And therefore I need a solution to create an empty DataFrame with only the column names.
For now I have something like this:
df = pd.DataFrame(columns=COLUMN_NAMES) # Note that there is no row data inserted.
PS: It is important that the column names would still appear in a DataFrame.
But when I use it like this I get something like that as a result:
Index([], dtype='object')
Empty DataFrame
The "Empty DataFrame" part is good! But instead of the Index thing I need to still display the columns.
An important thing that I found out: I am converting this DataFrame to a PDF using Jinja2, so therefore I'm calling out a method to first output it to HTML like that:
df.to_html()
This is where the columns get lost I think.
In general, I followed this example: http://pbpython.com/pdf-reports.html. The css is also from the link. That's what I do to send the dataframe to the PDF:
env = Environment(loader=FileSystemLoader('.'))
template = env.get_template("pdf_report_template.html")
template_vars = {"my_dataframe": df.to_html()}
html_out = template.render(template_vars)
HTML(string=html_out).write_pdf("my_pdf.pdf", stylesheets=["pdf_report_style.css"])
",https://stackoverflow.com/questions/44513738/pandas-create-empty-dataframe-with-only-column-names,366,907851.0,5.0,,,2017-06-13 06:22:57,2023-04-12 22:46:52,2023-04-12 22:46:52,,,python;pandas;dataframe,E. Muuli,4410,1772193,registered,true,44514187,,CC BY-SA 4.0,,1700,1330,4,1,0,3,true,false,false,true,true,true,52,8,false,0.006,0.0004,3448,2017,6,6,Tuesday,false,true,false,false,false,false,false
38309729,Count unique values per groups with Pandas,"I need to count unique ID values in every domain.
I have data:
ID, domain
123, vk.com
123, vk.com
123, twitter.com
456, vk.com'
456, facebook.com
456, vk.com
456, google.com
789, twitter.com
789, vk.com
I try df.groupby(['domain', 'ID']).count()
But I want to get
domain count
vk.com 3
twitter.com 2
facebook.com 1
google.com 1
",https://stackoverflow.com/questions/38309729/count-unique-values-per-groups-with-pandas,353,917292.0,4.0,,,2016-07-11 14:38:25,2023-10-31 18:43:35,2023-10-31 18:43:35,2018-07-13 02:03:48,Duplicate,python;pandas;group-by;unique,Arseniy Krupenin,3900,6327741,registered,true,38309823,,,2018-04-19 11:49:45,465,350,5,0,0,4,true,true,false,true,true,true,42,7,false,0.004,0.0004,3785,2016,7,14,Monday,false,true,false,false,false,false,false
40468069,Merge two dataframes by index,"I have the following dataframes:
> df1
id begin conditional confidence discoveryTechnique
0 278 56 false 0.0 1
1 421 18 false 0.0 1
> df2
concept
0 A
1 B
How do I merge on the indices to get:
id begin conditional confidence discoveryTechnique concept
0 278 56 false 0.0 1 A
1 421 18 false 0.0 1 B
I ask because it is my understanding that merge() i.e. df1.merge(df2) uses columns to do the matching. In fact, doing this I get:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/pandas/core/frame.py", line 4618, in merge
copy=copy, indicator=indicator)
File "/usr/local/lib/python2.7/dist-packages/pandas/tools/merge.py", line 58, in merge
copy=copy, indicator=indicator)
File "/usr/local/lib/python2.7/dist-packages/pandas/tools/merge.py", line 491, in __init__
self._validate_specification()
File "/usr/local/lib/python2.7/dist-packages/pandas/tools/merge.py", line 812, in _validate_specification
raise MergeError('No common columns to perform merge on')
pandas.tools.merge.MergeError: No common columns to perform merge on
Is it bad practice to merge on index? Is it impossible? If so, how can I shift the index into a new column called "index"?
",https://stackoverflow.com/questions/40468069/merge-two-dataframes-by-index,352,687609.0,7.0,,,2016-11-07 14:51:50,2025-01-21 09:56:08,2023-01-30 17:32:32,2025-01-21 08:45:42,Duplicate,python;pandas;dataframe;merge;concatenation,brucezepplin,9872,1268941,registered,true,40468090,,,,1615,1489,5,0,0,5,true,true,false,true,true,true,29,5,false,0.01,0.0005,3666,2016,11,14,Monday,false,true,false,false,false,false,false
24644656,How to print pandas DataFrame without index,"I want to print the whole dataframe, but I don't want to print the index
Besides, one column is datetime type, I just want to print time, not date.
The dataframe looks like:
User ID Enter Time Activity Number
0 123 2014-07-08 00:09:00 1411
1 123 2014-07-08 00:18:00 893
2 123 2014-07-08 00:49:00 1041
I want it print as
User ID Enter Time Activity Number
123 00:09:00 1411
123 00:18:00 893
123 00:49:00 1041
",https://stackoverflow.com/questions/24644656/how-to-print-pandas-dataframe-without-index,349,622360.0,12.0,,,2014-07-09 02:50:29,2025-03-02 00:16:22,2018-08-09 10:33:28,,,python;datetime;pandas;dataframe,lserlohn,6266,3804098,registered,true,32662331,,CC BY-SA 4.0,,632,556,2,0,0,4,true,false,false,true,true,true,43,7,false,0.019,0.0006,4518,2014,7,2,Wednesday,false,true,false,false,false,false,false
21319929,How to determine whether a Pandas Column contains a particular value,"I am trying to determine whether there is an entry in a Pandas column that has a particular value. I tried to do this with if x in df['id']. I thought this was working, except when I fed it a value that I knew was not in the column 43 in df['id'] it still returned True. When I subset to a data frame only containing entries matching the missing id df[df['id'] == 43] there are, obviously, no entries in it. How to I determine if a column in a Pandas data frame contains a particular value and why doesn't my current method work? (FYI, I have the same problem when I use the implementation in this answer to a similar question).
",https://stackoverflow.com/questions/21319929/how-to-determine-whether-a-pandas-column-contains-a-particular-value,347,942602.0,10.0,,,2014-01-23 21:41:11,2022-09-16 06:15:45,2017-05-23 12:34:08,,,python;pandas,Michael,14124,2327821,registered,true,21320011,,CC BY-SA 3.0,,747,629,4,1,0,2,true,false,false,true,true,true,68,11,false,0.011,0.0004,4685,2014,1,21,Thursday,false,true,false,false,false,false,false
53927460,Select rows in pandas MultiIndex DataFrame,"What are the most common pandas ways to select/filter rows of a dataframe whose index is a MultiIndex?
- Slicing based on a single value/label
- Slicing based on multiple labels from one or more levels
- Filtering on boolean conditions and expressions
- Which methods are applicable in what circumstances
Assumptions for simplicity:
- input dataframe does not have duplicate index keys
- input dataframe below only has two levels. (Most solutions shown here generalize to N levels)
Example input:
mux = pd.MultiIndex.from_arrays([
list('aaaabbbbbccddddd'),
list('tuvwtuvwtuvwtuvw')
], names=['one', 'two'])
df = pd.DataFrame({'col': np.arange(len(mux))}, mux)
col
one two
a t 0
u 1
v 2
w 3
b t 4
u 5
v 6
w 7
t 8
c u 9
v 10
d w 11
t 12
u 13
v 14
w 15
Question 1: Selecting a Single Item
How do I select rows having ""a"" in level ""one""?
col
one two
a t 0
u 1
v 2
w 3
Additionally, how would I be able to drop level ""one"" in the output?
col
two
t 0
u 1
v 2
w 3
Question 1b
How do I slice all rows with value ""t"" on level ""two""?
col
one two
a t 0
b t 4
t 8
d t 12
Question 2: Selecting Multiple Values in a Level
How can I select rows corresponding to items ""b"" and ""d"" in level ""one""?
col
one two
b t 4
u 5
v 6
w 7
t 8
d w 11
t 12
u 13
v 14
w 15
Question 2b
How would I get all values corresponding to ""t"" and ""w"" in level ""two""?
col
one two
a t 0
w 3
b t 4
w 7
t 8
d w 11
t 12
w 15
Question 3: Slicing a Single Cross Section (x, y)
How do I retrieve a cross section, i.e., a single row having a specific values for the index from df? Specifically, how do I retrieve the cross section of ('c', 'u'), given by
col
one two
c u 9
Question 4: Slicing Multiple Cross Sections [(a, b), (c, d), ...]
How do I select the two rows corresponding to ('c', 'u'), and ('a', 'w')?
col
one two
c u 9
a w 3
Question 5: One Item Sliced per Level
How can I retrieve all rows corresponding to ""a"" in level ""one"" or ""t"" in level ""two""?
col
one two
a t 0
u 1
v 2
w 3
b t 4
t 8
d t 12
Question 6: Arbitrary Slicing
How can I slice specific cross sections? For ""a"" and ""b"", I would like to select all rows with sub-levels ""u"" and ""v"", and for ""d"", I would like to select rows with sub-level ""w"".
col
one two
a u 1
v 2
b u 5
v 6
d w 11
w 15
Question 7 will use a unique setup consisting of a numeric level:
np.random.seed(0)
mux2 = pd.MultiIndex.from_arrays([
list('aaaabbbbbccddddd'),
np.random.choice(10, size=16)
], names=['one', 'two'])
df2 = pd.DataFrame({'col': np.arange(len(mux2))}, mux2)
col
one two
a 5 0
0 1
3 2
3 3
b 7 4
9 5
3 6
5 7
2 8
c 4 9
7 10
d 6 11
8 12
8 13
1 14
6 15
Question 7: Filtering by numeric inequality on individual levels of the multiindex
How do I get all rows where values in level ""two"" are greater than 5?
col
one two
b 7 4
9 5
c 7 10
d 6 11
8 12
8 13
6 15
Note: This post will not go through how to create MultiIndexes, how to perform assignment operations on them, or any performance related discussions (these are separate topics for another time).
",https://stackoverflow.com/questions/53927460/select-rows-in-pandas-multiindex-dataframe,347,154607.0,7.0,,,2018-12-26 04:36:11,2023-05-22 17:17:12,2019-11-20 15:36:04,,,python;pandas;dataframe;slice;multi-index,coldspeed95,407735,4909087,registered,true,53927461,,CC BY-SA 4.0,2019-12-27 09:10:30,4691,3855,18,1,0,5,true,false,false,true,true,true,42,6,false,0.045,0.0022,2887,2018,12,4,Wednesday,false,true,false,false,false,false,false
22676081,What is the difference between join and merge in Pandas?,"Suppose I have two DataFrames like so:
left = pd.DataFrame({'key1': ['foo', 'bar'], 'lval': [1, 2]})
right = pd.DataFrame({'key2': ['foo', 'bar'], 'rval': [4, 5]})
I want to merge them, so I try something like this:
pd.merge(left, right, left_on='key1', right_on='key2')
And I'm happy
key1 lval key2 rval
0 foo 1 foo 4
1 bar 2 bar 5
But I'm trying to use the join method, which I've been lead to believe is pretty similar.
left.join(right, on=['key1', 'key2'])
And I get this:
//anaconda/lib/python2.7/site-packages/pandas/tools/merge.pyc in _validate_specification(self)
406 if self.right_index:
407 if not ((len(self.left_on) == self.right.index.nlevels)):
--> 408 raise AssertionError()
409 self.right_on = [None] * n
410 elif self.right_on is not None:
AssertionError:
What am I missing?
",https://stackoverflow.com/questions/22676081/what-is-the-difference-between-join-and-merge-in-pandas,344,255387.0,7.0,,,2014-03-27 00:42:47,2024-05-21 13:44:08,2018-12-08 02:53:41,,,python;pandas;dataframe;join,munk,13223,633094,registered,true,22676213,,CC BY-SA 4.0,,1109,947,5,0,0,4,true,false,false,true,true,true,56,10,true,0.027,0.0013,4622,2014,3,0,Thursday,false,true,false,false,false,false,false
12497402,"Remove duplicates by columns A, keeping the row with the highest value in column B","I have a dataframe with repeat values in column A. I want to drop duplicates, keeping the row with the highest value in column B.
So this:
A B
1 10
1 20
2 30
2 40
3 10
Should turn into this:
A B
1 20
2 40
3 10
I'm guessing there's probably an easy way to do this—maybe as easy as sorting the DataFrame before dropping duplicates—but I don't know groupby's internal logic well enough to figure it out. Any suggestions?
",https://stackoverflow.com/questions/12497402/remove-duplicates-by-columns-a-keeping-the-row-with-the-highest-value-in-column,342,518911.0,15.0,,,2012-09-19 15:01:32,2023-08-14 14:05:08,2022-01-09 17:08:57,,,python;duplicates;pandas,Abe,24228,660664,registered,true,13059751,,CC BY-SA 4.0,,498,422,2,0,0,3,true,false,false,true,true,true,82,15,false,0.029,0.0007,5176,2012,9,15,Wednesday,false,true,false,false,false,false,false
14247586,How to select rows with one or more nulls from a pandas DataFrame without listing columns explicitly?,"I have a dataframe with ~300K rows and ~40 columns.
I want to find out if any rows contain null values - and put these 'null'-rows into a separate dataframe so that I could explore them easily.
I can create a mask explicitly:
mask = False
for col in df.columns:
mask = mask | df[col].isnull()
dfnulls = df[mask]
Or I can do something like:
df.ix[df.index[(df.T == np.nan).sum() > 1]]
Is there a more elegant way of doing it (locating rows with nulls in them)?
",https://stackoverflow.com/questions/14247586/how-to-select-rows-with-one-or-more-nulls-from-a-pandas-dataframe-without-listin,340,527468.0,6.0,,,2013-01-09 22:22:05,2021-06-06 07:17:08,2019-11-25 15:00:12,,,python;pandas;null;nan,Lev Selector,3841,1442475,registered,true,,,CC BY-SA 4.0,,551,475,2,0,0,4,false,false,false,true,true,true,101,17,true,0.011,0.0006,5064,2013,1,22,Wednesday,false,true,false,false,false,false,false
14984119,python pandas remove duplicate columns,"What is the easiest way to remove duplicate columns from a dataframe?
I am reading a text file that has duplicate columns via:
import pandas as pd
df=pd.read_table(fname)
The column names are:
Time, Time Relative, N2, Time, Time Relative, H2, etc...
All the Time and Time Relative columns contain the same data. I want:
Time, Time Relative, N2, H2
All my attempts at dropping, deleting, etc such as:
df=df.T.drop_duplicates().T
Result in uniquely valued index errors:
Reindexing only valid with uniquely valued index objects
Sorry for being a Pandas noob. Any Suggestions would be appreciated.
Additional Details
Pandas version: 0.9.0
Python Version: 2.7.3
Windows 7
(installed via Pythonxy 2.7.3.0)
data file (note: in the real file, columns are separated by tabs, here they are separated by 4 spaces):
Time Time Relative [s] N2[%] Time Time Relative [s] H2[ppm]
2/12/2013 9:20:55 AM 6.177 9.99268e+001 2/12/2013 9:20:55 AM 6.177 3.216293e-005
2/12/2013 9:21:06 AM 17.689 9.99296e+001 2/12/2013 9:21:06 AM 17.689 3.841667e-005
2/12/2013 9:21:18 AM 29.186 9.992954e+001 2/12/2013 9:21:18 AM 29.186 3.880365e-005
... etc ...
2/12/2013 2:12:44 PM 17515.269 9.991756+001 2/12/2013 2:12:44 PM 17515.269 2.800279e-005
2/12/2013 2:12:55 PM 17526.769 9.991754e+001 2/12/2013 2:12:55 PM 17526.769 2.880386e-005
2/12/2013 2:13:07 PM 17538.273 9.991797e+001 2/12/2013 2:13:07 PM 17538.273 3.131447e-005
",https://stackoverflow.com/questions/14984119/python-pandas-remove-duplicate-columns,335,546153.0,18.0,,,2013-02-20 15:49:17,2025-06-09 16:50:39,2013-02-20 17:53:59,,,python;pandas,Onlyjus,6239,979203,registered,true,40435354,,CC BY-SA 3.0,,1786,1539,6,0,0,2,true,false,false,true,true,true,38,5,false,0.033,0.0006,5022,2013,2,15,Wednesday,false,true,false,false,false,false,false
27842613,"pandas groupby, then sort within groups","I want to group my dataframe by two columns and then sort the aggregated results within those groups.
In [167]: df
Out[167]:
count job source
0 2 sales A
1 4 sales B
2 6 sales C
3 3 sales D
4 7 sales E
5 5 market A
6 3 market B
7 2 market C
8 4 market D
9 1 market E
In [168]: df.groupby(['job','source']).agg({'count':sum})
Out[168]:
count
job source
market A 5
B 3
C 2
D 4
E 1
sales A 2
B 4
C 6
D 3
E 7
I would now like to sort the 'count' column in descending order within each of the groups, and then take only the top three rows. To get something like:
count
job source
market A 5
D 4
B 3
sales E 7
C 6
B 4
",https://stackoverflow.com/questions/27842613/pandas-groupby-then-sort-within-groups,335,780489.0,9.0,,,2015-01-08 14:37:19,2022-06-16 00:35:43,2022-06-16 00:35:43,,,python;sorting;pandas;group-by,JoeDanger,3605,3198411,registered,true,27844045,,CC BY-SA 4.0,,1099,1037,2,0,0,4,true,false,false,true,true,true,39,6,false,0.012,0.0004,4335,2015,1,14,Thursday,false,true,false,false,false,false,false
20612645,How to find the installed pandas version,"I am having trouble with some of pandas functionalities. How do I check what is my installation version?
",https://stackoverflow.com/questions/20612645/how-to-find-the-installed-pandas-version,335,565916.0,6.0,,,2013-12-16 13:55:12,2024-11-15 20:25:49,2024-11-15 20:25:49,,,python;pandas;version,idoda,6458,1945306,registered,true,20612691,,CC BY-SA 4.0,,112,105,0,0,0,3,true,false,false,true,true,true,40,7,false,0.011,0.0006,4723,2013,12,13,Monday,false,true,false,false,false,false,false
75956209,Error "'DataFrame' object has no attribute 'append'","I am trying to append a dictionary to a DataFrame object, but I get the following error:
AttributeError: 'DataFrame' object has no attribute 'append'
As far as I know, DataFrame does have the method "append".
Code snippet:
df = pd.DataFrame(df).append(new_row, ignore_index=True)
I was expecting the dictionary new_row to be added as a new row.
How can I fix it?
",https://stackoverflow.com/questions/75956209/error-dataframe-object-has-no-attribute-append,333,757541.0,4.0,,,2023-04-07 07:05:59,2025-04-06 20:14:13,2025-01-22 18:45:23,,,python;pandas;dataframe;concatenation;attributeerror,Maksimjeet Chowdhary,3511,13595011,registered,true,,,CC BY-SA 4.0,2023-09-29 13:26:22,517,376,2,0,0,5,false,false,false,true,true,true,78,7,false,0.005,0.0004,1324,2023,4,7,Friday,false,true,false,false,false,false,false
16597265,Appending to an empty DataFrame in Pandas?,"Is it possible to append to an empty data frame that doesn't contain any indices or columns?
I have tried to do this, but keep getting an empty dataframe at the end.
e.g.
import pandas as pd
df = pd.DataFrame()
data = ['some kind of data here' --> I have checked the type already, and it is a dataframe]
df.append(data)
The result looks like this:
Empty DataFrame
Columns: []
Index: []
",https://stackoverflow.com/questions/16597265/appending-to-an-empty-dataframe-in-pandas,332,658866.0,6.0,,,2013-05-16 20:52:29,2023-04-15 06:43:14,2021-04-01 11:56:43,,,python;pandas,ericmjl,14964,1274908,registered,true,73641046,,CC BY-SA 4.0,2022-03-16 21:49:07,468,392,2,0,0,2,true,false,false,true,true,true,42,7,true,0.009,0.0005,4937,2013,5,20,Thursday,false,true,false,false,false,false,false
10665889,How to take column-slices of dataframe in pandas,"I load some machine learning data from a CSV file. The first 2 columns are observations and the remaining columns are features.
Currently, I do the following:
data = pandas.read_csv('mydata.csv')
which gives something like:
data = pandas.DataFrame(np.random.rand(10,5), columns = list('abcde'))
I'd like to slice this dataframe in two dataframes: one containing the columns a and b and one containing the columns c, d and e.
It is not possible to write something like
observations = data[:'c']
features = data['c':]
I'm not sure what the best method is. Do I need a pd.Panel?
By the way, I find dataframe indexing pretty inconsistent: data['a'] is permitted, but data[0] is not. On the other side, data['a':] is not permitted but data[0:] is.
Is there a practical reason for this? This is really confusing if columns are indexed by Int, given that data[0] != data[0:1]
",https://stackoverflow.com/questions/10665889/how-to-take-column-slices-of-dataframe-in-pandas,332,715597.0,11.0,,,2012-05-19 14:11:42,2021-10-25 22:32:58,2019-01-22 15:27:56,,,python;pandas;numpy;dataframe;slice,cpa,3904,1350862,registered,true,44736467,,CC BY-SA 4.0,2019-07-03 22:11:27,1146,882,14,0,0,5,true,false,false,true,true,true,48,8,false,0.015,0.0005,5299,2012,5,14,Saturday,true,true,false,false,false,false,false
14657241,How do I get a list of all the duplicate items using pandas in python?,"I have a list of items that likely has some export issues. I would like to get a list of the duplicate items so I can manually compare them. When I try to use pandas duplicated method, it only returns the first duplicate. Is there a a way to get all of the duplicates and not just the first one?
A small subsection of my dataset looks like this:
ID,ENROLLMENT_DATE,TRAINER_MANAGING,TRAINER_OPERATOR,FIRST_VISIT_DATE
1536D,12-Feb-12,""06DA1B3-Lebanon NH"",,15-Feb-12
F15D,18-May-12,""06405B2-Lebanon NH"",,25-Jul-12
8096,8-Aug-12,""0643D38-Hanover NH"",""0643D38-Hanover NH"",25-Jun-12
A036,1-Apr-12,""06CB8CF-Hanover NH"",""06CB8CF-Hanover NH"",9-Aug-12
8944,19-Feb-12,""06D26AD-Hanover NH"",,4-Feb-12
1004E,8-Jun-12,""06388B2-Lebanon NH"",,24-Dec-11
11795,3-Jul-12,""0649597-White River VT"",""0649597-White River VT"",30-Mar-12
30D7,11-Nov-12,""06D95A3-Hanover NH"",""06D95A3-Hanover NH"",30-Nov-11
3AE2,21-Feb-12,""06405B2-Lebanon NH"",,26-Oct-12
B0FE,17-Feb-12,""06D1B9D-Hartland VT"",,16-Feb-12
127A1,11-Dec-11,""064456E-Hanover NH"",""064456E-Hanover NH"",11-Nov-12
161FF,20-Feb-12,""0643D38-Hanover NH"",""0643D38-Hanover NH"",3-Jul-12
A036,30-Nov-11,""063B208-Randolph VT"",""063B208-Randolph VT"",
475B,25-Sep-12,""06D26AD-Hanover NH"",,5-Nov-12
151A3,7-Mar-12,""06388B2-Lebanon NH"",,16-Nov-12
CA62,3-Jan-12,,,
D31B,18-Dec-11,""06405B2-Lebanon NH"",,9-Jan-12
20F5,8-Jul-12,""0669C50-Randolph VT"",,3-Feb-12
8096,19-Dec-11,""0649597-White River VT"",""0649597-White River VT"",9-Apr-12
14E48,1-Aug-12,""06D3206-Hanover NH"",,
177F8,20-Aug-12,""063B208-Randolph VT"",""063B208-Randolph VT"",5-May-12
553E,11-Oct-12,""06D95A3-Hanover NH"",""06D95A3-Hanover NH"",8-Mar-12
12D5F,18-Jul-12,""0649597-White River VT"",""0649597-White River VT"",2-Nov-12
C6DC,13-Apr-12,""06388B2-Lebanon NH"",,
11795,27-Feb-12,""0643D38-Hanover NH"",""0643D38-Hanover NH"",19-Jun-12
17B43,11-Aug-12,,,22-Oct-12
A036,11-Aug-12,""06D3206-Hanover NH"",,19-Jun-12
My code looks like this currently:
df_bigdata_duplicates = df_bigdata[df_bigdata.duplicated(cols='ID')]
There area a couple duplicate items. But, when I use the above code, I only get the first item. In the API reference, I see how I can get the last item, but I would like to have all of them so I can visually inspect them to see why I am getting the discrepancy. So, in this example I would like to get all three A036 entries and both 11795 entries and any other duplicated entries, instead of the just first one. Any help is most appreciated.
",https://stackoverflow.com/questions/14657241/how-do-i-get-a-list-of-all-the-duplicate-items-using-pandas-in-python,330,726068.0,13.0,,,2013-02-02 00:22:08,2023-01-26 22:35:34,2020-05-31 02:37:47,,,python;pandas;duplicates,BigHandsome,5433,1467553,registered,true,14657511,,CC BY-SA 4.0,2020-05-16 07:58:50,2606,2432,2,1,0,3,true,false,false,true,true,true,70,15,true,0.018,0.0005,5040,2013,2,0,Saturday,true,true,false,false,false,false,false
32072076,Find the unique values in a column and then sort them,"I have a pandas dataframe. I want to print the unique values of one of its columns in ascending order. This is how I am doing it:
import pandas as pd
df = pd.DataFrame({'A':[1,1,3,2,6,2,8]})
a = df['A'].unique()
print a.sort()
The problem is that I am getting a None for the output.
",https://stackoverflow.com/questions/32072076/find-the-unique-values-in-a-column-and-then-sort-them,329,664821.0,9.0,,,2015-08-18 12:10:49,2023-10-15 15:14:25,2019-10-31 16:28:18,,,python;pandas;sorting;dataframe;unique,MAS,5119,4127806,registered,true,32072252,,CC BY-SA 4.0,,337,286,2,0,0,5,true,false,false,true,true,true,53,11,false,0.014,0.0005,4113,2015,8,12,Tuesday,false,true,false,false,false,false,false
15777951,How to suppress Pandas Future warning?,"When I run the program, Pandas gives 'Future warning' like below every time.
D:\Python\lib\site-packages\pandas\core\frame.py:3581:
FutureWarning: rename with inplace=True will return None from pandas 0.11 onward
" from pandas 0.11 onward", FutureWarning)
I got the message, but I just want to stop Pandas showing such message again and again. Is there any builtin parameter that I can set to make Pandas stop popping up the 'Future warning'?
",https://stackoverflow.com/questions/15777951/how-to-suppress-pandas-future-warning,327,474792.0,7.0,,,2013-04-03 02:37:48,2025-03-05 14:52:37,2024-07-25 16:30:42,,,python;pandas;warnings;suppress-warnings;future-warning,bigbug,60024,1072888,registered,true,15778297,,CC BY-SA 4.0,,536,459,1,0,0,5,true,false,false,true,true,true,38,6,true,0.015,0.0007,4980,2013,4,2,Wednesday,false,true,false,false,false,false,false
25962114,How do I read a large csv file with pandas?,"I am trying to read a large csv file (aprox. 6 GB) in pandas and i am getting a memory error:
MemoryError Traceback (most recent call last)
<ipython-input-58-67a72687871b> in <module>()
----> 1 data=pd.read_csv('aphro.csv',sep=';')
...
MemoryError:
Any help on this?
",https://stackoverflow.com/questions/25962114/how-do-i-read-a-large-csv-file-with-pandas,327,587100.0,16.0,,,2014-09-21 17:46:43,2023-08-13 10:10:58,2020-04-10 14:23:18,,,python;pandas;csv;memory;chunks,Rajkumar Kumawat,3787,4064040,registered,true,,,CC BY-SA 4.0,2019-06-17 11:39:57,356,318,1,0,0,5,false,false,false,true,true,true,43,10,true,0.027,0.0006,4444,2014,9,17,Sunday,true,true,false,false,false,false,false
24458645,Label encoding across multiple columns in scikit-learn,"I'm trying to use scikit-learn's LabelEncoder to encode a pandas DataFrame of string labels. As the dataframe has many (50+) columns, I want to avoid creating a LabelEncoder object for each column; I'd rather just have one big LabelEncoder objects that works across all my columns of data.
Throwing the entire DataFrame into LabelEncoder creates the below error. Please bear in mind that I'm using dummy data here; in actuality I'm dealing with about 50 columns of string labeled data, so need a solution that doesn't reference any columns by name.
import pandas
from sklearn import preprocessing
df = pandas.DataFrame({
'pets': ['cat', 'dog', 'cat', 'monkey', 'dog', 'dog'],
'owner': ['Champ', 'Ron', 'Brick', 'Champ', 'Veronica', 'Ron'],
'location': ['San_Diego', 'New_York', 'New_York', 'San_Diego', 'San_Diego',
'New_York']
})
le = preprocessing.LabelEncoder()
le.fit(df)
Traceback (most recent call last):
File """", line 1, in
File ""/Users/bbalin/anaconda/lib/python2.7/site-packages/sklearn/preprocessing/label.py"", line 103, in fit
y = column_or_1d(y, warn=True)
File ""/Users/bbalin/anaconda/lib/python2.7/site-packages/sklearn/utils/validation.py"", line 306, in column_or_1d
raise ValueError(""bad input shape {0}"".format(shape))
ValueError: bad input shape (6, 3)
Any thoughts on how to get around this problem?
",https://stackoverflow.com/questions/24458645/label-encoding-across-multiple-columns-in-scikit-learn,326,404101.0,25.0,,,2014-06-27 18:29:40,2022-09-27 16:18:35,2020-08-26 13:02:29,,,python;pandas;scikit-learn,Bryan,6199,1884063,registered,true,,,CC BY-SA 4.0,2019-07-03 22:15:09,1584,1420,7,0,0,3,false,false,false,true,true,true,54,7,false,0.062,0.0008,4530,2014,6,18,Friday,false,true,false,false,false,false,false
28218698,How to iterate over columns of a pandas dataframe,"I have this code using Pandas in Python:
all_data = {}
for ticker in ['FIUIX', 'FSAIX', 'FSAVX', 'FSTMX']:
all_data[ticker] = web.get_data_yahoo(ticker, '1/1/2010', '1/1/2015')
prices = DataFrame({tic: data['Adj Close'] for tic, data in all_data.iteritems()})
returns = prices.pct_change()
I know I can run a regression like this:
regs = sm.OLS(returns.FIUIX,returns.FSTMX).fit()
but how can I do this for each column in the dataframe? Specifically, how can I iterate over columns, in order to run the regression on each?
Specifically, I want to regress each other ticker symbol (FIUIX, FSAIX and FSAVX) on FSTMX, and store the residuals for each regression.
I've tried various versions of the following, but nothing I've tried gives the desired result:
resids = {}
for k in returns.keys():
reg = sm.OLS(returns[k],returns.FSTMX).fit()
resids[k] = reg.resid
Is there something wrong with the returns[k] part of the code? How can I use the k value to access a column? Or else is there a simpler approach?
",https://stackoverflow.com/questions/28218698/how-to-iterate-over-columns-of-a-pandas-dataframe,325,959695.0,12.0,,,2015-01-29 15:42:25,2025-01-08 15:58:36,2023-10-13 19:34:35,,,python;pandas,itzy,11885,368311,registered,true,32558621,,CC BY-SA 4.0,2019-07-03 22:17:32,1196,1022,5,0,0,2,true,false,false,true,true,true,49,9,false,0.013,0.0003,4314,2015,1,15,Thursday,false,true,false,false,false,false,false
23668427,pandas three-way joining multiple dataframes on columns,"I have 3 CSV files. Each has the first column as the (string) names of people, while all the other columns in each dataframe are attributes of that person.
How can I ""join"" together all three CSV documents to create a single CSV with each row having all the attributes for each unique value of the person's string name?
The join() function in pandas specifies that I need a multiindex, but I'm confused about what a hierarchical indexing scheme has to do with making a join based on a single index.
",https://stackoverflow.com/questions/23668427/pandas-three-way-joining-multiple-dataframes-on-columns,323,602269.0,12.0,,,2014-05-15 02:51:40,2022-12-08 11:21:28,2018-09-10 21:08:32,,,python;pandas;join;merge,lollercoaster,16623,712997,registered,true,30512931,,CC BY-SA 4.0,2019-08-09 13:45:48,537,503,1,0,0,4,true,false,false,true,true,true,55,7,false,0.02,0.0005,4573,2014,5,2,Thursday,false,true,false,false,false,false,false
17383094,How can I map True/False to 1/0 in a Pandas DataFrame?,"I have a column in python pandas DataFrame that has boolean True/False values, but for further calculations I need 1/0 representation. Is there a quick pandas/numpy way to do that?
",https://stackoverflow.com/questions/17383094/how-can-i-map-true-false-to-1-0-in-a-pandas-dataframe,323,457144.0,14.0,,,2013-06-29 17:53:19,2024-07-05 20:49:10,2022-01-17 14:51:13,,,python;pandas;dataframe;numpy;boolean,Simon Righley,5018,2107632,registered,true,27362540,,CC BY-SA 4.0,,279,181,7,0,0,5,true,false,false,true,true,true,54,11,true,0.031,0.0007,4893,2013,6,17,Saturday,true,true,false,false,false,false,false
22551403,Python pandas Filtering out nan from a data selection of a column of strings,"Without using groupby how would I filter out data without NaN?
Let say I have a matrix where customers will fill in 'N/A','n/a' or any of its variations and others leave it blank:
import pandas as pd
import numpy as np
df = pd.DataFrame({'movie': ['thg', 'thg', 'mol', 'mol', 'lob', 'lob'],
'rating': [3., 4., 5., np.nan, np.nan, np.nan],
'name': ['John', np.nan, 'N/A', 'Graham', np.nan, np.nan]})
nbs = df['name'].str.extract('^(N/A|NA|na|n/a)')
nms=df[(df['name'] != nbs) ]
output:
>>> nms
movie name rating
0 thg John 3
1 thg NaN 4
3 mol Graham NaN
4 lob NaN NaN
5 lob NaN NaN
How would I filter out NaN values so I can get results to work with like this:
movie name rating
0 thg John 3
3 mol Graham NaN
I am guessing I need something like ~np.isnan but the tilda does not work with strings.
",https://stackoverflow.com/questions/22551403/python-pandas-filtering-out-nan-from-a-data-selection-of-a-column-of-strings,323,770311.0,7.0,,,2014-03-21 06:04:19,2026-01-27 21:37:44,2020-11-16 03:06:15,,,python;pandas;dataframe,ccsv,8745,3159981,registered,true,22553757,,CC BY-SA 4.0,,1099,927,8,0,0,3,true,false,false,true,true,true,76,14,false,0.009,0.0004,4628,2014,3,6,Friday,false,true,false,false,false,false,false
36519086,How to get rid of "Unnamed: 0" column in a pandas DataFrame read in from CSV file?,"I have a situation wherein sometimes when I read a csv from df I get an unwanted index-like column named unnamed:0.
file.csv
,A,B,C
0,1,2,3
1,4,5,6
2,7,8,9
The CSV is read with this:
pd.read_csv('file.csv')
Unnamed: 0 A B C
0 0 1 2 3
1 1 4 5 6
2 2 7 8 9
This is very annoying! Does anyone have an idea on how to get rid of this?
",https://stackoverflow.com/questions/36519086/how-to-get-rid-of-unnamed-0-column-in-a-pandas-dataframe-read-in-from-csv-fil,322,516650.0,13.0,,,2016-04-09 15:47:43,2024-12-14 17:48:48,2021-11-27 18:58:27,,,python;pandas;csv;dataframe,Collective Action,8077,5211377,registered,true,36519122,,CC BY-SA 4.0,2019-01-25 04:03:18,520,385,6,0,0,4,true,false,false,true,true,true,92,17,true,0.025,0.0006,3878,2016,4,15,Saturday,true,true,false,false,false,false,false
17977540,Pandas: Looking up the list of sheets in an excel file,"The new version of Pandas uses the following interface to load Excel files:
read_excel('path_to_file.xls', 'Sheet1', index_col=None, na_values=['NA'])
but what if I don't know the sheets that are available?
For example, I am working with excel files that the following sheets
Data 1, Data 2 ..., Data N, foo, bar
but I don't know N a priori.
Is there any way to get the list of sheets from an excel document in Pandas?
",https://stackoverflow.com/questions/17977540/pandas-looking-up-the-list-of-sheets-in-an-excel-file,320,453321.0,13.0,,,2013-07-31 17:57:19,2024-06-05 06:04:28,2018-08-24 17:27:59,,,python;excel;pandas;openpyxl;xlrd,Amelio Vazquez-Reina,97532,283296,registered,true,17977609,,CC BY-SA 4.0,,676,431,2,1,0,5,true,false,false,true,true,true,54,11,false,0.029,0.0007,4861,2013,7,17,Wednesday,false,true,false,false,false,false,false
19758364,Rename specific column(s) in pandas,"I've got a dataframe called data. How would I rename the only one column header? For example gdp to log(gdp)?
data =
y gdp cap
0 1 2 5
1 2 3 9
2 8 7 2
3 3 4 7
4 6 7 7
5 4 8 3
6 8 2 8
7 9 9 10
8 6 6 4
9 10 10 7
",https://stackoverflow.com/questions/19758364/rename-specific-columns-in-pandas,317,559468.0,8.0,,,2013-11-03 21:28:48,2024-05-29 14:53:34,2019-04-07 09:42:44,,,python;pandas;dataframe;rename,natsuki_2002,25639,2428549,registered,true,19758398,,CC BY-SA 4.0,2021-12-13 15:16:35,365,295,4,0,0,4,true,false,false,true,true,true,35,5,false,0.014,0.0006,4766,2013,11,21,Sunday,true,true,false,false,false,false,false
23377108,Pandas percentage of total with groupby,"This is obviously simple, but as a numpy newbe I'm getting stuck.
I have a CSV file that contains 3 columns, the State, the Office ID, and the Sales for that office.
I want to calculate the percentage of sales per office in a given state (total of all percentages in each state is 100%).
df = pd.DataFrame({'state': ['CA', 'WA', 'CO', 'AZ'] * 3,
'office_id': list(range(1, 7)) * 2,
'sales': [np.random.randint(100000, 999999)
for _ in range(12)]})
df.groupby(['state', 'office_id']).agg({'sales': 'sum'})
This returns:
sales
state office_id
AZ 2 839507
4 373917
6 347225
CA 1 798585
3 890850
5 454423
CO 1 819975
3 202969
5 614011
WA 2 163942
4 369858
6 959285
I can't seem to figure out how to "reach up" to the state level of the groupby to total up the sales for the entire state to calculate the fraction.
",https://stackoverflow.com/questions/23377108/pandas-percentage-of-total-with-groupby,314,572241.0,17.0,,,2014-04-29 23:30:40,2025-07-19 07:18:34,2023-01-05 18:38:40,,,python;pandas;group-by,erikcw,11085,126617,registered,true,23377232,,CC BY-SA 4.0,,1219,1084,6,0,0,3,true,false,false,true,true,true,39,6,false,0.03,0.0005,4589,2014,4,23,Tuesday,false,true,false,false,false,false,false
21415661,Logical operators for Boolean indexing in Pandas,"I'm working with a Boolean index in Pandas.
The question is why the statement:
a[(a['some_column']==some_number) & (a['some_other_column']==some_other_number)]
works fine whereas
a[(a['some_column']==some_number) and (a['some_other_column']==some_other_number)]
exits with error?
Example:
a = pd.DataFrame({'x':[1,1],'y':[10,20]})
In: a[(a['x']==1)&(a['y']==10)]
Out: x y
0 1 10
In: a[(a['x']==1) and (a['y']==10)]
Out: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
",https://stackoverflow.com/questions/21415661/logical-operators-for-boolean-indexing-in-pandas,314,555519.0,4.0,,,2014-01-28 20:04:04,2023-08-23 23:04:48,2021-09-09 09:16:16,,,python;pandas;dataframe;boolean;filtering,user2988577,4237,2988577,registered,true,21415990,,CC BY-SA 4.0,,660,553,3,0,0,5,true,false,false,true,true,true,48,7,false,0.007,0.0006,4680,2014,1,20,Tuesday,false,true,false,false,false,false,false
17679089,Pandas DataFrame Groupby two columns and get counts,"I have a pandas dataframe in the following format:
df = pd.DataFrame([
[1.1, 1.1, 1.1, 2.6, 2.5, 3.4,2.6,2.6,3.4,3.4,2.6,1.1,1.1,3.3],
list('AAABBBBABCBDDD'),
[1.1, 1.7, 2.5, 2.6, 3.3, 3.8,4.0,4.2,4.3,4.5,4.6,4.7,4.7,4.8],
['x/y/z','x/y','x/y/z/n','x/u','x','x/u/v','x/y/z','x','x/u/v/b','-','x/y','x/y/z','x','x/u/v/w'],
['1','3','3','2','4','2','5','3','6','3','5','1','1','1']
]).T
df.columns = ['col1','col2','col3','col4','col5']
df:
col1 col2 col3 col4 col5
0 1.1 A 1.1 x/y/z 1
1 1.1 A 1.7 x/y 3
2 1.1 A 2.5 x/y/z/n 3
3 2.6 B 2.6 x/u 2
4 2.5 B 3.3 x 4
5 3.4 B 3.8 x/u/v 2
6 2.6 B 4 x/y/z 5
7 2.6 A 4.2 x 3
8 3.4 B 4.3 x/u/v/b 6
9 3.4 C 4.5 - 3
10 2.6 B 4.6 x/y 5
11 1.1 D 4.7 x/y/z 1
12 1.1 D 4.7 x 1
13 3.3 D 4.8 x/u/v/w 1
I want to get the count by each row like following. Expected Output:
col5 col2 count
1 A 1
D 3
2 B 2
etc...
How to get my expected output? And I want to find largest count for each 'col2' value?
",https://stackoverflow.com/questions/17679089/pandas-dataframe-groupby-two-columns-and-get-counts,314,1229863.0,8.0,,,2013-07-16 14:19:44,2023-11-07 18:06:15,2023-11-07 18:06:15,,,python;pandas;dataframe;group-by;pivot-table,Nilani Algiriyage,36166,461436,registered,true,17679980,,CC BY-SA 4.0,2019-07-15 12:53:46,1381,1166,3,0,0,5,true,false,false,true,true,true,51,8,false,0.007,0.0003,4876,2013,7,14,Tuesday,false,true,false,false,false,false,false
39050539,How to add multiple columns to pandas dataframe in one assignment,"I'm trying to figure out how to add multiple columns to pandas simultaneously with Pandas. I would like to do this in one step rather than multiple repeated steps.
import pandas as pd
data = {'col_1': [0, 1, 2, 3],
'col_2': [4, 5, 6, 7]}
df = pd.DataFrame(data)
I thought this would work here...
df[['column_new_1', 'column_new_2', 'column_new_3']] = [np.nan, 'dogs', 3]
",https://stackoverflow.com/questions/39050539/how-to-add-multiple-columns-to-pandas-dataframe-in-one-assignment,313,533394.0,14.0,,,2016-08-20 04:40:49,2025-06-18 16:16:42,2023-04-09 18:19:39,,,python;pandas;dataframe,runningbirds,6705,3788557,registered,true,39050916,,CC BY-SA 4.0,2023-04-10 18:45:44,445,383,2,0,0,3,true,false,false,true,true,true,65,11,false,0.026,0.0006,3745,2016,8,4,Saturday,true,true,false,false,false,false,false
19851005,Rename Pandas DataFrame Index,"I've a csv file without header, with a DateTime index. I want to rename the index and column name, but with df.rename() only the column name is renamed. Bug? I'm on version 0.12.0
In [2]: df = pd.read_csv(r'D:\Data\DataTimeSeries_csv//seriesSM.csv', header=None, parse_dates=[[0]], index_col=[0] )
In [3]: df.head()
Out[3]:
1
0
2002-06-18 0.112000
2002-06-22 0.190333
2002-06-26 0.134000
2002-06-30 0.093000
2002-07-04 0.098667
In [4]: df.rename(index={0:'Date'}, columns={1:'SM'}, inplace=True)
In [5]: df.head()
Out[5]:
SM
0
2002-06-18 0.112000
2002-06-22 0.190333
2002-06-26 0.134000
2002-06-30 0.093000
2002-07-04 0.098667
",https://stackoverflow.com/questions/19851005/rename-pandas-dataframe-index,312,770832.0,9.0,,,2013-11-08 03:19:20,2022-02-02 10:18:27,2022-02-02 10:18:27,,,python;pandas;dataframe;rename,Mattijn,14160,2459096,registered,true,19851521,,CC BY-SA 4.0,2018-05-17 07:31:08,750,719,1,0,0,4,true,false,false,true,true,true,29,4,false,0.012,0.0004,4761,2013,11,3,Friday,false,true,false,false,false,false,false
18689823,pandas DataFrame: replace nan values with average of columns,"I've got a pandas DataFrame filled mostly with real numbers, but there is a few nan values in it as well.
How can I replace the nans with averages of columns where they are?
This question is very similar to this one: numpy array: replace nan values with average of columns but, unfortunately, the solution given there doesn't work for a pandas DataFrame.
",https://stackoverflow.com/questions/18689823/pandas-dataframe-replace-nan-values-with-average-of-columns,311,712354.0,12.0,,,2013-09-08 23:54:05,2021-07-07 09:41:24,2017-05-23 11:55:10,,,python;pandas;nan,piokuc,26296,300886,registered,true,18691949,,CC BY-SA 3.0,2018-06-27 22:28:41,519,358,2,1,0,3,true,false,false,true,true,true,60,9,false,0.017,0.0004,4822,2013,9,23,Sunday,true,true,false,false,false,false,false
30522724,Take multiple lists into dataframe,"How do I take multiple lists and put them as different columns in a python dataframe? I tried this solution but had some trouble.
Attempt 1:
- Have three lists, and zip them together and use that
res = zip(lst1,lst2,lst3)
- Yields just one column
Attempt 2:
percentile_list = pd.DataFrame({'lst1Tite' : [lst1],
'lst2Tite' : [lst2],
'lst3Tite' : [lst3] },
columns=['lst1Tite','lst1Tite', 'lst1Tite'])
- yields either one row by 3 columns (the way above) or if I transpose it is 3 rows and 1 column
How do I get a 100 row (length of each independent list) by 3 column (three lists) pandas dataframe?
",https://stackoverflow.com/questions/30522724/take-multiple-lists-into-dataframe,308,665556.0,9.0,,,2015-05-29 06:37:49,2022-11-09 17:45:06,2019-01-26 13:54:25,,,python;numpy;pandas,jfalkson,3789,3105909,registered,true,30522778,,CC BY-SA 4.0,2018-07-07 08:37:05,914,701,2,1,0,3,true,false,false,true,true,true,34,5,false,0.014,0.0005,4194,2015,5,6,Friday,false,true,false,false,false,false,false
17241004,How do I convert a Pandas series or index to a NumPy array?,"How can I get the index or column of a DataFrame as a NumPy array or Python list?
",https://stackoverflow.com/questions/17241004/how-do-i-convert-a-pandas-series-or-index-to-a-numpy-array,308,599468.0,8.0,,,2013-06-21 17:25:25,2022-09-02 23:34:38,2022-09-02 23:26:27,2020-07-12 06:05:41,Duplicate,python;pandas,ericmjl,14964,1274908,registered,true,17242374,,,2019-07-04 00:10:51,89,82,0,0,0,2,true,true,false,true,true,true,59,13,true,0.013,0.0005,4901,2013,6,17,Friday,false,true,false,false,false,false,false
18429491,pandas GroupBy columns with NaN (missing) values,"I have a DataFrame with many missing values in columns which I wish to groupby:
import pandas as pd
import numpy as np
df = pd.DataFrame({'a': ['1', '2', '3'], 'b': ['4', np.NaN, '6']})
In [4]: df.groupby('b').groups
Out[4]: {'4': [0], '6': [2]}
By default pandas groupby dropped rows with NaN in the grouped column.
How can I include NaNs values as a group ?
",https://stackoverflow.com/questions/18429491/pandas-groupby-columns-with-nan-missing-values,307,439037.0,7.0,,,2013-08-25 13:28:41,2024-06-05 06:07:01,2024-06-05 06:07:01,,,python;pandas;group-by;nan,Gyula Sámuel Karli,3382,2715498,registered,true,,,CC BY-SA 4.0,2020-10-28 03:17:15,420,362,2,0,0,4,false,false,false,true,true,true,48,7,false,0.016,0.0007,4836,2013,8,13,Sunday,true,true,false,false,false,false,false
32244753,How to save a Seaborn plot into a file,"I tried the following code (test_seaborn.py):
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
matplotlib.style.use('ggplot')
import seaborn as sns
sns.set()
df = sns.load_dataset('iris')
sns_plot = sns.pairplot(df, hue='species', size=2.5)
fig = sns_plot.get_figure()
fig.savefig(""output.png"")
#sns.plt.show()
But I get this error:
Traceback (most recent call last):
File ""test_searborn.py"", line 11, in <module>
fig = sns_plot.get_figure()
AttributeError: 'PairGrid' object has no attribute 'get_figure'
I expect the final output.png will exist and look like this:
How can I resolve the problem?
",https://stackoverflow.com/questions/32244753/how-to-save-a-seaborn-plot-into-a-file,307,551466.0,12.0,,,2015-08-27 08:51:07,2025-04-14 03:42:32,2023-10-25 17:16:07,,,python;pandas;file;output;seaborn,neversaint,64786,67405,registered,true,,,CC BY-SA 4.0,2019-03-21 02:02:21,894,644,4,1,1,5,false,false,false,true,true,true,38,9,false,0.022,0.0006,4104,2015,8,8,Thursday,false,true,false,false,false,false,false
16396903,Delete the first three rows of a dataframe in pandas,"I need to delete the first three rows of a dataframe in pandas.
I know df.ix[:-1] would remove the last row, but I can't figure out how to remove first n rows.
",https://stackoverflow.com/questions/16396903/delete-the-first-three-rows-of-a-dataframe-in-pandas,306,549039.0,10.0,,,2013-05-06 10:35:58,2024-02-22 10:23:30,2019-03-06 21:48:53,,,python;pandas,Nilani Algiriyage,36166,461436,registered,true,16398361,,CC BY-SA 4.0,,188,161,1,0,0,2,true,false,false,true,true,true,52,10,false,0.018,0.0006,4947,2013,5,10,Monday,false,true,false,false,false,false,false
27975069,How to filter rows containing a string pattern from a Pandas dataframe,"Assume we have a data frame in Python Pandas that looks like this:
df = pd.DataFrame({'vals': [1, 2, 3, 4], 'ids': [u'aball', u'bball', u'cnut', u'fball']})
Or, in table form:
ids vals
aball 1
bball 2
cnut 3
fball 4
How do I filter rows which contain the key word ""ball?"" For example, the output should be:
ids vals
aball 1
bball 2
fball 4
",https://stackoverflow.com/questions/27975069/how-to-filter-rows-containing-a-string-pattern-from-a-pandas-dataframe,305,768773.0,4.0,,,2015-01-15 23:44:22,2019-04-21 03:23:12,2018-12-15 14:57:27,2019-01-24 11:35:38,Duplicate,python;pandas;dataframe,John Knight,3383,4383051,registered,true,27975230,,,2019-07-22 10:05:14,540,369,3,0,0,3,true,true,false,true,true,true,70,12,false,0.005,0.0004,4328,2015,1,23,Thursday,false,true,false,false,false,false,false
38134012,Pandas dataframe fillna() only some columns in place,"I am trying to fill none values in a Pandas dataframe with 0's for only some subset of columns.
When I do:
import pandas as pd
df = pd.DataFrame(data={'a':[1,2,3,None],'b':[4,5,None,6],'c':[None,None,7,8]})
print df
df.fillna(value=0, inplace=True)
print df
The output:
a b c
0 1.0 4.0 NaN
1 2.0 5.0 NaN
2 3.0 NaN 7.0
3 NaN 6.0 8.0
a b c
0 1.0 4.0 0.0
1 2.0 5.0 0.0
2 3.0 0.0 7.0
3 0.0 6.0 8.0
It replaces every None with 0's. What I want to do is, only replace Nones in columns a and b, but not c.
What is the best way of doing this?
",https://stackoverflow.com/questions/38134012/pandas-dataframe-fillna-only-some-columns-in-place,305,497815.0,10.0,,,2016-06-30 22:06:16,2023-05-17 08:06:06,2019-04-29 20:36:23,,,python;pandas;dataframe,Sait,19928,547820,registered,true,38134049,,CC BY-SA 4.0,,750,589,8,0,0,3,true,false,false,true,true,true,52,8,false,0.02,0.0006,3796,2016,6,22,Thursday,false,true,false,false,false,false,false
24284342,Insert a row to pandas dataframe,"I have a dataframe:
s1 = pd.Series([5, 6, 7])
s2 = pd.Series([7, 8, 9])
df = pd.DataFrame([list(s1), list(s2)], columns = [""A"", ""B"", ""C""])
A B C
0 5 6 7
1 7 8 9
[2 rows x 3 columns]
and I need to add a first row [2, 3, 4] to get:
A B C
0 2 3 4
1 5 6 7
2 7 8 9
I've tried append() and concat() functions but can't find the right way how to do that.
How to add/insert series to dataframe?
",https://stackoverflow.com/questions/24284342/insert-a-row-to-pandas-dataframe,302,1232935.0,20.0,,,2014-06-18 11:27:35,2025-02-23 18:08:31,2019-12-11 03:54:19,,,python;pandas;dataframe;insert,Meloun,15387,55129,registered,true,,,CC BY-SA 4.0,2023-04-28 14:46:02,526,424,4,0,0,4,false,false,false,true,true,true,32,6,false,0.016,0.0002,4539,2014,6,11,Wednesday,false,true,false,false,false,false,false
14162723,Replacing Pandas or Numpy Nan with a None to use with MysqlDB,"I am trying to write a Pandas dataframe (or can use a numpy array) to a mysql database using MysqlDB . MysqlDB doesn't seem understand 'nan' and my database throws out an error saying nan is not in the field list. I need to find a way to convert the 'nan' into a NoneType.
Any ideas?
",https://stackoverflow.com/questions/14162723/replacing-pandas-or-numpy-nan-with-a-none-to-use-with-mysqldb,301,518976.0,19.0,,,2013-01-04 18:26:06,2024-06-21 11:21:28,2019-01-04 12:20:22,,,python;pandas;numpy;mysql-python,FinDev,4917,365781,registered,true,14163209,,CC BY-SA 4.0,,300,286,0,0,0,4,true,false,false,true,true,true,61,12,false,0.037,0.0006,5069,2013,1,18,Friday,false,true,false,false,false,false,false
27405483,How to loop over grouped Pandas dataframe?,"DataFrame:
c_os_family_ss c_os_major_is l_customer_id_i
0 Windows 7 90418
1 Windows 7 90418
2 Windows 7 90418
Code:
for name, group in df.groupby('l_customer_id_i').agg(lambda x: ','.join(x)):
print name
print group
I'm trying to just loop over the aggregated data, but I get the error:
ValueError: too many values to unpack
I wish to loop over every group. How do I do it?
",https://stackoverflow.com/questions/27405483/how-to-loop-over-grouped-pandas-dataframe,301,505193.0,4.0,,,2014-12-10 16:01:40,2024-03-28 02:18:30,2023-11-02 06:11:59,,,python;pandas;dataframe;loops;group-by,Tjorriemorrie,17402,184379,registered,true,27422749,,CC BY-SA 4.0,2019-07-16 16:26:43,689,474,3,0,0,5,true,false,false,true,true,true,42,7,true,0.008,0.0006,4364,2014,12,16,Wednesday,false,true,false,false,false,false,false
21546739,Load data from txt with pandas,"I am loading a txt file containig a mix of float and string data. I want to store them in an array where I can access each element. Now I am just doing
import pandas as pd
data = pd.read_csv('output_list.txt', header = None)
print data
Each line in the input file looks like the following:
1 0 2000.0 70.2836942112 1347.28369421 /file_address.txt
Now the data are imported as a unique column. How can I divide it, so to store different elements separately (so I can call data[i,j])? And how can I define a header?
",https://stackoverflow.com/questions/21546739/load-data-from-txt-with-pandas,300,1413978.0,13.0,,,2014-02-04 07:48:58,2025-10-03 16:56:00,2023-10-20 19:40:10,,,python;pandas;file-io,albusdemens,6744,2828086,registered,true,51067912,,CC BY-SA 4.0,,676,518,3,0,0,3,true,false,false,true,true,true,30,6,false,0.009,0.0002,4673,2014,2,7,Tuesday,false,true,false,false,false,false,false
31037298,pandas get column average/mean,"I can't get the average or mean of a column in pandas. A have a dataframe. Neither of things I tried below gives me the average of the column weight
>>> allDF
ID birthyear weight
0 619040 1962 0.1231231
1 600161 1963 0.981742
2 25602033 1963 1.3123124
3 624870 1987 0.94212
The following returns several values, not one:
allDF[['weight']].mean(axis=1)
So does this:
allDF.groupby('weight').mean()
",https://stackoverflow.com/questions/31037298/pandas-get-column-average-mean,300,1130291.0,12.0,,,2015-06-24 21:22:11,2023-01-06 03:32:52,2020-07-21 19:14:48,,,python;pandas,PepperoniPizza,9222,1398915,registered,true,31037360,,CC BY-SA 4.0,,620,514,4,0,0,2,true,false,false,true,true,true,30,4,false,0.011,0.0003,4168,2015,6,21,Wednesday,false,true,false,false,false,false,false
15923826,Random row selection in Pandas dataframe,"Is there a way to select random rows from a DataFrame in Pandas.
In R, using the car package, there is a useful function some(x, n) which is similar to head but selects, in this example, 10 rows at random from x.
I have also looked at the slicing documentation and there seems to be nothing equivalent.
Update
Now using version 20. There is a sample method.
df.sample(n)
",https://stackoverflow.com/questions/15923826/random-row-selection-in-pandas-dataframe,300,236949.0,6.0,,,2013-04-10 10:52:47,2022-05-05 07:26:31,2022-03-17 09:45:05,,,python;pandas;random,John,43800,390388,registered,true,15923878,,CC BY-SA 4.0,,446,372,2,0,0,3,true,false,false,true,true,true,40,6,false,0.025,0.0013,4973,2013,4,10,Wednesday,false,true,false,false,false,false,false
65254535,xlrd.biffh.XLRDError: Excel xlsx file; not supported,"I am trying to read a macro-enabled Excel worksheet using pandas.read_excel with the xlrd library. It's running fine in local, but when I try to push the same into PCF, I am getting this error:
2020-12-11T21:09:53.441+05:30 [APP/PROC/WEB/0] [ERR] df1=pd.read_excel(os.path.join(APP_PATH, os.path.join("Data", "aug_latest.xlsm")),sheet_name=None)
2020-12-11T21:09:53.441+05:30 [APP/PROC/WEB/0] [ERR] return open_workbook(filepath_or_buffer)
2020-12-11T21:09:53.441+05:30 [APP/PROC/WEB/0] [ERR] File "/home/vcap/deps/0/python/lib/python3.8/site-packages/xlrd/__init__.py", line 170, in open_workbook
2020-12-11T21:09:53.441+05:30 [APP/PROC/WEB/0] [ERR] raise XLRDError(FILE_FORMAT_DESCRIPTIONS[file_format]+'; not supported')
2020-12-11T21:09:53.441+05:30 [APP/PROC/WEB/0] [ERR] xlrd.biffh.XLRDError: Excel xlsx file; not supported
How can I resolve this error?
",https://stackoverflow.com/questions/65254535/xlrd-biffh-xlrderror-excel-xlsx-file-not-supported,299,636435.0,2.0,,,2020-12-11 15:53:36,2021-02-08 14:50:47,2021-02-08 14:50:47,2020-12-16 12:40:36,Duplicate,python;pandas;xlrd;pcf,Vignesh K,3009,14808721,registered,true,,,,,982,892,2,0,0,4,false,true,false,true,true,true,52,6,false,0.003,0.0005,2171,2020,12,15,Friday,false,true,false,false,false,false,false
12589481,Multiple aggregations of the same column using pandas GroupBy.agg(),"Is there a pandas built-in way to apply two different aggregating functions f1, f2 to the same column df["returns"], without having to call agg() multiple times?
Example dataframe:
import pandas as pd
import datetime as dt
import numpy as np
pd.np.random.seed(0)
df = pd.DataFrame({
"date" : [dt.date(2012, x, 1) for x in range(1, 11)],
"returns" : 0.05 * np.random.randn(10),
"dummy" : np.repeat(1, 10)
})
The syntactically wrong, but intuitively right, way to do it would be:
# Assume `f1` and `f2` are defined for aggregating.
df.groupby("dummy").agg({"returns": f1, "returns": f2})
Obviously, Python doesn't allow duplicate keys. Is there any other manner for expressing the input to agg()? Perhaps a list of tuples [(column, function)] would work better, to allow multiple functions applied to the same column? But agg() seems like it only accepts a dictionary.
Is there a workaround for this besides defining an auxiliary function that just applies both of the functions inside of it? (How would this work with aggregation anyway?)
",https://stackoverflow.com/questions/12589481/multiple-aggregations-of-the-same-column-using-pandas-groupby-agg,299,317314.0,6.0,,,2012-09-25 19:05:26,2026-01-17 19:33:38,2024-12-02 18:45:31,,,python;pandas;dataframe;group-by;aggregate,ely,78025,567620,registered,true,13592901,,CC BY-SA 4.0,,1310,1149,8,0,0,5,true,false,false,true,true,true,67,9,false,0.019,0.0009,5170,2012,9,19,Tuesday,false,true,false,false,false,false,false
34091877,How to add header row to a pandas DataFrame,"I am reading a csv file into pandas. This csv file consists of four columns and some rows, but does not have a header row, which I want to add. I have been trying the following:
Cov = pd.read_csv("path/to/file.txt", sep='\t')
Frame = pd.DataFrame([Cov], columns = ["Sequence", "Start", "End", "Coverage"])
Frame.to_csv("path/to/file.txt", sep='\t')
But when I apply the code, I get the following Error:
ValueError: Shape of passed values is (1, 1), indices imply (4, 1)
What exactly does the error mean? And what would be a clean way in python to add a header row to my csv file/pandas df?
",https://stackoverflow.com/questions/34091877/how-to-add-header-row-to-a-pandas-dataframe,297,902608.0,7.0,,,2015-12-04 15:35:59,2025-04-08 03:06:02,2025-04-08 03:06:02,,,python;pandas;dataframe;csv;file-io,sequence_hard,5453,5347728,registered,true,34092032,,CC BY-SA 4.0,2019-07-03 22:20:28,797,652,2,0,0,5,true,false,false,true,true,true,43,9,false,0.008,0.0003,4005,2015,12,15,Friday,false,true,false,false,false,false,false
31511997,"Pandas DataFrame: replace all values in a column, based on condition","I have a simple DataFrame like the following:
Team
First Season
Total Games
0
Dallas Cowboys
1960
894
1
Chicago Bears
1920
1357
2
Green Bay Packers
1921
1339
3
Miami Dolphins
1966
792
4
Baltimore Ravens
1996
326
5
San Francisco 49ers
1950
1003
I want to select all values from the First Season column and replace those that are over 1990 by 1. In this example, only Baltimore Ravens would have the 1996 replaced by 1 (keeping the rest of the data intact).
I have used the following:
df.loc[(df['First Season'] > 1990)] = 1
But, it replaces all the values in that row by 1, not just the values in the 'First Season' column.
How can I replace just the values from that column?
",https://stackoverflow.com/questions/31511997/pandas-dataframe-replace-all-values-in-a-column-based-on-condition,297,687560.0,10.0,,,2015-07-20 08:35:34,2024-02-06 16:09:00,2023-02-26 05:02:27,,,python;pandas;dataframe,ichimok,3107,4801661,registered,true,31512025,,CC BY-SA 4.0,2020-06-11 03:45:20,1187,702,2,0,0,3,true,false,false,true,true,true,68,11,false,0.015,0.0004,4142,2015,7,8,Monday,false,true,false,false,false,false,false
20937538,How to display pandas DataFrame of floats using a format string for columns?,"I would like to display a pandas dataframe with a given format using print() and the IPython display(). For example:
df = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890],
index=['foo','bar','baz','quux'],
columns=['cost'])
print df
cost
foo 123.4567
bar 234.5678
baz 345.6789
quux 456.7890
I would like to somehow coerce this into printing
cost
foo $123.46
bar $234.57
baz $345.68
quux $456.79
without having to modify the data itself or create a copy, just change the way it is displayed.
How can I do this?
",https://stackoverflow.com/questions/20937538/how-to-display-pandas-dataframe-of-floats-using-a-format-string-for-columns,295,657199.0,10.0,,,2014-01-05 18:39:43,2023-08-08 22:17:49,2016-12-09 20:06:37,,,python;python-2.7;pandas;ipython;dataframe,Jason S,191310,44330,registered,true,20937592,,CC BY-SA 3.0,2019-07-03 22:19:40,693,591,4,0,0,5,true,false,false,true,true,true,76,13,true,0.015,0.0004,4703,2014,1,18,Sunday,true,true,false,false,false,false,false
19914937,Applying function with multiple arguments to create a new pandas column,"I want to create a new column in a pandas data frame by applying a function to two existing columns. Following this answer I've been able to create a new column when I only need one column as an argument:
import pandas as pd
df = pd.DataFrame({""A"": [10,20,30], ""B"": [20, 30, 10]})
def fx(x):
return x * x
print(df)
df['newcolumn'] = df.A.apply(fx)
print(df)
However, I cannot figure out how to do the same thing when the function requires multiple arguments. For example, how do I create a new column by passing column A and column B to the function below?
def fxy(x, y):
return x * y
",https://stackoverflow.com/questions/19914937/applying-function-with-multiple-arguments-to-create-a-new-pandas-column,292,416266.0,7.0,,,2013-11-11 20:07:30,2024-04-08 09:15:41,2017-05-23 10:31:15,,,python;pandas,Michael,14124,2327821,registered,true,19976286,,CC BY-SA 3.0,,734,600,3,1,0,2,true,false,false,true,true,true,71,11,false,0.017,0.0007,4758,2013,11,20,Monday,false,true,false,false,false,false,false
21137150,Format / Suppress Scientific Notation from Pandas Aggregation Results,"How can one modify the format for the output from a groupby operation in pandas that produces scientific notation for very large numbers?
I know how to do string formatting in python but I'm at a loss when it comes to applying it here.
df1.groupby('dept')['data1'].sum()
dept
value1 1.192433e+08
value2 1.293066e+08
value3 1.077142e+08
This suppresses the scientific notation if I convert to string but now I'm just wondering how to string format and add decimals.
sum_sales_dept.astype(str)
",https://stackoverflow.com/questions/21137150/format-suppress-scientific-notation-from-pandas-aggregation-results,292,531355.0,8.0,,,2014-01-15 12:14:36,2025-06-23 05:42:39,2022-02-18 17:03:18,,,python;pandas;floating-point;scientific-notation;number-formatting,horatio1701d,9259,2329714,registered,true,21140339,,CC BY-SA 4.0,2019-07-16 16:23:57,589,520,2,0,0,5,true,false,false,true,true,true,69,9,false,0.015,0.0005,4693,2014,1,12,Wednesday,false,true,false,false,false,false,false
32444138,Concatenate a list of pandas dataframes together,"I have a list of Pandas dataframes that I would like to combine into one Pandas dataframe. I am using Python 2.7.10 and Pandas 0.16.2
I created the list of dataframes from:
import pandas as pd
dfs = []
sqlall = ""select * from mytable""
for chunk in pd.read_sql_query(sqlall , cnxn, chunksize=10000):
dfs.append(chunk)
This returns a list of dataframes
type(dfs[0])
Out[6]: pandas.core.frame.DataFrame
type(dfs)
Out[7]: list
len(dfs)
Out[8]: 408
Here is some sample data
# sample dataframes
d1 = pd.DataFrame({'one' : [1., 2., 3., 4.], 'two' : [4., 3., 2., 1.]})
d2 = pd.DataFrame({'one' : [5., 6., 7., 8.], 'two' : [9., 10., 11., 12.]})
d3 = pd.DataFrame({'one' : [15., 16., 17., 18.], 'two' : [19., 10., 11., 12.]})
# list of dataframes
mydfs = [d1, d2, d3]
I would like to combine d1, d2, and d3 into one pandas dataframe. Alternatively, a method of reading a large-ish table directly into a dataframe when using the chunksize option would be very helpful.
",https://stackoverflow.com/questions/32444138/concatenate-a-list-of-pandas-dataframes-together,292,477173.0,6.0,,,2015-09-07 18:13:42,2023-06-18 09:29:34,2018-12-08 06:00:57,,,python;pandas;dataframe;concatenation,Whitebeard,6263,1683061,registered,true,32444187,,CC BY-SA 4.0,,1139,980,7,0,0,4,true,false,false,true,true,true,48,7,false,0.013,0.0006,4093,2015,9,18,Monday,false,true,false,false,false,false,false
17097643,Search for "does-not-contain" on a DataFrame in pandas,"I've done some searching and can't figure out how to filter a dataframe by
df["col"].str.contains(word)
however I'm wondering if there is a way to do the reverse: filter a dataframe by that set's compliment. eg: to the effect of
!(df["col"].str.contains(word))
Can this be done through a DataFrame method?
",https://stackoverflow.com/questions/17097643/search-for-does-not-contain-on-a-dataframe-in-pandas,291,466219.0,11.0,,,2013-06-13 21:43:26,2024-10-15 08:41:29,2022-04-16 21:59:00,,,python;pandas;contains,stites,5131,1529734,registered,true,17097777,,CC BY-SA 4.0,,410,328,3,0,0,3,true,false,false,true,true,true,64,8,false,0.024,0.0006,4909,2013,6,21,Thursday,false,true,false,false,false,false,false
21285380,Find column whose name contains a specific string,"I have a dataframe with column names, and I want to find the one that contains a certain string, but does not exactly match it. I'm searching for 'spike' in column names like 'spike-2', 'hey spike', 'spiked-in' (the 'spike' part is always continuous).
I want the column name to be returned as a string or a variable, so I access the column later with df['name'] or df[name] as normal. I've tried to find ways to do this, to no avail. Any tips?
",https://stackoverflow.com/questions/21285380/find-column-whose-name-contains-a-specific-string,289,562204.0,8.0,,,2014-01-22 14:17:43,2022-01-05 07:30:19,2019-03-11 03:35:38,,,python;python-3.x;string;pandas;dataframe,erikfas,4657,2795726,registered,true,21285575,,CC BY-SA 4.0,,551,446,7,0,0,5,true,false,false,true,true,true,49,8,false,0.014,0.0005,4686,2014,1,14,Wednesday,false,true,false,false,false,false,false
20067636,Pandas dataframe get first row of each group,"I have a pandas DataFrame like following:
df = pd.DataFrame({'id' : [1,1,1,2,2,3,3,3,3,4,4,5,6,6,6,7,7],
'value' : ["first","second","second","first",
"second","first","third","fourth",
"fifth","second","fifth","first",
"first","second","third","fourth","fifth"]})
I want to group this by ["id","value"] and get the first row of each group:
id value
0 1 first
1 1 second
2 1 second
3 2 first
4 2 second
5 3 first
6 3 third
7 3 fourth
8 3 fifth
9 4 second
10 4 fifth
11 5 first
12 6 first
13 6 second
14 6 third
15 7 fourth
16 7 fifth
Expected outcome:
id value
1 first
2 first
3 first
4 second
5 first
6 first
7 fourth
I tried following, which only gives the first row of the DataFrame.
In [25]: for index, row in df.iterrows():
....: df2 = pd.DataFrame(df.groupby(['id','value']).reset_index().ix[0])
",https://stackoverflow.com/questions/20067636/pandas-dataframe-get-first-row-of-each-group,289,377123.0,8.0,,,2013-11-19 09:24:34,2024-07-30 15:22:33,2024-07-30 15:18:59,,,python;pandas;dataframe;group-by;row,Nilani Algiriyage,36166,461436,registered,true,20067665,,CC BY-SA 4.0,,1435,1272,7,0,0,5,true,false,false,true,true,true,44,8,false,0.021,0.0008,4750,2013,11,9,Tuesday,false,true,false,false,false,false,false
17426292,How to create a dictionary of two pandas DataFrame columns,"What is the most efficient way to organise the following pandas Dataframe:
data =
Position Letter
1 a
2 b
3 c
4 d
5 e
into a dictionary like alphabet[1 : 'a', 2 : 'b', 3 : 'c', 4 : 'd', 5 : 'e']?
",https://stackoverflow.com/questions/17426292/how-to-create-a-dictionary-of-two-pandas-dataframe-columns,288,344161.0,8.0,,,2013-07-02 12:58:45,2024-09-26 17:16:22,2021-12-04 19:54:34,,,python;dictionary;pandas;dataframe,user1083734,5223,1083734,registered,true,17426500,,CC BY-SA 4.0,,311,253,2,0,0,4,true,false,false,true,true,true,58,10,false,0.023,0.0008,4890,2013,7,12,Tuesday,false,true,false,false,false,false,false
13445241,Replacing blank values (white space) with NaN in pandas,"I want to find all values in a Pandas dataframe that contain whitespace (any arbitrary amount) and replace those values with NaNs.
Any ideas how this can be improved?
Basically I want to turn this:
A B C
2000-01-01 -0.532681 foo 0
2000-01-02 1.490752 bar 1
2000-01-03 -1.387326 foo 2
2000-01-04 0.814772 baz
2000-01-05 -0.222552 4
2000-01-06 -1.176781 qux
Into this:
A B C
2000-01-01 -0.532681 foo 0
2000-01-02 1.490752 bar 1
2000-01-03 -1.387326 foo 2
2000-01-04 0.814772 baz NaN
2000-01-05 -0.222552 NaN 4
2000-01-06 -1.176781 qux NaN
I've managed to do it with the code below, but man is it ugly. It's not Pythonic and I'm sure it's not the most efficient use of pandas either. I loop through each column and do boolean replacement against a column mask generated by applying a function that does a regex search of each value, matching on whitespace.
for i in df.columns:
df[i][df[i].apply(lambda i: True if re.search('^\s*$', str(i)) else False)]=None
It could be optimized a bit by only iterating through fields that could contain empty strings:
if df[i].dtype == np.dtype('object')
But that's not much of an improvement
And finally, this code sets the target strings to None, which works with Pandas' functions like fillna(), but it would be nice for completeness if I could actually insert a NaN directly instead of None.
",https://stackoverflow.com/questions/13445241/replacing-blank-values-white-space-with-nan-in-pandas,288,604127.0,14.0,,,2012-11-18 22:22:39,2024-07-21 20:52:27,2019-01-21 09:25:18,,,python;pandas;dataframe,Chris Clark,4834,221390,registered,true,21942746,,CC BY-SA 4.0,,1737,1468,7,0,0,3,true,false,false,true,true,true,55,9,false,0.023,0.0005,5116,2012,11,22,Sunday,true,true,false,false,false,false,false
48647534,Find difference between two data frames,"I have two data frames df1 and df2, where df2 is a subset of df1. How do I get a new data frame (df3) which is the difference between the two data frames?
In other word, a data frame that has all the rows/columns in df1 that are not in df2?
",https://stackoverflow.com/questions/48647534/find-difference-between-two-data-frames,287,519172.0,19.0,,,2018-02-06 16:25:41,2023-01-26 17:08:29,2022-11-18 14:00:14,,,python;pandas;dataframe,userPyGeo,4061,7719336,registered,true,48647840,,CC BY-SA 4.0,2019-08-27 05:25:28,406,244,0,1,1,3,true,false,false,true,true,true,39,6,false,0.037,0.0006,3210,2018,2,16,Tuesday,false,true,false,false,false,false,false
28654047,Convert some columns into rows with Pandas,"So my dataset has some information by location for n dates. The problem is each date is actually a different column header. For example the CSV looks like
location name Jan-2010 Feb-2010 March-2010
A "test" 12 20 30
B "foo" 18 20 25
What I would like is for it to look like
location name Date Value
A "test" Jan-2010 12
A "test" Feb-2010 20
A "test" March-2010 30
B "foo" Jan-2010 18
B "foo" Feb-2010 20
B "foo" March-2010 25
My problem is I don't know how many dates are in the column (though I know they will always start after name)
",https://stackoverflow.com/questions/28654047/convert-some-columns-into-rows-with-pandas,284,334755.0,6.0,,,2015-02-22 03:08:28,2026-02-23 17:00:12,2026-02-23 17:00:12,,,python;pandas,Wizuriel,3797,1477617,registered,true,28654127,,CC BY-SA 4.0,,868,799,2,0,0,2,true,false,false,true,true,true,42,7,false,0.018,0.0008,4290,2015,2,3,Sunday,true,true,false,false,false,false,false
36226083,How to find which columns contain any NaN value in Pandas dataframe,"Given a pandas dataframe containing possible NaN values scattered here and there:
Question: How do I determine which columns contain NaN values? In particular, can I get a list of the column names containing NaNs?
",https://stackoverflow.com/questions/36226083/how-to-find-which-columns-contain-any-nan-value-in-pandas-dataframe,282,492577.0,16.0,,,2016-03-25 18:50:36,2025-02-05 12:33:58,2020-01-05 20:17:34,,,python;pandas;dataframe;nan,Jesper - jtk.eth,7574,3462321,registered,true,36226137,,CC BY-SA 4.0,,246,215,0,0,0,4,true,false,false,true,true,true,67,12,false,0.032,0.0006,3893,2016,3,18,Friday,false,true,false,false,false,false,false
21487329,Add x and y labels to a pandas plot,"Suppose I have the following code that plots something very simple using pandas:
import pandas as pd
values = [[1, 2], [2, 5]]
df2 = pd.DataFrame(values, columns=['Type A', 'Type B'],
index=['Index 1', 'Index 2'])
df2.plot(lw=2, colormap='jet', marker='.', markersize=10,
title='Video streaming dropout by category')
![]()
How do I easily set x and y-labels while preserving my ability to use specific colormaps? I noticed that the plot() wrapper for pandas DataFrames doesn't take any parameters specific for that.
",https://stackoverflow.com/questions/21487329/add-x-and-y-labels-to-a-pandas-plot,281,599213.0,8.0,,,2014-01-31 18:23:09,2021-06-24 17:20:14,2018-10-20 23:05:02,,,python;pandas;dataframe;matplotlib,Everaldo Aguiar,4156,369710,registered,true,65875329,,CC BY-SA 4.0,,659,545,2,0,1,4,true,false,false,true,true,true,35,9,false,0.013,0.0005,4677,2014,1,18,Friday,false,true,false,false,false,false,false
27905295,How to replace NaNs by preceding or next values in pandas DataFrame?,"Suppose I have a DataFrame with some NaNs:
>>> import pandas as pd
>>> df = pd.DataFrame([[1, 2, 3], [4, None, None], [None, None, 9]])
>>> df
0 1 2
0 1 2 3
1 4 NaN NaN
2 NaN NaN 9
What I need to do is replace every NaN with the first non-NaN value in the same column above it. It is assumed that the first row will never contain a NaN. So for the previous example the result would be
0 1 2
0 1 2 3
1 4 2 3
2 4 2 9
I can just loop through the whole DataFrame column-by-column, element-by-element and set the values directly, but is there an easy (optimally a loop-free) way of achieving this?
",https://stackoverflow.com/questions/27905295/how-to-replace-nans-by-preceding-or-next-values-in-pandas-dataframe,281,298122.0,10.0,,,2015-01-12 15:22:48,2022-12-10 02:31:04,2021-04-21 12:43:21,,,python;python-3.x;pandas;dataframe;nan,zegkljan,8439,461202,registered,true,27905350,,CC BY-SA 4.0,,779,658,6,0,0,5,true,false,false,true,true,true,68,12,true,0.034,0.0009,4331,2015,1,15,Monday,false,true,false,false,false,false,false
20069009,Pandas get topmost n records within each group,"Suppose I have pandas DataFrame like this:
df = pd.DataFrame({'id':[1,1,1,2,2,2,2,3,4], 'value':[1,2,3,1,2,3,4,1,1]})
which looks like:
id value
0 1 1
1 1 2
2 1 3
3 2 1
4 2 2
5 2 3
6 2 4
7 3 1
8 4 1
I want to get a new DataFrame with top 2 records for each id, like this:
id value
0 1 1
1 1 2
3 2 1
4 2 2
7 3 1
8 4 1
I can do it with numbering records within group after groupby:
dfN = df.groupby('id').apply(lambda x:x['value'].reset_index()).reset_index()
which looks like:
id level_1 index value
0 1 0 0 1
1 1 1 1 2
2 1 2 2 3
3 2 0 3 1
4 2 1 4 2
5 2 2 5 3
6 2 3 6 4
7 3 0 7 1
8 4 0 8 1
then for the desired output:
dfN[dfN['level_1'] <= 1][['id', 'value']]
Output:
id value
0 1 1
1 1 2
3 2 1
4 2 2
7 3 1
8 4 1
But is there more effective/elegant approach to do this? And also is there more elegant approach to number records within each group (like SQL window function row_number()).
",https://stackoverflow.com/questions/20069009/pandas-get-topmost-n-records-within-each-group,280,323216.0,6.0,,,2013-11-19 10:28:36,2023-02-10 01:02:34,2022-10-07 07:19:01,,,python;pandas;group-by;greatest-n-per-group;window-functions,roman,118614,1744834,registered,true,20069379,,CC BY-SA 4.0,,1868,1233,8,1,0,5,true,false,false,true,true,true,46,8,false,0.019,0.0009,4750,2013,11,10,Tuesday,false,true,false,false,false,false,false
45759966,Counting unique values in a column in pandas dataframe like in Qlik?,"If I have a table like this:
df = pd.DataFrame({
'hID': [101, 102, 103, 101, 102, 104, 105, 101],
'dID': [10, 11, 12, 10, 11, 10, 12, 10],
'uID': ['James', 'Henry', 'Abe', 'James', 'Henry', 'Brian', 'Claude', 'James'],
'mID': ['A', 'B', 'A', 'B', 'A', 'A', 'A', 'C']
})
I can do count(distinct hID) in Qlik to come up with count of 5 for unique hID. How do I do that in python using a pandas dataframe? Or maybe a numpy array? Similarly, if were to do count(hID) I will get 8 in Qlik. What is the equivalent way to do it in pandas?
",https://stackoverflow.com/questions/45759966/counting-unique-values-in-a-column-in-pandas-dataframe-like-in-qlik,279,733051.0,8.0,,,2017-08-18 15:15:32,2025-03-05 22:26:51,2017-08-18 15:21:15,,,python;pandas;numpy;qlikview;qliksense,Alhpa Delta,3700,8484261,registered,true,45760042,,CC BY-SA 3.0,,641,577,3,0,0,5,true,false,false,true,true,true,68,12,true,0.011,0.0004,3382,2017,8,15,Friday,false,true,false,false,false,false,false
15325182,How to filter rows in pandas by regex,"I would like to cleanly filter a dataframe using regex on one of the columns.
For a contrived example:
In [210]: foo = pd.DataFrame({'a' : [1,2,3,4], 'b' : ['hi', 'foo', 'fat', 'cat']})
In [211]: foo
Out[211]:
a b
0 1 hi
1 2 foo
2 3 fat
3 4 cat
I want to filter the rows to those that start with f using a regex. First go:
In [213]: foo.b.str.match('f.*')
Out[213]:
0 []
1 ()
2 ()
3 []
That's not too terribly useful. However this will get me my boolean index:
In [226]: foo.b.str.match('(f.*)').str.len() > 0
Out[226]:
0 False
1 True
2 True
3 False
Name: b
So I could then do my restriction by:
In [229]: foo[foo.b.str.match('(f.*)').str.len() > 0]
Out[229]:
a b
1 2 foo
2 3 fat
That makes me artificially put a group into the regex though, and seems like maybe not the clean way to go. Is there a better way to do this?
",https://stackoverflow.com/questions/15325182/how-to-filter-rows-in-pandas-by-regex,279,349873.0,10.0,,,2013-03-10 17:23:39,2024-03-13 16:30:06,2016-04-09 18:08:38,,,python;regex;pandas,justinvf,3179,1704581,registered,true,,,CC BY-SA 3.0,,1047,896,5,0,0,3,false,false,false,true,true,true,37,8,false,0.029,0.0008,5004,2013,3,17,Sunday,true,true,false,false,false,false,false
26577516,"How to test if a string contains one of the substrings in a list, in pandas?","Is there any function that would be the equivalent of a combination of df.isin() and df[col].str.contains()?
For example, say I have the series
s = pd.Series(['cat','hat','dog','fog','pet']), and I want to find all places where s contains any of ['og', 'at'], I would want to get everything but 'pet'.
I have a solution, but it's rather inelegant:
searchfor = ['og', 'at']
found = [s.str.contains(x) for x in searchfor]
result = pd.DataFrame[found]
result.any()
Is there a better way to do this?
",https://stackoverflow.com/questions/26577516/how-to-test-if-a-string-contains-one-of-the-substrings-in-a-list-in-pandas,275,410024.0,4.0,,,2014-10-26 20:23:37,2023-10-28 03:57:20,2019-07-01 18:11:17,,,python;string;pandas;dataframe;match,ari,4623,1628722,registered,true,26577689,,CC BY-SA 4.0,2025-10-28 17:08:02,619,502,6,0,0,5,true,false,false,true,true,true,76,16,true,0.01,0.0007,4409,2014,10,20,Sunday,true,true,false,false,false,false,false
20025882,Add a string prefix to each value in a pandas string column,"I would like to prepend a string to the start of each value in a said column of a pandas dataframe. I am currently using:
df.ix[(df['col'] != False), 'col'] = 'str' + df[(df['col'] != False), 'col']
This seems an inelegant method. Do you know any other way (which maybe also adds the character to rows where that column is 0 or NaN)?
As an example, I would like to turn:
col
1 a
2 0
into:
col
1 stra
2 str0
",https://stackoverflow.com/questions/20025882/add-a-string-prefix-to-each-value-in-a-pandas-string-column,273,439978.0,7.0,,,2013-11-17 00:56:09,2023-12-06 19:12:43,2023-12-06 19:12:43,,,python;string;pandas;dataframe,TheChymera,18166,1893275,registered,true,20027386,,CC BY-SA 4.0,,652,437,3,0,0,4,true,false,false,true,true,true,59,12,false,0.016,0.0006,4752,2013,11,0,Sunday,true,true,false,false,false,false,false
12182744,python pandas: apply a function with arguments to a series,"I want to apply a function with arguments to a series in python pandas:
x = my_series.apply(my_function, more_arguments_1)
y = my_series.apply(my_function, more_arguments_2)
...
The documentation describes support for an apply method, but it doesn't accept any arguments. Is there a different method that accepts arguments? Alternatively, am I missing a simple workaround?
Update (October 2017): Note that since this question was originally asked that pandas apply() has been updated to handle positional and keyword arguments and the documentation link above now reflects that and shows how to include either type of argument.
",https://stackoverflow.com/questions/12182744/python-pandas-apply-a-function-with-arguments-to-a-series,272,452669.0,7.0,,,2012-08-29 16:46:39,2022-08-16 16:01:37,2017-10-15 15:05:08,,,python;pandas;apply,Abe,24228,660664,registered,true,12183507,,CC BY-SA 3.0,,821,635,2,1,0,3,true,false,false,true,true,true,58,10,false,0.015,0.0006,5197,2012,8,16,Wednesday,false,true,false,false,false,false,false
20110170,Turn Pandas Multi-Index into column,"I have a dataframe with 2 index levels:
value
Trial measurement
1 0 13
1 3
2 4
2 0 NaN
1 12
3 0 34
Which I want to turn into this:
Trial measurement value
1 0 13
1 1 3
1 2 4
2 0 NaN
2 1 12
3 0 34
How can I best do this?
I need this because I want to aggregate the data as instructed here, but I can't select my columns like that if they are in use as indices.
",https://stackoverflow.com/questions/20110170/turn-pandas-multi-index-into-column,272,273797.0,8.0,,,2013-11-21 00:37:03,2023-08-14 11:18:44,2017-05-23 12:34:44,,,python;pandas;dataframe;flatten;multi-index,TheChymera,18166,1893275,registered,true,25733562,,CC BY-SA 3.0,,841,706,2,1,0,5,true,false,false,true,true,true,35,5,false,0.029,0.001,4748,2013,11,0,Thursday,false,true,false,false,false,false,false
9758450,Pandas convert dataframe to array of tuples,"I have manipulated some data using pandas and now I want to carry out a batch save back to the database. This requires me to convert the dataframe into an array of tuples, with each tuple corresponding to a ""row"" of the dataframe.
My DataFrame looks something like:
In [182]: data_set
Out[182]:
index data_date data_1 data_2
0 14303 2012-02-17 24.75 25.03
1 12009 2012-02-16 25.00 25.07
2 11830 2012-02-15 24.99 25.15
3 6274 2012-02-14 24.68 25.05
4 2302 2012-02-13 24.62 24.77
5 14085 2012-02-10 24.38 24.61
I want to convert it to an array of tuples like:
[(datetime.date(2012,2,17),24.75,25.03),
(datetime.date(2012,2,16),25.00,25.07),
...etc. ]
Any suggestion on how I can efficiently do this?
",https://stackoverflow.com/questions/9758450/pandas-convert-dataframe-to-array-of-tuples,270,380016.0,11.0,,,2012-03-18 12:53:06,2023-05-04 17:27:47,2017-01-04 21:49:07,,,python;pandas,enrishi,3123,939715,registered,true,34551914,,CC BY-SA 3.0,,819,743,2,0,0,2,true,false,false,true,true,true,43,7,false,0.029,0.0007,5361,2012,3,12,Sunday,true,true,false,false,false,false,false
31726643,How to plot in multiple subplots,"I am a little confused about how this code works:
fig, axes = plt.subplots(nrows=2, ncols=2)
plt.show()
How does the fig, axes work in this case? What does it do?
Also why wouldn't this work to do the same thing:
fig = plt.figure()
axes = fig.subplots(nrows=2, ncols=2)
",https://stackoverflow.com/questions/31726643/how-to-plot-in-multiple-subplots,270,660037.0,13.0,,,2015-07-30 14:31:58,2024-08-25 08:58:22,2021-08-15 16:41:36,,,python;pandas;matplotlib;seaborn;subplot,bugsyb,6191,3594588,registered,true,31728991,,CC BY-SA 4.0,2019-04-29 10:44:02,345,276,2,0,0,5,true,false,false,true,true,true,32,6,false,0.02,0.0004,4132,2015,7,14,Thursday,false,true,false,false,false,false,false
20444087,Right way to reverse a pandas DataFrame?,"Here is my code:
import pandas as pd
data = pd.DataFrame({'Odd':[1,3,5,6,7,9], 'Even':[0,2,4,6,8,10]})
for i in reversed(data):
print(data['Odd'], data['Even'])
When I run this code, i get the following error:
Traceback (most recent call last):
File ""C:\Python33\lib\site-packages\pandas\core\generic.py"", line 665, in _get_item_cache
return cache[item]
KeyError: 5
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File ""C:\Users\*****\Documents\******\********\****.py"", line 5, in <module>
for i in reversed(data):
File ""C:\Python33\lib\site-packages\pandas\core\frame.py"", line 2003, in __getitem__
return self._get_item_cache(key)
File ""C:\Python33\lib\site-packages\pandas\core\generic.py"", line 667, in _get_item_cache
values = self._data.get(item)
File ""C:\Python33\lib\site-packages\pandas\core\internals.py"", line 1656, in get
_, block = self._find_block(item)
File ""C:\Python33\lib\site-packages\pandas\core\internals.py"", line 1936, in _find_block
self._check_have(item)
File ""C:\Python33\lib\site-packages\pandas\core\internals.py"", line 1943, in _check_have
raise KeyError('no item named %s' % com.pprint_thing(item))
KeyError: 'no item named 5'
Why am I getting this error?
How can I fix that?
What is the right way to reverse pandas.DataFrame?
",https://stackoverflow.com/questions/20444087/right-way-to-reverse-a-pandas-dataframe,269,483348.0,8.0,,,2013-12-07 17:07:58,2024-09-25 18:44:06,2020-12-21 10:05:13,,,python;pandas;reverse,Michael,16303,2598876,registered,true,20444256,,CC BY-SA 4.0,2021-01-17 18:02:56,1482,1375,3,0,0,3,true,false,false,true,true,true,40,7,true,0.017,0.0006,4732,2013,12,17,Saturday,true,true,false,false,false,false,false
23667369,Drop all duplicate rows across multiple columns in Python Pandas,"The pandas drop_duplicates function is great for "uniquifying" a dataframe. I would like to drop all rows which are duplicates across a subset of columns. Is this possible?
A B C
0 foo 0 A
1 foo 1 A
2 foo 1 B
3 bar 1 A
As an example, I would like to drop rows which match on columns A and C so this should drop rows 0 and 1.
",https://stackoverflow.com/questions/23667369/drop-all-duplicate-rows-across-multiple-columns-in-python-pandas,268,599101.0,8.0,,,2014-05-15 00:31:47,2023-01-26 19:11:33,2023-01-26 19:10:16,,,python;pandas;dataframe;duplicates;drop-duplicates,Jamie Bull,13649,1706564,registered,true,34272155,,CC BY-SA 4.0,2019-07-16 16:27:26,476,360,4,0,0,5,true,false,false,true,true,true,64,10,false,0.013,0.0004,4573,2014,5,0,Thursday,false,true,false,false,false,false,false
37292872,How can I one hot encode in Python?,"I have a machine learning classification problem with 80% categorical variables. Must I use one hot encoding if I want to use some classifier for the classification? Can i pass the data to a classifier without the encoding?
I am trying to do the following for feature selection:
I read the train file:
num_rows_to_read = 10000
train_small = pd.read_csv(""../../dataset/train.csv"", nrows=num_rows_to_read)
I change the type of the categorical features to 'category':
non_categorial_features = ['orig_destination_distance',
'srch_adults_cnt',
'srch_children_cnt',
'srch_rm_cnt',
'cnt']
for categorical_feature in list(train_small.columns):
if categorical_feature not in non_categorial_features:
train_small[categorical_feature] = train_small[categorical_feature].astype('category')
I use one hot encoding:
train_small_with_dummies = pd.get_dummies(train_small, sparse=True)
The problem is that the 3'rd part often get stuck, although I am using a strong machine.
Thus, without the one hot encoding I can't do any feature selection, for determining the importance of the features.
What do you recommend?
",https://stackoverflow.com/questions/37292872/how-can-i-one-hot-encode-in-python,266,632874.0,22.0,,,2016-05-18 07:26:52,2022-09-27 08:08:48,2020-08-31 14:54:34,,,python;pandas;machine-learning;one-hot-encoding,avicohen,3067,6275292,registered,true,,,CC BY-SA 4.0,2018-04-20 05:50:04,1398,1234,3,0,0,4,false,false,false,true,true,true,35,8,true,0.035,0.0004,3839,2016,5,7,Wednesday,false,true,false,false,false,false,false
28986489,How to replace text in a string column of a Pandas dataframe?,"I have a column in my dataframe like this:
range
"(2,30)"
"(50,290)"
"(400,1000)"
...
and I want to replace the , comma with - dash. I'm currently using this method but nothing is changed.
org_info_exc['range'].replace(',', '-', inplace=True)
Can anybody help?
",https://stackoverflow.com/questions/28986489/how-to-replace-text-in-a-string-column-of-a-pandas-dataframe,264,749569.0,7.0,,,2015-03-11 12:19:59,2025-05-26 17:08:57,2021-12-21 22:11:56,,,python;replace;pandas;dataframe,UserYmY,8654,2058811,registered,true,28986536,,CC BY-SA 4.0,,389,294,4,0,0,4,true,false,false,true,true,true,61,12,true,0.009,0.0004,4273,2015,3,12,Wednesday,false,true,false,false,false,false,false
27263805,"Pandas column of lists, create a row for each list element","I have a dataframe where some cells contain lists of multiple values. Rather than storing multiple
values in a cell, I'd like to expand the dataframe so that each item in the list gets its own row (with the same values in all other columns). So if I have:
import pandas as pd
import numpy as np
df = pd.DataFrame(
{'trial_num': [1, 2, 3, 1, 2, 3],
'subject': [1, 1, 1, 2, 2, 2],
'samples': [list(np.random.randn(3).round(2)) for i in range(6)]
}
)
df
Out[10]:
samples subject trial_num
0 [0.57, -0.83, 1.44] 1 1
1 [-0.01, 1.13, 0.36] 1 2
2 [1.18, -1.46, -0.94] 1 3
3 [-0.08, -4.22, -2.05] 2 1
4 [0.72, 0.79, 0.53] 2 2
5 [0.4, -0.32, -0.13] 2 3
How do I convert to long form, e.g.:
subject trial_num sample sample_num
0 1 1 0.57 0
1 1 1 -0.83 1
2 1 1 1.44 2
3 1 2 -0.01 0
4 1 2 1.13 1
5 1 2 0.36 2
6 1 3 1.18 0
# etc.
The index is not important, it's OK to set existing
columns as the index and the final ordering isn't
important.
",https://stackoverflow.com/questions/27263805/pandas-column-of-lists-create-a-row-for-each-list-element,264,297877.0,10.0,,,2014-12-03 04:44:44,2021-04-01 06:27:37,2019-07-23 14:37:05,,,python;pandas;list,Marius,60706,1222578,registered,true,48532692,,CC BY-SA 4.0,,1364,1295,2,0,0,3,true,false,false,true,true,true,58,11,false,0.034,0.0009,4371,2014,12,4,Wednesday,false,true,false,false,false,false,false
26047209,What is the difference between a pandas Series and a single-column DataFrame?,"Why does pandas make a distinction between a Series and a single-column DataFrame?
In other words: what is the reason of existence of the Series class?
I'm mainly using time series with datetime index, maybe that helps to set the context.
",https://stackoverflow.com/questions/26047209/what-is-the-difference-between-a-pandas-series-and-a-single-column-dataframe,264,175458.0,6.0,,,2014-09-25 20:09:21,2021-04-28 18:38:02,2014-09-25 20:28:29,,,python;pandas,saroele,10269,566942,registered,true,26240208,,CC BY-SA 3.0,2019-07-03 22:19:11,299,242,3,0,0,2,true,false,false,true,true,true,77,12,true,0.034,0.0015,4440,2014,9,20,Thursday,false,true,false,false,false,false,false
21104592,JSON to pandas DataFrame,"What I am trying to do is extract elevation data from a google maps API along a path specified by latitude and longitude coordinates as follows:
from urllib2 import Request, urlopen
import json
path1 = '42.974049,-81.205203|42.974298,-81.195755'
request=Request('http://maps.googleapis.com/maps/api/elevation/json?locations='+path1+'&sensor=false')
response = urlopen(request)
elevations = response.read()
This gives me a data that looks like this:
elevations.splitlines()
['{',
' ""results"" : [',
' {',
' ""elevation"" : 243.3462677001953,',
' ""location"" : {',
' ""lat"" : 42.974049,',
' ""lng"" : -81.205203',
' },',
' ""resolution"" : 19.08790397644043',
' },',
' {',
' ""elevation"" : 244.1318664550781,',
' ""location"" : {',
' ""lat"" : 42.974298,',
' ""lng"" : -81.19575500000001',
' },',
' ""resolution"" : 19.08790397644043',
' }',
' ],',
' ""status"" : ""OK""',
'}']
when putting into as DataFrame here is what I get:
![]()
pd.read_json(elevations)
and here is what I want:
![]()
I'm not sure if this is possible, but mainly what I am looking for is a way to be able to put the elevation, latitude and longitude data together in a pandas dataframe (doesn't have to have fancy mutiline headers).
If any one can help or give some advice on working with this data that would be great! If you can't tell I haven't worked much with json data before...
EDIT:
This method isn't all that attractive but seems to work:
data = json.loads(elevations)
lat,lng,el = [],[],[]
for result in data['results']:
lat.append(result[u'location'][u'lat'])
lng.append(result[u'location'][u'lng'])
el.append(result[u'elevation'])
df = pd.DataFrame([lat,lng,el]).T
ends up dataframe having columns latitude, longitude, elevation
![]()
",https://stackoverflow.com/questions/21104592/json-to-pandas-dataframe,263,931822.0,14.0,,,2014-01-14 01:32:07,2021-08-16 15:09:50,2014-01-14 05:16:50,,,python;json;google-maps;pandas,pbreach,17197,2593236,registered,true,21266043,,CC BY-SA 3.0,2019-07-22 10:04:39,2286,1872,4,0,3,4,true,false,false,true,true,true,24,4,false,0.015,0.0003,4694,2014,1,1,Tuesday,false,true,false,false,false,false,false
20297332,How do I retrieve the number of columns in a Pandas data frame?,"How do you programmatically retrieve the number of columns in a pandas dataframe? I was hoping for something like:
df.num_columns
",https://stackoverflow.com/questions/20297332/how-do-i-retrieve-the-number-of-columns-in-a-pandas-data-frame,262,522428.0,11.0,,,2013-11-30 06:28:21,2021-06-08 03:56:56,2019-03-08 17:31:40,,,python;pandas;dataframe,user1802143,16022,1802143,registered,true,20297639,,CC BY-SA 4.0,,163,132,1,0,0,3,true,false,false,true,true,true,63,13,true,0.021,0.0005,4739,2013,11,6,Saturday,true,true,false,false,false,false,false
27517425,"Whether to use apply vs transform on a group object, to subtract two columns and get mean","Consider the following dataframe:
columns = ['A', 'B', 'C', 'D']
records = [
['foo', 'one', 0.162003, 0.087469],
['bar', 'one', -1.156319, -1.5262719999999999],
['foo', 'two', 0.833892, -1.666304],
['bar', 'three', -2.026673, -0.32205700000000004],
['foo', 'two', 0.41145200000000004, -0.9543709999999999],
['bar', 'two', 0.765878, -0.095968],
['foo', 'one', -0.65489, 0.678091],
['foo', 'three', -1.789842, -1.130922]
]
df = pd.DataFrame.from_records(records, columns=columns)
"""
A B C D
0 foo one 0.162003 0.087469
1 bar one -1.156319 -1.526272
2 foo two 0.833892 -1.666304
3 bar three -2.026673 -0.322057
4 foo two 0.411452 -0.954371
5 bar two 0.765878 -0.095968
6 foo one -0.654890 0.678091
7 foo three -1.789842 -1.130922
"""
The following commands work:
df.groupby('A').apply(lambda x: (x['C'] - x['D']))
df.groupby('A').apply(lambda x: (x['C'] - x['D']).mean())
but none of the following work:
df.groupby('A').transform(lambda x: (x['C'] - x['D']))
# KeyError or ValueError: could not broadcast input array from shape (5) into shape (5,3)
df.groupby('A').transform(lambda x: (x['C'] - x['D']).mean())
# KeyError or TypeError: cannot concatenate a non-NDFrame object
Why? The example on the documentation seems to suggest that calling transform on a group allows one to do row-wise operation processing:
# Note that the following suggests row-wise operation (x.mean is the column mean)
zscore = lambda x: (x - x.mean()) / x.std()
transformed = ts.groupby(key).transform(zscore)
In other words, I thought that transform is essentially a specific type of apply (the one that does not aggregate). Where am I wrong?
For reference, below is the construction of the original dataframe above:
df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
'foo', 'bar', 'foo', 'foo'],
'B' : ['one', 'one', 'two', 'three',
'two', 'two', 'one', 'three'],
'C' : randn(8), 'D' : randn(8)})
",https://stackoverflow.com/questions/27517425/whether-to-use-apply-vs-transform-on-a-group-object-to-subtract-two-columns-and,261,200213.0,5.0,,,2014-12-17 02:27:43,2023-11-15 02:20:45,2023-11-15 02:20:45,,,python;pandas,Amelio Vazquez-Reina,97532,283296,registered,true,47143056,,CC BY-SA 4.0,,2407,2100,6,1,0,2,true,false,false,true,true,true,89,17,false,0.025,0.0013,4357,2014,12,2,Wednesday,false,true,false,false,false,false,false
26658240,getting the index of a row in a pandas apply function,"I am trying to access the index of a row in a function applied across an entire DataFrame in Pandas. I have something like this:
df = pandas.DataFrame([[1,2,3],[4,5,6]], columns=['a','b','c'])
>>> df
a b c
0 1 2 3
1 4 5 6
and I'll define a function that access elements with a given row
def rowFunc(row):
return row['a'] + row['b'] * row['c']
I can apply it like so:
df['d'] = df.apply(rowFunc, axis=1)
>>> df
a b c d
0 1 2 3 7
1 4 5 6 34
Awesome! Now what if I want to incorporate the index into my function?
The index of any given row in this DataFrame before adding d would be Index([u'a', u'b', u'c', u'd'], dtype='object'), but I want the 0 and 1. So I can't just access row.index.
I know I could create a temporary column in the table where I store the index, but I'm wondering if it is stored in the row object somewhere.
",https://stackoverflow.com/questions/26658240/getting-the-index-of-a-row-in-a-pandas-apply-function,261,240841.0,3.0,,,2014-10-30 16:22:13,2023-01-13 21:20:03,2020-05-21 00:40:15,,,python;pandas;dataframe,Mike,7273,2055368,registered,true,26658301,,CC BY-SA 4.0,,1060,888,8,0,0,3,true,false,false,true,true,true,53,11,false,0.012,0.0011,4405,2014,10,16,Thursday,false,true,false,false,false,false,false
21269399,datetime dtypes in pandas read_csv,"I'm reading in a csv file with multiple datetime columns. I'd need to set the data types upon reading in the file, but datetimes appear to be a problem. For instance:
headers = ['col1', 'col2', 'col3', 'col4']
dtypes = ['datetime', 'datetime', 'str', 'float']
pd.read_csv(file, sep='\t', header=None, names=headers, dtype=dtypes)
When run gives a error:
TypeError: data type ""datetime"" not understood
Converting columns after the fact, via pandas.to_datetime() isn't an option I can't know which columns will be datetime objects. That information can change and comes from whatever informs my dtypes list.
Alternatively, I've tried to load the csv file with numpy.genfromtxt, set the dtypes in that function, and then convert to a pandas.dataframe but it garbles the data. Any help is greatly appreciated!
",https://stackoverflow.com/questions/21269399/datetime-dtypes-in-pandas-read-csv,260,484796.0,6.0,,,2014-01-21 21:24:17,2025-04-06 08:32:41,2018-10-19 14:39:13,,,python;csv;datetime;pandas;dataframe,user3221055,2611,3221055,registered,true,,,CC BY-SA 4.0,,904,820,1,0,0,5,false,false,false,true,true,true,34,5,false,0.012,0.0005,4687,2014,1,21,Tuesday,false,true,false,false,false,false,false
22591174,pandas: multiple conditions while indexing data frame - unexpected behavior,"I am filtering rows in a dataframe by values in two columns.
For some reason the OR operator behaves like I would expect AND operator to behave and vice versa.
My test code:
df = pd.DataFrame({'a': range(5), 'b': range(5) })
# let's insert some -1 values
df['a'][1] = -1
df['b'][1] = -1
df['a'][3] = -1
df['b'][4] = -1
df1 = df[(df.a != -1) & (df.b != -1)]
df2 = df[(df.a != -1) | (df.b != -1)]
print(pd.concat([df, df1, df2], axis=1,
keys = [ 'original df', 'using AND (&)', 'using OR (|)',]))
And the result:
original df using AND (&) using OR (|)
a b a b a b
0 0 0 0 0 0 0
1 -1 -1 NaN NaN NaN NaN
2 2 2 2 2 2 2
3 -1 3 NaN NaN -1 3
4 4 -1 NaN NaN 4 -1
[5 rows x 6 columns]
As you can see, the AND operator drops every row in which at least one value equals -1. On the other hand, the OR operator requires both values to be equal to -1 to drop them. I would expect exactly the opposite result. Could anyone explain this behavior?
I am using pandas 0.13.1.
",https://stackoverflow.com/questions/22591174/pandas-multiple-conditions-while-indexing-data-frame-unexpected-behavior,260,726985.0,5.0,,,2014-03-23 12:52:59,2026-04-24 04:09:45,2026-04-24 04:09:45,,,python;pandas;dataframe;indexing;conditional-statements,Wojciech Walczak,3639,1407427,registered,true,22591267,,CC BY-SA 4.0,,1455,1237,6,0,0,5,true,false,false,true,true,true,75,10,false,0.007,0.0004,4626,2014,3,12,Sunday,true,true,false,false,false,false,false
7908636,How to add hovering annotations to a plot,"I am using matplotlib to make scatter plots. Each point on the scatter plot is associated with a named object. I would like to be able to see the name of an object when I hover my cursor over the point on the scatter plot associated with that object. In particular, it would be nice to be able to quickly see the names of the points that are outliers. The closest thing I have been able to find while searching here is the annotate command, but that appears to create a fixed label on the plot. Unfortunately, with the number of points that I have, the scatter plot would be unreadable if I labeled each point. Does anyone know of a way to create labels that only appear when the cursor hovers in the vicinity of that point?
",https://stackoverflow.com/questions/7908636/how-to-add-hovering-annotations-to-a-plot,260,311600.0,13.0,,,2011-10-26 20:38:14,2023-10-11 08:19:16,2022-06-19 14:44:46,,,python;pandas;matplotlib;seaborn;mplcursors,jdmcbr,6566,897640,registered,true,47166787,,CC BY-SA 4.0,2019-03-21 02:03:53,732,725,0,0,0,5,true,false,false,true,true,true,41,8,false,0.042,0.0008,5505,2011,10,20,Wednesday,false,true,false,false,false,false,false
18528533,Pretty Printing a pandas dataframe,"How can I print a pandas dataframe as a nice text-based table, like the following?
+------------+---------+-------------+
| column_one | col_two | column_3 |
+------------+---------+-------------+
| 0 | 0.0001 | ABCD |
| 1 | 1e-005 | ABCD |
| 2 | 1e-006 | long string |
| 3 | 1e-007 | ABCD |
+------------+---------+-------------+
",https://stackoverflow.com/questions/18528533/pretty-printing-a-pandas-dataframe,259,500468.0,10.0,,,2013-08-30 08:40:28,2024-07-18 14:05:01,2019-01-23 22:35:38,,,python;pandas;dataframe;printing,Ofer,3213,374047,registered,true,,,CC BY-SA 4.0,,428,397,1,0,0,4,false,false,false,true,true,true,34,5,false,0.02,0.0005,4831,2013,8,8,Friday,false,true,false,false,false,false,false
32400867,Pandas read_csv from url,"I'm trying to read a csv-file from given URL, using Python 3.x:
import pandas as pd
import requests
url = "https://github.com/cs109/2014_data/blob/master/countries.csv"
s = requests.get(url).content
c = pd.read_csv(s)
I have the following error
"Expected file path name or file-like object, got <class 'bytes'> type"
How can I fix this? I'm using Python 3.4
",https://stackoverflow.com/questions/32400867/pandas-read-csv-from-url,259,447458.0,6.0,,,2015-09-04 14:44:24,2024-04-17 15:57:57,2021-01-31 03:57:54,,,python;csv;pandas;request,venom,2743,5301159,registered,true,32400969,,CC BY-SA 4.0,,465,388,1,0,0,4,true,false,false,true,true,true,24,4,false,0.013,0.0006,4096,2015,9,14,Friday,false,true,false,false,false,false,false
13611065,Efficient way to apply multiple filters to pandas DataFrame or Series,"I have a scenario where a user wants to apply several filters to a Pandas DataFrame or Series object. Essentially, I want to efficiently chain a bunch of filtering (comparison operations) together that are specified at run-time by the user.
- The filters should be additive (aka each one applied should narrow results).
- I'm currently using
reindex() (as below) but this creates a new object each time and copies the underlying data (if I understand the documentation correctly). I want to avoid this unnecessary copying as it will be really inefficient when filtering a big Series or DataFrame.
- I'm thinking that using
apply(), map(), or something similar might be better. I'm pretty new to Pandas though so still trying to wrap my head around everything.
- Also, I would like to expand this so that the dictionary passed in can include the columns to operate on and filter an entire DataFrame based on the input dictionary. However, I'm assuming whatever works for a Series can be easily expanded to a DataFrame.
TL;DR
I want to take a dictionary of the following form and apply each operation to a given Series object and return a 'filtered' Series object.
relops = {'>=': [1], '<=': [1]}
Long Example
I'll start with an example of what I have currently and just filtering a single Series object. Below is the function I'm currently using:
def apply_relops(series, relops):
"""
Pass dictionary of relational operators to perform on given series object
"""
for op, vals in relops.iteritems():
op_func = ops[op]
for val in vals:
filtered = op_func(series, val)
series = series.reindex(series[filtered])
return series
The user provides a dictionary with the operations they want to perform:
>>> df = pandas.DataFrame({'col1': [0, 1, 2], 'col2': [10, 11, 12]})
>>> print df
>>> print df
col1 col2
0 0 10
1 1 11
2 2 12
>>> from operator import le, ge
>>> ops ={'>=': ge, '<=': le}
>>> apply_relops(df['col1'], {'>=': [1]})
col1
1 1
2 2
Name: col1
>>> apply_relops(df['col1'], relops = {'>=': [1], '<=': [1]})
col1
1 1
Name: col1
Again, the 'problem' with my above approach is that I think there is a lot of possibly unnecessary copying of the data for the in-between steps.
",https://stackoverflow.com/questions/13611065/efficient-way-to-apply-multiple-filters-to-pandas-dataframe-or-series,259,608212.0,7.0,,,2012-11-28 17:34:35,2022-10-07 18:09:06,2022-04-23 04:51:33,,,python;pandas;algorithm;filter,durden2.0,9632,1108031,registered,true,13616382,,CC BY-SA 4.0,,2693,2433,6,0,0,4,true,false,false,true,true,true,69,11,false,0.012,0.0004,5106,2012,11,17,Wednesday,false,true,false,false,false,false,false
27298178,Concatenate strings from several rows using Pandas groupby,"I want to apply some sort of concatenation of the strings in a column using groupby.
This is my code so far:
import pandas as pd
from io import StringIO
data = StringIO("""
"name1","hej","2014-11-01"
"name1","du","2014-11-02"
"name1","aj","2014-12-01"
"name1","oj","2014-12-02"
"name2","fin","2014-11-01"
"name2","katt","2014-11-02"
"name2","mycket","2014-12-01"
"name2","lite","2014-12-01"
""")
# load string as stream into dataframe
df = pd.read_csv(data,header=0, names=["name","text","date"],parse_dates=[2])
# add column with month
df["month"] = df["date"].apply(lambda x: x.month)
I want the end result to look like this:
![]()
",https://stackoverflow.com/questions/27298178/concatenate-strings-from-several-rows-using-pandas-groupby,258,387716.0,8.0,,,2014-12-04 15:48:35,2024-01-23 21:23:36,2023-11-01 20:09:17,,,python;python-3.x;pandas;group-by,mattiasostmar,3199,1842091,registered,true,27298308,,CC BY-SA 4.0,,1085,953,1,0,1,4,true,false,false,true,true,true,58,8,false,0.021,0.0007,4370,2014,12,15,Thursday,false,true,false,false,false,false,false
11976503,How to keep index when using pandas merge,"I would like to merge two DataFrames, and keep the index from the first frame as the index on the merged dataset. However, when I do the merge, the resulting DataFrame has integer index. How can I specify that I want to keep the index from the left data frame?
In [4]: a = pd.DataFrame({'col1': {'a': 1, 'b': 2, 'c': 3},
'to_merge_on': {'a': 1, 'b': 3, 'c': 4}})
In [5]: b = pd.DataFrame({'col2': {0: 1, 1: 2, 2: 3},
'to_merge_on': {0: 1, 1: 3, 2: 5}})
In [6]: a
Out[6]:
col1 to_merge_on
a 1 1
b 2 3
c 3 4
In [7]: b
Out[7]:
col2 to_merge_on
0 1 1
1 2 3
2 3 5
In [8]: a.merge(b, how='left')
Out[8]:
col1 to_merge_on col2
0 1 1 1.0
1 2 3 2.0
2 3 4 NaN
In [9]: _.index
Out[9]: Int64Index([0, 1, 2], dtype='int64')
EDIT: Switched to example code that can be easily reproduced
",https://stackoverflow.com/questions/11976503/how-to-keep-index-when-using-pandas-merge,258,212200.0,10.0,,,2012-08-15 20:10:04,2023-11-03 16:06:30,2017-09-11 17:40:58,,,python;pandas,DanB,4055,670525,registered,true,11982843,,CC BY-SA 3.0,,1041,990,2,0,0,2,true,false,false,true,true,true,41,8,false,0.047,0.0012,5211,2012,8,20,Wednesday,false,true,false,false,false,false,false
38067704,How to change the datetime format in Pandas,"My dataframe has a DOB column (example format 1/26/2016) which by default gets converted to Pandas dtype 'object'.
Converting this to date format with df['DOB'] = pd.to_datetime(df['DOB']), the date gets converted to: 2016-01-26 and its dtype is datetime64[ns].
Now I want to convert this date format to 01/26/2016 or any other general date format. How do I do it?
(Whatever the method I try, it always shows the date in 2016-01-26 format.)
",https://stackoverflow.com/questions/38067704/how-to-change-the-datetime-format-in-pandas,257,1020347.0,9.0,,,2016-06-28 05:26:50,2025-04-11 19:41:41,2025-04-11 19:30:36,,,python;pandas;datetime,yome,3193,5066010,registered,true,38067805,,CC BY-SA 4.0,2019-08-04 08:25:33,611,441,7,0,0,3,true,false,false,true,true,true,43,8,false,0.009,0.0003,3798,2016,6,5,Tuesday,false,true,false,false,false,false,false
38250710,"How to split data into 3 sets (train, validation and test)?","I have a pandas dataframe and I wish to divide it to 3 separate sets. I know that using train_test_split from sklearn.cross_validation, one can divide the data in two sets (train and test). However, I couldn't find any solution about splitting the data into three sets. Preferably, I'd like to have the indices of the original data.
I know that a workaround would be to use train_test_split two times and somehow adjust the indices. But is there a more standard / built-in way to split the data into 3 sets instead of 2?
",https://stackoverflow.com/questions/38250710/how-to-split-data-into-3-sets-train-validation-and-test,257,269480.0,13.0,,,2016-07-07 16:26:26,2025-08-25 20:00:46,2025-08-25 20:00:46,,,python;pandas;dataframe;scikit-learn,CentAu,11380,3450064,registered,true,38251213,,CC BY-SA 4.0,,690,523,2,1,0,4,true,false,false,true,true,true,59,11,true,0.048,0.001,3789,2016,7,16,Thursday,false,true,false,false,false,false,false
26921651,How to delete the last row of data of a pandas dataframe,"I think this should be simple, but I tried a few ideas and none of them worked:
last_row = len(DF)
DF = DF.drop(DF.index[last_row]) #<-- fail!
I tried using negative indices but that also lead to errors. I must still be misunderstanding something basic.
",https://stackoverflow.com/questions/26921651/how-to-delete-the-last-row-of-data-of-a-pandas-dataframe,255,480825.0,11.0,,,2014-11-14 01:47:18,2022-12-26 11:29:50,2020-02-14 05:28:47,,,python;pandas,tumultous_rooster,12720,2822004,registered,true,,,CC BY-SA 4.0,,299,261,1,0,0,2,false,false,false,true,true,true,56,12,false,0.023,0.0005,4390,2014,11,1,Friday,false,true,false,false,false,false,false
20868394,Changing a specific column name in pandas DataFrame,"I was looking for an elegant way to change a specified column name in a DataFrame.
play data ...
import pandas as pd
d = {
'one': [1, 2, 3, 4, 5],
'two': [9, 8, 7, 6, 5],
'three': ['a', 'b', 'c', 'd', 'e']
}
df = pd.DataFrame(d)
The most elegant solution I have found so far ...
names = df.columns.tolist()
names[names.index('two')] = 'new_name'
df.columns = names
I was hoping for a simple one-liner ... this attempt failed ...
df.columns[df.columns.tolist().index('one')] = 'another_name'
Any hints gratefully received.
",https://stackoverflow.com/questions/20868394/changing-a-specific-column-name-in-pandas-dataframe,255,444392.0,10.0,,,2014-01-01 11:59:54,2021-08-31 21:00:06,2014-01-01 12:05:08,2021-07-08 07:47:55,Duplicate,python;pandas,Mark Graph,5151,1577110,registered,true,20868446,,,2019-07-03 22:15:21,683,563,4,0,0,2,true,true,false,true,true,true,51,8,false,0.023,0.0006,4707,2014,1,11,Wednesday,false,true,false,false,false,false,false
20297317,python dataframe pandas drop column using int,"I understand that to drop a column you use df.drop('column name', axis=1). Is there a way to drop a column using a numerical index instead of the column name?
",https://stackoverflow.com/questions/20297317/python-dataframe-pandas-drop-column-using-int,255,466047.0,11.0,,,2013-11-30 06:27:11,2022-04-20 14:56:05,2013-12-05 06:16:11,,,python;pandas;dataframe,user1802143,16022,1802143,registered,true,,,CC BY-SA 3.0,2019-07-16 16:24:14,166,159,0,0,0,3,false,false,false,true,true,true,45,7,false,0.024,0.0005,4739,2013,11,6,Saturday,true,true,false,false,false,false,false
14808945,check if variable is dataframe,"when my function f is called with a variable I want to check if var is a pandas dataframe:
def f(var):
if var == pd.DataFrame():
print ""do stuff""
I guess the solution might be quite simple but even with
def f(var):
if var.values != None:
print ""do stuff""
I can't get it to work like expected.
",https://stackoverflow.com/questions/14808945/check-if-variable-is-dataframe,255,318711.0,3.0,,,2013-02-11 09:10:07,2022-07-31 01:19:28,2018-12-14 07:24:36,,,python;pandas,trbck,5647,439693,registered,true,14809149,,CC BY-SA 4.0,,394,325,2,0,0,2,true,false,false,true,true,true,30,5,false,0.009,0.0008,5031,2013,2,9,Monday,false,true,false,false,false,false,false
24645153,pandas dataframe columns scaling with sklearn,"I have a pandas dataframe with mixed type columns, and I'd like to apply sklearn's min_max_scaler to some of the columns. Ideally, I'd like to do these transformations in place, but haven't figured out a way to do that yet. I've written the following code that works:
import pandas as pd
import numpy as np
from sklearn import preprocessing
scaler = preprocessing.MinMaxScaler()
dfTest = pd.DataFrame({'A':[14.00,90.20,90.95,96.27,91.21],'B':[103.02,107.26,110.35,114.23,114.68], 'C':['big','small','big','small','small']})
min_max_scaler = preprocessing.MinMaxScaler()
def scaleColumns(df, cols_to_scale):
for col in cols_to_scale:
df[col] = pd.DataFrame(min_max_scaler.fit_transform(pd.DataFrame(dfTest[col])),columns=[col])
return df
dfTest
A B C
0 14.00 103.02 big
1 90.20 107.26 small
2 90.95 110.35 big
3 96.27 114.23 small
4 91.21 114.68 small
scaled_df = scaleColumns(dfTest,['A','B'])
scaled_df
A B C
0 0.000000 0.000000 big
1 0.926219 0.363636 small
2 0.935335 0.628645 big
3 1.000000 0.961407 small
4 0.938495 1.000000 small
I'm curious if this is the preferred/most efficient way to do this transformation. Is there a way I could use df.apply that would be better?
I'm also surprised I can't get the following code to work:
bad_output = min_max_scaler.fit_transform(dfTest['A'])
If I pass an entire dataframe to the scaler it works:
dfTest2 = dfTest.drop('C', axis = 1)
good_output = min_max_scaler.fit_transform(dfTest2)
good_output
I'm confused why passing a series to the scaler fails. In my full working code above I had hoped to just pass a series to the scaler then set the dataframe column = to the scaled series.
",https://stackoverflow.com/questions/24645153/pandas-dataframe-columns-scaling-with-sklearn,255,359413.0,9.0,,,2014-07-09 03:57:55,2023-04-19 05:43:23,2022-03-03 08:38:44,,,python;pandas;scikit-learn;dataframe,flyingmeatball,8037,2255198,registered,true,36475297,,CC BY-SA 4.0,,1857,1750,3,0,0,4,true,false,false,true,true,true,45,6,false,0.025,0.0007,4518,2014,7,3,Wednesday,false,true,false,false,false,false,false
31357611,Format y axis as percent,"I have an existing plot that was created with pandas like this:
df['myvar'].plot(kind='bar')
The y axis is format as float and I want to change the y axis to percentages. All of the solutions I found use ax.xyz syntax and I can only place code below the line above that creates the plot (I cannot add ax=ax to the line above.)
How can I format the y axis as percentages without changing the line above?
Here is the solution I found but requires that I redefine the plot:
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.ticker as mtick
data = [8,12,15,17,18,18.5]
perc = np.linspace(0,100,len(data))
fig = plt.figure(1, (7,4))
ax = fig.add_subplot(1,1,1)
ax.plot(perc, data)
fmt = '%.0f%%' # Format you want the ticks, e.g. '40%'
xticks = mtick.FormatStrFormatter(fmt)
ax.xaxis.set_major_formatter(xticks)
plt.show()
Link to the above solution: Pyplot: using percentage on x axis
",https://stackoverflow.com/questions/31357611/format-y-axis-as-percent,254,381382.0,10.0,,,2015-07-11 13:21:01,2023-11-06 08:21:22,2017-05-23 10:31:16,,,python;pandas;matplotlib;plot,Chris,13890,3971910,registered,true,36319915,,CC BY-SA 3.0,,1142,915,2,1,0,4,true,false,false,true,true,true,24,5,false,0.026,0.0007,4151,2015,7,13,Saturday,true,true,false,false,false,false,false
22691010,How to print a groupby object,"I want to print the result of grouping with Pandas.
I have a dataframe:
import pandas as pd
df = pd.DataFrame({'A': ['one', 'one', 'two', 'three', 'three', 'one'], 'B': range(6)})
print(df)
A B
0 one 0
1 one 1
2 two 2
3 three 3
4 three 4
5 one 5
When printing after grouping by 'A' I have the following:
print(df.groupby('A'))
<pandas.core.groupby.DataFrameGroupBy object at 0x05416E90>
How can I print the dataframe grouped?
If I do:
print(df.groupby('A').head())
I obtain the dataframe as if it was not grouped:
A B
A
one 0 one 0
1 one 1
two 2 two 2
three 3 three 3
4 three 4
one 5 one 5
I was expecting something like:
A B
A
one 0 one 0
1 one 1
5 one 5
two 2 two 2
three 3 three 3
4 three 4
",https://stackoverflow.com/questions/22691010/how-to-print-a-groupby-object,254,415560.0,17.0,,,2014-03-27 14:42:29,2022-12-11 20:10:36,2018-08-24 13:37:12,,,python;pandas,user3465658,2751,3465658,registered,true,,,CC BY-SA 4.0,,1055,886,5,0,0,2,false,false,false,true,true,true,29,6,false,0.041,0.0006,4622,2014,3,14,Thursday,false,true,false,false,false,false,false
20109391,How to make good reproducible pandas examples,"Having spent a decent amount of time watching both the r and pandas tags on SO, the impression that I get is that pandas questions are less likely to contain reproducible data. This is something that the R community has been pretty good about encouraging, and thanks to guides like this, newcomers are able to get some help on putting together these examples. People who are able to read these guides and come back with reproducible data will often have much better luck getting answers to their questions.
How can we create good reproducible examples for pandas questions? Simple dataframes can be put together, e.g.:
import pandas as pd
df = pd.DataFrame({'user': ['Bob', 'Jane', 'Alice'],
'income': [40000, 50000, 42000]})
But many example datasets need more complicated structure, e.g.:
datetime indices or data
- Multiple categorical variables (is there an equivalent to R's
expand.grid() function, which produces all possible combinations of some given variables?)
- MultiIndex data
For datasets that are hard to mock up using a few lines of code, is there an equivalent to R's dput() that allows you to generate copy-pasteable code to regenerate your datastructure?
",https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples,253,58176.0,5.0,,,2013-11-20 23:31:39,2026-05-12 07:50:11,2023-12-11 17:10:58,,,python;pandas,Marius,60706,1222578,registered,true,20159305,,CC BY-SA 4.0,2023-12-08 13:23:00,1850,1192,6,3,0,2,true,false,false,true,true,true,45,7,false,0.086,0.0043,4749,2013,11,23,Wednesday,false,true,false,false,false,false,false
12850345,How do I combine two dataframes?,"I have a initial dataframe D. I extract two data frames from it like this:
A = D[D.label == k]
B = D[D.label != k]
I want to combine A and B into one DataFrame. The order of the data is not important. However, when we sample A and B from D, they retain their indexes from D.
",https://stackoverflow.com/questions/12850345/how-do-i-combine-two-dataframes,253,675377.0,9.0,,,2012-10-11 23:53:37,2025-10-14 23:55:29,2022-07-01 23:39:01,,,python;pandas,MKoosej,3696,445491,registered,true,12850453,,CC BY-SA 4.0,2023-04-27 16:27:50,405,276,8,0,0,2,true,false,false,true,true,true,32,6,true,0.013,0.0004,5154,2012,10,23,Thursday,false,true,false,false,false,false,false
19324453,Add missing dates to pandas dataframe,"My data can have multiple events on a given date or NO events on a date. I take these events, get a count by date and plot them. However, when I plot them, my two series don't always match.
idx = pd.date_range(df['simpleDate'].min(), df['simpleDate'].max())
s = df.groupby(['simpleDate']).size()
In the above code idx becomes a range of say 30 dates. 09-01-2013 to 09-30-2013
However S may only have 25 or 26 days because no events happened for a given date. I then get an AssertionError as the sizes dont match when I try to plot:
fig, ax = plt.subplots()
ax.bar(idx.to_pydatetime(), s, color='green')
What's the proper way to tackle this? Do I want to remove dates with no values from IDX or (which I'd rather do) is add to the series the missing date with a count of 0. I'd rather have a full graph of 30 days with 0 values. If this approach is right, any suggestions on how to get started? Do I need some sort of dynamic reindex function?
Here's a snippet of S ( df.groupby(['simpleDate']).size() ), notice no entries for 04 and 05.
09-02-2013 2
09-03-2013 10
09-06-2013 5
09-07-2013 1
",https://stackoverflow.com/questions/19324453/add-missing-dates-to-pandas-dataframe,252,246495.0,7.0,,,2013-10-11 17:58:15,2022-12-19 17:16:01,2017-09-15 13:41:30,,,python;date;plot;pandas;dataframe,KHibma,3149,1756833,registered,true,19324591,,CC BY-SA 3.0,,1318,1124,5,0,0,5,true,false,false,true,true,true,37,6,false,0.028,0.001,4789,2013,10,17,Friday,false,true,false,false,false,false,false
17465045,Can pandas automatically read dates from a CSV file?,"Today I was positively surprised by the fact that while reading data from a data file (for example) pandas is able to recognize types of values:
df = pandas.read_csv('test.dat', delimiter=r""\s+"", names=['col1','col2','col3'])
For example it can be checked in this way:
for i, r in df.iterrows():
print type(r['col1']), type(r['col2']), type(r['col3'])
In particular integer, floats and strings were recognized correctly. However, I have a column that has dates in the following format: 2013-6-4. These dates were recognized as strings (not as python date-objects). Is there a way to ""learn"" pandas to recognized dates?
",https://stackoverflow.com/questions/17465045/can-pandas-automatically-read-dates-from-a-csv-file,251,430988.0,13.0,,,2013-07-04 08:08:39,2025-05-27 18:21:57,2021-08-15 00:40:42,,,python;date;types;dataframe;pandas,Roman,132560,245549,registered,true,17468012,,CC BY-SA 4.0,2019-07-16 16:24:38,711,629,3,0,0,5,true,false,false,true,true,true,52,9,true,0.03,0.0006,4888,2013,7,8,Thursday,false,true,false,false,false,false,false
14663004,How to get the last N rows of a pandas DataFrame?,"I have pandas dataframe df1:
STK_ID RPT_Date TClose sales discount
0 000568 20060331 3.69 5.975 NaN
1 000568 20060630 9.14 10.143 NaN
2 000568 20060930 9.49 13.854 NaN
3 000568 20061231 15.84 19.262 NaN
4 000568 20070331 17.00 6.803 NaN
5 000568 20070630 26.31 12.940 NaN
6 000568 20070930 39.12 19.977 NaN
7 000568 20071231 45.94 29.269 NaN
8 000568 20080331 38.75 12.668 NaN
9 000568 20080630 30.09 21.102 NaN
10 000568 20080930 26.00 30.769 NaN
I wanted to select the last 3 rows and tried df1.ix[-3:], but it returns all the rows. Why? How to get the last 3 rows of df1? I'm using pandas 0.10.1.
",https://stackoverflow.com/questions/14663004/how-to-get-the-last-n-rows-of-a-pandas-dataframe,250,495172.0,4.0,,,2013-02-02 14:40:31,2024-10-04 14:19:48,2024-01-30 00:22:13,,,python;pandas;dataframe;indexing,bigbug,60024,1072888,registered,true,14760930,,CC BY-SA 4.0,,862,746,4,0,0,4,true,false,false,true,true,true,49,11,true,0.008,0.0005,5040,2013,2,14,Saturday,true,true,false,false,false,false,false
28311655,Ignoring NaNs with str.contains,"I want to find rows that contain a string, like so:
DF[DF.col.str.contains(""foo"")]
However, this fails because some elements are NaN:
ValueError: cannot index with vector containing NA / NaN values
So I resort to the obfuscated
DF[DF.col.notnull()][DF.col.dropna().str.contains(""foo"")]
Is there a better way?
",https://stackoverflow.com/questions/28311655/ignoring-nans-with-str-contains,250,250917.0,6.0,,,2015-02-04 00:57:17,2023-01-08 02:45:36,2019-03-07 08:20:50,,,python;pandas,Emre,6260,832188,registered,true,28312011,,CC BY-SA 4.0,,429,321,2,0,0,2,true,false,false,true,true,true,31,4,false,0.024,0.001,4308,2015,2,0,Wednesday,false,true,false,false,false,false,false
34165731,A column-vector y was passed when a 1d array was expected,"I need to fit RandomForestRegressor from sklearn.ensemble.
forest = ensemble.RandomForestRegressor(**RF_tuned_parameters)
model = forest.fit(train_fold, train_y)
yhat = model.predict(test_fold)
This code always worked until I made some preprocessing of data (train_y).
The error message says:
DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples,), for example using ravel().
model = forest.fit(train_fold, train_y)
Previously train_y was a Series, now it's numpy array (it is a column-vector). If I apply train_y.ravel(), then it becomes a row vector and no error message appears, through the prediction step takes very long time (actually it never finishes...).
In the docs of RandomForestRegressor I found that train_y should be defined as y : array-like, shape = [n_samples] or [n_samples, n_outputs]
Any idea how to solve this issue?
",https://stackoverflow.com/questions/34165731/a-column-vector-y-was-passed-when-a-1d-array-was-expected,250,369560.0,10.0,,,2015-12-08 20:47:29,2025-02-05 15:52:31,2020-06-20 09:12:55,,,python;pandas;numpy;scikit-learn,Klausos Klausos,16138,1089623,registered,true,,,CC BY-SA 4.0,,1109,914,9,0,0,4,false,false,false,true,true,true,57,11,false,0.027,0.0007,4001,2015,12,20,Tuesday,false,true,false,false,false,false,false
18327624,Find element's index in pandas Series,"I know this is a very basic question but for some reason I can't find an answer. How can I get the index of certain element of a Series in python pandas? (first occurrence would suffice)
I.e., I'd like something like:
import pandas as pd
myseries = pd.Series([1,4,0,7,5], index=[0,1,2,3,4])
print myseries.find(7) # should output 3
Certainly, it is possible to define such a method with a loop:
def find(s, el):
for i in s.index:
if s[i] == el:
return i
return None
print find(myseries, 7)
but I assume there should be a better way. Is there?
",https://stackoverflow.com/questions/18327624/find-elements-index-in-pandas-series,250,587546.0,13.0,,,2013-08-20 05:33:54,2026-07-03 22:26:24,,,,python;pandas,sashkello,18017,1564449,registered,true,18327852,,CC BY-SA 3.0,2019-07-16 16:24:25,656,580,2,0,0,2,true,false,false,true,true,false,41,6,false,0.022,0.0004,4841,2013,8,5,Tuesday,false,true,false,false,false,false,false
25039626,How do I find numeric columns in Pandas?,"Let's say df is a pandas DataFrame.
I would like to find all columns of numeric type.
Something like:
isNumeric = is_numeric(df)
",https://stackoverflow.com/questions/25039626/how-do-i-find-numeric-columns-in-pandas,248,401792.0,15.0,,,2014-07-30 14:36:21,2023-09-07 22:11:08,2017-10-18 08:33:46,,,python;types;pandas,Hanan Shteingart,9216,2424587,registered,true,,,CC BY-SA 3.0,2024-11-19 02:41:31,175,131,2,0,0,3,false,false,false,true,true,true,40,8,true,0.037,0.0006,4497,2014,7,14,Wednesday,false,true,false,false,false,false,false
16353729,Why isn't my Pandas 'apply' function referencing multiple columns working?,"I have some problems with the Pandas apply function, when using multiple columns with the following dataframe
df = DataFrame ({'a' : np.random.randn(6),
'b' : ['foo', 'bar'] * 3,
'c' : np.random.randn(6)})
and the following function
def my_test(a, b):
return a % b
When I try to apply this function with :
df['Value'] = df.apply(lambda row: my_test(row[a], row[c]), axis=1)
I get the error message:
NameError: (""global name 'a' is not defined"", u'occurred at index 0')
I do not understand this message, I defined the name properly.
I would highly appreciate any help on this issue
Update
Thanks for your help. I made indeed some syntax mistakes with the code, the index should be put ''. However I still get the same issue using a more complex function such as:
def my_test(a):
cum_diff = 0
for ix in df.index():
cum_diff = cum_diff + (a - df['a'][ix])
return cum_diff
",https://stackoverflow.com/questions/16353729/why-isnt-my-pandas-apply-function-referencing-multiple-columns-working,248,435062.0,6.0,,,2013-05-03 07:25:48,2019-03-04 02:36:10,2019-03-04 02:36:10,2019-03-08 01:39:23,Not suitable for this site,python;python-2.7;pandas;dataframe;apply,Andy,10181,2331506,registered,true,16354730,,,,1122,946,5,0,0,5,true,true,false,true,true,true,86,10,true,0.014,0.0006,4950,2013,5,7,Friday,false,true,false,false,false,false,false
54432583,When should I (not) want to use pandas apply() in my code?,"I have seen many answers posted to questions on Stack Overflow involving the use of the Pandas method apply. I have also seen users commenting under them saying that ""apply is slow, and should be avoided"".
I have read many articles on the topic of performance that explain apply is slow. I have also seen a disclaimer in the docs about how apply is simply a convenience function for passing UDFs (can't seem to find that now). So, the general consensus is that apply should be avoided if possible. However, this raises the following questions:
- If
apply is so bad, then why is it in the API?
- How and when should I make my code
apply-free?
- Are there ever any situations where
apply is good (better than other possible solutions)?
",https://stackoverflow.com/questions/54432583/when-should-i-not-want-to-use-pandas-apply-in-my-code,246,71130.0,5.0,,,2019-01-30 02:34:29,2024-04-14 17:14:11,2020-10-15 00:05:37,,,python;pandas;performance;apply,coldspeed95,407735,4909087,registered,true,54432584,,CC BY-SA 4.0,,898,735,8,0,0,4,true,false,false,true,true,true,58,12,true,0.07,0.0035,2852,2019,1,2,Wednesday,false,true,false,false,false,false,false
23586510,Return multiple columns from pandas apply(),"I have a pandas DataFrame, df_test. It contains a column 'size' which represents size in bytes. I've calculated KB, MB, and GB using the following code:
df_test = pd.DataFrame([
{'dir': '/Users/uname1', 'size': 994933},
{'dir': '/Users/uname2', 'size': 109338711},
])
df_test['size_kb'] = df_test['size'].astype(int).apply(lambda x: locale.format(""%.1f"", x / 1024.0, grouping=True) + ' KB')
df_test['size_mb'] = df_test['size'].astype(int).apply(lambda x: locale.format(""%.1f"", x / 1024.0 ** 2, grouping=True) + ' MB')
df_test['size_gb'] = df_test['size'].astype(int).apply(lambda x: locale.format(""%.1f"", x / 1024.0 ** 3, grouping=True) + ' GB')
df_test
dir size size_kb size_mb size_gb
0 /Users/uname1 994933 971.6 KB 0.9 MB 0.0 GB
1 /Users/uname2 109338711 106,776.1 KB 104.3 MB 0.1 GB
[2 rows x 5 columns]
I've run this over 120,000 rows and time it takes about 2.97 seconds per column * 3 = ~9 seconds according to %timeit.
Is there anyway I can make this faster? For example, can I instead of returning one column at a time from apply and running it 3 times, can I return all three columns in one pass to insert back into the original dataframe?
The other questions I've found all want to take multiple values and return a single value. I want to take a single value and return multiple columns.
",https://stackoverflow.com/questions/23586510/return-multiple-columns-from-pandas-apply,245,261802.0,13.0,,,2014-05-10 21:27:50,2025-06-02 10:24:33,2020-04-19 11:40:57,,,python;pandas;dataframe;apply,PaulMest,15355,872328,registered,true,35208597,,CC BY-SA 4.0,,1468,1369,2,0,0,4,true,false,false,true,true,true,43,6,false,0.05,0.0009,4578,2014,5,21,Saturday,true,true,false,false,false,false,false
40353079,How to check dtype for all columns in a Pandas dataframe?,"It seems that dtype only works for Series, right? Is there a function to display data types of all columns at once?
",https://stackoverflow.com/questions/40353079/how-to-check-dtype-for-all-columns-in-a-pandas-dataframe,245,684534.0,7.0,,,2016-11-01 01:50:18,2025-12-04 15:50:55,2025-09-20 14:55:44,,,python;pandas;dataframe,user3768495,4757,3768495,registered,true,40353394,,CC BY-SA 4.0,,149,116,2,0,0,3,true,false,false,true,true,true,57,11,true,0.01,0.0004,3672,2016,11,1,Tuesday,false,true,false,false,false,false,false
11548005,NumPy or Pandas: Keeping array type as integer while having a NaN value,"Is there a preferred way to keep the data type of a numpy array fixed as int (or int64 or whatever), while still having an element inside listed as numpy.NaN?
In particular, I am converting an in-house data structure to a Pandas DataFrame. In our structure, we have integer-type columns that still have NaN's (but the dtype of the column is int). It seems to recast everything as a float if we make this a DataFrame, but we'd really like to be int.
Thoughts?
Things tried:
I tried using the from_records() function under pandas.DataFrame, with coerce_float=False and this did not help. I also tried using NumPy masked arrays, with NaN fill_value, which also did not work. All of these caused the column data type to become a float.
",https://stackoverflow.com/questions/11548005/numpy-or-pandas-keeping-array-type-as-integer-while-having-a-nan-value,245,129485.0,10.0,,,2012-07-18 18:30:02,2024-04-01 09:24:13,2017-01-05 00:00:02,,,python;numpy;int;pandas;type-conversion,ely,78025,567620,registered,true,51997100,,CC BY-SA 3.0,,879,736,7,0,0,5,true,false,false,true,true,true,71,13,false,0.077,0.0019,5239,2012,7,18,Wednesday,false,true,false,false,false,false,false
36684013,Extract column value based on another column in Pandas,"I am kind of getting stuck on extracting value of one variable conditioning on another variable. For example, the following dataframe:
A B
p1 1
p1 2
p3 3
p2 4
How can I get the value of A when B=3? Every time when I extracted the value of A, I got an object, not a string.
",https://stackoverflow.com/questions/36684013/extract-column-value-based-on-another-column-in-pandas,244,584468.0,7.0,,,2016-04-18 01:12:52,2024-09-11 11:31:42,2022-08-18 12:54:35,,,python;pandas;dataframe,Gejun,4712,2344011,registered,true,36685531,,CC BY-SA 4.0,,355,278,4,0,0,3,true,false,false,true,true,true,54,9,false,0.012,0.0004,3869,2016,4,1,Monday,false,true,false,false,false,false,false
28757389,pandas loc vs. iloc vs. at vs. iat?,"Recently began branching out from my safe place (R) into Python and and am a bit confused by the cell localization/selection in Pandas. I've read the documentation but I'm struggling to understand the practical implications of the various localization/selection options.
Is there a reason why I should ever use .loc or .iloc over at, and iat or vice versa? In what situations should I use which method?
Note: future readers be aware that this question is old and was written before pandas v0.20 when there used to exist a function called .ix. This method was later split into two - loc and iloc - to make the explicit distinction between positional and label based indexing. Please beware that ix was discontinued due to inconsistent behavior and being hard to grok, and no longer exists in current versions of pandas (>= 1.0).
",https://stackoverflow.com/questions/28757389/pandas-loc-vs-iloc-vs-at-vs-iat,244,190313.0,7.0,,,2015-02-27 04:12:39,2025-08-01 05:15:24,2020-12-18 12:18:34,,,python;pandas;performance;indexing;lookup,scribbles,4369,4613042,registered,true,30022658,,CC BY-SA 4.0,,1032,835,9,0,0,5,true,false,false,true,true,true,35,8,true,0.037,0.0013,4285,2015,2,4,Friday,false,true,false,false,false,false,false
16031056,How to form tuple column from two columns in Pandas,"I've got a Pandas DataFrame and I want to combine the 'lat' and 'long' columns to form a tuple.
<class 'pandas.core.frame.DataFrame'>
Int64Index: 205482 entries, 0 to 209018
Data columns:
Month 205482 non-null values
Reported by 205482 non-null values
Falls within 205482 non-null values
Easting 205482 non-null values
Northing 205482 non-null values
Location 205482 non-null values
Crime type 205482 non-null values
long 205482 non-null values
lat 205482 non-null values
dtypes: float64(4), object(5)
The code I tried to use was:
def merge_two_cols(series):
return (series['lat'], series['long'])
sample['lat_long'] = sample.apply(merge_two_cols, axis=1)
However, this returned the following error:
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-261-e752e52a96e6> in <module>()
2 return (series['lat'], series['long'])
3
----> 4 sample['lat_long'] = sample.apply(merge_two_cols, axis=1)
5
...
AssertionError: Block shape incompatible with manager
How can I solve this problem?
",https://stackoverflow.com/questions/16031056/how-to-form-tuple-column-from-two-columns-in-pandas,243,252363.0,7.0,,,2013-04-16 07:21:52,2024-06-17 20:45:47,,,,python;dataframe;pandas;tuples,elksie5000,7908,386861,registered,true,16068497,,CC BY-SA 3.0,,1369,1238,4,0,0,4,true,false,false,true,true,false,51,10,false,0.028,0.001,4967,2013,4,7,Tuesday,false,true,false,false,false,false,false
22483588,How to plot multiple dataframes in subplots,"I have a few Pandas DataFrames sharing the same value scale, but having different columns and indices. When invoking df.plot(), I get separate plot images. what I really want is to have them all in the same plot as subplots, but I'm unfortunately failing to come up with a solution to how and would highly appreciate some help.
",https://stackoverflow.com/questions/22483588/how-to-plot-multiple-dataframes-in-subplots,242,449303.0,10.0,,,2014-03-18 15:18:11,2023-03-11 17:37:56,2022-07-20 21:59:08,,,python;pandas;matplotlib;seaborn;subplot,Jimmy C,9750,1672420,registered,true,22484249,,CC BY-SA 4.0,,349,329,1,0,0,5,true,false,false,true,true,true,43,7,false,0.022,0.0005,4631,2014,3,15,Tuesday,false,true,false,false,false,false,false
9652832,How to load a tsv file into a Pandas DataFrame?,"I'm trying to get a TAB-delimited (tsv) file loaded into a pandas DataFrame.
This is what I'm trying and the error I'm getting:
>>> df1 = DataFrame(csv.reader(open('c:/~/trainSetRel3.txt'), delimiter='\t'))
Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
df1 = DataFrame(csv.reader(open('c:/~/trainSetRel3.txt'), delimiter='\t'))
File "C:\Python27\lib\site-packages\pandas\core\frame.py", line 318, in __init__
raise PandasError('DataFrame constructor not properly called!')
PandasError: DataFrame constructor not properly called!
",https://stackoverflow.com/questions/9652832/how-to-load-a-tsv-file-into-a-pandas-dataframe,242,423512.0,9.0,,,2012-03-11 06:00:56,2023-10-25 16:52:57,2023-10-25 16:52:57,,,python;pandas;csv;input,screechOwl,28327,914308,registered,true,9652858,,CC BY-SA 4.0,,691,614,4,0,0,4,true,false,false,true,true,true,47,10,true,0.021,0.0006,5368,2012,3,6,Sunday,true,true,false,false,false,false,false
25055712,Pandas every nth row,"Dataframe.resample() works only with timeseries data. I cannot find a way of getting every nth row from non-timeseries data. What is the best method?
",https://stackoverflow.com/questions/25055712/pandas-every-nth-row,242,275414.0,7.0,,,2014-07-31 09:44:55,2021-06-25 09:52:51,2021-06-25 09:52:51,,,python;pandas;resampling,mikael,2337,1014352,registered,true,25057724,,CC BY-SA 4.0,,170,150,1,0,0,3,true,false,false,true,true,true,20,4,false,0.025,0.0009,4496,2014,7,9,Thursday,false,true,false,false,false,false,false
17001389,pandas resample documentation,"So I completely understand how to use resample, but the documentation does not do a good job explaining the options.
So most options in the resample function are pretty straight forward except for these two:
- rule : the offset string or object representing target conversion
- how : string, method for down- or re-sampling, default to ‘mean’
So from looking at as many examples as I found online I can see for rule you can do 'D' for day, 'xMin' for minutes, 'xL' for milliseconds, but that is all I could find.
for how I have seen the following: 'first', np.max, 'last', 'mean', and 'n1n2n3n4...nx' where nx is the first letter of each column index.
So is there somewhere in the documentation that I am missing that displays every option for pandas.resample's rule and how inputs? If yes, where because I could not find it. If no, what are all the options for them?
",https://stackoverflow.com/questions/17001389/pandas-resample-documentation,242,162128.0,3.0,,,2013-06-08 16:09:43,2023-08-10 09:28:45,2018-06-22 09:55:06,,,python;documentation;pandas,Ryan Saxe,17989,2127988,registered,true,17001474,,CC BY-SA 4.0,,1257,871,10,1,0,3,true,false,false,true,true,true,29,3,false,0.019,0.0015,4914,2013,6,16,Saturday,true,true,false,false,false,false,false
19071199,Drop columns whose name contains a specific string from pandas DataFrame,"I have a pandas dataframe with the following column names:
Result1, Test1, Result2, Test2, Result3, Test3, etc...
I want to drop all the columns whose name contains the word ""Test"". The numbers of such columns is not static but depends on a previous function.
How can I do that?
",https://stackoverflow.com/questions/19071199/drop-columns-whose-name-contains-a-specific-string-from-pandas-dataframe,241,321444.0,13.0,,,2013-09-28 20:10:42,2023-09-11 18:36:45,2019-01-29 07:29:16,,,python;pandas;dataframe,Alexis Eggermont,8225,2827060,registered,true,19071572,,CC BY-SA 4.0,,310,282,0,0,0,3,true,false,false,true,true,true,72,11,false,0.04,0.0007,4802,2013,9,20,Saturday,true,true,false,false,false,false,false
66060487,"ValueError: numpy.ndarray size changed, may indicate binary incompatibility. Expected 88 from C header, got 80 from PyObject","Importing from pyxdameraulevenshtein gives the following error, I have
pyxdameraulevenshtein==1.5.3
pandas==1.1.4
scikit-learn==0.20.2.
Numpy is 1.16.1.
Works well in Python 3.6, Issue in Python 3.7.
Has anyone been facing similar issues with Python 3.7 (3.7.9), docker image python:3.7-buster?
from pyxdameraulevenshtein import normalized_damerau_levenshtein_distance as norm_dl_dist
__init__.pxd:242: in init pyxdameraulevenshtein
???
E ValueError: numpy.ndarray size changed, may indicate binary incompatibility. Expected 88 from C header, got 80 from PyObject
",https://stackoverflow.com/questions/66060487/valueerror-numpy-ndarray-size-changed-may-indicate-binary-incompatibility-exp,241,397844.0,20.0,,,2021-02-05 09:11:48,2024-06-24 09:36:36,2023-01-16 06:33:13,,,python;pandas;numpy;scikit-learn;python-3.7,Sachit Jani,2511,15150567,registered,true,,,CC BY-SA 4.0,2023-01-16 20:34:08,675,573,4,0,0,5,false,false,false,true,true,true,124,17,false,0.05,0.0006,2115,2021,2,9,Friday,false,true,false,false,false,false,false
41286569,Get total of Pandas column,"I have a Pandas data frame, as shown below, with multiple columns and would like to get the total of column, MyColumn.
X MyColumn Y Z
0 A 84 13.0 69.0
1 B 76 77.0 127.0
2 C 28 69.0 16.0
3 D 28 28.0 31.0
4 E 19 20.0 85.0
5 F 84 193.0 70.0
Expected Output
I'd have expected the output to be the total of this column: 319.
Or alternatively, I would like df to be edited with a new row entitled TOTAL containing the total:
X MyColumn Y Z
0 A 84 13.0 69.0
1 B 76 77.0 127.0
2 C 28 69.0 16.0
3 D 28 28.0 31.0
4 E 19 20.0 85.0
5 F 84 193.0 70.0
TOTAL 319
I have attempted to get the sum of the column using groupby and .sum():
Total = df.groupby['MyColumn'].sum()
This causes the following error:
TypeError: 'instancemethod' object has no attribute '__getitem__'
",https://stackoverflow.com/questions/41286569/get-total-of-pandas-column,241,723767.0,6.0,,,2016-12-22 15:29:18,2024-02-06 18:38:16,2024-02-06 18:38:16,,,python;pandas;dataframe;sum,Enigmatic,4286,4847912,registered,true,41286607,,CC BY-SA 4.0,,1748,1340,10,0,0,4,true,false,false,true,true,true,26,5,false,0.008,0.0003,3621,2016,12,15,Thursday,false,true,false,false,false,false,false
26645515,Pandas join issue: columns overlap but no suffix specified,"I have the following data frames:
print(df_a)
mukey DI PI
0 100000 35 14
1 1000005 44 14
2 1000006 44 14
3 1000007 43 13
4 1000008 43 13
print(df_b)
mukey niccdcd
0 190236 4
1 190237 6
2 190238 7
3 190239 4
4 190240 7
When I try to join these data frames:
join_df = df_a.join(df_b, on='mukey', how='left')
I get the error:
*** ValueError: columns overlap but no suffix specified: Index([u'mukey'], dtype='object')
Why is this so? The data frames do have common 'mukey' values.
",https://stackoverflow.com/questions/26645515/pandas-join-issue-columns-overlap-but-no-suffix-specified,241,431894.0,6.0,,,2014-10-30 05:09:05,2024-06-04 04:23:43,2021-10-16 08:41:38,,,python;join;pandas,user308827,22551,308827,registered,true,26654201,,CC BY-SA 4.0,,662,549,4,0,0,3,true,false,false,true,true,true,58,9,false,0.014,0.0006,4405,2014,10,5,Thursday,false,true,false,false,false,false,false
17978133,Python Pandas merge only certain columns,"Is it possible to only merge some columns? I have a DataFrame df1 with columns x, y, z, and df2 with columns x, a ,b, c, d, e, f, etc.
I want to merge the two DataFrames on x, but I only want to merge columns df2.a, df2.b - not the entire DataFrame.
The result would be a DataFrame with x, y, z, a, b.
I could merge then delete the unwanted columns, but it seems like there is a better method.
",https://stackoverflow.com/questions/17978133/python-pandas-merge-only-certain-columns,239,507571.0,7.0,,,2013-07-31 18:30:28,2025-05-08 10:12:09,2016-12-22 01:08:09,,,python;merge;pandas,BubbleGuppies,5990,1827947,registered,true,17978414,,CC BY-SA 3.0,,426,398,0,0,0,3,true,false,false,true,true,true,40,6,false,0.014,0.0005,4861,2013,7,18,Wednesday,false,true,false,false,false,false,false
16888888,How to read a .xlsx file using the pandas Library in iPython?,"I want to read a .xlsx file using the Pandas Library of python and port the data to a postgreSQL table.
All I could do up until now is:
import pandas as pd
data = pd.ExcelFile(""*File Name*"")
Now I know that the step got executed successfully, but I want to know how i can parse the excel file that has been read so that I can understand how the data in the excel maps to the data in the variable data.
I learnt that data is a Dataframe object if I'm not wrong. So How do i parse this dataframe object to extract each line row by row.
",https://stackoverflow.com/questions/16888888/how-to-read-a-xlsx-file-using-the-pandas-library-in-ipython,239,827897.0,7.0,,,2013-06-03 01:20:08,2025-07-29 08:44:10,2014-07-18 18:09:42,,,python;pandas;ipython;jupyter-notebook;dataframe,Sabareesh Kappagantu,2637,1024273,registered,true,16896091,,CC BY-SA 3.0,2025-07-29 08:49:09,601,541,1,0,0,5,true,false,false,true,true,true,61,12,true,0.008,0.0003,4919,2013,6,1,Monday,false,true,false,false,false,false,false
20076195,What is the most efficient way of counting occurrences in pandas?,"I have a large (about 12M rows) DataFrame df:
df.columns = ['word','documents','frequency']
The following ran in a timely fashion:
word_grouping = df[['word','frequency']].groupby('word')
MaxFrequency_perWord = word_grouping[['frequency']].max().reset_index()
MaxFrequency_perWord.columns = ['word','MaxFrequency']
However, this is taking an unexpectedly long time to run:
Occurrences_of_Words = word_grouping[['word']].count().reset_index()
What am I doing wrong here? Is there a better way to count occurrences in a large DataFrame?
df.word.describe()
ran pretty well, so I really did not expect this Occurrences_of_Words DataFrame to take very long to build.
",https://stackoverflow.com/questions/20076195/what-is-the-most-efficient-way-of-counting-occurrences-in-pandas,239,397609.0,4.0,,,2013-11-19 15:58:33,2024-05-24 02:10:15,2022-06-06 00:02:11,,,python;pandas,tipanverella,3747,1311866,registered,true,20076611,,CC BY-SA 4.0,,824,667,6,0,0,2,true,false,false,true,true,true,65,11,true,0.01,0.0006,4750,2013,11,15,Tuesday,false,true,false,false,false,false,false
17095101,Compare two DataFrames and output their differences side-by-side,"I am trying to highlight exactly what changed between two dataframes.
Suppose I have two Python Pandas dataframes:
""StudentRoster Jan-1"":
id Name score isEnrolled Comment
111 Jack 2.17 True He was late to class
112 Nick 1.11 False Graduated
113 Zoe 4.12 True
""StudentRoster Jan-2"":
id Name score isEnrolled Comment
111 Jack 2.17 True He was late to class
112 Nick 1.21 False Graduated
113 Zoe 4.12 False On vacation
My goal is to output an HTML table that:
- Identifies rows that have changed (could be int, float, boolean, string)
Outputs rows with same, OLD and NEW values (ideally into an HTML table) so the consumer can clearly see what changed between two dataframes:
""StudentRoster Difference Jan-1 - Jan-2"":
id Name score isEnrolled Comment
112 Nick was 1.11| now 1.21 False Graduated
113 Zoe 4.12 was True | now False was """" | now ""On vacation""
I suppose I could do a row by row and column by column comparison, but is there an easier way?
",https://stackoverflow.com/questions/17095101/compare-two-dataframes-and-output-their-differences-side-by-side,238,420968.0,16.0,,,2013-06-13 19:08:16,2023-10-09 15:01:01,2020-07-02 07:41:06,,,python;pandas;dataframe,sky,2621,1625152,registered,true,17095620,,CC BY-SA 4.0,2021-08-01 00:41:42,1445,1335,2,0,0,3,true,false,false,true,true,true,64,8,false,0.038,0.0006,4909,2013,6,19,Thursday,false,true,false,false,false,false,false
19112398,converting list of header and row lists into pandas DataFrame,"I am reading contents of a spreadsheet into pandas. DataNitro has a method that returns a rectangular selection of cells as a list of lists. So
table = Cell(""A1"").table
gives
table = [['Heading1', 'Heading2'], [1 , 2], [3, 4]]
headers = table.pop(0) # gives the headers as list and leaves data
I am busy writing code to translate this, but my guess is that it is such a simple use that there must be method to do this. Cant seem to find it in documentation. Any pointers to the method that would simplify this?
",https://stackoverflow.com/questions/19112398/converting-list-of-header-and-row-lists-into-pandas-dataframe,237,284481.0,4.0,,,2013-10-01 09:19:40,2023-06-19 12:10:26,2023-06-19 12:10:26,,,python;pandas;datanitro,Joop,8208,2107677,registered,true,19112890,,CC BY-SA 4.0,,596,527,2,0,0,3,true,false,false,true,true,true,61,10,false,0.014,0.0008,4799,2013,10,9,Tuesday,false,true,false,false,false,false,false
22470690,Get list of pandas dataframe columns based on data type,"If I have a dataframe with the following columns:
1. NAME object
2. On_Time object
3. On_Budget object
4. %actual_hr float64
5. Baseline Start Date datetime64[ns]
6. Forecast Start Date datetime64[ns]
I would like to be able to say: for this dataframe, give me a list of the columns which are of type 'object' or of type 'datetime'?
I have a function which converts numbers ('float64') to two decimal places, and I would like to use this list of dataframe columns, of a particular type, and run it through this function to convert them all to 2dp.
Maybe something like:
For c in col_list: if c.dtype = "Something"
list[]
List.append(c)?
",https://stackoverflow.com/questions/22470690/get-list-of-pandas-dataframe-columns-based-on-data-type,234,576098.0,14.0,,,2014-03-18 04:54:22,2022-05-12 17:25:24,2021-12-22 08:44:41,,,python;pandas;dtype,yoshiserry,21645,3098818,registered,true,22475141,,CC BY-SA 4.0,2018-09-05 02:41:02,918,825,2,0,0,3,true,false,false,true,true,true,55,10,false,0.024,0.0004,4631,2014,3,4,Tuesday,false,true,false,false,false,false,false
42406233,How to add a title to a Seaborn boxplot,"Suppose I create a boxplot in Seaborn like:
import pandas as pd
import seaborn as sns
df = pd.DataFrame([[1, 1], [2, 2]], columns = ('Day', 'Count'))
plot = sns.boxplot(x='Day', y='Count', data=df)
I tried using .title, but it doesn't work:
>>> plot.title('lalala')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'Text' object is not callable
How can I add the title? Does it matter if I am also using Matplotlib directly in the code?
",https://stackoverflow.com/questions/42406233/how-to-add-a-title-to-a-seaborn-boxplot,234,487572.0,6.0,,,2017-02-23 03:04:19,2024-08-06 23:55:30,2024-08-06 23:44:44,,,python;pandas;matplotlib;seaborn,itstoocold,2583,7468566,registered,true,,,CC BY-SA 4.0,,588,506,3,0,0,4,false,false,false,true,true,true,39,9,false,0.012,0.0005,3558,2017,2,3,Thursday,false,true,false,false,false,false,false
23307301,Replacing column values in a pandas DataFrame,"I'm trying to replace the values in one column of a dataframe. The column ('female') only contains the values 'female' and 'male'.
I have tried the following:
w['female']['female']='1'
w['female']['male']='0'
But receive the exact same copy of the previous results.
I would ideally like to get some output which resembles the following loop element-wise.
if w['female'] =='female':
w['female'] = '1';
else:
w['female'] = '0';
I've looked through the gotchas documentation (http://pandas.pydata.org/pandas-docs/stable/gotchas.html) but cannot figure out why nothing happens.
Any help will be appreciated.
",https://stackoverflow.com/questions/23307301/replacing-column-values-in-a-pandas-dataframe,232,861857.0,16.0,,,2014-04-26 06:04:24,2022-12-06 21:30:29,2019-01-08 08:47:48,,,python;pandas,Black,4702,2771315,registered,true,23307361,,CC BY-SA 4.0,,784,623,2,1,0,2,true,false,false,true,true,true,45,7,false,0.019,0.0003,4592,2014,4,6,Saturday,true,true,false,false,false,false,false
13682044,Remove unwanted parts from strings in a column,"I am looking for an efficient way to remove unwanted parts from strings in a DataFrame column.
Data looks like:
time result
1 09:00 +52A
2 10:00 +62B
3 11:00 +44a
4 12:00 +30b
5 13:00 -110a
I need to trim these data to:
time result
1 09:00 52
2 10:00 62
3 11:00 44
4 12:00 30
5 13:00 110
I tried .str.lstrip('+-') and .str.rstrip('aAbBcC'), but got an error:
TypeError: wrapper() takes exactly 1 argument (2 given)
Any pointers would be greatly appreciated!
",https://stackoverflow.com/questions/13682044/remove-unwanted-parts-from-strings-in-a-column,232,728283.0,11.0,,,2012-12-03 11:11:56,2024-09-10 09:42:28,2019-01-22 06:39:34,,,python;string;pandas;dataframe,Yannan Wang,2323,1872240,registered,true,13682381,,CC BY-SA 4.0,2019-01-22 06:40:05,667,534,5,0,0,4,true,false,false,true,true,true,46,8,false,0.015,0.0003,5101,2012,12,11,Monday,false,true,false,false,false,false,false
23549231,Check if a value exists in pandas dataframe index,"I am sure there is an obvious way to do this but cant think of anything slick right now.
Basically instead of raising exception I would like to get True or False to see if a value exists in pandas df index.
import pandas as pd
df = pd.DataFrame({'test':[1,2,3,4]}, index=['a','b','c','d'])
df.loc['g'] # (should give False)
What I have working now is the following
sum(df.index == 'g')
",https://stackoverflow.com/questions/23549231/check-if-a-value-exists-in-pandas-dataframe-index,232,366845.0,7.0,,,2014-05-08 17:59:49,2022-03-26 19:21:42,2019-03-31 08:36:58,,,python;pandas;ipython,Abhi,6305,369541,registered,true,23549599,,CC BY-SA 4.0,2019-07-16 16:25:15,501,393,5,0,0,3,true,false,false,true,true,true,49,9,false,0.019,0.0006,4580,2014,5,17,Thursday,false,true,false,false,false,false,false
29902714,Print very long string in Pandas dataframe,"I have a Pandas data frame containing a very long string:
df = pd.DataFrame({'one' : ['one', 'two',
'This is very long string very long string very long string veryvery long string']})
When I print it, I see only part of the string. I tried:
- using
print(df.iloc[2]).
- using
to_html.
- using
to_string.
- to increase column width by using Pandas display option.
I also do not get how set_printoptions would solve this.
",https://stackoverflow.com/questions/29902714/print-very-long-string-in-pandas-dataframe,229,324628.0,10.0,,,2015-04-27 17:54:00,2025-04-22 11:53:21,2025-04-21 16:08:25,,,python;pandas;string,Yantraguru,3904,3907612,registered,true,29902819,,CC BY-SA 4.0,2025-04-22 11:57:00,601,422,5,0,0,3,true,false,false,true,true,true,42,7,false,0.031,0.0007,4226,2015,4,17,Monday,false,true,false,false,false,false,false
19231871,Convert unix time to readable date in pandas dataframe,"I have a dataframe with unix times and prices in it. I want to convert the index column so that it shows in human readable dates.
So for instance I have date as 1349633705 in the index column but I'd want it to show as 10/07/2012 (or at least 10/07/2012 18:15).
For some context, here is the code I'm working with and what I've tried already:
import json
import urllib2
from datetime import datetime
response = urllib2.urlopen('http://blockchain.info/charts/market-price?&format=json')
data = json.load(response)
df = DataFrame(data['values'])
df.columns = [""date"",""price""]
#convert dates
df.date = df.date.apply(lambda d: datetime.strptime(d, ""%Y-%m-%d""))
df.index = df.date
As you can see I'm using
df.date = df.date.apply(lambda d: datetime.strptime(d, ""%Y-%m-%d"")) here which doesn't work since I'm working with integers, not strings. I think I need to use datetime.date.fromtimestamp but I'm not quite sure how to apply this to the whole of df.date.
Thanks.
",https://stackoverflow.com/questions/19231871/convert-unix-time-to-readable-date-in-pandas-dataframe,228,350361.0,5.0,,,2013-10-07 18:21:02,2024-05-14 17:49:29,2019-04-28 07:35:59,,,python;pandas;unix-timestamp;dataframe,W A Carnegie,2373,2714570,registered,true,19231939,,CC BY-SA 4.0,,1133,983,8,0,0,4,true,false,false,true,true,true,54,9,false,0.014,0.0007,4793,2013,10,18,Monday,false,true,false,false,false,false,false
19078325,Naming returned columns in Pandas aggregate function?,"I'm having trouble with Pandas' groupby functionality. I've read the documentation, but I can't see to figure out how to apply aggregate functions to multiple columns and have custom names for those columns.
This comes very close, but the data structure returned has nested column headings:
data.groupby("Country").agg({
"column1": {"foo": sum()},
"column2": {"mean": np.mean, "std": np.std}
})
(ie. I want to take the mean and std of column2, but return those columns as "mean" and "std")
What am I missing?
",https://stackoverflow.com/questions/19078325/naming-returned-columns-in-pandas-aggregate-function,228,349230.0,6.0,,,2013-09-29 13:00:05,2023-08-29 20:47:58,2023-08-29 20:47:58,2019-06-29 05:26:06,Duplicate,python;group-by;pandas;aggregate-functions,David Chouinard,6955,249323,registered,true,43897124,,,,740,594,1,1,0,4,true,true,false,true,true,true,53,7,true,0.017,0.0007,4801,2013,9,13,Sunday,true,true,false,false,false,false,false
18089667,How to estimate how much memory a Pandas' DataFrame will need?,"I have been wondering... If I am reading, say, a 400MB csv file into a pandas dataframe (using read_csv or read_table), is there any way to guesstimate how much memory this will need? Just trying to get a better feel of data frames and memory...
",https://stackoverflow.com/questions/18089667/how-to-estimate-how-much-memory-a-pandas-dataframe-will-need,228,229998.0,8.0,,,2013-08-06 20:18:55,2024-08-27 17:12:18,2014-12-03 03:24:24,,,python;pandas,Anne,7142,2565842,registered,true,,,CC BY-SA 3.0,,254,247,0,0,0,2,false,false,false,true,true,true,66,11,true,0.035,0.001,4855,2013,8,20,Tuesday,false,true,false,false,false,false,false
17326973,Is there a way to auto-adjust Excel column widths with pandas.ExcelWriter?,"I am being asked to generate some Excel reports. I am currently using pandas quite heavily for my data, so naturally I would like to use the pandas.ExcelWriter method to generate these reports. However the fixed column widths are a problem.
The code I have so far is simple enough. Say I have a dataframe called df:
writer = pd.ExcelWriter(excel_file_path, engine='openpyxl')
df.to_excel(writer, sheet_name="Summary")
I was looking over the pandas docs, and I don't really see any options to set column widths. Is there a trick to make it such that the columns auto-adjust to the data? Or is there something I can do after the fact to the xlsx file to adjust the column widths?
(I am using the OpenPyXL library, and generating .xlsx files - if that makes any difference.)
",https://stackoverflow.com/questions/17326973/is-there-a-way-to-auto-adjust-excel-column-widths-with-pandas-excelwriter,228,261687.0,24.0,,,2013-06-26 17:44:08,2026-03-08 21:10:03,2022-08-21 15:55:17,,,python;excel;pandas;openpyxl,badideas,3647,152018,registered,true,,,CC BY-SA 4.0,,864,786,3,0,0,4,false,false,false,true,true,true,74,11,true,0.092,0.0009,4896,2013,6,17,Wednesday,false,true,false,false,false,false,false
23748995,Pandas DataFrame column to list,"I am pulling a subset of data from a column based on conditions in another column being met.
I can get the correct values back but it is in pandas.core.frame.DataFrame. How do I convert that to list?
import pandas as pd
tst = pd.read_csv('C:\\SomeCSV.csv')
lookupValue = tst['SomeCol'] == ""SomeValue""
ID = tst[lookupValue][['SomeCol']]
#How To convert ID to a list
",https://stackoverflow.com/questions/23748995/pandas-dataframe-column-to-list,227,765869.0,4.0,,,2014-05-20 00:00:09,2020-05-01 11:31:25,2020-05-01 11:31:25,2019-04-08 21:19:32,Duplicate,python;pandas,user3646105,2579,3646105,registered,true,,,,,409,371,1,0,0,2,false,true,false,true,true,true,31,5,false,0.005,0.0003,4568,2014,5,0,Tuesday,false,true,false,false,false,false,false
25748683,Pandas: sum DataFrame rows for given columns,"I have the following DataFrame:
In [1]:
df = pd.DataFrame({'a': [1, 2, 3],
'b': [2, 3, 4],
'c': ['dd', 'ee', 'ff'],
'd': [5, 9, 1]})
df
Out [1]:
a b c d
0 1 2 dd 5
1 2 3 ee 9
2 3 4 ff 1
I would like to add a column 'e' which is the sum of columns 'a', 'b' and 'd'.
Going across forums, I thought something like this would work:
df['e'] = df[['a', 'b', 'd']].map(sum)
But it didn't.
I would like to know the appropriate operation with the list of columns ['a', 'b', 'd'] and df as inputs.
",https://stackoverflow.com/questions/25748683/pandas-sum-dataframe-rows-for-given-columns,226,606992.0,8.0,,,2014-09-09 15:36:03,2023-05-10 08:46:47,2022-04-28 07:19:13,,,python;pandas;dataframe;sum,Colonel Beauvel,31271,3628236,registered,true,25748826,,CC BY-SA 4.0,2018-07-09 18:20:59,728,567,8,0,0,4,true,false,false,true,true,true,44,7,false,0.013,0.0004,4456,2014,9,15,Tuesday,false,true,false,false,false,false,false
53218931,"How to unnest (explode) a column in a pandas DataFrame, into multiple rows","I have the following DataFrame where one of the columns is an object (list type cell):
df = pd.DataFrame({'A': [1, 2], 'B': [[1, 2], [1, 2]]})
Output:
A B
0 1 [1, 2]
1 2 [1, 2]
My expected output is:
A B
0 1 1
1 1 2
3 2 1
4 2 2
What should I do to achieve this?
Related question:
Pandas column of lists, create a row for each list element -
Good question and answer but only handle one column with list. (In my answer the self-def function will work for multiple columns, also the accepted answer is use the most time consuming apply, which is not recommended, check more info When should I (not) want to use pandas apply() in my code?)
",https://stackoverflow.com/questions/53218931/how-to-unnest-explode-a-column-in-a-pandas-dataframe-into-multiple-rows,226,164521.0,16.0,,,2018-11-09 02:19:22,2025-09-26 17:07:26,2025-09-26 16:11:52,,,python;pandas;dataframe;pandas-explode,BENY,324300,7964527,registered,true,53218939,,CC BY-SA 4.0,2019-11-14 15:32:00,1044,666,4,2,0,4,true,false,false,true,true,true,74,13,false,0.097,0.0014,2934,2018,11,2,Friday,false,true,false,false,false,false,false
14734533,How to access subdataframes of pandas groupby by key,"How do I access the corresponding groupby dataframe in a groupby object by the key?
With the following groupby:
rand = np.random.RandomState(1)
df = pd.DataFrame({'A': ['foo', 'bar'] * 3,
'B': rand.randn(6),
'C': rand.randint(0, 20, 6)})
gb = df.groupby(['A'])
I can iterate through it to get the keys and groups:
In [11]: for k, gp in gb:
print 'key=' + str(k)
print gp
key=bar
A B C
1 bar -0.611756 18
3 bar -1.072969 10
5 bar -2.301539 18
key=foo
A B C
0 foo 1.624345 5
2 foo -0.528172 11
4 foo 0.865408 14
I would like to be able to access a group by its key:
In [12]: gb['foo']
Out[12]:
A B C
0 foo 1.624345 5
2 foo -0.528172 11
4 foo 0.865408 14
But when I try doing that with gb[('foo',)] I get this weird pandas.core.groupby.DataFrameGroupBy object thing which doesn't seem to have any methods that correspond to the DataFrame I want.
The best I could think of is:
In [13]: def gb_df_key(gb, key, orig_df):
ix = gb.indices[key]
return orig_df.ix[ix]
gb_df_key(gb, 'foo', df)
Out[13]:
A B C
0 foo 1.624345 5
2 foo -0.528172 11
4 foo 0.865408 14
but this is kind of nasty, considering how nice pandas usually is at these things.
What's the built-in way of doing this?
",https://stackoverflow.com/questions/14734533/how-to-access-subdataframes-of-pandas-groupby-by-key,225,372406.0,6.0,,,2013-02-06 16:55:54,2023-11-04 17:40:58,2023-11-04 17:40:58,,,python;pandas;dataframe;group-by,beardc,21233,386279,registered,true,14734627,,CC BY-SA 4.0,,1560,1385,6,0,0,4,true,false,false,true,true,true,52,9,false,0.016,0.0006,5036,2013,2,16,Wednesday,false,true,false,false,false,false,false
26977076,pandas unique values multiple columns,"df = pd.DataFrame({'Col1': ['Bob', 'Joe', 'Bill', 'Mary', 'Joe'],
'Col2': ['Joe', 'Steve', 'Bob', 'Bob', 'Steve'],
'Col3': np.random.random(5)})
What is the best way to return the unique values of 'Col1' and 'Col2'?
The desired output is
'Bob', 'Joe', 'Bill', 'Mary', 'Steve'
",https://stackoverflow.com/questions/26977076/pandas-unique-values-multiple-columns,224,477679.0,13.0,,,2014-11-17 16:21:12,2024-01-24 14:06:21,2016-12-11 17:15:53,,,python;pandas;dataframe;unique,user2333196,5856,2333196,registered,true,26977495,,CC BY-SA 3.0,,382,320,2,0,0,4,true,false,false,true,true,true,37,5,false,0.027,0.0005,4387,2014,11,16,Monday,false,true,false,false,false,false,false
35268817,unique combinations of values in selected columns in pandas data frame and count,"I have my data in pandas data frame as follows:
df1 = pd.DataFrame({'A':['yes','yes','yes','yes','no','no','yes','yes','yes','no'],
'B':['yes','no','no','no','yes','yes','no','yes','yes','no']})
So, my data looks like this
----------------------------
index A B
0 yes yes
1 yes no
2 yes no
3 yes no
4 no yes
5 no yes
6 yes no
7 yes yes
8 yes yes
9 no no
-----------------------------
I would like to transform it to another data frame. The expected output can be shown in the following python script:
output = pd.DataFrame({'A':['no','no','yes','yes'],'B':['no','yes','no','yes'],'count':[1,2,4,3]})
So, my expected output looks like this
--------------------------------------------
index A B count
--------------------------------------------
0 no no 1
1 no yes 2
2 yes no 4
3 yes yes 3
--------------------------------------------
Actually, I can achieve to find all combinations and count them by using the following command: mytable = df1.groupby(['A','B']).size()
However, it turns out that such combinations are in a single column. I would like to separate each value in a combination into different column and also add one more column for the result of counting. Is it possible to do that? May I have your suggestions? Thank you in advance.
",https://stackoverflow.com/questions/35268817/unique-combinations-of-values-in-selected-columns-in-pandas-data-frame-and-count,223,325629.0,6.0,,,2016-02-08 11:42:44,2022-01-14 13:13:31,2016-02-08 11:49:58,,,python;pandas,Ratchainant Thammasudjarit,3217,5141727,registered,true,35268906,,CC BY-SA 3.0,,1707,1556,5,0,0,2,true,false,false,true,true,true,80,13,false,0.018,0.0007,3939,2016,2,11,Monday,false,true,false,false,false,false,false
48083405,What are the differences between feather and parquet?,"Both are columnar (disk-)storage formats for use in data analysis systems.
Both are integrated within Apache Arrow (pyarrow package for python) and are
designed to correspond with Arrow as a columnar in-memory analytics layer.
How do both formats differ?
Should you always prefer feather when working with pandas when possible?
What are the use cases where feather is more suitable than parquet and the
other way round?
Appendix
I found some hints here https://github.com/wesm/feather/issues/188,
but given the young age of this project, it's possibly a bit out of date.
Not a serious speed test because I'm just dumping and loading a whole
Dataframe but to give you some impression if you never
heard of the formats before:
# IPython
import numpy as np
import pandas as pd
import pyarrow as pa
import pyarrow.feather as feather
import pyarrow.parquet as pq
import fastparquet as fp
df = pd.DataFrame({'one': [-1, np.nan, 2.5],
'two': ['foo', 'bar', 'baz'],
'three': [True, False, True]})
print(""pandas df to disk ####################################################"")
print('example_feather:')
%timeit feather.write_feather(df, 'example_feather')
# 2.62 ms ± 35.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
print('example_parquet:')
%timeit pq.write_table(pa.Table.from_pandas(df), 'example.parquet')
# 3.19 ms ± 51 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
print()
print(""for comparison:"")
print('example_pickle:')
%timeit df.to_pickle('example_pickle')
# 2.75 ms ± 18.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
print('example_fp_parquet:')
%timeit fp.write('example_fp_parquet', df)
# 7.06 ms ± 205 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)
print('example_hdf:')
%timeit df.to_hdf('example_hdf', 'key_to_store', mode='w', table=True)
# 24.6 ms ± 4.45 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)
print()
print(""pandas df from disk ##################################################"")
print('example_feather:')
%timeit feather.read_feather('example_feather')
# 969 µs ± 1.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
print('example_parquet:')
%timeit pq.read_table('example.parquet').to_pandas()
# 1.9 ms ± 5.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
print(""for comparison:"")
print('example_pickle:')
%timeit pd.read_pickle('example_pickle')
# 1.07 ms ± 6.21 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
print('example_fp_parquet:')
%timeit fp.ParquetFile('example_fp_parquet').to_pandas()
# 4.53 ms ± 260 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)
print('example_hdf:')
%timeit pd.read_hdf('example_hdf')
# 10 ms ± 43.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
# pandas version: 0.22.0
# fastparquet version: 0.1.3
# numpy version: 1.13.3
# pandas version: 0.22.0
# pyarrow version: 0.8.0
# sys.version: 3.6.3
# example Dataframe taken from https://arrow.apache.org/docs/python/parquet.html
",https://stackoverflow.com/questions/48083405/what-are-the-differences-between-feather-and-parquet,223,96020.0,3.0,,,2018-01-03 18:48:30,2024-07-03 15:37:25,,,,python;pandas;parquet;feather;pyarrow,Darkonaut,22002,9059420,registered,true,48097717,,CC BY-SA 3.0,,3543,2998,1,6,0,5,true,false,false,true,true,false,53,8,true,0.031,0.0023,3244,2018,1,18,Wednesday,false,true,false,false,false,false,false
31328861,Replacing Header with Top Row,"I currently have a dataframe that looks like this:
Unnamed: 1 Unnamed: 2 Unnamed: 3 Unnamed: 4
0 Sample Number Group Number Sample Name Group Name
1 1.0 1.0 s_1 g_1
2 2.0 1.0 s_2 g_1
3 3.0 1.0 s_3 g_1
4 4.0 2.0 s_4 g_2
I'm looking for a way to delete the header row and make the first row the new header row, so the new dataframe would look like this:
Sample Number Group Number Sample Name Group Name
0 1.0 1.0 s_1 g_1
1 2.0 1.0 s_2 g_1
2 3.0 1.0 s_3 g_1
3 4.0 2.0 s_4 g_2
I've tried stuff along the lines of if 'Unnamed' in df.columns: then make the dataframe without the header
df.to_csv(newformat, header=False, index=False)
but I don't seem to be getting anywhere.
",https://stackoverflow.com/questions/31328861/replacing-header-with-top-row,219,456689.0,14.0,,,2015-07-09 21:50:35,2024-05-14 11:02:38,2022-12-24 16:19:07,,,python;pandas;header;row,Jeremy G,2419,5042082,registered,true,31328974,,CC BY-SA 4.0,,1123,1010,4,0,0,4,true,false,false,true,true,true,29,5,false,0.031,0.0005,4153,2015,7,21,Thursday,false,true,false,false,false,false,false
23853553,Python Pandas: How to read only first n rows of CSV files in?,"I have a very large data set and I can't afford to read the entire data set in. So, I'm thinking of reading only one chunk of it to train but I have no idea how to do it.
",https://stackoverflow.com/questions/23853553/python-pandas-how-to-read-only-first-n-rows-of-csv-files-in,219,327790.0,3.0,,,2014-05-25 08:50:00,2023-02-14 01:52:24,2023-02-14 01:51:47,,,python;pandas;dataframe;csv;file-io,bensw,3038,1334657,registered,true,23853569,,CC BY-SA 4.0,,178,171,0,0,0,5,true,false,false,true,true,true,61,13,true,0.009,0.0007,4563,2014,5,8,Sunday,true,true,false,false,false,false,false
29919306,Find the column name which has the maximum value for each row,"I have a DataFrame like this one:
Communications and Search Business General Lifestyle
0 0.745763 0.050847 0.118644 0.084746
0 0.333333 0.000000 0.583333 0.083333
0 0.617021 0.042553 0.297872 0.042553
0 0.435897 0.000000 0.410256 0.153846
0 0.358974 0.076923 0.410256 0.153846
I want to create a new column comprised of the column labels of each row’s maximum value. The desired output is like this:
Communications and Search Business General Lifestyle Max
0 0.745763 0.050847 0.118644 0.084746 Communications
0 0.333333 0.000000 0.583333 0.083333 Business
0 0.617021 0.042553 0.297872 0.042553 Communications
0 0.435897 0.000000 0.410256 0.153846 Communications
0 0.358974 0.076923 0.410256 0.153846 Business
",https://stackoverflow.com/questions/29919306/find-the-column-name-which-has-the-maximum-value-for-each-row,216,193381.0,5.0,,,2015-04-28 12:18:57,2023-12-12 03:33:32,2023-12-12 03:33:32,,,python;pandas;dataframe;max;argmax,markov zain,13095,4744765,registered,true,29919489,,CC BY-SA 4.0,,1030,890,2,0,0,5,true,false,false,true,true,true,61,12,false,0.026,0.0011,4225,2015,4,12,Tuesday,false,true,false,false,false,false,false
30530663,How to "select distinct" across multiple data frame columns in pandas?,"I'm looking for a way to do the equivalent to the SQL
SELECT DISTINCT col1, col2 FROM dataframe_table
The pandas sql comparison doesn't have anything about distinct.
.unique() only works for a single column, so I suppose I could concat the columns, or put them in a list/tuple and compare that way, but this seems like something pandas should do in a more native way.
Am I missing something obvious, or is there no way to do this?
",https://stackoverflow.com/questions/30530663/how-to-select-distinct-across-multiple-data-frame-columns-in-pandas,215,497143.0,9.0,,,2015-05-29 13:17:32,2024-06-11 09:18:18,2021-01-21 18:40:58,,,python;pandas;dataframe;duplicates;distinct,Jody,8351,10235,registered,true,30531939,,CC BY-SA 4.0,,517,439,3,0,0,5,true,false,false,true,true,true,80,11,true,0.018,0.0004,4194,2015,5,13,Friday,false,true,false,false,false,false,false
19155718,Select Pandas rows based on list index,"I have a dataframe df:
20060930 10.103 NaN 10.103 7.981
20061231 15.915 NaN 15.915 12.686
20070331 3.196 NaN 3.196 2.710
20070630 7.907 NaN 7.907 6.459
Then I want to select rows with certain sequence numbers which indicated in a list, suppose here is [1,3], then left:
20061231 15.915 NaN 15.915 12.686
20070630 7.907 NaN 7.907 6.459
How or what function can do that?
",https://stackoverflow.com/questions/19155718/select-pandas-rows-based-on-list-index,212,431509.0,8.0,,,2013-10-03 09:36:32,2022-11-22 17:17:17,2021-09-13 05:01:38,,,python;pandas,user2806761,2967,2806761,registered,true,,,CC BY-SA 4.0,2018-03-01 09:12:12,535,453,3,0,0,2,false,false,false,true,true,true,38,7,false,0.019,0.0005,4797,2013,10,9,Thursday,false,true,false,false,false,false,false
20107570,Removing index column in pandas when reading a csv,"I have the following code which imports a CSV file. There are 3 columns and I want to set the first two of them to variables. When I set the second column to the variable ""efficiency"" the index column is also tacked on. How can I get rid of the index column?
df = pd.DataFrame.from_csv('Efficiency_Data.csv', header=0, parse_dates=False)
energy = df.index
efficiency = df.Efficiency
print efficiency
I tried using
del df['index']
after I set
energy = df.index
which I found in another post but that results in ""KeyError: 'index' ""
",https://stackoverflow.com/questions/20107570/removing-index-column-in-pandas-when-reading-a-csv,211,1058526.0,10.0,,,2013-11-20 21:38:13,2024-12-15 13:22:26,2018-12-29 07:46:31,,,python;pandas,Bogdan Janiszewski,2873,2137083,registered,true,20107825,,CC BY-SA 4.0,,645,545,3,0,0,2,true,false,false,true,true,true,50,9,false,0.009,0.0002,4749,2013,11,21,Wednesday,false,true,false,false,false,false,false
17978092,Combine Date and Time columns using pandas,"I have a pandas dataframe with the following columns:
data = {'Date': ['01-06-2013', '02-06-2013', '02-06-2013', '02-06-2013', '02-06-2013', '03-06-2013', '03-06-2013', '03-06-2013', '03-06-2013', '04-06-2013'],
'Time': ['23:00:00', '01:00:00', '21:00:00', '22:00:00', '23:00:00', '01:00:00', '21:00:00', '22:00:00', '23:00:00', '01:00:00']}
df = pd.DataFrame(data)
Date Time
0 01-06-2013 23:00:00
1 02-06-2013 01:00:00
2 02-06-2013 21:00:00
3 02-06-2013 22:00:00
4 02-06-2013 23:00:00
5 03-06-2013 01:00:00
6 03-06-2013 21:00:00
7 03-06-2013 22:00:00
8 03-06-2013 23:00:00
9 04-06-2013 01:00:00
How do I combine data['Date'] & data['Time'] to get the following? Is there a way of doing it using pd.to_datetime?
Date
01-06-2013 23:00:00
02-06-2013 01:00:00
02-06-2013 21:00:00
02-06-2013 22:00:00
02-06-2013 23:00:00
03-06-2013 01:00:00
03-06-2013 21:00:00
03-06-2013 22:00:00
03-06-2013 23:00:00
04-06-2013 01:00:00
",https://stackoverflow.com/questions/17978092/combine-date-and-time-columns-using-pandas,210,269164.0,13.0,,,2013-07-31 18:27:40,2022-08-26 17:22:08,2022-08-26 17:22:08,,,python;pandas;datetime;time-series,richie,18768,1948860,registered,true,17978188,,CC BY-SA 4.0,2024-03-18 17:17:35,1079,967,3,0,0,4,true,false,false,true,true,true,42,7,false,0.048,0.0008,4861,2013,7,18,Wednesday,false,true,false,false,false,false,false
45545110,Make Pandas DataFrame apply() use all cores?,"As of August 2017, Pandas DataFame.apply() is unfortunately still limited to working with a single core, meaning that a multi-core machine will waste the majority of its compute-time when you run df.apply(myfunc, axis=1).
How can you use all your cores to run apply on a dataframe in parallel?
",https://stackoverflow.com/questions/45545110/make-pandas-dataframe-apply-use-all-cores,210,204645.0,12.0,,,2017-08-07 10:49:23,2022-07-07 09:12:12,2020-06-03 21:55:14,,,pandas;dask,Roko Mijic,7095,6903458,registered,true,51669468,,CC BY-SA 4.0,,438,297,1,1,0,2,true,false,false,true,true,true,44,7,true,0.059,0.001,3393,2017,8,10,Monday,false,false,false,false,false,false,false
20853474,ImportError: No module named dateutil.parser,"I am receiving the following error when importing pandas in a Python program
monas-mbp:book mona$ sudo pip install python-dateutil
Requirement already satisfied (use --upgrade to upgrade): python-dateutil in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python
Cleaning up...
monas-mbp:book mona$ python t1.py
No module named dateutil.parser
Traceback (most recent call last):
File ""t1.py"", line 4, in <module>
import pandas as pd
File ""/Library/Python/2.7/site-packages/pandas/__init__.py"", line 6, in <module>
from . import hashtable, tslib, lib
File ""tslib.pyx"", line 31, in init pandas.tslib (pandas/tslib.c:48782)
ImportError: No module named dateutil.parser
Also here's the program:
import codecs
from math import sqrt
import numpy as np
import pandas as pd
users = {""Angelica"": {""Blues Traveler"": 3.5, ""Broken Bells"": 2.0,
""Norah Jones"": 4.5, ""Phoenix"": 5.0,
""Slightly Stoopid"": 1.5,
""The Strokes"": 2.5, ""Vampire Weekend"": 2.0},
""Bill"":{""Blues Traveler"": 2.0, ""Broken Bells"": 3.5,
""Deadmau5"": 4.0, ""Phoenix"": 2.0,
""Slightly Stoopid"": 3.5, ""Vampire Weekend"": 3.0},
""Chan"": {""Blues Traveler"": 5.0, ""Broken Bells"": 1.0,
""Deadmau5"": 1.0, ""Norah Jones"": 3.0, ""Phoenix"": 5,
""Slightly Stoopid"": 1.0},
""Dan"": {""Blues Traveler"": 3.0, ""Broken Bells"": 4.0,
""Deadmau5"": 4.5, ""Phoenix"": 3.0,
""Slightly Stoopid"": 4.5, ""The Strokes"": 4.0,
""Vampire Weekend"": 2.0},
""Hailey"": {""Broken Bells"": 4.0, ""Deadmau5"": 1.0,
""Norah Jones"": 4.0, ""The Strokes"": 4.0,
""Vampire Weekend"": 1.0},
""Jordyn"": {""Broken Bells"": 4.5, ""Deadmau5"": 4.0,
""Norah Jones"": 5.0, ""Phoenix"": 5.0,
""Slightly Stoopid"": 4.5, ""The Strokes"": 4.0,
""Vampire Weekend"": 4.0},
""Sam"": {""Blues Traveler"": 5.0, ""Broken Bells"": 2.0,
""Norah Jones"": 3.0, ""Phoenix"": 5.0,
""Slightly Stoopid"": 4.0, ""The Strokes"": 5.0},
""Veronica"": {""Blues Traveler"": 3.0, ""Norah Jones"": 5.0,
""Phoenix"": 4.0, ""Slightly Stoopid"": 2.5,
""The Strokes"": 3.0}
}
class recommender:
def __init__(self, data, k=1, metric='pearson', n=5):
"""""" initialize recommender
currently, if data is dictionary the recommender is initialized
to it.
For all other data types of data, no initialization occurs
k is the k value for k nearest neighbor
metric is which distance formula to use
n is the maximum number of recommendations to make""""""
self.k = k
self.n = n
self.username2id = {}
self.userid2name = {}
self.productid2name = {}
# for some reason I want to save the name of the metric
self.metric = metric
if self.metric == 'pearson':
self.fn = self.pearson
#
# if data is dictionary set recommender data to it
#
if type(data).__name__ == 'dict':
self.data = data
def convertProductID2name(self, id):
""""""Given product id number return product name""""""
if id in self.productid2name:
return self.productid2name[id]
else:
return id
def userRatings(self, id, n):
""""""Return n top ratings for user with id""""""
print (""Ratings for "" + self.userid2name[id])
ratings = self.data[id]
print(len(ratings))
ratings = list(ratings.items())
ratings = [(self.convertProductID2name(k), v)
for (k, v) in ratings]
# finally sort and return
ratings.sort(key=lambda artistTuple: artistTuple[1],
reverse = True)
ratings = ratings[:n]
for rating in ratings:
print(""%s\t%i"" % (rating[0], rating[1]))
def loadBookDB(self, path=''):
""""""loads the BX book dataset. Path is where the BX files are
located""""""
self.data = {}
i = 0
#
# First load book ratings into self.data
#
f = codecs.open(path + ""BX-Book-Ratings.csv"", 'r', 'utf8')
for line in f:
i += 1
#separate line into fields
fields = line.split(';')
user = fields[0].strip('""')
book = fields[1].strip('""')
rating = int(fields[2].strip().strip('""'))
if user in self.data:
currentRatings = self.data[user]
else:
currentRatings = {}
currentRatings[book] = rating
self.data[user] = currentRatings
f.close()
#
# Now load books into self.productid2name
# Books contains isbn, title, and author among other fields
#
f = codecs.open(path + ""BX-Books.csv"", 'r', 'utf8')
for line in f:
i += 1
#separate line into fields
fields = line.split(';')
isbn = fields[0].strip('""')
title = fields[1].strip('""')
author = fields[2].strip().strip('""')
title = title + ' by ' + author
self.productid2name[isbn] = title
f.close()
#
# Now load user info into both self.userid2name and
# self.username2id
#
f = codecs.open(path + ""BX-Users.csv"", 'r', 'utf8')
for line in f:
i += 1
#print(line)
#separate line into fields
fields = line.split(';')
userid = fields[0].strip('""')
location = fields[1].strip('""')
if len(fields) > 3:
age = fields[2].strip().strip('""')
else:
age = 'NULL'
if age != 'NULL':
value = location + ' (age: ' + age + ')'
else:
value = location
self.userid2name[userid] = value
self.username2id[location] = userid
f.close()
print(i)
def pearson(self, rating1, rating2):
sum_xy = 0
sum_x = 0
sum_y = 0
sum_x2 = 0
sum_y2 = 0
n = 0
for key in rating1:
if key in rating2:
n += 1
x = rating1[key]
y = rating2[key]
sum_xy += x * y
sum_x += x
sum_y += y
sum_x2 += pow(x, 2)
sum_y2 += pow(y, 2)
if n == 0:
return 0
# now compute denominator
denominator = (sqrt(sum_x2 - pow(sum_x, 2) / n)
* sqrt(sum_y2 - pow(sum_y, 2) / n))
if denominator == 0:
return 0
else:
return (sum_xy - (sum_x * sum_y) / n) / denominator
def computeNearestNeighbor(self, username):
""""""creates a sorted list of users based on their distance to
username""""""
distances = []
for instance in self.data:
if instance != username:
distance = self.fn(self.data[username],
self.data[instance])
distances.append((instance, distance))
# sort based on distance -- closest first
distances.sort(key=lambda artistTuple: artistTuple[1],
reverse=True)
return distances
def recommend(self, user):
""""""Give list of recommendations""""""
recommendations = {}
# first get list of users ordered by nearness
nearest = self.computeNearestNeighbor(user)
#
# now get the ratings for the user
#
userRatings = self.data[user]
#
# determine the total distance
totalDistance = ",https://stackoverflow.com/questions/20853474/importerror-no-module-named-dateutil-parser,210,441036.0,12.0,,,2013-12-31 07:18:17,2024-01-15 06:23:19,2013-12-31 10:38:01,,,python;pandas;pip,Mona Jalal,39075,2414957,registered,true,22920808,,CC BY-SA 3.0,,9970,9882,4,0,0,3,true,false,false,true,true,true,44,5,false,0.027,0.0005,4708,2013,12,7,Tuesday,false,true,false,false,false,false,false
21608228,Conditional Replace Pandas,"I have a DataFrame, and I want to replace the values in a particular column that exceed a value with zero. I had thought this was a way of achieving this:
df[df.my_channel > 20000].my_channel = 0
If I copy the channel into a new data frame it's simple:
df2 = df.my_channel
df2[df2 > 20000] = 0
This does exactly what I want, but seems not to work with the channel as part of the original DataFrame.
",https://stackoverflow.com/questions/21608228/conditional-replace-pandas,209,461351.0,6.0,,,2014-02-06 16:16:54,2024-06-30 00:18:19,2020-07-21 08:27:26,2024-04-05 23:22:50,Duplicate,python;pandas;replace;conditional-statements;series,BMichell,3791,3215592,registered,true,44311454,,,2019-07-22 10:06:09,478,409,2,0,0,5,true,true,false,true,true,true,26,3,false,0.013,0.0005,4671,2014,2,16,Thursday,false,true,false,false,false,false,false
11077023,What are the differences between Pandas and NumPy+SciPy in Python?,"They both seem exceedingly similar and I'm curious as to which package would be more beneficial for financial data analysis.
",https://stackoverflow.com/questions/11077023/what-are-the-differences-between-pandas-and-numpyscipy-in-python,209,141317.0,3.0,,,2012-06-18 04:45:48,2026-01-27 17:13:13,2017-01-04 23:23:28,2015-07-21 00:21:27,Opinion-based,python;numpy;scipy;pandas,user1462733,,,does_not_exist,true,11077215,,,,142,126,0,0,0,4,true,true,false,true,false,true,66,10,true,0.021,0.0015,5269,2012,6,4,Monday,false,true,false,false,false,false,false
36909977,Update row values where certain condition is met in pandas,"Say I have the following dataframe:
What is the most efficient way to update the values of the columns feat and another_feat where the stream is number 2?
Is this it?
for index, row in df.iterrows():
if df1.loc[index,'stream'] == 2:
# do something
How do I do it if there are more than 100 columns? I don't want to explicitly name the columns that I want to update. I want to divide the value of each column by 2 (except for the stream column).
So to be clear, my goal is:
Dividing all values by 2 of all rows that have stream 2, but not changing the stream column.
",https://stackoverflow.com/questions/36909977/update-row-values-where-certain-condition-is-met-in-pandas,209,410313.0,3.0,,,2016-04-28 09:03:15,2024-12-02 18:31:21,2024-12-02 18:31:21,,,python;pandas;indexing;conditional-statements;iterator,Stanko,4555,3296266,registered,true,36910033,,CC BY-SA 4.0,,894,579,1,1,1,5,true,false,false,true,true,true,58,10,false,0.007,0.0005,3859,2016,4,9,Thursday,false,true,false,false,false,false,false
37561991,"What is dtype('O'), in pandas?","I have a dataframe in pandas and I'm trying to figure out what the types of its values are. I am unsure what the type is of column 'Test'. However, when I run myFrame['Test'].dtype, I get;
dtype('O')
What does this mean?
",https://stackoverflow.com/questions/37561991/what-is-dtypeo-in-pandas,209,309390.0,5.0,,,2016-06-01 07:22:00,2024-02-25 18:46:13,2020-06-08 23:47:58,,,python;pandas;numpy;dataframe;types,quant,23750,1613983,registered,true,37562101,,CC BY-SA 4.0,,288,224,3,0,0,5,true,false,false,true,true,true,38,5,true,0.016,0.0007,3825,2016,6,7,Wednesday,false,true,false,false,false,false,false
18695605,How to convert a dataframe to a dictionary,"I have a dataframe with two columns and I intend to convert it to a dictionary. The first column will be the key and the second will be the value.
Dataframe:
id value
0 0 10.2
1 1 5.7
2 2 7.4
How can I do this?
",https://stackoverflow.com/questions/18695605/how-to-convert-a-dataframe-to-a-dictionary,208,374125.0,22.0,,,2013-09-09 09:49:56,2025-03-16 21:55:52,2025-03-16 21:55:52,,,python;pandas;dataframe;dictionary;type-conversion,perigee,9988,857130,registered,true,,,CC BY-SA 4.0,,326,242,1,0,0,5,false,false,false,true,true,true,42,8,false,0.059,0.0006,4821,2013,9,9,Monday,false,true,false,false,false,false,false
45273731,Binning a column with pandas,"I have a data frame column with numeric values:
df['percentage'].head()
46.5
44.2
100.0
42.12
I want to see the column as bin counts:
bins = [0, 1, 5, 10, 25, 50, 100]
How can I get the result as bins with their value counts?
[0, 1] bin amount
[1, 5] etc
[5, 10] etc
...
",https://stackoverflow.com/questions/45273731/binning-a-column-with-pandas,208,293076.0,4.0,,,2017-07-24 06:13:08,2023-03-16 13:04:12,2022-08-25 17:26:25,,,python;pandas;numpy;dataframe;binning,Night Walker,21467,140100,registered,true,45273750,,CC BY-SA 4.0,,450,274,3,1,0,5,true,false,false,true,true,true,28,5,false,0.014,0.0007,3407,2017,7,6,Monday,false,true,false,false,false,false,false
12307099,Modifying a subset of rows in a pandas dataframe,"Assume I have a pandas DataFrame with two columns, A and B. I'd like to modify this DataFrame (or create a copy) so that B is always NaN whenever A is 0. How would I achieve that?
I tried the following
df['A'==0]['B'] = np.nan
and
df['A'==0]['B'].values.fill(np.nan)
without success.
",https://stackoverflow.com/questions/12307099/modifying-a-subset-of-rows-in-a-pandas-dataframe,207,241690.0,7.0,,,2012-09-06 19:32:25,2023-08-27 07:57:44,,,,python;pandas,Arthur B.,3605,645212,registered,true,12307162,,CC BY-SA 3.0,2019-07-03 22:20:20,367,291,2,0,0,2,true,false,false,true,true,false,48,9,false,0.029,0.0009,5189,2012,9,19,Thursday,false,true,false,false,false,false,false
25646200,Python: Convert timedelta to int in a dataframe,"I would like to create a column in a pandas data frame that is an integer representation of the number of days in a timedelta column. Is it possible to use 'datetime.days' or do I need to do something more manual?
timedelta column
7 days, 23:29:00
day integer column
7
",https://stackoverflow.com/questions/25646200/python-convert-timedelta-to-int-in-a-dataframe,207,504189.0,6.0,,,2014-09-03 13:53:18,2022-06-23 15:08:57,,,,python;pandas;timedelta,Asaf Hanish,2089,4004150,registered,true,,,CC BY-SA 3.0,,417,298,0,0,0,3,false,false,false,true,true,false,47,8,false,0.012,0.0004,4462,2014,9,13,Wednesday,false,true,false,false,false,false,false
15222754,GroupBy pandas DataFrame and select most common value,"I have a data frame with three string columns. I know that the only one value in the 3rd column is valid for every combination of the first two. To clean the data I have to group by data frame by first two columns and select most common value of the third column for each combination.
My code:
import pandas as pd
from scipy import stats
source = pd.DataFrame({
'Country': ['USA', 'USA', 'Russia', 'USA'],
'City': ['New-York', 'New-York', 'Sankt-Petersburg', 'New-York'],
'Short name': ['NY', 'New', 'Spb', 'NY']})
source.groupby(['Country','City']).agg(lambda x: stats.mode(x['Short name'])[0])
Last line of code doesn't work, it says KeyError: 'Short name' and if I try to group only by City, then I got an AssertionError. What can I do fix it?
",https://stackoverflow.com/questions/15222754/groupby-pandas-dataframe-and-select-most-common-value,205,301815.0,14.0,,,2013-03-05 11:34:38,2024-08-01 03:51:46,2024-08-01 03:51:46,,,python;pandas;dataframe;group-by;mode,Viacheslav Nefedov,2469,1956483,registered,true,15223034,,CC BY-SA 4.0,2019-10-15 15:22:07,821,763,2,0,0,5,true,false,false,true,true,true,53,8,false,0.046,0.0007,5009,2013,3,11,Tuesday,false,true,false,false,false,false,false
28006793,Pandas DataFrame to List of Lists,"It's easy to turn a list of lists into a pandas dataframe:
import pandas as pd
df = pd.DataFrame([[1,2,3],[3,4,5]])
But how do I turn df back into a list of lists?
lol = df.what_to_do_now?
print lol
# [[1,2,3],[3,4,5]]
",https://stackoverflow.com/questions/28006793/pandas-dataframe-to-list-of-lists,205,270496.0,14.0,,,2015-01-18 03:14:21,2023-01-02 14:49:08,,,,python;pandas,bumpkin,3509,2004922,registered,true,28006809,,CC BY-SA 3.0,,286,224,2,0,0,2,true,false,false,true,true,false,33,6,false,0.052,0.0008,4325,2015,1,3,Sunday,true,true,false,false,false,false,false
17315737,Split a large pandas dataframe,"I have a large dataframe with 423244 lines. I want to split this in to 4. I tried the following code which gave an error? ValueError: array split does not result in an equal division
for item in np.split(df, 4):
print item
How to split this dataframe in to 4 groups?
",https://stackoverflow.com/questions/17315737/split-a-large-pandas-dataframe,204,359949.0,11.0,,,2013-06-26 09:01:24,2025-08-19 03:08:55,,,,python;pandas,Nilani Algiriyage,36166,461436,registered,true,17315875,,CC BY-SA 3.0,,325,274,2,0,0,2,true,false,false,true,true,false,30,5,false,0.031,0.0006,4896,2013,6,9,Wednesday,false,true,false,false,false,false,false
26147180,Convert row to column header for Pandas DataFrame,"The data I have to work with is a bit messy.. It has header names inside of its data. How can I choose a row from an existing pandas dataframe and make it (rename it to) a column header?
I want to do something like:
header = df[df['old_header_name1'] == 'new_header_name1']
df.columns = header
",https://stackoverflow.com/questions/26147180/convert-row-to-column-header-for-pandas-dataframe,204,570592.0,6.0,,,2014-10-01 17:33:44,2024-09-16 20:22:43,2024-09-16 20:22:43,,,python;pandas;rename;dataframe,E.K.,4379,3128336,registered,true,26147330,,CC BY-SA 4.0,,336,298,1,0,0,4,true,false,false,true,true,true,49,8,false,0.011,0.0004,4434,2014,10,17,Wednesday,false,true,false,false,false,false,false
1987694,"How do I print the full NumPy array, without truncation?","When I print a numpy array, I get a truncated representation, but I want the full array.
>>> numpy.arange(10000)
array([ 0, 1, 2, ..., 9997, 9998, 9999])
>>> numpy.arange(10000).reshape(250,40)
array([[ 0, 1, 2, ..., 37, 38, 39],
[ 40, 41, 42, ..., 77, 78, 79],
[ 80, 81, 82, ..., 117, 118, 119],
...,
[9880, 9881, 9882, ..., 9917, 9918, 9919],
[9920, 9921, 9922, ..., 9957, 9958, 9959],
[9960, 9961, 9962, ..., 9997, 9998, 9999]])
",https://stackoverflow.com/questions/1987694/how-do-i-print-the-full-numpy-array-without-truncation,929,1289715.0,23.0,,,2010-01-01 01:51:46,2025-03-12 15:36:56,2022-07-29 06:37:15,,,python;arrays;numpy;output-formatting,kame,22393,237934,registered,true,1988024,,CC BY-SA 4.0,2019-07-05 09:47:50,567,536,1,0,0,4,true,false,false,true,true,true,56,10,true,0.018,0.0007,6168,2010,1,1,Friday,false,true,false,false,false,false,false
6910641,How do I get indices of N maximum values in a NumPy array?,"NumPy proposes a way to get the index of the maximum value of an array via np.argmax.
I would like a similar thing, but returning the indexes of the N maximum values.
For instance, if I have an array, [1, 3, 2, 4, 5], then nargmax(array, n=3) would return the indices [4, 3, 1] which correspond to the elements [5, 4, 3].
",https://stackoverflow.com/questions/6910641/how-do-i-get-indices-of-n-maximum-values-in-a-numpy-array,839,821259.0,21.0,,,2011-08-02 10:29:25,2022-11-09 16:26:03,2022-06-13 07:36:06,,,python;numpy;max;numpy-ndarray,Alexis Métaireau,11333,147077,registered,true,23734295,,CC BY-SA 4.0,2019-07-05 09:49:39,519,322,6,1,0,4,true,false,false,true,true,true,58,13,true,0.026,0.001,5590,2011,8,10,Tuesday,false,true,false,false,false,false,false
6081008,Dump a NumPy array into a csv file,"How do I dump a 2D NumPy array into a csv file in a human-readable format?
",https://stackoverflow.com/questions/6081008/dump-a-numpy-array-into-a-csv-file,829,1426143.0,13.0,,,2011-05-21 10:01:16,2025-03-19 07:08:12,2025-03-19 07:08:12,,,python;arrays;numpy;csv;file-io,Dexter,11961,308254,registered,true,6081043,,CC BY-SA 4.0,2020-09-28 15:30:25,82,75,0,0,0,5,true,false,false,true,true,true,34,8,false,0.009,0.0006,5663,2011,5,10,Saturday,true,true,false,false,false,false,false
1401712,How can the Euclidean distance be calculated with NumPy?,"I have two points in 3D space:
a = (ax, ay, az)
b = (bx, by, bz)
I want to calculate the distance between them:
dist = sqrt((ax-bx)^2 + (ay-by)^2 + (az-bz)^2)
How do I do this with NumPy? I have:
import numpy
a = numpy.array((ax, ay, az))
b = numpy.array((bx, by, bz))
",https://stackoverflow.com/questions/1401712/how-can-the-euclidean-distance-be-calculated-with-numpy,812,1545735.0,26.0,,,2009-09-09 19:48:49,2024-01-09 12:43:02,2023-07-12 05:06:56,,,python;numpy;euclidean-distance,Nathan Fellman,129274,1084,registered,true,1401828,,CC BY-SA 4.0,,480,272,3,0,0,3,true,false,false,true,true,true,56,9,true,0.017,0.0005,6282,2009,9,19,Wednesday,false,true,false,false,false,false,false
35215161,Most efficient way to map function over numpy array,"What is the most efficient way to map a function over a numpy array? I am currently doing:
import numpy as np
x = np.array([1, 2, 3, 4, 5])
# Obtain array of square of each element in x
squarer = lambda t: t ** 2
squares = np.array([squarer(xi) for xi in x])
However, this is probably very inefficient, since I am using a list comprehension to construct the new array as a Python list before converting it back to a numpy array. Can we do better?
",https://stackoverflow.com/questions/35215161/most-efficient-way-to-map-function-over-numpy-array,716,1246161.0,12.0,,,2016-02-05 02:08:10,2024-09-10 03:05:30,2022-06-13 07:47:18,,,python;performance;numpy,Ryan,8371,3334595,registered,true,,,CC BY-SA 4.0,,489,451,1,0,0,3,false,false,false,true,true,true,51,9,false,0.01,0.0006,3942,2016,2,2,Friday,false,true,false,false,false,false,false
18691084,What does -1 mean in numpy reshape?,"A 2D array can be reshaped into a 1D array using .reshape(-1).
For example:
>>> a = numpy.array([[1, 2, 3, 4], [5, 6, 7, 8]])
>>> a.reshape(-1)
array([[1, 2, 3, 4, 5, 6, 7, 8]])
Usually, array[-1] means the last element.
But what does -1 mean here?
",https://stackoverflow.com/questions/18691084/what-does-1-mean-in-numpy-reshape,695,732763.0,12.0,,,2013-09-09 03:25:02,2023-02-02 13:12:33,2022-06-13 07:32:02,,,python;numpy;reshape;numpy-ndarray,user2262504,7417,2262504,registered,true,,,CC BY-SA 4.0,2019-07-05 09:50:49,332,268,3,0,0,4,false,false,false,true,true,true,35,7,true,0.016,0.0009,4821,2013,9,3,Monday,false,true,false,false,false,false,false
4455076,How do I access the ith column of a NumPy multidimensional array?,"Given:
test = np.array([[1, 2], [3, 4], [5, 6]])
test[i] gives the ith row (e.g. [1, 2]). How do I access the ith column? (e.g. [1, 3, 5]). Also, would this be an expensive operation?
",https://stackoverflow.com/questions/4455076/how-do-i-access-the-ith-column-of-a-numpy-multidimensional-array,687,1281122.0,10.0,,,2010-12-15 21:27:41,2023-10-28 02:00:52,2023-04-18 06:55:44,,,python;arrays;numpy;indexing,lpl,6919,537441,unregistered,true,4455154,,CC BY-SA 4.0,,317,185,4,0,0,4,true,false,false,true,true,true,65,12,true,0.008,0.0005,5820,2010,12,21,Wednesday,false,true,false,false,false,false,false
28663856,How do I count the occurrence of a certain item in an ndarray?,"How do I count the number of 0s and 1s in the following array?
y = np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])
y.count(0) gives:
numpy.ndarray object has no attribute count
",https://stackoverflow.com/questions/28663856/how-do-i-count-the-occurrence-of-a-certain-item-in-an-ndarray,680,1243705.0,32.0,,,2015-02-22 22:05:48,2023-01-05 10:01:01,2022-06-13 07:50:44,,,python;numpy;multidimensional-array;count,mflowww,7535,3341945,registered,true,28663910,,CC BY-SA 4.0,2019-07-05 09:51:37,321,180,6,0,0,4,true,false,false,true,true,true,62,13,true,0.026,0.0005,4290,2015,2,22,Sunday,true,true,false,false,false,false,false
432112,Is there a NumPy function to return the first index of something in an array?,"I know there is a method for a Python list to return the first index of something:
>>> xs = [1, 2, 3]
>>> xs.index(2)
1
Is there something like that for NumPy arrays?
",https://stackoverflow.com/questions/432112/is-there-a-numpy-function-to-return-the-first-index-of-something-in-an-array,678,1174535.0,24.0,,,2009-01-11 01:21:39,2024-05-12 01:27:47,2022-06-06 05:53:37,,,python;arrays;numpy,Nope,36360,41718,registered,true,432289,,CC BY-SA 4.0,2018-04-10 01:42:42,224,186,1,0,0,3,true,false,false,true,true,true,77,15,true,0.02,0.0006,6523,2009,1,1,Sunday,true,true,false,false,false,false,false
3518778,How do I read CSV data into a record array in NumPy?,"Is there a direct way to import the contents of a CSV file into a record array, just like how R's read.table(), read.delim(), and read.csv() import data into R dataframes?
Or should I use csv.reader() and then apply numpy.core.records.fromrecords()?
",https://stackoverflow.com/questions/3518778/how-do-i-read-csv-data-into-a-record-array-in-numpy,583,1331441.0,14.0,,,2010-08-19 04:41:53,2022-08-02 01:28:41,2022-06-13 07:55:03,,,python;numpy;scipy;genfromtxt,hatmatrix,45660,143476,registered,true,3519314,,CC BY-SA 4.0,2024-11-20 03:13:02,430,250,5,1,0,4,true,false,false,true,true,true,52,12,true,0.011,0.0004,5938,2010,8,4,Thursday,false,true,false,false,false,false,false
993984,What are the advantages of NumPy over regular Python lists?,"What are the advantages of NumPy over regular Python lists?
I have approximately 100 financial markets series, and I am going to create a cube array of 100x100x100 = 1 million cells. I will be regressing (3-variable) each x with each y and z, to fill the array with standard errors.
I have heard that for ""large matrices"" I should use NumPy as opposed to Python lists, for performance and scalability reasons. Thing is, I know Python lists and they seem to work for me.
What will the benefits be if I move to NumPy?
What if I had 1000 series (that is, 1 billion floating point cells in the cube)?
",https://stackoverflow.com/questions/993984/what-are-the-advantages-of-numpy-over-regular-python-lists,577,267165.0,8.0,,,2009-06-14 23:02:14,2024-08-08 21:22:22,2019-02-27 00:29:22,,,python;arrays;list;numpy;numpy-ndarray,Thomas Browne,25218,122792,registered,true,994010,,CC BY-SA 4.0,2023-07-15 16:32:06,704,603,0,1,0,5,true,false,false,true,true,true,59,10,true,0.03,0.0022,6369,2009,6,23,Sunday,true,true,false,false,false,false,false
2828059,Sorting arrays in NumPy by column,"How do I sort a NumPy array by its nth column?
For example, given:
a = array([[9, 2, 3],
[4, 5, 6],
[7, 0, 5]])
I want to sort the rows of a by the second column to obtain:
array([[7, 0, 5],
[9, 2, 3],
[4, 5, 6]])
",https://stackoverflow.com/questions/2828059/sorting-arrays-in-numpy-by-column,521,572570.0,16.0,,,2010-05-13 15:32:57,2022-06-20 03:05:14,2022-06-20 03:02:24,,,python;arrays;sorting;numpy;scipy,user248237,,,does_not_exist,true,2828371,,CC BY-SA 4.0,,334,252,3,0,0,5,true,false,false,true,false,true,33,6,false,0.028,0.0009,6036,2010,5,15,Thursday,false,true,false,false,false,false,false
21494489,What does numpy.random.seed(0) do?,"What does np.random.seed do?
np.random.seed(0)
",https://stackoverflow.com/questions/21494489/what-does-numpy-random-seed0-do,518,797109.0,12.0,,,2014-02-01 05:28:33,2022-10-16 03:40:10,2022-06-20 03:18:36,,,python;numpy,covariance,7353,2564905,registered,true,21494630,,CC BY-SA 4.0,,202,48,2,1,0,2,true,false,false,true,true,true,34,4,true,0.015,0.0006,4676,2014,2,5,Saturday,true,true,false,false,false,false,false
36013063,What is the purpose of meshgrid in NumPy?,"What is the purpose of np.meshgrid? I know it creates some kind of grid of coordinates for plotting, but I can't see the direct benefit of it.
The official documentation gives the following example, but its output doesn't make sense to me:
x = np.arange(-5, 5, 1)
y = np.arange(-5, 5, 1)
xx, yy = np.meshgrid(x, y, sparse=True)
z = np.sin(xx**2 + yy**2) / (xx**2 + yy**2)
h = plt.contourf(x,y,z)
",https://stackoverflow.com/questions/36013063/what-is-the-purpose-of-meshgrid-in-numpy,508,386057.0,10.0,,,2016-03-15 13:43:43,2024-07-20 12:20:10,2023-08-19 10:04:12,,,python;numpy;multidimensional-array;mesh;numpy-ndarray,HonzaB,7405,3441597,registered,true,36014586,,CC BY-SA 4.0,,548,397,2,1,0,5,true,false,false,true,true,true,41,8,true,0.026,0.0013,3903,2016,3,13,Tuesday,false,true,false,false,false,false,false
2566412,Find nearest value in numpy array,"How do I find the nearest value in a numpy array? Example:
np.find_nearest(array, value)
",https://stackoverflow.com/questions/2566412/find-nearest-value-in-numpy-array,499,639433.0,21.0,,,2010-04-02 11:38:23,2024-04-23 09:21:22,2022-06-20 03:12:09,,,python;search;numpy,Fookatchu,7475,307633,registered,true,2566508,,CC BY-SA 4.0,2019-03-23 01:37:08,130,90,1,0,0,3,true,false,false,true,true,true,33,6,false,0.033,0.0008,6077,2010,4,11,Friday,false,true,false,false,false,false,false
384759,How do I convert a PIL Image into a NumPy array?,"How do I convert a PIL Image back and forth to a NumPy array so that I can do faster pixel-wise transformations than PIL's PixelAccess allows? I can convert it to a NumPy array via:
pic = Image.open("foo.jpg")
pix = numpy.array(pic.getdata()).reshape(pic.size[0], pic.size[1], 3)
But how do I load it back into the PIL Image after I've modified the array? pic.putdata() isn't working well.
",https://stackoverflow.com/questions/384759/how-do-i-convert-a-pil-image-into-a-numpy-array,498,998748.0,8.0,,,2008-12-21 18:21:32,2023-02-14 20:35:43,2022-07-30 06:21:19,,,python;image;numpy;python-imaging-library;numpy-ndarray,akdom,33609,145,registered,true,384926,,CC BY-SA 4.0,,491,401,5,0,0,5,true,false,false,true,true,true,48,11,true,0.008,0.0005,6544,2008,12,18,Sunday,true,true,false,false,false,false,false
2891790,Pretty-print a NumPy array without scientific notation and with given precision,"How do I print formatted NumPy arrays in a way similar to this:
x = 1.23456
print('%.3f' % x)
If I want to print the numpy.ndarray of floats, it prints several decimals, often in 'scientific' format, which is rather hard to read even for low-dimensional arrays. However, numpy.ndarray apparently has to be printed as a string, i.e., with %s. Is there a solution for this?
",https://stackoverflow.com/questions/2891790/pretty-print-a-numpy-array-without-scientific-notation-and-with-given-precision,496,682382.0,14.0,,,2010-05-23 12:54:29,2023-10-02 17:16:05,2022-07-30 06:05:56,,,python;numpy;pretty-print,camillio,4975,348260,registered,true,2891805,,CC BY-SA 4.0,2019-07-05 09:51:13,450,373,4,0,0,3,true,false,false,true,true,true,79,11,false,0.021,0.0007,6026,2010,5,12,Sunday,true,true,false,false,false,false,false
26646362,NumPy array is not JSON serializable,"After creating a NumPy array, and saving it as a Django context variable, I receive the following error when loading the webpage:
array([ 0, 239, 479, 717, 952, 1192, 1432, 1667], dtype=int64) is not JSON serializable
What does this mean?
",https://stackoverflow.com/questions/26646362/numpy-array-is-not-json-serializable,482,601617.0,17.0,,,2014-10-30 06:23:48,2025-08-22 13:17:30,2018-04-18 20:15:34,,,python;json;django;numpy,Karnivaurus,24469,3320135,registered,true,32850511,,CC BY-SA 3.0,,286,248,1,0,0,4,true,false,false,true,true,true,36,6,false,0.028,0.0008,4405,2014,10,6,Thursday,false,true,false,false,false,false,false
14415741,What is the difference between np.array() and np.asarray()?,"What is the difference between NumPy's np.array and np.asarray? When should I use one rather than the other? They seem to generate identical output.
",https://stackoverflow.com/questions/14415741/what-is-the-difference-between-np-array-and-np-asarray,478,207742.0,8.0,,,2013-01-19 15:18:46,2023-06-11 15:08:01,2022-07-30 06:13:51,,,python;arrays;numpy,Benjamin Hodgson,45154,1523776,registered,true,52103839,,CC BY-SA 4.0,,404,149,2,2,0,3,true,false,false,true,true,true,59,8,true,0.039,0.0023,5054,2013,1,15,Saturday,true,true,false,false,false,false,false
10580676,"Comparing two NumPy arrays for equality, element-wise","What is the simplest way to compare two NumPy arrays for equality (where equality is defined as: A = B iff for all indices i: A[i] == B[i])?
Simply using == gives me a boolean array:
>>> numpy.array([1,1,1]) == numpy.array([1,1,1])
array([ True, True, True], dtype=bool)
Do I have to and the elements of this array to determine if the arrays are equal, or is there a simpler way to compare?
",https://stackoverflow.com/questions/10580676/comparing-two-numpy-arrays-for-equality-element-wise,469,820811.0,9.0,,,2012-05-14 09:30:18,2024-10-07 15:59:45,2019-11-07 09:02:33,,,python;arrays;numpy;elementwise-operations,clstaudt,22748,626537,registered,true,10580782,,CC BY-SA 4.0,,492,408,4,0,0,4,true,false,false,true,true,true,53,7,false,0.011,0.0006,5304,2012,5,9,Monday,false,true,false,false,false,false,false
8486294,How do I add an extra column to a NumPy array?,"Given the following 2D array:
a = np.array([
[1, 2, 3],
[2, 3, 4],
])
I want to add a column of zeros along the second axis to get:
b = np.array([
[1, 2, 3, 0],
[2, 3, 4, 0],
])
",https://stackoverflow.com/questions/8486294/how-do-i-add-an-extra-column-to-a-numpy-array,463,877981.0,17.0,,,2011-12-13 08:36:10,2023-08-19 22:23:35,2022-07-30 08:33:04,,,python;numpy,Peter Smit,29087,85514,registered,true,8489498,,CC BY-SA 4.0,2018-06-27 20:24:49,258,196,2,0,0,2,true,false,false,true,true,true,46,11,true,0.019,0.0005,5457,2011,12,8,Tuesday,false,true,false,false,false,false,false
28930465,What is the difference between flatten and ravel functions in numpy?,"import numpy as np
y = np.array(((1,2,3),(4,5,6),(7,8,9)))
OUTPUT:
print(y.flatten())
[1 2 3 4 5 6 7 8 9]
print(y.ravel())
[1 2 3 4 5 6 7 8 9]
Both function return the same list.
Then what is the need of two different functions performing same job.
",https://stackoverflow.com/questions/28930465/what-is-the-difference-between-flatten-and-ravel-functions-in-numpy,461,148847.0,4.0,,,2015-03-08 18:49:44,2025-10-21 15:35:35,2019-04-27 21:20:36,,,python;numpy;multidimensional-array;flatten;numpy-ndarray,cryptomanic,6356,4110320,registered,true,28930580,,CC BY-SA 4.0,2021-02-23 09:57:09,314,283,1,0,0,5,true,false,false,true,true,true,68,11,true,0.027,0.0031,4276,2015,3,18,Sunday,true,true,false,false,false,false,false
568962,How do I create an empty array and then append to it in NumPy?,"I want to create an empty array and append items to it, one at a time.
xs = []
for item in data:
xs.append(item)
Can I use this list-style notation with NumPy arrays?
",https://stackoverflow.com/questions/568962/how-do-i-create-an-empty-array-and-then-append-to-it-in-numpy,459,1643980.0,17.0,,,2009-02-20 09:58:11,2024-12-04 15:58:48,2022-06-20 01:58:22,,,python;arrays;numpy,Ben,69024,11522,registered,true,569063,,CC BY-SA 4.0,,277,173,1,1,0,3,true,false,false,true,true,true,62,14,true,0.01,0.0003,6483,2009,2,9,Friday,false,true,false,false,false,false,false
3061761,Numpy array dimensions,"How do I get the dimensions of an array? For instance, this is 2x2:
a = np.array([[1, 2], [3, 4]])
",https://stackoverflow.com/questions/3061761/numpy-array-dimensions,452,1117150.0,10.0,,,2010-06-17 12:55:51,2023-11-15 23:27:21,2023-06-22 16:12:06,,,python;arrays;numpy;dimensions,Cristi P,6261,198088,registered,true,3061789,,CC BY-SA 4.0,2014-11-03 09:36:28,168,100,1,0,0,4,true,false,false,true,true,true,22,3,false,0.009,0.0004,6001,2010,6,12,Thursday,false,true,false,false,false,false,false
4151128,What are the differences between numpy arrays and matrices? Which one should I use?,"What are the advantages and disadvantages of each?
From what I've seen, either one can work as a replacement for the other if need be, so should I bother using both or should I stick to just one of them?
Will the style of the program influence my choice? I am doing some machine learning using numpy, so there are indeed lots of matrices, but also lots of vectors (arrays).
",https://stackoverflow.com/questions/4151128/what-are-the-differences-between-numpy-arrays-and-matrices-which-one-should-i-u,451,221508.0,7.0,,,2010-11-11 03:25:09,2022-03-04 23:31:23,2015-08-10 08:40:50,2024-06-15 21:51:03,Opinion-based,python;arrays;matrix;numpy,levesque,8974,131100,registered,true,61156350,,,2019-07-05 09:51:31,397,376,0,0,0,4,true,true,false,true,true,true,83,14,true,0.032,0.002,5854,2010,11,3,Thursday,false,true,false,false,false,false,false
902761,Saving a Numpy array as an image,"I have a matrix in the type of a Numpy array. How would I write it to disk it as an image? Any format works (png, jpeg, bmp...). One important constraint is that PIL is not present.
",https://stackoverflow.com/questions/902761/saving-a-numpy-array-as-an-image,449,1025932.0,24.0,,,2009-05-24 00:08:50,2025-08-14 12:21:08,2009-05-24 10:36:16,,,python;image;numpy,M456,5877,49412,registered,true,902774,,CC BY-SA 2.5,2022-12-06 06:30:50,192,185,0,0,0,3,true,false,false,true,true,true,32,7,false,0.023,0.0004,6390,2009,5,0,Sunday,true,true,false,false,false,false,false
1966207,Convert NumPy array to Python list,"How do I convert a NumPy array into a Python list?
",https://stackoverflow.com/questions/1966207/convert-numpy-array-to-python-list,449,736465.0,7.0,,,2009-12-27 15:29:55,2026-11-16 14:48:18,2026-11-16 14:48:18,,,python;list;numpy;numpy-ndarray,Alex Brooks,5503,177674,registered,true,1966210,,CC BY-SA 4.0,,133,51,0,1,0,4,true,false,false,true,true,true,34,6,false,0.01,0.0006,6173,2009,12,15,Sunday,true,true,false,false,false,false,false
22053050,"Difference between numpy.array shape (R, 1) and (R,)","In numpy, some of the operations return in shape (R, 1) but some return (R,). This will make matrix multiplication more tedious since explicit reshape is required. For example, given a matrix M, if we want to do numpy.dot(M[:,0], numpy.ones((1, R))) where R is the number of rows (of course, the same issue also occurs column-wise). We will get matrices are not aligned error since M[:,0] is in shape (R,) but numpy.ones((1, R)) is in shape (1, R).
So my questions are:
What's the difference between shape (R, 1) and (R,). I know literally it's list of numbers and list of lists where all list contains only a number. Just wondering why not design numpy so that it favors shape (R, 1) instead of (R,) for easier matrix multiplication.
Are there better ways for the above example? Without explicitly reshape like this: numpy.dot(M[:,0].reshape(R, 1), numpy.ones((1, R)))
",https://stackoverflow.com/questions/22053050/difference-between-numpy-array-shape-r-1-and-r,439,250280.0,8.0,,,2014-02-26 20:55:35,2022-03-11 04:16:50,2015-01-09 18:06:28,,,python;numpy;matrix;multidimensional-array,clwen,21119,477865,registered,true,22074424,,CC BY-SA 3.0,,1163,874,18,0,0,4,true,false,false,true,true,true,52,8,false,0.032,0.0018,4651,2014,2,20,Wednesday,false,true,false,false,false,false,false
9413216,Simple Digit Recognition OCR in OpenCV-Python,"I am trying to implement a ""Digit Recognition OCR"" in OpenCV-Python (cv2). It is just for learning purposes. I would like to learn both KNearest and SVM features in OpenCV.
I have 100 samples (i.e. images) of each digit. I would like to train with them.
There is a sample letter_recog.py that comes with OpenCV sample. But I still couldn't figure out on how to use it. I don't understand what are the samples, responses etc. Also, it loads a txt file at first, which I didn't understand first.
Later on searching a little bit, I could find a letter_recognition.data in cpp samples. I used it and made a code for cv2.KNearest in the model of letter_recog.py (just for testing):
import numpy as np
import cv2
fn = 'letter-recognition.data'
a = np.loadtxt(fn, np.float32, delimiter=',', converters={ 0 : lambda ch : ord(ch)-ord('A') })
samples, responses = a[:,1:], a[:,0]
model = cv2.KNearest()
retval = model.train(samples,responses)
retval, results, neigh_resp, dists = model.find_nearest(samples, k = 10)
print results.ravel()
It gave me an array of size 20000, I don't understand what it is.
Questions:
1) What is letter_recognition.data file? How to build that file from my own data set?
2) What does results.reval() denote?
3) How we can write a simple digit recognition tool using letter_recognition.data file (either KNearest or SVM)?
",https://stackoverflow.com/questions/9413216/simple-digit-recognition-ocr-in-opencv-python,432,279758.0,3.0,,,2012-02-23 12:37:22,2024-07-17 10:51:14,2018-01-24 08:16:31,,,python;opencv;numpy;computer-vision;ocr,Abid Rahman K,52751,1134940,registered,true,9620295,,CC BY-SA 3.0,2015-02-27 20:03:20,1485,1355,3,0,0,5,true,false,false,true,true,true,45,6,false,0.011,0.0015,5385,2012,2,12,Thursday,false,true,false,false,false,false,false
10062954,ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all(),"Let x be a NumPy array. The following:
(x > 1) and (x < 3)
Gives the error message:
ValueError: The truth value of an array with more than one element is
ambiguous. Use a.any() or a.all()
How do I fix this?
",https://stackoverflow.com/questions/10062954/valueerror-the-truth-value-of-an-array-with-more-than-one-element-is-ambiguous,424,1899247.0,11.0,,,2012-04-08 12:56:07,2024-02-02 10:35:28,2022-07-30 07:17:27,,,python;numpy,Homunculus Reticulli,69294,962891,registered,true,10063039,,CC BY-SA 4.0,2019-07-07 20:15:00,306,216,2,0,0,2,true,false,false,true,true,true,103,18,false,0.006,0.0002,5340,2012,4,12,Sunday,true,true,false,false,false,false,false
9236926,Concatenating two one-dimensional NumPy arrays,"How do I concatenate two one-dimensional arrays in NumPy? I tried numpy.concatenate:
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5])
np.concatenate(a, b)
But I get an error:
TypeError: only length-1 arrays can be converted to Python scalars
",https://stackoverflow.com/questions/9236926/concatenating-two-one-dimensional-numpy-arrays,423,600712.0,7.0,,,2012-02-11 01:11:06,2023-07-25 03:13:39,2022-07-30 08:04:53,,,python;arrays;numpy;concatenation;numpy-ndarray,highBandWidth,17394,429850,registered,true,9236970,,CC BY-SA 4.0,,512,260,2,2,0,5,true,false,false,true,true,true,46,5,false,0.012,0.0007,5397,2012,2,1,Saturday,true,true,false,false,false,false,false
5891410,NumPy array initialization (fill with identical values),"I need to create a NumPy array of length n, each element of which is v.
Is there anything better than:
a = empty(n)
for i in range(n):
a[i] = v
I know zeros and ones would work for v = 0, 1. I could use v * ones(n), but it won't work when v is None, and also would be much slower.
",https://stackoverflow.com/questions/5891410/numpy-array-initialization-fill-with-identical-values,411,767336.0,9.0,,,2011-05-05 00:34:20,2026-02-10 08:58:11,2019-05-19 20:18:20,2023-09-19 22:08:08,Duplicate,python;arrays;numpy,max,53041,336527,registered,true,20606278,,,,432,289,8,0,0,3,true,true,false,true,true,true,55,7,false,0.012,0.0005,5679,2011,5,0,Thursday,false,true,false,false,false,false,false
15879315,What is the difference between ndarray and array in NumPy?,"What is the difference between ndarray and array in NumPy? Where is their implementation in the NumPy source code?
",https://stackoverflow.com/questions/15879315/what-is-the-difference-between-ndarray-and-array-in-numpy,410,233711.0,6.0,,,2013-04-08 12:41:55,2024-09-05 13:24:04,2022-07-30 06:31:04,,,python;arrays;numpy;multidimensional-array;numpy-ndarray,flxb,4625,2050944,registered,true,15879527,,CC BY-SA 4.0,,344,115,2,2,0,5,true,false,false,true,true,true,58,10,true,0.026,0.0018,4975,2013,4,12,Monday,false,true,false,false,false,false,false
10741346,Frequency counts for unique values in a NumPy array,"How do I efficiently obtain the frequency count for each unique value in a NumPy array?
>>> x = np.array([1,1,1,2,2,2,5,25,1,1])
>>> freq_count(x)
[(1, 5), (2, 3), (5, 1), (25, 1)]
",https://stackoverflow.com/questions/10741346/frequency-counts-for-unique-values-in-a-numpy-array,406,592552.0,17.0,,,2012-05-24 16:15:18,2022-10-17 08:19:01,2022-06-20 02:33:47,,,python;arrays;performance;numpy,Abe,24228,660664,registered,true,10741692,,CC BY-SA 4.0,,231,200,1,0,0,4,true,false,false,true,true,true,51,9,false,0.029,0.0007,5294,2012,5,16,Thursday,false,true,false,false,false,false,false
29241056,How do I use np.newaxis?,"What is numpy.newaxis and when should I use it?
Using it on a 1-D array x produces:
>>> x
array([0, 1, 2, 3])
>>> x[np.newaxis, :]
array([[0, 1, 2, 3]])
>>> x[:, np.newaxis]
array([[0],
[1],
[2],
[3]])
",https://stackoverflow.com/questions/29241056/how-do-i-use-np-newaxis,402,536362.0,5.0,,,2015-03-24 19:18:59,2024-09-13 14:49:25,2022-07-30 08:27:13,,,python;numpy;multidimensional-array;array-broadcasting;numpy-ndarray,Yue Harriet Huang,4299,2934350,registered,true,,,CC BY-SA 4.0,,453,253,3,1,0,5,false,false,false,true,true,true,24,5,true,0.009,0.0007,4260,2015,3,19,Tuesday,false,true,false,false,false,false,false
9452775,Converting numpy dtypes to native python types,"If I have a numpy dtype, how do I automatically convert it to its closest python data type? For example,
numpy.float32 -> ""python float""
numpy.float64 -> ""python float""
numpy.uint32 -> ""python int""
numpy.int16 -> ""python int""
I could try to come up with a mapping of all of these cases, but does numpy provide some automatic way of converting its dtypes into the closest possible native python types? This mapping need not be exhaustive, but it should convert the common dtypes that have a close python analog. I think this already happens somewhere in numpy.
",https://stackoverflow.com/questions/9452775/converting-numpy-dtypes-to-native-python-types,402,519212.0,13.0,,,2012-02-26 11:40:11,2025-03-21 15:44:53,2016-09-08 09:37:16,,,python;numpy,conradlee,13975,189336,registered,true,11389998,,CC BY-SA 3.0,2019-07-05 09:53:57,619,581,1,0,0,2,true,false,false,true,true,true,46,7,false,0.025,0.0008,5382,2012,2,11,Sunday,true,true,false,false,false,false,false
11620914,How do I remove NaN values from a NumPy array?,"How do I remove NaN values from a NumPy array?
[1, 2, NaN, 4, NaN, 8] ⟶ [1, 2, 4, 8]
",https://stackoverflow.com/questions/11620914/how-do-i-remove-nan-values-from-a-numpy-array,393,896577.0,13.0,,,2012-07-23 21:36:54,2022-07-30 05:52:24,2022-07-30 05:36:58,,,python;numpy;nan,Dax Feliz,13069,1464677,registered,true,11620982,,CC BY-SA 4.0,2019-07-05 09:54:58,121,90,1,0,0,3,true,false,false,true,true,true,46,10,true,0.014,0.0004,5234,2012,7,21,Monday,false,true,false,false,false,false,false
1520234,How do I check which version of NumPy I'm using?,"How can I check which version of NumPy I'm using?
",https://stackoverflow.com/questions/1520234/how-do-i-check-which-version-of-numpy-im-using,391,775342.0,17.0,,,2009-10-05 13:56:50,2023-08-19 10:28:35,2021-12-28 09:01:59,,,python;numpy;version,larus,4587,184403,unregistered,true,1520275,,CC BY-SA 4.0,2018-06-27 20:36:08,57,50,0,0,0,3,true,false,false,true,true,true,52,10,true,0.022,0.0005,6256,2009,10,13,Monday,false,true,false,false,false,false,false
26089893,Understanding NumPy's einsum,"How does np.einsum work?
Given arrays A and B, their matrix multiplication followed by transpose is computed using (A @ B).T, or equivalently, using:
np.einsum("ij, jk -> ki", A, B)
",https://stackoverflow.com/questions/26089893/understanding-numpys-einsum,385,207673.0,8.0,,,2014-09-28 21:33:51,2025-04-25 17:04:37,2022-07-30 08:51:12,,,python;arrays;numpy;multidimensional-array;numpy-einsum,Lance Strait,4361,3424684,registered,true,33641428,,CC BY-SA 4.0,,384,196,5,1,0,5,true,false,false,true,true,true,32,3,false,0.039,0.0019,4437,2014,9,21,Sunday,true,true,false,false,false,false,false
6771428,Most efficient way to reverse a numpy array,"Believe it or not, after profiling my current code, the repetitive operation of numpy array reversion ate a giant chunk of the running time. What I have right now is the common view-based method:
reversed_arr = arr[::-1]
Is there any other way to do it more efficiently, or is it just an illusion from my obsession with unrealistic numpy performance?
",https://stackoverflow.com/questions/6771428/most-efficient-way-to-reverse-a-numpy-array,380,650195.0,8.0,,,2011-07-21 04:58:24,2022-08-08 03:44:51,2022-08-08 03:44:51,,,python;numpy,nye17,13497,560844,registered,true,6771620,,CC BY-SA 4.0,2019-07-05 09:52:02,390,352,1,0,0,2,true,false,false,true,true,true,43,8,false,0.012,0.0006,5602,2011,7,4,Thursday,false,true,false,false,false,false,false
2659312,How do I convert a numpy array to (and display) an image?,"I have created an array thusly:
import numpy as np
data = np.zeros( (512,512,3), dtype=np.uint8)
data[256,256] = [255,0,0]
What I want this to do is display a single red dot in the center of a 512x512 image. (At least to begin with... I think I can figure out the rest from there)
",https://stackoverflow.com/questions/2659312/how-do-i-convert-a-numpy-array-to-and-display-an-image,378,967477.0,11.0,,,2010-04-17 17:28:30,2023-08-19 10:37:36,2019-04-27 22:27:34,,,python;arrays;image;numpy;data-visualization,jlswint,3893,319326,registered,true,2659378,,CC BY-SA 4.0,,322,284,1,0,0,5,true,false,false,true,true,true,57,12,true,0.011,0.0004,6062,2010,4,17,Saturday,true,true,false,false,false,false,false
10873824,Convert 2D float array to 2D int array in NumPy,"How do I convert a float NumPy array into an int NumPy array?
",https://stackoverflow.com/questions/10873824/convert-2d-float-array-to-2d-int-array-in-numpy,370,470133.0,4.0,,,2012-06-03 20:46:28,2022-07-30 08:39:14,2022-07-30 08:38:00,,,python;numpy,Shan,19341,623300,registered,true,10873843,,CC BY-SA 4.0,2019-07-05 09:51:55,69,62,0,0,0,2,true,false,false,true,true,true,47,10,false,0.009,0.0008,5284,2012,6,20,Sunday,true,true,false,false,false,false,false
10996140,How to remove specific elements in a numpy array,"How can I remove some specific elements from a numpy array? Say I have
import numpy as np
a = np.array([1,2,3,4,5,6,7,8,9])
I then want to remove 3,4,7 from a. All I know is the index of the values (index=[2,3,6]).
",https://stackoverflow.com/questions/10996140/how-to-remove-specific-elements-in-a-numpy-array,365,1002923.0,13.0,,,2012-06-12 11:54:37,2023-08-19 10:44:31,,,,python;arrays;numpy,Daniel Thaagaard Andreasen,8646,1340702,registered,true,10996196,,CC BY-SA 3.0,,296,219,4,0,0,3,true,false,false,true,true,false,48,9,false,0.013,0.0004,5275,2012,6,11,Tuesday,false,true,false,false,false,false,false
29831489,Convert array of indices to one-hot encoded array in NumPy,"Given a 1D array of indices:
a = array([1, 0, 3])
I want to one-hot encode this as a 2D array:
b = array([[0,1,0,0], [1,0,0,0], [0,0,0,1]])
",https://stackoverflow.com/questions/29831489/convert-array-of-indices-to-one-hot-encoded-array-in-numpy,359,361095.0,24.0,,,2015-04-23 18:24:54,2025-10-11 13:11:44,2022-07-30 08:42:50,,,python;numpy;machine-learning;numpy-ndarray;one-hot-encoding,James Atwood,4359,938325,registered,true,29831596,,CC BY-SA 4.0,,204,142,2,0,0,5,true,false,false,true,true,true,58,10,false,0.066,0.001,4230,2015,4,18,Thursday,false,true,false,false,false,false,false
34097281,Convert a tensor to numpy array in Tensorflow?,"How to convert a tensor into a numpy array when using Tensorflow with Python bindings?
",https://stackoverflow.com/questions/34097281/convert-a-tensor-to-numpy-array-in-tensorflow,347,1025639.0,13.0,,,2015-12-04 20:55:54,2023-01-09 16:06:40,2020-10-21 20:59:15,,,python;numpy;tensorflow,mathetes,12135,1978504,registered,true,56554855,,CC BY-SA 4.0,2019-02-02 10:42:14,94,87,0,0,0,3,true,false,false,true,true,true,46,8,true,0.013,0.0003,4005,2015,12,20,Friday,false,true,false,false,false,false,false
4601373,Better way to shuffle two numpy arrays in unison,"I have two numpy arrays of different shapes, but with the same length (leading dimension). I want to shuffle each of them, such that corresponding elements continue to correspond -- i.e. shuffle them in unison with respect to their leading indices.
This code works, and illustrates my goals:
def shuffle_in_unison(a, b):
assert len(a) == len(b)
shuffled_a = numpy.empty(a.shape, dtype=a.dtype)
shuffled_b = numpy.empty(b.shape, dtype=b.dtype)
permutation = numpy.random.permutation(len(a))
for old_index, new_index in enumerate(permutation):
shuffled_a[new_index] = a[old_index]
shuffled_b[new_index] = b[old_index]
return shuffled_a, shuffled_b
For example:
>>> a = numpy.asarray([[1, 1], [2, 2], [3, 3]])
>>> b = numpy.asarray([1, 2, 3])
>>> shuffle_in_unison(a, b)
(array([[2, 2],
[1, 1],
[3, 3]]), array([2, 1, 3]))
However, this feels clunky, inefficient, and slow, and it requires making a copy of the arrays -- I'd rather shuffle them in-place, since they'll be quite large.
Is there a better way to go about this? Faster execution and lower memory usage are my primary goals, but elegant code would be nice, too.
One other thought I had was this:
def shuffle_in_unison_scary(a, b):
rng_state = numpy.random.get_state()
numpy.random.shuffle(a)
numpy.random.set_state(rng_state)
numpy.random.shuffle(b)
This works...but it's a little scary, as I see little guarantee it'll continue to work -- it doesn't look like the sort of thing that's guaranteed to survive across numpy version, for example.
",https://stackoverflow.com/questions/4601373/better-way-to-shuffle-two-numpy-arrays-in-unison,346,218423.0,18.0,,,2011-01-05 06:23:56,2022-05-28 12:17:00,2019-04-27 22:06:46,,,python;numpy;random;shuffle;numpy-ndarray,Josh Bleecher Snyder,8442,190280,registered,true,4603609,,CC BY-SA 4.0,,1732,1611,3,0,0,5,true,false,false,true,true,true,48,9,false,0.082,0.0016,5799,2011,1,6,Wednesday,false,true,false,false,false,false,false
7818811,Error "Import Error: No module named numpy" on Windows,"I have a very similar question to this question, but I am still one step behind. I have only one version of Python 3 installed on my Windows 7 (sorry) 64-bit system.
I installed NumPy following this link - as suggested in the question. The installation went fine but when I execute
import numpy
I got the following error:
Import error: No module named numpy
",https://stackoverflow.com/questions/7818811/error-import-error-no-module-named-numpy-on-windows,341,1801682.0,27.0,,,2011-10-19 08:54:16,2023-04-24 15:57:39,2022-08-22 15:04:34,2024-01-14 22:08:01,Duplicate,python;python-3.x;numpy;import;scipy,Seb,3895,1002744,registered,true,7818845,,,2017-11-13 17:01:41,697,361,1,2,0,5,true,true,false,true,true,true,64,9,false,0.015,0.0002,5512,2011,10,8,Wednesday,false,true,false,false,false,false,false
4674473,ValueError: setting an array element with a sequence,"Why do the following code samples:
np.array([[1, 2], [2, 3, 4]])
np.array([1.2, "abc"], dtype=float)
all give the following error?
ValueError: setting an array element with a sequence.
",https://stackoverflow.com/questions/4674473/valueerror-setting-an-array-element-with-a-sequence,339,1992682.0,11.0,,,2011-01-12 21:58:19,2026-02-23 17:24:55,2023-09-06 17:45:32,,,python;arrays;numpy;slice;valueerror,MedicalMath,3417,573404,unregistered,true,4675383,,CC BY-SA 4.0,,299,198,2,0,0,5,true,false,false,true,true,true,52,8,false,0.006,0.0002,5792,2011,1,21,Wednesday,false,true,false,false,false,false,false
21030391,How to normalize a numpy array to a unit vector,"I would like to convert a NumPy array to a unit vector. More specifically, I am looking for an equivalent version of this normalisation function:
def normalize(v):
norm = np.linalg.norm(v)
if norm == 0:
return v
return v / norm
This function handles the situation where vector v has the norm value of 0.
Is there any similar functions provided in sklearn or numpy?
",https://stackoverflow.com/questions/21030391/how-to-normalize-a-numpy-array-to-a-unit-vector,331,1152322.0,16.0,,,2014-01-09 20:25:03,2023-11-19 06:41:32,2023-06-15 18:11:27,,,python;numpy;scikit-learn;statistics;normalization,Donbeo,17767,2411173,registered,true,21031303,,CC BY-SA 4.0,2019-07-12 14:41:50,470,386,4,0,0,5,true,false,false,true,true,true,47,10,false,0.014,0.0003,4699,2014,1,20,Thursday,false,true,false,false,false,false,false
34968722,How to implement the Softmax function in Python?,"From the Udacity's deep learning class, the softmax of y_i is simply the exponential divided by the sum of exponential of the whole Y vector:
Where S(y_i) is the softmax function of y_i and e is the exponential and j is the no. of columns in the input vector Y.
I've tried the following:
import numpy as np
def softmax(x):
"""Compute softmax values for each sets of scores in x."""
e_x = np.exp(x - np.max(x))
return e_x / e_x.sum()
scores = [3.0, 1.0, 0.2]
print(softmax(scores))
which returns:
[ 0.8360188 0.11314284 0.05083836]
But the suggested solution was:
def softmax(x):
"""Compute softmax values for each sets of scores in x."""
return np.exp(x) / np.sum(np.exp(x), axis=0)
which produces the same output as the first implementation, even though the first implementation explicitly takes the difference of each column and the max and then divides by the sum.
Can someone show mathematically why? Is one correct and the other one wrong?
Are the implementation similar in terms of code and time complexity? Which is more efficient?
",https://stackoverflow.com/questions/34968722/how-to-implement-the-softmax-function-in-python,321,468199.0,24.0,,,2016-01-23 20:52:50,2024-08-28 17:39:31,2024-08-28 13:55:21,,,python;numpy;machine-learning;logistic-regression;softmax,alvas,123759,610569,registered,true,34969389,,CC BY-SA 4.0,2018-12-07 00:29:43,1593,1128,8,2,1,5,true,false,false,true,true,true,48,8,true,0.051,0.0007,3955,2016,1,20,Saturday,true,true,false,false,false,false,false
2374640,How do I calculate percentiles with python/numpy?,"Is there a convenient way to calculate percentiles for a sequence or single-dimensional numpy array?
I am looking for something similar to Excel's percentile function.
",https://stackoverflow.com/questions/2374640/how-do-i-calculate-percentiles-with-python-numpy,319,530936.0,12.0,,,2010-03-03 20:21:13,2023-11-16 22:49:49,2023-11-16 22:49:49,,,python;numpy;statistics;quantile;percentile,Uri,90201,23072,registered,true,2374662,,CC BY-SA 4.0,2019-07-05 09:54:10,195,168,1,0,0,5,true,false,false,true,true,true,49,7,true,0.023,0.0006,6107,2010,3,20,Wednesday,false,true,false,false,false,false,false
13728392,Moving average or running mean,"Is there a SciPy function or NumPy function or module for Python that calculates the running mean of a 1D array given a specific window?
",https://stackoverflow.com/questions/13728392/moving-average-or-running-mean,314,713382.0,31.0,,,2012-12-05 16:57:05,2026-08-20 09:34:57,2020-02-23 11:17:49,,,python;numpy;scipy;moving-average,Shejo284,4831,1394513,registered,true,44797397,,CC BY-SA 4.0,2017-03-07 19:39:24,144,137,0,0,0,4,true,false,false,true,true,true,30,5,false,0.043,0.0004,5099,2012,12,16,Wednesday,false,true,false,false,false,false,false
1704823,Create numpy matrix filled with NaNs,"I have the following code:
r = numpy.zeros(shape = (width, height, 9))
It creates a width x height x 9 matrix filled with zeros. Instead, I'd like to know if there's a function or way to initialize them instead to NaNs in an easy way.
",https://stackoverflow.com/questions/1704823/create-numpy-matrix-filled-with-nans,310,481391.0,11.0,,,2009-11-10 00:10:07,2023-03-28 09:57:54,2019-10-11 14:21:48,,,python;numpy,devoured elysium,106194,130758,registered,true,1704853,,CC BY-SA 4.0,,302,238,3,0,0,2,true,false,false,true,true,true,36,6,false,0.023,0.0006,6220,2009,11,0,Tuesday,false,true,false,false,false,false,false
20618804,How to smooth a curve for a dataset,"Lets assume we have a dataset which might be given approximately by:
import numpy as np
x = np.linspace(0,2*np.pi,100)
y = np.sin(x) + np.random.random(100) * 0.2
Therefore we have a variation of 20% of the dataset. My first idea was to use the UnivariateSpline function of scipy, but the problem is that this does not consider the small noise well. If you consider the frequencies, the background is much smaller than the signal, so a spline only of the cutoff might be an idea, but that would involve a back and forth Fourier transformation, which might result in bad behavior.
Another way would be a moving average, but this would also need the right choice of delay.
Any hints/books or links on how to tackle this problem?
![]()
",https://stackoverflow.com/questions/20618804/how-to-smooth-a-curve-for-a-dataset,307,621157.0,12.0,,,2013-12-16 19:06:31,2024-06-10 08:05:10,2024-06-10 08:05:10,,,python;numpy;scipy;signal-processing;smoothing,varantir,6904,1117766,registered,true,,,CC BY-SA 4.0,2019-07-09 14:25:27,853,729,2,0,1,5,false,false,false,true,true,true,35,8,false,0.019,0.0005,4723,2013,12,19,Monday,false,true,false,false,false,false,false
21174961,How do I create a numpy array of all True or all False?,"In Python, how do I create a numpy array of arbitrary shape filled with all True or all False?
",https://stackoverflow.com/questions/21174961/how-do-i-create-a-numpy-array-of-all-true-or-all-false,307,440378.0,7.0,,,2014-01-16 23:22:01,2022-08-15 14:43:01,2022-08-15 14:43:01,,,python;arrays;numpy;boolean;numpy-ndarray,Michael B. Currie,14846,1832942,registered,true,21174962,,CC BY-SA 4.0,2019-07-05 09:54:47,128,95,2,0,0,5,true,false,false,true,true,true,55,13,true,0.016,0.0007,4692,2014,1,23,Thursday,false,true,false,false,false,false,false
11295609,How can I check whether a numpy array is empty or not?,"How can I check whether a numpy array is empty or not?
I used the following code, but this fails if the array contains a zero.
if not self.Definition.all():
Is this the solution?
if self.Definition == array([]):
",https://stackoverflow.com/questions/11295609/how-can-i-check-whether-a-numpy-array-is-empty-or-not,302,452670.0,4.0,,,2012-07-02 14:24:45,2026-07-07 15:58:09,2022-02-28 22:05:46,,,python;numpy,Kicsi Mano,3841,737640,registered,true,11295857,,CC BY-SA 4.0,,283,214,2,0,0,2,true,false,false,true,true,true,54,12,true,0.009,0.0007,5255,2012,7,14,Monday,false,true,false,false,false,false,false
10965417,How to convert a NumPy array to PIL image applying matplotlib colormap,"I want to take a NumPy 2D array which represents a grayscale image, and convert it to an RGB PIL image while applying some of the matplotlib colormaps.
I can get a reasonable PNG output by using the pyplot.figure.figimage command:
dpi = 100.0
w, h = myarray.shape[1]/dpi, myarray.shape[0]/dpi
fig = plt.figure(figsize=(w,h), dpi=dpi)
fig.figimage(sub, cmap=cm.gist_earth)
plt.savefig('out.png')
Although I could adapt this to get what I want (probably using StringIO do get the PIL image), I wonder if there is not a simpler way to do that, since it seems to be a very natural problem of image visualization. Let's say, something like this:
colored_PIL_image = magic_function(array, cmap)
",https://stackoverflow.com/questions/10965417/how-to-convert-a-numpy-array-to-pil-image-applying-matplotlib-colormap,299,667246.0,3.0,,,2012-06-09 23:48:26,2025-09-03 17:55:18,2024-10-31 14:13:36,,,python;numpy;matplotlib;python-imaging-library;color-mapping,heltonbiker,27775,401828,registered,true,10967471,,CC BY-SA 4.0,2025-09-03 18:45:53,773,691,3,0,0,5,true,false,false,true,true,true,70,12,false,0.004,0.0004,5278,2012,6,23,Saturday,true,true,false,false,false,false,false
21562986,numpy matrix vector multiplication,"When I multiply two numpy arrays of sizes (n x n)*(n x 1), I get a matrix of size (n x n). Following normal matrix multiplication rules, an (n x 1) vector is expected, but I simply cannot find any information about how this is done in Python's Numpy module.
The thing is that I don't want to implement it manually to preserve the speed of the program.
Example code is shown below:
a = np.array([[5, 1, 3], [1, 1, 1], [1, 2, 1]])
b = np.array([1, 2, 3])
print a*b
>>
[[5 2 9]
[1 2 3]
[1 4 3]]
What I want is:
print a*b
>>
[16 6 8]
",https://stackoverflow.com/questions/21562986/numpy-matrix-vector-multiplication,295,845598.0,1.0,,,2014-02-04 20:43:59,2022-10-11 14:30:33,2021-09-05 08:57:34,2014-02-05 15:58:38,Duplicate,python;arrays;numpy;vector;matrix,user3272574,3125,3272574,registered,true,21563036,,,,652,563,3,0,0,5,true,true,false,true,true,true,34,4,false,0.001,0.0003,4673,2014,2,20,Tuesday,false,true,false,false,false,false,false
5954603,Transposing a 1D NumPy array,"I use Python and NumPy and have some problems with ""transpose"":
import numpy as np
a = np.array([5,4])
print(a)
print(a.T)
Invoking a.T is not transposing the array. If a is for example [[],[]] then it transposes correctly, but I need the transpose of [...,...,...].
",https://stackoverflow.com/questions/5954603/transposing-a-1d-numpy-array,294,574339.0,15.0,,,2011-05-10 18:24:30,2022-01-10 10:08:36,2020-12-04 00:31:49,,,python;numpy;transpose,thaking,3705,530877,registered,true,5954747,,CC BY-SA 4.0,2019-07-12 14:41:02,361,271,5,0,0,3,true,false,false,true,true,true,28,5,false,0.026,0.0005,5674,2011,5,18,Tuesday,false,true,false,false,false,false,false
19666626,Replace all elements of NumPy array that are greater than some value,"I have a 2D NumPy array. How do I replace all values in it greater than a threshold T = 255 with a value x = 255? A slow for-loop based method would be:
# arr = arr.copy() # Optionally, do not modify original arr.
for i in range(arr.shape[0]):
for j in range(arr.shape[1]):
if arr[i, j] > 255:
arr[i, j] = x
",https://stackoverflow.com/questions/19666626/replace-all-elements-of-numpy-array-that-are-greater-than-some-value,288,648355.0,8.0,,,2013-10-29 18:42:54,2023-08-19 23:26:35,2023-08-19 23:26:35,,,python;arrays;numpy;replace;conditional-statements,NLi10Me,3332,2909568,registered,true,19666680,,CC BY-SA 4.0,,395,338,3,0,0,5,true,false,false,true,true,true,68,12,false,0.012,0.0004,4771,2013,10,18,Tuesday,false,true,false,false,false,false,false
6200910,Relationship between SciPy and NumPy,"SciPy appears to provide most (but not all [1]) of NumPy's functions in its own namespace. In other words, if there's a function named numpy.foo, there's almost certainly a scipy.foo. Most of the time, the two appear to be exactly the same, oftentimes even pointing to the same function object.
Sometimes, they're different. To give an example that came up recently:
numpy.log10 is a ufunc that returns NaNs for negative arguments;
scipy.log10 returns complex values for negative arguments and doesn't appear to be a ufunc.
The same can be said about log, log2 and logn, but not about log1p [2].
On the other hand, numpy.exp and scipy.exp appear to be different names for the same ufunc. This is also true of scipy.log1p and numpy.log1p.
Another example is numpy.linalg.solve vs scipy.linalg.solve. They're similar, but the latter offers some additional features over the former.
Why the apparent duplication? If this is meant to be a wholesale import of numpy into the scipy namespace, why the subtle differences in behaviour and the missing functions? Is there some overarching logic that would help clear up the confusion?
[1] numpy.min, numpy.max, numpy.abs and a few others have no counterparts in the scipy namespace.
[2] Tested using NumPy 1.5.1 and SciPy 0.9.0rc2.
",https://stackoverflow.com/questions/6200910/relationship-between-scipy-and-numpy,282,63149.0,8.0,,,2011-06-01 12:11:19,2018-08-04 01:39:09,2018-08-04 01:34:08,,,python;numpy;scipy,NPE,504110,367273,registered,true,6201054,,CC BY-SA 4.0,,1711,1283,20,1,0,3,true,false,false,true,true,true,36,5,false,0.127,0.0045,5652,2011,6,12,Wednesday,false,true,false,false,false,false,false
16486252,Is it possible to use argsort in descending order?,"Consider the following code:
avgDists = np.array([1, 8, 6, 9, 4])
ids = avgDists.argsort()[:n]
This gives me indices of the n smallest elements. Is it possible to use this same argsort in descending order to get the indices of n highest elements?
",https://stackoverflow.com/questions/16486252/is-it-possible-to-use-argsort-in-descending-order,279,394880.0,10.0,,,2013-05-10 15:57:47,2022-11-08 09:28:45,2019-08-30 08:22:35,,,python;numpy,shn,5336,995434,registered,true,16486305,,CC BY-SA 4.0,,327,250,4,0,0,2,true,false,false,true,true,true,50,9,true,0.025,0.0007,4943,2013,5,15,Friday,false,true,false,false,false,false,false
10346336,List of lists into numpy array,"How do I convert a simple list of lists into a numpy array? The rows are individual sublists and each row contains the elements in the sublist.
",https://stackoverflow.com/questions/10346336/list-of-lists-into-numpy-array,276,483295.0,9.0,,,2012-04-27 07:15:07,2023-01-11 17:28:31,2016-03-14 10:29:26,,,python;list;numpy,Richa Sachdev,3107,1304336,registered,true,,,CC BY-SA 3.0,,151,144,0,0,0,3,false,false,false,true,true,true,30,6,false,0.019,0.0006,5321,2012,4,7,Friday,false,true,false,false,false,false,false
20518632,ImportError: numpy.core.multiarray failed to import,"I'm trying to run this program
import cv2
import time
cv.NamedWindow("camera", 1)
capture = cv.CaptureFromCAM(0)
while True:
img = cv.QueryFrame(capture)
cv.ShowImage("camera", img)
if cv.WaitKey(10) == 27:
break
cv.DestroyAllWindows()
But I'm having a problem with numpy, I'm using pyschopy along with opencv.
The problem I keep getting is this error report:
RuntimeError: module compiled against API version 7 but this version of numpy is 6
Traceback (most recent call last):
File "C:\Users\John\Documents\EyeTracking\Programs\GetImage.py", line 1, in
import cv2
ImportError: numpy.core.multiarray failed to import
I have numpy-1.6.1-py2.7 in the psychopy folder, I'm just confused as to what is wrong?
",https://stackoverflow.com/questions/20518632/importerror-numpy-core-multiarray-failed-to-import,270,843903.0,35.0,,,2013-12-11 12:03:02,2023-07-27 21:23:55,2022-09-02 09:39:28,,,python;python-2.7;numpy;opencv,user3090952,,,does_not_exist,true,,,CC BY-SA 4.0,2019-08-24 05:29:55,885,763,2,0,0,4,false,false,false,true,false,true,51,5,false,0.041,0.0003,4728,2013,12,12,Wednesday,false,true,false,false,false,false,false
8364674,How to count the number of true elements in a NumPy bool array,"I have a NumPy array 'boolarr' of boolean type. I want to count the number of elements whose values are True. Is there a NumPy or Python routine dedicated for this task? Or, do I need to iterate over the elements in my script?
",https://stackoverflow.com/questions/8364674/how-to-count-the-number-of-true-elements-in-a-numpy-bool-array,267,380469.0,6.0,,,2011-12-03 01:13:26,2022-03-30 14:44:22,2017-09-19 06:44:39,,,python;arrays;numpy;count;boolean,norio,3962,883431,registered,true,8364723,,CC BY-SA 3.0,,247,227,1,0,0,5,true,false,false,true,true,true,62,13,false,0.016,0.0007,5467,2011,12,1,Saturday,true,true,false,false,false,false,false
20054243,np.mean() vs np.average() in Python NumPy?,"I notice that
In [30]: np.mean([1, 2, 3])
Out[30]: 2.0
In [31]: np.average([1, 2, 3])
Out[31]: 2.0
However, there should be some differences, since after all they are two different functions.
What are the differences between them?
",https://stackoverflow.com/questions/20054243/np-mean-vs-np-average-in-python-numpy,267,246515.0,5.0,,,2013-11-18 17:43:30,2020-05-19 17:28:38,2019-04-27 22:44:02,,,python;numpy;statistics;average;mean,Sibbs Gambling,21145,2106753,registered,true,20054396,,CC BY-SA 4.0,2019-07-12 14:41:15,299,237,1,0,0,5,true,false,false,true,true,true,42,6,true,0.02,0.0011,4751,2013,11,17,Monday,false,true,false,false,false,false,false
16970982,Find unique rows in numpy.array,"I need to find unique rows in a numpy.array.
For example:
>>> a # I have
array([[1, 1, 1, 0, 0, 0],
[0, 1, 1, 1, 0, 0],
[0, 1, 1, 1, 0, 0],
[1, 1, 1, 0, 0, 0],
[1, 1, 1, 1, 1, 0]])
>>> new_a # I want to get to
array([[1, 1, 1, 0, 0, 0],
[0, 1, 1, 1, 0, 0],
[1, 1, 1, 1, 1, 0]])
I know that i can create a set and loop over the array, but I am looking for an efficient pure numpy solution. I believe that there is a way to set data type to void and then I could just use numpy.unique, but I couldn't figure out how to make it work.
",https://stackoverflow.com/questions/16970982/find-unique-rows-in-numpy-array,262,191433.0,20.0,,,2013-06-06 19:51:36,2023-08-07 13:56:30,2013-08-12 22:14:36,,,python;arrays;numpy;unique,Akavall,87022,1078084,registered,true,44069948,,CC BY-SA 3.0,2019-07-05 09:54:17,679,595,4,0,0,4,true,false,false,true,true,true,31,5,false,0.104,0.0014,4916,2013,6,19,Thursday,false,true,false,false,false,false,false
9777783,Suppress Scientific Notation in Numpy When Creating Array From Nested List,"I have a nested Python list that looks like the following:
my_list = [[3.74, 5162, 13683628846.64, 12783387559.86, 1.81],
[9.55, 116, 189688622.37, 260332262.0, 1.97],
[2.2, 768, 6004865.13, 5759960.98, 1.21],
[3.74, 4062, 3263822121.39, 3066869087.9, 1.93],
[1.91, 474, 44555062.72, 44555062.72, 0.41],
[5.8, 5006, 8254968918.1, 7446788272.74, 3.25],
[4.5, 7887, 30078971595.46, 27814989471.31, 2.18],
[7.03, 116, 66252511.46, 81109291.0, 1.56],
[6.52, 116, 47674230.76, 57686991.0, 1.43],
[1.85, 623, 3002631.96, 2899484.08, 0.64],
[13.76, 1227, 1737874137.5, 1446511574.32, 4.32],
[13.76, 1227, 1737874137.5, 1446511574.32, 4.32]]
I then import Numpy, and set print options to (suppress=True). When I create an array:
my_array = numpy.array(my_list)
I can't for the life of me suppress scientific notation:
[[ 3.74000000e+00 5.16200000e+03 1.36836288e+10 1.27833876e+10
1.81000000e+00]
[ 9.55000000e+00 1.16000000e+02 1.89688622e+08 2.60332262e+08
1.97000000e+00]
[ 2.20000000e+00 7.68000000e+02 6.00486513e+06 5.75996098e+06
1.21000000e+00]
[ 3.74000000e+00 4.06200000e+03 3.26382212e+09 3.06686909e+09
1.93000000e+00]
[ 1.91000000e+00 4.74000000e+02 4.45550627e+07 4.45550627e+07
4.10000000e-01]
[ 5.80000000e+00 5.00600000e+03 8.25496892e+09 7.44678827e+09
3.25000000e+00]
[ 4.50000000e+00 7.88700000e+03 3.00789716e+10 2.78149895e+10
2.18000000e+00]
[ 7.03000000e+00 1.16000000e+02 6.62525115e+07 8.11092910e+07
1.56000000e+00]
[ 6.52000000e+00 1.16000000e+02 4.76742308e+07 5.76869910e+07
1.43000000e+00]
[ 1.85000000e+00 6.23000000e+02 3.00263196e+06 2.89948408e+06
6.40000000e-01]
[ 1.37600000e+01 1.22700000e+03 1.73787414e+09 1.44651157e+09
4.32000000e+00]
[ 1.37600000e+01 1.22700000e+03 1.73787414e+09 1.44651157e+09
4.32000000e+00]]
If I create a simple numpy array directly:
new_array = numpy.array([1.5, 4.65, 7.845])
I have no problem and it prints as follows:
[ 1.5 4.65 7.845]
Does anyone know what my problem is?
",https://stackoverflow.com/questions/9777783/suppress-scientific-notation-in-numpy-when-creating-array-from-nested-list,256,279137.0,4.0,,,2012-03-19 20:54:15,2023-12-20 20:27:47,2020-04-29 04:41:13,,,python;numpy;number-formatting;scientific-notation,donopj2,4163,1432934,registered,true,10854323,,CC BY-SA 4.0,2019-07-12 14:43:08,2283,2108,6,0,0,4,true,false,false,true,true,true,74,11,false,0.014,0.0009,5360,2012,3,20,Monday,false,true,false,false,false,false,false
3881453,Numpy - add row to array,"How does one add rows to a numpy array?
I have an array A:
A = array([[0, 1, 2], [0, 2, 0]])
I wish to add rows to this array from another array X if the first element of each row in X meets a specific condition.
Numpy arrays do not have a method 'append' like that of lists, or so it seems.
If A and X were lists I would merely do:
for i in X:
if i[0] < 3:
A.append(i)
Is there a numpythonic way to do the equivalent?
Thanks,
S ;-)
",https://stackoverflow.com/questions/3881453/numpy-add-row-to-array,256,823892.0,10.0,,,2010-10-07 12:09:13,2021-12-04 08:02:45,2010-10-07 12:21:14,,,python;arrays;numpy;rows,Darren J. Fitzpatrick,7469,233816,registered,true,3881487,,CC BY-SA 2.5,,564,458,2,0,0,4,true,false,false,true,true,true,24,6,false,0.012,0.0003,5889,2010,10,12,Thursday,false,true,false,false,false,false,false
9171158,How do you get the magnitude of a vector in Numpy?,"In keeping with the ""There's only one obvious way to do it"", how do you get the magnitude of a vector (1D array) in Numpy?
def mag(x):
return math.sqrt(sum(i**2 for i in x))
The above works, but I cannot believe that I must specify such a trivial and core function myself.
",https://stackoverflow.com/questions/9171158/how-do-you-get-the-magnitude-of-a-vector-in-numpy,256,614381.0,8.0,,,2012-02-07 04:48:50,2022-09-14 12:59:38,2016-10-10 20:26:30,,,python;numpy,Nick T,27035,194586,registered,true,9171196,,CC BY-SA 3.0,,328,281,1,0,0,2,true,false,false,true,true,true,50,11,true,0.013,0.0004,5401,2012,2,4,Tuesday,false,true,false,false,false,false,false
18757742,How to flatten only some dimensions of a numpy array,"Is there a quick way to ""sub-flatten"" or flatten only some of the first dimensions in a numpy array?
For example, given a numpy array of dimensions (50,100,25), the resultant dimensions would be (5000,25)
",https://stackoverflow.com/questions/18757742/how-to-flatten-only-some-dimensions-of-a-numpy-array,256,264729.0,6.0,,,2013-09-12 07:12:21,2026-04-15 15:17:11,2017-08-31 23:35:59,,,python;numpy;flatten,IssamLaradji,6915,1248073,registered,true,18758049,,CC BY-SA 3.0,,246,206,2,0,0,3,true,false,false,true,true,true,52,10,false,0.023,0.001,4818,2013,9,7,Thursday,false,true,false,false,false,false,false
14313510,How can I calculate a rolling / moving average using Python + NumPy / SciPy?,"There doesn’t seem to be any function in NumPy or SciPy that simply calculate the moving average, leading to convoluted solutions.
My question is twofold:
- What's the easiest way to (correctly) implement a moving average with NumPy?
- Since this seems nontrivial and error-prone, is there a good reason not to have the batteries included in this case?
",https://stackoverflow.com/questions/14313510/how-can-i-calculate-a-rolling-moving-average-using-python-numpy-scipy,255,484174.0,22.0,,,2013-01-14 04:59:12,2026-03-18 09:42:56,2025-09-13 14:03:52,,,python;numpy;time-series;moving-average;rolling-computation,loopbackbee,23732,1595865,registered,true,54628145,,CC BY-SA 4.0,2021-08-06 19:18:45,607,351,0,2,0,5,true,false,false,true,true,true,76,15,true,0.045,0.0005,5059,2013,1,4,Monday,false,true,false,false,false,false,false
50916422,Python - TypeError: Object of type 'int64' is not JSON serializable,"I have a data frame that stores store name and daily sales count. I am trying to insert this to Salesforce using the Python script below.
However, I get the following error:
TypeError: Object of type 'int64' is not JSON serializable
Below, there is the view of the data frame.
Storename,Count
Store A,10
Store B,12
Store C,5
I use the following code to insert it to Salesforce.
update_list = []
for i in range(len(store)):
update_data = {
'name': store['entity_name'].iloc[i],
'count__c': store['count'].iloc[i]
}
update_list.append(update_data)
sf_data_cursor = sf_datapull.salesforce_login()
sf_data_cursor.bulk.Account.update(update_list)
I get the error when the last line above gets executed.
How do I fix this?
",https://stackoverflow.com/questions/50916422/python-typeerror-object-of-type-int64-is-not-json-serializable,253,374284.0,15.0,,,2018-06-18 19:39:16,2024-09-04 07:06:37,2021-07-06 22:55:12,,,python;numpy,dark horse,3817,9739252,registered,true,,,CC BY-SA 4.0,,864,750,3,0,0,2,false,false,false,true,true,true,75,11,false,0.04,0.0007,3078,2018,6,19,Monday,false,true,false,false,false,false,false
13635032,What is the inverse function of zip in python?,"I've used the zip function from the Numpy library to sort tuples and now I have a list containing all the tuples. I had since modified that list and now I would like to restore the tuples so I can use my data. How can I do this?
",https://stackoverflow.com/questions/13635032/what-is-the-inverse-function-of-zip-in-python,252,108468.0,1.0,,,2012-11-29 21:26:25,2023-01-14 08:49:06,2023-01-14 08:49:06,2023-01-14 08:48:27,Duplicate,python;list;numpy;tuples,user17151,2795,1850751,registered,true,13635074,,,,249,229,1,0,0,4,true,true,false,true,true,true,46,9,true,0.009,0.0023,5105,2012,11,21,Thursday,false,true,false,false,false,false,false
9775297,Concatenate a NumPy array to another NumPy array,"I have a numpy_array. Something like [ a b c ].
And then I want to concatenate it with another NumPy array (just like we create a list of lists). How do we create a NumPy array containing NumPy arrays?
I tried to do the following without any luck
>>> M = np.array([])
>>> M
array([], dtype=float64)
>>> M.append(a,axis=0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'numpy.ndarray' object has no attribute 'append'
>>> a
array([1, 2, 3])
",https://stackoverflow.com/questions/9775297/concatenate-a-numpy-array-to-another-numpy-array,252,925200.0,11.0,,,2012-03-19 17:55:24,2021-10-18 09:11:22,2020-10-28 01:04:13,,,python;numpy,frazman,33581,902885,registered,true,9775378,,CC BY-SA 4.0,,599,541,2,0,0,2,true,false,false,true,true,true,48,8,false,0.012,0.0003,5360,2012,3,17,Monday,false,true,false,false,false,false,false
3433486,How to do exponential and logarithmic curve fitting in Python? I found only polynomial fitting,"I have a set of data and I want to compare which line describes it best (polynomials of different orders, exponential or logarithmic).
I use Python and Numpy and for polynomial fitting there is a function polyfit(). But I found no such functions for exponential and logarithmic fitting.
Are there any? Or how to solve it otherwise?
",https://stackoverflow.com/questions/3433486/how-to-do-exponential-and-logarithmic-curve-fitting-in-python-i-found-only-poly,251,529082.0,8.0,,,2010-08-08 07:36:16,2024-10-03 14:25:36,2013-03-12 19:17:34,,,python;numpy;scipy;curve-fitting;linear-regression,Tomas Novotny,8487,377313,registered,true,3433503,,CC BY-SA 3.0,,369,335,1,0,0,5,true,false,false,true,true,true,94,15,false,0.015,0.0005,5949,2010,8,7,Sunday,true,true,false,false,false,false,false
15933741,How do I catch a numpy warning like it's an exception (not just for testing)?,"I have to make a Lagrange polynomial in Python for a project I'm doing. I'm doing a barycentric style one to avoid using an explicit for-loop as opposed to a Newton's divided difference style one. The problem I have is that I need to catch a division by zero, but Python (or maybe numpy) just makes it a warning instead of a normal exception.
So, what I need to know how to do is to catch this warning as if it were an exception. The related questions to this I found on this site were answered not in the way I needed. Here's my code:
import numpy as np
import matplotlib.pyplot as plt
import warnings
class Lagrange:
def __init__(self, xPts, yPts):
self.xPts = np.array(xPts)
self.yPts = np.array(yPts)
self.degree = len(xPts)-1
self.weights = np.array([np.product([x_j - x_i for x_j in xPts if x_j != x_i]) for x_i in xPts])
def __call__(self, x):
warnings.filterwarnings(""error"")
try:
bigNumerator = np.product(x - self.xPts)
numerators = np.array([bigNumerator/(x - x_j) for x_j in self.xPts])
return sum(numerators/self.weights*self.yPts)
except Exception, e: # Catch division by 0. Only possible in 'numerators' array
return yPts[np.where(xPts == x)[0][0]]
L = Lagrange([-1,0,1],[1,0,1]) # Creates quadratic poly L(x) = x^2
L(1) # This should catch an error, then return 1.
When this code is executed, the output I get is:
Warning: divide by zero encountered in int_scalars
That's the warning I want to catch. It should occur inside the list comprehension.
",https://stackoverflow.com/questions/15933741/how-do-i-catch-a-numpy-warning-like-its-an-exception-not-just-for-testing,251,217269.0,6.0,,,2013-04-10 18:36:21,2023-12-18 22:26:21,2015-11-13 21:03:59,,,python;exception;numpy;warnings;divide-by-zero,John K.,2613,2267416,registered,true,15934081,,CC BY-SA 3.0,,1666,1590,2,0,0,5,true,false,false,true,true,true,81,15,true,0.028,0.0012,4973,2013,4,18,Wednesday,false,true,false,false,false,false,false
77364550,AttributeError: module 'pkgutil' has no attribute 'ImpImporter'. Did you mean: 'zipimporter'?,"Earlier I installed some packages like Matplotlib, NumPy, pip (version 23.3.1), wheel (version 0.41.2), etc., and did some programming with those. I used the command C:\Users\UserName>pip list to find the list of packages that I have installed, and I am using Python 3.12.0 (by employing code C:\Users\UserName>py -V).
I need to use pyspedas to analyse some data. I am following the instruction that that I received from site to install the package, with a variation (I am not sure whether it matters or not: I am using py, instead of python). The commands that I use, in the order, are:
py -m venv pyspedas
.\pyspedas\Scripts\activate
pip install pyspedas
After the last step, I am getting the following output:
Collecting pyspedas
Using cached pyspedas-1.4.47-py3-none-any.whl.metadata (14 kB)
Collecting numpy>=1.19.5 (from pyspedas)
Using cached numpy-1.26.1-cp312-cp312-win_amd64.whl.metadata (61 kB)
Collecting requests (from pyspedas)
Using cached requests-2.31.0-py3-none-any.whl.metadata (4.6 kB)
Collecting geopack>=1.0.10 (from pyspedas)
Using cached geopack-1.0.10-py3-none-any.whl (114 kB)
Collecting cdflib<1.0.0 (from pyspedas)
Using cached cdflib-0.4.9-py3-none-any.whl (72 kB)
Collecting cdasws>=1.7.24 (from pyspedas)
Using cached cdasws-1.7.43.tar.gz (21 kB)
Installing build dependencies ... done
Getting requirements to build wheel ... done
Preparing metadata (pyproject.toml) ... done
Collecting netCDF4>=1.6.2 (from pyspedas)
Using cached netCDF4-1.6.5-cp312-cp312-win_amd64.whl.metadata (1.8 kB)
Collecting pywavelets (from pyspedas)
Using cached PyWavelets-1.4.1.tar.gz (4.6 MB)
Installing build dependencies ... done
Getting requirements to build wheel ... error
error: subprocess-exited-with-error
× Getting requirements to build wheel did not run successfully.
│ exit code: 1
╰─> [33 lines of output]
Traceback (most recent call last):
File "C:\Users\UserName\pyspedas\Lib\site-packages\pip\_vendor\pyproject_hooks\_in_process\_in_process.py", line 353, in <module>
main()
File "C:\Users\UserName\pyspedas\Lib\site-packages\pip\_vendor\pyproject_hooks\_in_process\_in_process.py", line 335, in main
json_out['return_val'] = hook(**hook_input['kwargs'])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\UserName\pyspedas\Lib\site-packages\pip\_vendor\pyproject_hooks\_in_process\_in_process.py", line 112, in get_requires_for_build_wheel
backend = _build_backend()
^^^^^^^^^^^^^^^^
File "C:\Users\UserName\pyspedas\Lib\site-packages\pip\_vendor\pyproject_hooks\_in_process\_in_process.py", line 77, in _build_backend
obj = import_module(mod_path)
^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\UserName\AppData\Local\Programs\Python\Python312\Lib\importlib\__init__.py", line 90, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<frozen importlib._bootstrap>", line 1381, in _gcd_import
File "<frozen importlib._bootstrap>", line 1354, in _find_and_load
File "<frozen importlib._bootstrap>", line 1304, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed
File "<frozen importlib._bootstrap>", line 1381, in _gcd_import
File "<frozen importlib._bootstrap>", line 1354, in _find_and_load
File "<frozen importlib._bootstrap>", line 1325, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 929, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 994, in exec_module
File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed
File "C:\Users\UserName\AppData\Local\Temp\pip-build-env-_lgbq70y\overlay\Lib\site-packages\setuptools\__init__.py", line 16, in <module>
import setuptools.version
File "C:\Users\UserName\AppData\Local\Temp\pip-build-env-_lgbq70y\overlay\Lib\site-packages\setuptools\version.py", line 1, in <module>
import pkg_resources
File "C:\Users\UserName\AppData\Local\Temp\pip-build-env-_lgbq70y\overlay\Lib\site-packages\pkg_resources\__init__.py", line 2191, in <module>
register_finder(pkgutil.ImpImporter, find_on_path)
^^^^^^^^^^^^^^^^^^^
AttributeError: module 'pkgutil' has no attribute 'ImpImporter'. Did you mean: 'zipimporter'?
[end of output]
note: This error originates from a subprocess, and is likely not a problem with pip.
error: subprocess-exited-with-error
× Getting requirements to build wheel did not run successfully.
│ exit code: 1
╰─> See above for output.
note: This error originates from a subprocess, and is likely not a problem with pip.
After little bit of googling, I came to know that this issues was reported at multiple places, but none for this package. I did install wheel in the new environment as mentioned in the answer here, but the problem still persists.
Instead of setting up a virtual environment, I simply executed the command py -m pip install pyspedas. But I am still getting the error.
What I could gather is that the program has an issue with
Collecting pywavelets (from pyspedas)
Using cached PyWavelets-1.4.1.tar.gz (4.6 MB)
Installing build dependencies ... done
I am using IDLE in Windows 11.
",https://stackoverflow.com/questions/77364550/attributeerror-module-pkgutil-has-no-attribute-impimporter-did-you-mean,250,450114.0,9.0,,,2023-10-26 06:22:24,2025-07-20 02:31:15,2024-09-04 00:40:25,,,python;python-3.x;numpy;pip,Sreeraj,2785,6323020,registered,true,77364602,,CC BY-SA 4.0,2024-04-02 09:51:04,6392,5759,8,5,0,4,true,false,false,true,true,true,117,11,true,0.02,0.0006,1122,2023,10,6,Thursday,false,true,false,false,false,false,false
1550130,"Cloning" row or column vectors,"Sometimes it is useful to "clone" a row or column vector to a matrix. By cloning I mean converting a row vector such as
[1, 2, 3]
Into a matrix
[[1, 2, 3],
[1, 2, 3],
[1, 2, 3]]
or a column vector such as
[[1],
[2],
[3]]
into
[[1, 1, 1]
[2, 2, 2]
[3, 3, 3]]
In MATLAB or octave this is done pretty easily:
x = [1, 2, 3]
a = ones(3, 1) * x
a =
1 2 3
1 2 3
1 2 3
b = (x') * ones(1, 3)
b =
1 1 1
2 2 2
3 3 3
I want to repeat this in numpy, but unsuccessfully
In [14]: x = array([1, 2, 3])
In [14]: ones((3, 1)) * x
Out[14]:
array([[ 1., 2., 3.],
[ 1., 2., 3.],
[ 1., 2., 3.]])
# so far so good
In [16]: x.transpose() * ones((1, 3))
Out[16]: array([[ 1., 2., 3.]])
# DAMN
# I end up with
In [17]: (ones((3, 1)) * x).transpose()
Out[17]:
array([[ 1., 1., 1.],
[ 2., 2., 2.],
[ 3., 3., 3.]])
Why wasn't the first method (In [16]) working? Is there a way to achieve this task in python in a more elegant way?
",https://stackoverflow.com/questions/1550130/cloning-row-or-column-vectors,246,223775.0,13.0,,,2009-10-11 07:54:05,2025-06-15 04:56:17,2021-01-28 22:17:06,,,python;numpy;linear-algebra,Boris Gorelik,32215,17523,registered,true,1550137,,CC BY-SA 4.0,,1233,1027,7,0,0,3,true,false,false,true,true,true,41,5,false,0.058,0.0011,6250,2009,10,7,Sunday,true,true,false,false,false,false,false
16243955,Numpy first occurrence of value greater than existing value,"I have a 1D array in numpy and I want to find the position of the index where a value exceeds the value in numpy array.
E.g.
aa = range(-10,10)
Find position in aa where, the value 5 gets exceeded.
",https://stackoverflow.com/questions/16243955/numpy-first-occurrence-of-value-greater-than-existing-value,243,317689.0,8.0,,,2013-04-26 19:35:50,2026-09-09 14:10:29,2017-04-25 17:03:14,,,python;numpy,user308827,22551,308827,registered,true,16244044,,CC BY-SA 3.0,,273,202,3,0,0,2,true,false,false,true,true,true,59,9,false,0.025,0.0008,4957,2013,4,19,Friday,false,true,false,false,false,false,false
8386675,Extracting specific columns in numpy array,"This is an easy question but say I have an MxN matrix. All I want to do is extract specific columns and store them in another numpy array but I get invalid syntax errors.
Here is the code:
extractedData = data[[:,1],[:,9]].
It seems like the above line should suffice but I guess not. I looked around but couldn't find anything syntax wise regarding this specific scenario.
",https://stackoverflow.com/questions/8386675/extracting-specific-columns-in-numpy-array,243,517708.0,11.0,,,2011-12-05 14:20:47,2023-04-18 12:44:47,2011-12-05 14:24:20,,,python;syntax;numpy,Aladdin,2519,948872,registered,true,8386737,,CC BY-SA 3.0,2019-07-12 14:43:00,416,378,1,0,0,3,true,false,false,true,true,true,42,6,false,0.021,0.0005,5465,2011,12,14,Monday,false,true,false,false,false,false,false
14262654,Numpy: Get random set of rows from 2D array,"I have a very large 2D array which looks something like this:
a=
[[a1, b1, c1],
[a2, b2, c2],
...,
[an, bn, cn]]
Using numpy, is there an easy way to get a new 2D array with, e.g., 2 random rows from the initial array a (without replacement)?
e.g.
b=
[[a4, b4, c4],
[a99, b99, c99]]
",https://stackoverflow.com/questions/14262654/numpy-get-random-set-of-rows-from-2d-array,240,303535.0,10.0,,,2013-01-10 16:30:47,2023-01-17 11:11:35,2019-06-13 19:40:59,,,python;numpy,gha,3689,501275,registered,true,14262743,,CC BY-SA 4.0,,377,295,3,0,0,2,true,false,false,true,true,true,43,9,false,0.033,0.0008,5063,2013,1,16,Thursday,false,true,false,false,false,false,false
22392497,How to add a new row to an empty numpy array,"Using standard Python arrays, I can do the following:
arr = []
arr.append([1,2,3])
arr.append([4,5,6])
# arr is now [[1,2,3],[4,5,6]]
However, I cannot do the same thing in numpy. For example:
arr = np.array([])
arr = np.append(arr, np.array([1,2,3]))
arr = np.append(arr, np.array([4,5,6]))
# arr is now [1,2,3,4,5,6]
I also looked into vstack, but when I use vstack on an empty array, I get:
ValueError: all the input array dimensions except for the concatenation axis must match exactly
So how do I do append a new row to an empty array in numpy?
",https://stackoverflow.com/questions/22392497/how-to-add-a-new-row-to-an-empty-numpy-array,239,469274.0,7.0,,,2014-03-13 22:39:26,2021-04-09 19:24:07,2014-03-14 14:21:51,,,python;numpy;scipy,Tony Stark,3453,522795,registered,true,22394181,,CC BY-SA 3.0,,685,559,5,0,0,3,true,false,false,true,true,true,44,11,false,0.015,0.0005,4636,2014,3,22,Thursday,false,true,false,false,false,false,false
11784329,Python memory usage of numpy arrays,"I'm using python to analyse some large files and I'm running into memory issues, so I've been using sys.getsizeof() to try and keep track of the usage, but it's behaviour with numpy arrays is bizarre. Here's an example involving a map of albedos that I'm having to open:
>>> import numpy as np
>>> import struct
>>> from sys import getsizeof
>>> f = open('Albedo_map.assoc', 'rb')
>>> getsizeof(f)
144
>>> albedo = struct.unpack('%df' % (7200*3600), f.read(7200*3600*4))
>>> getsizeof(albedo)
207360056
>>> albedo = np.array(albedo).reshape(3600,7200)
>>> getsizeof(albedo)
80
Well the data's still there, but the size of the object, a 3600x7200 pixel map, has gone from ~200 Mb to 80 bytes. I'd like to hope that my memory issues are over and just convert everything to numpy arrays, but I feel that this behaviour, if true, would in some way violate some law of information theory or thermodynamics, or something, so I'm inclined to believe that getsizeof() doesn't work with numpy arrays. Any ideas?
",https://stackoverflow.com/questions/11784329/python-memory-usage-of-numpy-arrays,239,209361.0,4.0,,,2012-08-02 19:19:22,2023-07-19 22:18:40,,,,python;numpy;sys,EddyTheB,3250,1257599,registered,true,11784399,,CC BY-SA 3.0,,1125,1087,1,0,0,3,true,false,false,true,true,false,35,6,false,0.019,0.0011,5224,2012,8,19,Thursday,false,true,false,false,false,false,false
7465445,How to install python modules without root access?,"I'm taking some university classes and have been given an 'instructional account', which is a school account I can ssh into to do work. I want to run my computationally intensive Numpy, matplotlib, scipy code on that machine, but I cannot install these modules because I am not a system administrator.
How can I do the installation?
",https://stackoverflow.com/questions/7465445/how-to-install-python-modules-without-root-access,237,274940.0,10.0,,,2011-09-19 00:41:50,2025-03-27 14:20:00,2011-09-19 00:44:16,,,python;numpy;pip,Rishi,3596,509895,registered,true,7465532,,CC BY-SA 3.0,2025-04-28 17:38:45,348,334,0,0,0,3,true,false,false,true,true,true,50,8,true,0.036,0.0009,5542,2011,9,0,Monday,false,true,false,false,false,false,false
16343752,Numpy where function multiple conditions,"I have an array of distances called dists. I want to select dists which are within a range.
dists[(np.where(dists >= r)) and (np.where(dists <= r + dr))]
However, this selects only for the condition
(np.where(dists <= r + dr))
If I do the commands sequentially by using a temporary variable it works fine. Why does the above code not work, and how do I get it to work?
",https://stackoverflow.com/questions/16343752/numpy-where-function-multiple-conditions,235,652394.0,9.0,,,2013-05-02 17:03:19,2023-07-28 20:02:25,2022-04-19 12:53:39,,,python;numpy,user1654183,4665,1654183,registered,true,16343791,,CC BY-SA 4.0,2024-02-02 18:49:20,477,382,4,0,0,2,true,false,false,true,true,true,40,5,false,0.014,0.0004,4951,2013,5,17,Thursday,false,true,false,false,false,false,false
1735025,How to normalize a NumPy array to within a certain range?,"After doing some processing on an audio or image array, it needs to be normalized within a range before it can be written back to a file. This can be done like so:
# Normalize audio channels to between -1.0 and +1.0
audio[:,0] = audio[:,0]/abs(audio[:,0]).max()
audio[:,1] = audio[:,1]/abs(audio[:,1]).max()
# Normalize image to between 0 and 255
image = image/(image.max()/255.0)
Is there a less verbose, convenience function way to do this? matplotlib.colors.Normalize() doesn't seem to be related.
",https://stackoverflow.com/questions/1735025/how-to-normalize-a-numpy-array-to-within-a-certain-range,232,514298.0,8.0,,,2009-11-14 17:52:38,2023-06-03 08:36:01,2013-08-20 04:48:07,,,python;arrays;numpy;scipy;convenience-methods,endolith,27123,125507,registered,true,1735122,,CC BY-SA 3.0,,557,506,2,0,0,5,true,false,false,true,true,true,57,11,true,0.016,0.0005,6216,2009,11,17,Saturday,true,true,false,false,false,false,false
35673895,Type hinting / annotation (PEP 484) for numpy.ndarray,"Has anyone implemented type hinting for the specific numpy.ndarray class?
Right now, I'm using typing.Any, but it would be nice to have something more specific.
For instance if the NumPy people added a type alias for their array_like object class. Better yet, implement support at the dtype level, so that other objects would be supported, as well as ufunc.
",https://stackoverflow.com/questions/35673895/type-hinting-annotation-pep-484-for-numpy-ndarray,232,236061.0,7.0,,,2016-02-27 18:44:55,2025-07-17 06:12:38,2024-06-20 06:55:24,,,python;numpy;python-typing,Inon,2506,3368225,registered,true,35688036,,CC BY-SA 4.0,,997,358,2,6,0,3,true,false,false,true,true,true,53,8,false,0.03,0.001,3920,2016,2,18,Saturday,true,true,false,false,false,false,false
3949226,Calculating Pearson correlation and significance in Python,"I am looking for a function that takes as input two lists, and returns the Pearson correlation, and the significance of the correlation.
",https://stackoverflow.com/questions/3949226/calculating-pearson-correlation-and-significance-in-python,229,467607.0,16.0,,,2010-10-16 14:15:27,2023-06-26 12:56:23,2014-11-22 07:18:38,,,python;numpy;statistics;scipy,ariel,2299,477956,unregistered,true,,,CC BY-SA 3.0,2019-07-05 09:54:37,251,137,0,1,0,4,false,false,false,true,true,true,58,7,false,0.034,0.0005,5880,2010,10,14,Saturday,true,true,false,false,false,false,false
57507832,Unable to allocate array with shape and data type,"I'm facing an issue with allocating huge arrays in numpy on Ubuntu 18 while not facing the same issue on MacOS.
I am trying to allocate memory for a numpy array with shape (156816, 36, 53806)
with
np.zeros((156816, 36, 53806), dtype='uint8')
and while I'm getting an error on Ubuntu OS
>>> import numpy as np
>>> np.zeros((156816, 36, 53806), dtype='uint8')
Traceback (most recent call last):
File ""<stdin>"", line 1, in <module>
numpy.core._exceptions.MemoryError: Unable to allocate array with shape (156816, 36, 53806) and data type uint8
I'm not getting it on MacOS:
>>> import numpy as np
>>> np.zeros((156816, 36, 53806), dtype='uint8')
array([[[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
...,
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0]],
[[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
...,
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0]],
[[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
...,
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0]],
...,
[[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
...,
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0]],
[[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
...,
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0]],
[[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
...,
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0]]], dtype=uint8)
I've read somewhere that np.zeros shouldn't be really allocating the whole memory needed for the array, but only for the non-zero elements. Even though the Ubuntu machine has 64gb of memory, while my MacBook Pro has only 16gb.
versions:
Ubuntu
os -> ubuntu mate 18
python -> 3.6.8
numpy -> 1.17.0
mac
os -> 10.14.6
python -> 3.6.4
numpy -> 1.17.0
PS: also failed on Google Colab
",https://stackoverflow.com/questions/57507832/unable-to-allocate-array-with-shape-and-data-type,227,1005409.0,8.0,,,2019-08-15 09:48:35,2025-02-05 19:18:47,2024-03-05 16:20:55,,,python;numpy,Martin Brisiak,4111,5123537,registered,true,57511555,,CC BY-SA 4.0,2025-02-07 09:58:36,2581,2410,6,0,0,2,true,false,false,true,true,true,49,9,false,0.008,0.0002,2655,2019,8,9,Thursday,false,true,false,false,false,false,false
13730468,From ND to 1D arrays,"Say I have an array a:
a = np.array([[1,2,3], [4,5,6]])
array([[1, 2, 3],
[4, 5, 6]])
I would like to convert it to a 1D array (i.e. a column vector):
b = np.reshape(a, (1,np.product(a.shape)))
but this returns
array([[1, 2, 3, 4, 5, 6]])
which is not the same as:
array([1, 2, 3, 4, 5, 6])
I can take the first element of this array to manually convert it to a 1D array:
b = np.reshape(a, (1,np.product(a.shape)))[0]
but this requires me to know how many dimensions the original array has (and concatenate [0]'s when working with higher dimensions)
Is there a dimensions-independent way of getting a column/row vector from an arbitrary ndarray?
",https://stackoverflow.com/questions/13730468/from-nd-to-1d-arrays,222,471612.0,7.0,,,2012-12-05 18:59:13,2022-10-25 03:53:43,2016-07-18 17:10:30,,,python;numpy,Amelio Vazquez-Reina,97532,283296,registered,true,13730506,,CC BY-SA 3.0,2019-07-06 00:28:31,852,670,6,0,0,2,true,false,false,true,true,true,20,5,false,0.015,0.0005,5099,2012,12,18,Wednesday,false,true,false,false,false,false,false
33569668,numpy max vs amax vs maximum,"numpy has three different functions which seem like they can be used for the same things --- except that numpy.maximum can only be used element-wise, while numpy.max and numpy.amax can be used on particular axes, or all elements. Why is there more than just numpy.max? Is there some subtlety to this in performance?
(Similarly for min vs. amin vs. minimum)
",https://stackoverflow.com/questions/33569668/numpy-max-vs-amax-vs-maximum,221,341559.0,4.0,,,2015-11-06 15:02:46,2020-04-22 05:02:09,2017-01-10 21:20:34,,,python;numpy;math;max,DilithiumMatrix,18847,230468,registered,true,33569857,,CC BY-SA 3.0,,474,360,7,0,0,4,true,false,false,true,true,true,28,6,false,0.012,0.0006,4033,2015,11,15,Friday,false,true,false,false,false,false,false
32171917,"How to copy a 2D array into a 3rd dimension, N times?","I'd like to copy a numpy 2D array into a third dimension. For example, given the 2D numpy array:
import numpy as np
arr = np.array([[1, 2], [1, 2]])
# arr.shape = (2, 2)
convert it into a 3D matrix with N such copies in a new dimension. Acting on arr with N=3, the output should be:
new_arr[:,:,0]
# array([[1, 2], [1, 2]])
new_arr[:,:,1]
# array([[1, 2], [1, 2]])
new_arr[:,:,2]
# array([[1, 2], [1, 2]])
# new_arr.shape = (2, 2, 3)
",https://stackoverflow.com/questions/32171917/how-to-copy-a-2d-array-into-a-3rd-dimension-n-times,220,173649.0,7.0,,,2015-08-23 21:51:14,2023-09-20 06:23:44,2023-09-20 06:23:44,,,python;arrays;numpy,anon01,11250,5032941,registered,true,32171971,,CC BY-SA 4.0,,565,440,4,0,0,3,true,false,false,true,true,true,53,12,true,0.04,0.0013,4108,2015,8,21,Sunday,true,true,false,false,false,false,false
24560298,"ValueError: operands could not be broadcast together with shapes" when trying to calculate dot product,"In numpy, I have two "arrays", X is (m,n) and y is a vector (n,1).
Using
X*y
I am getting the error
ValueError: operands could not be broadcast together with shapes (97,2) (2,1)
When (97,2)x(2,1) is clearly a legal matrix operation and should give me a (97,1) vector.
I have corrected this using X.dot(y) but the original question still remains.
",https://stackoverflow.com/questions/24560298/valueerror-operands-could-not-be-broadcast-together-with-shapes-when-trying-t,220,1284346.0,12.0,,,2014-07-03 17:52:22,2025-11-07 07:59:37,2025-11-07 07:59:37,,,python;numpy,yayu,8318,696668,registered,true,,,CC BY-SA 4.0,,534,360,9,0,0,2,false,false,false,true,true,true,113,15,false,0.009,0.0002,4524,2014,7,17,Thursday,false,true,false,false,false,false,false
11144513,Cartesian product of x and y array points into single array of 2D points,"I have two numpy arrays that define the x and y axes of a grid. For example:
x = numpy.array([1,2,3])
y = numpy.array([4,5])
I'd like to generate the Cartesian product of these arrays to generate:
array([[1,4],[2,4],[3,4],[1,5],[2,5],[3,5]])
In a way that's not terribly inefficient since I need to do this many times in a loop. I'm assuming that converting them to a Python list and using itertools.product and back to a numpy array is not the most efficient form.
",https://stackoverflow.com/questions/11144513/cartesian-product-of-x-and-y-array-points-into-single-array-of-2d-points,219,138928.0,18.0,,,2012-06-21 18:30:19,2023-06-21 17:34:45,2019-07-10 18:16:45,,,python;numpy;cartesian-product,Rich,12793,42897,registered,true,11144716,,CC BY-SA 4.0,2018-03-30 02:12:29,556,474,3,0,0,3,true,false,false,true,true,true,72,14,false,0.13,0.0016,5266,2012,6,18,Thursday,false,true,false,false,false,false,false
18665873,Filtering a list based on a list of booleans,"I have a list of values which I need to filter given the values in a list of booleans:
list_a = [1, 2, 4, 6]
filter = [True, False, True, False]
I generate a new filtered list with the following line:
filtered_list = [i for indx,i in enumerate(list_a) if filter[indx] == True]
which results in:
print filtered_list
[1,4]
The line works but looks (to me) a bit overkill and I was wondering if there was a simpler way to achieve the same.
Advices
Summary of two good advices given in the answers below:
1- Don't name a list filter like I did because it is a built-in function.
2- Don't compare things to True like I did with if filter[idx]==True.. since it's unnecessary. Just using if filter[idx] is enough.
",https://stackoverflow.com/questions/18665873/filtering-a-list-based-on-a-list-of-booleans,218,198957.0,7.0,,,2013-09-06 20:12:29,2023-02-28 14:37:09,2013-09-06 21:51:01,,,python;list;numpy,Gabriel,43081,1391441,registered,true,18665893,,CC BY-SA 3.0,,908,722,7,0,0,3,true,false,false,true,true,true,44,9,false,0.035,0.0011,4824,2013,9,20,Friday,false,true,false,false,false,false,false
118370,How do you use the ellipsis slicing syntax in Python?,"This came up in Hidden features of Python, but I can't see good documentation or examples that explain how the feature works.
",https://stackoverflow.com/questions/118370/how-do-you-use-the-ellipsis-slicing-syntax-in-python,216,71910.0,5.0,,,2008-09-23 00:17:09,2024-04-25 21:18:25,2017-05-23 11:47:16,,,python;numpy;subclass;slice;ellipsis,miracle2k,32827,15677,registered,true,118395,,CC BY-SA 3.0,2019-07-12 14:42:28,217,127,0,1,0,5,true,false,false,true,true,true,53,10,true,0.07,0.003,6633,2008,9,0,Tuesday,false,true,false,false,false,false,false
1208118,Using NumPy to build an array of all combinations of two arrays,"I'm trying to run over the parameters space of a six-parameter function to study its numerical behavior before trying to do anything complex with it, so I'm searching for an efficient way to do this.
My function takes float values given in a 6-dim NumPy array as input. What I tried to do initially was this:
First, I created a function that takes two arrays and generate an array with all combinations of values from the two arrays:
from numpy import *
def comb(a, b):
c = []
for i in a:
for j in b:
c.append(r_[i,j])
return c
Then, I used reduce() to apply that to m copies of the same array:
def combs(a, m):
return reduce(comb, [a]*m)
Finally, I evaluate my function like this:
values = combs(np.arange(0, 1, 0.1), 6)
for val in values:
print F(val)
This works, but it's way too slow. I know the space of parameters is huge, but this shouldn't be so slow. I have only sampled 106 (a million) points in this example and it took more than 15 seconds just to create the array values.
Is there a more efficient way of doing this with NumPy?
I can modify the way the function F takes its arguments if it's necessary.
",https://stackoverflow.com/questions/1208118/using-numpy-to-build-an-array-of-all-combinations-of-two-arrays,216,285631.0,10.0,,,2009-07-30 17:32:27,2023-05-07 02:21:26,2023-01-13 13:21:54,,,python;arrays;numpy;multidimensional-array;cartesian-product,Rafael S. Calsaverini,14062,114388,registered,true,35608701,,CC BY-SA 4.0,2019-07-06 00:10:13,1347,1160,6,0,0,5,true,false,false,true,true,true,63,12,false,0.035,0.0008,6323,2009,7,17,Thursday,false,true,false,false,false,false,false
50997928,TypeError: only integer scalar arrays can be converted to a scalar index with 1D numpy indices array,"I want to write a function that randomly picks elements from a training set, based on the bin probabilities provided. I divide the set indices to 11 bins, then create custom probabilities for them.
bin_probs = [0.5, 0.3, 0.15, 0.04, 0.0025, 0.0025, 0.001, 0.001, 0.001, 0.001, 0.001]
X_train = list(range(2000000))
train_probs = bin_probs * int(len(X_train) / len(bin_probs)) # extend probabilities across bin elements
train_probs.extend([0.001]*(len(X_train) - len(train_probs))) # a small fix to match number of elements
train_probs = train_probs/np.sum(train_probs) # normalize
indices = np.random.choice(range(len(X_train)), replace=False, size=50000, p=train_probs)
out_images = X_train[indices.astype(int)] # this is where I get the error
I get the following error:
TypeError: only integer scalar arrays can be converted to a scalar index with 1D numpy indices array
I find this weird, since I already checked the array of indices that I have created. It is 1-D, it is integer, and it is scalar.
What am I missing?
Note : I tried to pass indices with astype(int). Same error.
",https://stackoverflow.com/questions/50997928/typeerror-only-integer-scalar-arrays-can-be-converted-to-a-scalar-index-with-1d,213,841942.0,6.0,,,2018-06-23 04:20:29,2022-08-14 10:39:17,2020-05-15 10:55:16,,,python;python-3.x;numpy,Bedir Yilmaz,4153,776348,registered,true,50997969,,CC BY-SA 4.0,,1303,1092,4,0,0,3,true,false,false,true,true,true,100,17,false,0.007,0.0003,3073,2018,6,4,Saturday,true,true,false,false,false,false,false
26984414,Efficiently sorting a numpy array in descending order?,"I am surprised this specific question hasn't been asked before, but I really didn't find it on SO nor on the documentation of np.sort.
Say I have a random numpy array holding integers, e.g:
> temp = np.random.randint(1,10, 10)
> temp
array([2, 4, 7, 4, 2, 2, 7, 6, 4, 4])
If I sort it, I get ascending order by default:
> np.sort(temp)
array([2, 2, 2, 4, 4, 4, 4, 6, 7, 7])
but I want the solution to be sorted in descending order.
Now, I know I can always do:
reverse_order = np.sort(temp)[::-1]
but is this last statement efficient? Doesn't it create a copy in ascending order, and then reverses this copy to get the result in reversed order? If this is indeed the case, is there an efficient alternative? It doesn't look like np.sort accepts parameters to change the sign of the comparisons in the sort operation to get things in reverse order.
",https://stackoverflow.com/questions/26984414/efficiently-sorting-a-numpy-array-in-descending-order,213,433256.0,12.0,,,2014-11-18 00:16:02,2025-04-19 11:15:22,,,,python;arrays;sorting;numpy,Amelio Vazquez-Reina,97532,283296,registered,true,26984520,,CC BY-SA 3.0,,1046,872,5,0,0,4,true,false,false,true,true,false,54,8,true,0.028,0.0005,4386,2014,11,0,Tuesday,false,true,false,false,false,false,false
367565,How do I build a numpy array from a generator?,"How can I build a numpy array out of a generator object?
Let me illustrate the problem:
>>> import numpy
>>> def gimme():
... for x in xrange(10):
... yield x
...
>>> gimme()
<generator object at 0x28a1758>
>>> list(gimme())
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> numpy.array(xrange(10))
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> numpy.array(gimme())
array(<generator object at 0x28a1758>, dtype=object)
>>> numpy.array(list(gimme()))
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In this instance, gimme() is the generator whose output I'd like to turn into an array. However, the array constructor does not iterate over the generator, it simply stores the generator itself. The behaviour I desire is that from numpy.array(list(gimme())), but I don't want to pay the memory overhead of having the intermediate list and the final array in memory at the same time. Is there a more space-efficient way?
",https://stackoverflow.com/questions/367565/how-do-i-build-a-numpy-array-from-a-generator,213,115284.0,5.0,,,2008-12-15 05:44:31,2022-08-11 11:04:41,2019-11-15 17:58:01,,,python;numpy;generator,saffsd,24410,37984,registered,true,367599,,CC BY-SA 4.0,,1045,974,3,0,0,3,true,false,false,true,true,true,46,10,true,0.043,0.0018,6550,2008,12,5,Monday,false,true,false,false,false,false,false
7332841,Add single element to array in numpy,"I have a numpy array containing:
[1, 2, 3]
I want to create an array containing:
[1, 2, 3, 1]
That is, I want to add the first element on to the end of the array.
I have tried the obvious:
np.concatenate((a, a[0]))
But I get an error saying ValueError: arrays must have same number of dimensions
I don't understand this - the arrays are both just 1d arrays.
",https://stackoverflow.com/questions/7332841/add-single-element-to-array-in-numpy,213,654456.0,9.0,,,2011-09-07 11:09:07,2022-06-02 21:21:56,,,,python;arrays;numpy,robintw,28869,1912,registered,true,7332977,,CC BY-SA 3.0,,496,369,4,0,0,3,true,false,false,true,true,false,36,7,false,0.014,0.0003,5554,2011,9,11,Wednesday,false,true,false,false,false,false,false
27516849,How to convert list of numpy arrays into single numpy array?,"Suppose I have ;
LIST = [[array([1, 2, 3, 4, 5]), array([1, 2, 3, 4, 5],[1,2,3,4,5])] # inner lists are numpy arrays
I try to convert;
array([[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5])
I am solving it by iteration on vstack right now but it is really slow for especially large LIST
What do you suggest for the best efficient way?
",https://stackoverflow.com/questions/27516849/how-to-convert-list-of-numpy-arrays-into-single-numpy-array,210,355118.0,5.0,,,2014-12-17 01:16:30,2023-10-20 14:46:27,,,,python;list;numpy,erogol,13704,648896,registered,true,27516930,,CC BY-SA 3.0,2019-07-07 20:14:19,435,359,2,0,0,3,true,false,false,true,true,false,60,11,true,0.014,0.0006,4357,2014,12,1,Wednesday,false,true,false,false,false,false,false
19286657,Index all *except* one item in python,"Is there a simple way to index all elements of a list (or array, or whatever) except for a particular index? E.g.,
mylist[3] will return the item in position 3
milist[~3] will return the whole list except for 3
",https://stackoverflow.com/questions/19286657/index-all-except-one-item-in-python,207,363385.0,11.0,,,2013-10-10 03:39:18,2023-05-10 15:07:14,2015-09-26 01:15:34,,,python;list;numpy;indexing,choldgraf,3739,1927102,registered,true,19286855,,CC BY-SA 3.0,2024-12-12 04:42:50,307,216,2,0,0,4,true,false,false,true,true,true,37,7,false,0.03,0.0006,4790,2013,10,3,Thursday,false,true,false,false,false,false,false
4588628,Find indices of elements equal to zero in a NumPy array,"NumPy has the efficient function/method nonzero() to identify the indices of non-zero elements in an ndarray object. What is the most efficient way to obtain the indices of the elements that do have a value of zero?
",https://stackoverflow.com/questions/4588628/find-indices-of-elements-equal-to-zero-in-a-numpy-array,206,419634.0,9.0,,,2011-01-03 21:40:08,2022-08-04 17:41:13,2018-01-09 22:29:23,,,python;numpy,gotgenes,40449,38140,registered,true,4588654,,CC BY-SA 3.0,,360,216,2,1,0,2,true,false,false,true,true,true,55,11,false,0.021,0.0005,5801,2011,1,21,Monday,false,true,false,false,false,false,false
3337301,Numpy matrix to array,"I am using numpy. I have a matrix with 1 column and N rows and I want to get an array from with N elements.
For example, if i have M = matrix([[1], [2], [3], [4]]), I want to get A = array([1,2,3,4]).
To achieve it, I use A = np.array(M.T)[0]. Does anyone know a more elegant way to get the same result?
Thanks!
",https://stackoverflow.com/questions/3337301/numpy-matrix-to-array,204,390324.0,10.0,,,2010-07-26 17:25:23,2021-10-05 22:12:38,2013-05-12 21:20:55,,,python;arrays;matrix;numpy,yassin,6807,256763,registered,true,3338368,,CC BY-SA 3.0,,382,315,3,0,0,4,true,false,false,true,true,true,21,4,false,0.026,0.0005,5962,2010,7,17,Monday,false,true,false,false,false,false,false
34142485,Difference between numpy dot() and Python 3.5+ matrix multiplication @,"I recently moved to Python 3.5 and noticed the new matrix multiplication operator (@) sometimes behaves differently from the numpy dot operator. In example, for 3d arrays:
import numpy as np
a = np.random.rand(8,13,13)
b = np.random.rand(8,13,13)
c = a @ b # Python 3.5+
d = np.dot(a, b)
The @ operator returns an array of shape:
c.shape
(8, 13, 13)
while the np.dot() function returns:
d.shape
(8, 13, 8, 13)
How can I reproduce the same result with numpy dot? Are there any other significant differences?
",https://stackoverflow.com/questions/34142485/difference-between-numpy-dot-and-python-3-5-matrix-multiplication,203,237362.0,5.0,,,2015-12-07 20:23:26,2023-03-26 18:33:15,2015-12-07 20:50:06,,,python;numpy;matrix-multiplication;python-3.5,blaz,4298,3604473,registered,true,34142617,,CC BY-SA 3.0,,834,518,5,2,0,4,true,false,false,true,true,true,70,10,false,0.021,0.0009,4002,2015,12,20,Monday,false,true,false,false,false,false,false
48121916,Numpy Resize/Rescale Image,"I would like to take an image and change the scale of the image, while it is a numpy array.
For example I have this image of a coca-cola bottle:
bottle-1
Which translates to a numpy array of shape (528, 203, 3) and I want to resize that to say the size of this second image:
bottle-2
Which has a shape of (140, 54, 3).
How do I change the size of the image to a certain shape while still maintaining the original image? Other answers suggest stripping every other or third row out, but what I want to do is basically shrink the image how you would via an image editor but in python code. Are there any libraries to do this in numpy/SciPy?
",https://stackoverflow.com/questions/48121916/numpy-resize-rescale-image,202,468417.0,10.0,,,2018-01-05 22:03:38,2022-11-28 01:17:30,,,,python;image;numpy;scipy;resize,Brian Hamill,2596,8848969,registered,true,48121983,,CC BY-SA 3.0,,830,643,2,2,0,5,true,false,false,true,true,false,26,3,false,0.021,0.0004,3242,2018,1,22,Friday,false,true,false,false,false,false,false
3030480,How do I select elements of an array given condition?,"Suppose I have a numpy array x = [5, 2, 3, 1, 4, 5], y = ['f', 'o', 'o', 'b', 'a', 'r']. I want to select the elements in y corresponding to elements in x that are greater than 1 and less than 5.
I tried
x = array([5, 2, 3, 1, 4, 5])
y = array(['f','o','o','b','a','r'])
output = y[x > 1 & x < 5] # desired output is ['o','o','a']
but this doesn't work. How would I do this?
",https://stackoverflow.com/questions/3030480/how-do-i-select-elements-of-an-array-given-condition,201,381724.0,6.0,,,2010-06-12 23:28:05,2020-04-02 15:58:38,2020-04-02 15:58:38,,,python;numpy,Bob,2045,365440,unregistered,true,3030662,,CC BY-SA 4.0,2019-07-06 00:10:01,486,389,5,0,0,2,true,false,false,true,true,true,53,10,true,0.016,0.0005,6006,2010,6,23,Saturday,true,true,false,false,false,false,false
16094563,numpy get index where value is true,">>> ex=np.arange(30)
>>> e=np.reshape(ex,[3,10])
>>> e
array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29]])
>>> e>15
array([[False, False, False, False, False, False, False, False, False,
False],
[False, False, False, False, False, False, True, True, True,
True],
[ True, True, True, True, True, True, True, True, True,
True]], dtype=bool)
I need to find the rows that have true or rows in e whose value are more than 15. I could iterate using a for loop, however, I would like to know if there is a way numpy could do this more efficiently?
",https://stackoverflow.com/questions/16094563/numpy-get-index-where-value-is-true,199,383577.0,4.0,,,2013-04-18 23:05:51,2023-09-11 21:16:10,2017-07-23 09:04:43,,,python;numpy;matrix,change,3628,469396,registered,true,16094877,,CC BY-SA 3.0,,773,729,2,0,0,3,true,false,false,true,true,true,35,7,false,0.01,0.0005,4965,2013,4,23,Thursday,false,true,false,false,false,false,false
4535374,initialize a numpy array,"Is there way to initialize a numpy array of a shape and add to it? I will explain what I need with a list example. If I want to create a list of objects generated in a loop, I can do:
a = []
for i in range(5):
a.append(i)
I want to do something similar with a numpy array. I know about vstack, concatenate etc. However, it seems these require two numpy arrays as inputs. What I need is:
big_array # Initially empty. This is where I don't know what to specify
for i in range(5):
array i of shape = (2,4) created.
add to big_array
The big_array should have a shape (10,4). How to do this?
EDIT:
I want to add the following clarification. I am aware that I can define big_array = numpy.zeros((10,4)) and then fill it up. However, this requires specifying the size of big_array in advance. I know the size in this case, but what if I do not? When we use the .append function for extending the list in python, we don't need to know its final size in advance. I am wondering if something similar exists for creating a bigger array from smaller arrays, starting with an empty array.
",https://stackoverflow.com/questions/4535374/initialize-a-numpy-array,199,914985.0,14.0,,,2010-12-26 20:52:45,2022-05-10 15:52:25,2016-12-18 11:29:02,2023-09-19 22:08:03,Duplicate,python;arrays;numpy,Curious2learn,33976,316357,registered,true,4535387,,,,1254,1098,6,0,0,3,true,true,false,true,true,true,24,4,false,0.015,0.0002,5809,2010,12,20,Sunday,true,true,false,false,false,false,false
4257394,"Slicing of a NumPy 2d array, or how do I extract an mxm submatrix from an nxn array (n>m)?","I want to slice a NumPy nxn array. I want to extract an arbitrary selection of m rows and columns of that array (i.e. without any pattern in the numbers of rows/columns), making it a new, mxm array. For this example let us say the array is 4x4 and I want to extract a 2x2 array from it.
Here is our array:
from numpy import *
x = range(16)
x = reshape(x,(4,4))
print x
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
The line and columns to remove are the same. The easiest case is when I want to extract a 2x2 submatrix that is at the beginning or at the end, i.e. :
In [33]: x[0:2,0:2]
Out[33]:
array([[0, 1],
[4, 5]])
In [34]: x[2:,2:]
Out[34]:
array([[10, 11],
[14, 15]])
But what if I need to remove another mixture of rows/columns? What if I need to remove the first and third lines/rows, thus extracting the submatrix [[5,7],[13,15]]? There can be any composition of rows/lines. I read somewhere that I just need to index my array using arrays/lists of indices for both rows and columns, but that doesn't seem to work:
In [35]: x[[1,3],[1,3]]
Out[35]: array([ 5, 15])
I found one way, which is:
In [61]: x[[1,3]][:,[1,3]]
Out[61]:
array([[ 5, 7],
[13, 15]])
First issue with this is that it is hardly readable, although I can live with that. If someone has a better solution, I'd certainly like to hear it.
Other thing is I read on a forum that indexing arrays with arrays forces NumPy to make a copy of the desired array, thus when treating with large arrays this could become a problem. Why is that so / how does this mechanism work?
",https://stackoverflow.com/questions/4257394/slicing-of-a-numpy-2d-array-or-how-do-i-extract-an-mxm-submatrix-from-an-nxn-ar,199,271210.0,7.0,,,2010-11-23 15:05:08,2018-08-26 05:32:49,2015-03-03 20:40:02,,,python;numpy;slice,levesque,8974,131100,registered,true,4258079,,CC BY-SA 3.0,,1874,1602,5,1,0,3,true,false,false,true,true,true,93,19,true,0.026,0.0007,5842,2010,11,15,Tuesday,false,true,false,false,false,false,false
6620471,Fitting empirical distribution to theoretical ones with Scipy?,"INTRODUCTION: I have a list of more than 30,000 integer values ranging from 0 to 47, inclusive, e.g.[0,0,0,0,..,1,1,1,1,...,2,2,2,2,...,47,47,47,...] sampled from some continuous distribution. The values in the list are not necessarily in order, but order doesn't matter for this problem.
PROBLEM: Based on my distribution I would like to calculate p-value (the probability of seeing greater values) for any given value. For example, as you can see p-value for 0 would be approaching 1 and p-value for higher numbers would be tending to 0.
I don't know if I am right, but to determine probabilities I think I need to fit my data to a theoretical distribution that is the most suitable to describe my data. I assume that some kind of goodness of fit test is needed to determine the best model.
Is there a way to implement such an analysis in Python (Scipy or Numpy)?
Could you present any examples?
",https://stackoverflow.com/questions/6620471/fitting-empirical-distribution-to-theoretical-ones-with-scipy,198,224688.0,13.0,,,2011-07-08 06:00:48,2025-04-04 16:26:06,2025-04-04 16:26:06,,,python;numpy;statistics;scipy;distribution,s_sherly,2367,428727,unregistered,true,,,CC BY-SA 4.0,2015-11-25 01:02:57,999,898,3,0,0,5,false,false,false,true,true,true,62,8,true,0.058,0.0009,5615,2011,7,6,Friday,false,true,false,false,false,false,false
78634235,"numpy.dtype size changed, may indicate binary incompatibility. Expected 96 from C header, got 88 from PyObject","I want to call my Python module from the Matlab. I received the error:
Error using numpy_ops>init thinc.backends.numpy_ops
Python Error:
ValueError: numpy.dtype size changed, may indicate binary incompatibility. Expected 96 from C header, got 88 from PyObject.
The Python script is as follows
import spacy
def text_recognizer(model_path, text):
try:
# Load the trained model
nlp = spacy.load(model_path)
print("Model loaded successfully.")
# Process the given text
doc = nlp(text)
ent_labels = [(ent.text, ent.label_) for ent in doc.ents]
return ent_labels
The Matlab script is as follows
% Set up the Python environment
pe = pyenv;
py.importlib.import_module('final_output');
% Add the directory containing the Python script to the Python path
path_add = fileparts(which('final_output.py'));
if count(py.sys.path, path_add) == 0
insert(py.sys.path, int64(0), path_add);
end
% Define model path and text to process
model_path = 'D:\trained_model\\output\\model-best';
text = 'Roses are red';
% Call the Python function
pyOut = py.final_output.text_recognizer(model_path, text);
% Convert the output to a MATLAB cell array
entity_labels = cell(pyOut);
disp(entity_labels);
I found one solution to update Numpy, what I did, but nothing changed. I am using Python 3.9 and Numpy version 2.0.0
The error was received when I tried to call the Python module using a Matlab script.
How can I fix the issue?
",https://stackoverflow.com/questions/78634235/numpy-dtype-size-changed-may-indicate-binary-incompatibility-expected-96-from,197,319746.0,8.0,,,2024-06-17 18:52:57,2025-11-08 07:16:33,2024-07-03 08:50:45,,,python;numpy;matlab;spacy,Encipher,3526,9357484,registered,true,78641304,,CC BY-SA 4.0,2025-11-08 07:43:38,1604,1459,4,0,0,4,true,false,false,true,true,true,110,16,false,0.025,0.0006,887,2024,6,18,Monday,false,true,false,false,false,false,false
12575421,Convert a 1D array to a 2D array in numpy,"I want to convert a 1-dimensional array into a 2-dimensional array by specifying the number of columns in the 2D array. Something that would work like this:
> import numpy as np
> A = np.array([1,2,3,4,5,6])
> B = vec2matrix(A,ncol=2)
> B
array([[1, 2],
[3, 4],
[5, 6]])
Does numpy have a function that works like my made-up function ""vec2matrix""? (I understand that you can index a 1D array like a 2D array, but that isn't an option in the code I have - I need to make this conversion.)
",https://stackoverflow.com/questions/12575421/convert-a-1d-array-to-a-2d-array-in-numpy,196,640034.0,11.0,,,2012-09-25 02:23:30,2025-08-11 13:18:06,2018-07-18 04:40:42,,,python;arrays;matrix;numpy;multidimensional-array,digbyterrell,3649,1666349,registered,true,12575451,,CC BY-SA 4.0,,555,517,1,0,0,5,true,false,false,true,true,true,41,10,false,0.017,0.0003,5170,2012,9,2,Tuesday,false,true,false,false,false,false,false
20553551,How do I get Pylint to recognize NumPy members?,"I am running Pylint on a Python project. Pylint makes many complaints about being unable to find NumPy members. How can I avoid this while avoiding skipping membership checks?
From the code:
import numpy as np
print np.zeros([1, 4])
Which, when ran, I get the expected:
[[ 0. 0. 0. 0.]]
However, Pylint gives me this error:
E: 3, 6: Module 'numpy' has no 'zeros' member (no-member)
For versions, I am using Pylint 1.0.0 (astroid 1.0.1, common 0.60.0) and trying to work with NumPy 1.8.0.
",https://stackoverflow.com/questions/20553551/how-do-i-get-pylint-to-recognize-numpy-members,196,111128.0,23.0,,,2013-12-12 20:27:12,2021-01-18 09:49:41,2021-01-18 04:36:40,,,python;numpy;pylint,Alphadelta14,2923,2947012,registered,true,,,CC BY-SA 4.0,2019-07-12 14:41:43,621,498,1,0,0,3,false,false,false,true,true,true,47,9,true,0.207,0.0018,4727,2013,12,20,Thursday,false,true,false,false,false,false,false
40845304,"RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility","I have this error for trying to load a saved SVM model. I have tried uninstalling sklearn, NumPy and SciPy, reinstalling the latest versions all-together again (using pip). I am still getting this error. Why?
In [1]: import sklearn; print sklearn.__version__
0.18.1
In [3]: import numpy; print numpy.__version__
1.11.2
In [5]: import scipy; print scipy.__version__
0.18.1
In [7]: import pandas; print pandas.__version__
0.19.1
In [10]: clf = joblib.load('model/trained_model.pkl')
---------------------------------------------------------------------------
RuntimeWarning Traceback (most recent call last)
<ipython-input-10-5e5db1331757> in <module>()
----> 1 clf = joblib.load('sentiment_classification/model/trained_model.pkl')
/usr/local/lib/python2.7/dist-packages/sklearn/externals/joblib/numpy_pickle.pyc in load(filename, mmap_mode)
573 return load_compatibility(fobj)
574
--> 575 obj = _unpickle(fobj, filename, mmap_mode)
576
577 return obj
/usr/local/lib/python2.7/dist-packages/sklearn/externals/joblib/numpy_pickle.pyc in _unpickle(fobj, filename, mmap_mode)
505 obj = None
506 try:
--> 507 obj = unpickler.load()
508 if unpickler.compat_mode:
509 warnings.warn(""The file '%s' has been generated with a ""
/usr/lib/python2.7/pickle.pyc in load(self)
862 while 1:
863 key = read(1)
--> 864 dispatch[key](self)
865 except _Stop, stopinst:
866 return stopinst.value
/usr/lib/python2.7/pickle.pyc in load_global(self)
1094 module = self.readline()[:-1]
1095 name = self.readline()[:-1]
-> 1096 klass = self.find_class(module, name)
1097 self.append(klass)
1098 dispatch[GLOBAL] = load_global
/usr/lib/python2.7/pickle.pyc in find_class(self, module, name)
1128 def find_class(self, module, name):
1129 # Subclasses may override this
-> 1130 __import__(module)
1131 mod = sys.modules[module]
1132 klass = getattr(mod, name)
/usr/local/lib/python2.7/dist-packages/sklearn/svm/__init__.py in <module>()
11 # License: BSD 3 clause (C) INRIA 2010
12
---> 13 from .classes import SVC, NuSVC, SVR, NuSVR, OneClassSVM, LinearSVC, \
14 LinearSVR
15 from .bounds import l1_min_c
/usr/local/lib/python2.7/dist-packages/sklearn/svm/classes.py in <module>()
2 import numpy as np
3
----> 4 from .base import _fit_liblinear, BaseSVC, BaseLibSVM
5 from ..base import BaseEstimator, RegressorMixin
6 from ..linear_model.base import LinearClassifierMixin, SparseCoefMixin, \
/usr/local/lib/python2.7/dist-packages/sklearn/svm/base.py in <module>()
6 from abc import ABCMeta, abstractmethod
7
----> 8 from . import libsvm, liblinear
9 from . import libsvm_sparse
10 from ..base import BaseEstimator, ClassifierMixin
__init__.pxd in init sklearn.svm.libsvm (sklearn/svm/libsvm.c:10207)()
RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected 96, got 80
UPDATE: OK, by following here, and
pip uninstall -y scipy scikit-learn
pip install --no-binary scipy scikit-learn
The error has now gone, though I still have no idea why it occurred in the first place...
",https://stackoverflow.com/questions/40845304/runtimewarning-numpy-dtype-size-changed-may-indicate-binary-incompatibility,195,264652.0,13.0,,,2016-11-28 13:17:48,2024-09-07 12:10:34,2018-08-02 11:12:11,,,python;numpy;scikit-learn,Blue482,3216,3319713,registered,true,40846742,,CC BY-SA 4.0,2019-07-12 14:43:33,3660,3438,2,1,0,3,true,false,false,true,true,true,77,8,false,0.049,0.0007,3645,2016,11,13,Monday,false,true,false,false,false,false,false
15033511,Compute a confidence interval from sample data,"I have sample data which I would like to compute a confidence interval for, assuming a normal distribution.
I have found and installed the numpy and scipy packages and have gotten numpy to return a mean and standard deviation (numpy.mean(data) with data being a list). Any advice on getting a sample confidence interval would be much appreciated.
",https://stackoverflow.com/questions/15033511/compute-a-confidence-interval-from-sample-data,194,408722.0,6.0,,,2013-02-22 21:29:50,2022-06-12 11:26:26,2021-01-13 10:11:42,,,python;numpy;scipy;statistics;confidence-interval,Bmayer0122,2248,1953958,registered,true,15034143,,CC BY-SA 4.0,2021-10-02 15:10:13,362,348,0,0,0,5,true,false,false,true,true,true,46,7,false,0.015,0.0005,5020,2013,2,21,Friday,false,true,false,false,false,false,false
14657375,Cython: "fatal error: numpy/arrayobject.h: No such file or directory","I'm trying to speed up the answer here using Cython. I try to compile the code (after doing the cygwinccompiler.py hack explained here), but get a fatal error: numpy/arrayobject.h: No such file or directory...compilation terminated error. Can anyone tell me if it's a problem with my code, or some esoteric subtlety with Cython?
Below is my code.
import numpy as np
import scipy as sp
cimport numpy as np
cimport cython
cdef inline np.ndarray[np.int, ndim=1] fbincount(np.ndarray[np.int_t, ndim=1] x):
cdef int m = np.amax(x)+1
cdef int n = x.size
cdef unsigned int i
cdef np.ndarray[np.int_t, ndim=1] c = np.zeros(m, dtype=np.int)
for i in xrange(n):
c[<unsigned int>x[i]] += 1
return c
cdef packed struct Point:
np.float64_t f0, f1
@cython.boundscheck(False)
def sparsemaker(np.ndarray[np.float_t, ndim=2] X not None,
np.ndarray[np.float_t, ndim=2] Y not None,
np.ndarray[np.float_t, ndim=2] Z not None):
cdef np.ndarray[np.float64_t, ndim=1] counts, factor
cdef np.ndarray[np.int_t, ndim=1] row, col, repeats
cdef np.ndarray[Point] indices
cdef int x_, y_
_, row = np.unique(X, return_inverse=True); x_ = _.size
_, col = np.unique(Y, return_inverse=True); y_ = _.size
indices = np.rec.fromarrays([row,col])
_, repeats = np.unique(indices, return_inverse=True)
counts = 1. / fbincount(repeats)
Z.flat *= counts.take(repeats)
return sp.sparse.csr_matrix((Z.flat,(row,col)), shape=(x_, y_)).toarray()
",https://stackoverflow.com/questions/14657375/cython-fatal-error-numpy-arrayobject-h-no-such-file-or-directory,194,144949.0,10.0,,,2013-02-02 00:38:35,2025-06-05 06:44:56,2019-11-20 18:44:19,,,python;windows-7;numpy;cython,Noob Saibot,4789,1658908,registered,true,14657667,,CC BY-SA 4.0,,1808,1532,3,2,0,4,true,false,false,true,true,true,79,9,false,0.069,0.0013,5040,2013,2,0,Saturday,true,true,false,false,false,false,false
19602187,Numpy: Divide each row by a vector element,"Suppose I have a numpy array:
data = np.array([[1,1,1],[2,2,2],[3,3,3]])
and I have a corresponding ""vector:""
vector = np.array([1,2,3])
How do I operate on data along each row to either subtract or divide so the result is:
sub_result = [[0,0,0], [0,0,0], [0,0,0]]
div_result = [[1,1,1], [1,1,1], [1,1,1]]
Long story short: How do I perform an operation on each row of a 2D array with a 1D array of scalars that correspond to each row?
",https://stackoverflow.com/questions/19602187/numpy-divide-each-row-by-a-vector-element,194,184307.0,6.0,,,2013-10-26 02:34:28,2021-03-13 23:51:56,,,,python;arrays;numpy;scipy,BFTM,3355,983310,registered,true,19602209,,CC BY-SA 3.0,,558,445,4,0,0,4,true,false,false,true,true,false,42,8,false,0.033,0.0011,4774,2013,10,2,Saturday,true,true,false,false,false,false,false
6252280,Find the most frequent number in a NumPy array,"Suppose I have the following NumPy array:
a = np.array([1,2,3,1,2,1,1,1,3,2,2,1])
How can I find the most frequent number in this array?
",https://stackoverflow.com/questions/6252280/find-the-most-frequent-number-in-a-numpy-array,192,298874.0,14.0,,,2011-06-06 12:51:40,2023-02-21 23:36:41,2020-11-22 11:55:28,,,python;numpy,JustInTime,2816,308849,registered,true,6252400,,CC BY-SA 4.0,,176,138,1,0,0,2,true,false,false,true,true,true,46,9,false,0.047,0.0006,5647,2011,6,12,Monday,false,true,false,false,false,false,false
32752292,How to create a DataFrame of random integers with Pandas?,"I know that if I use randn, the following code gives me what I am looking for, but with elements from a normal distribution. But what if I just wanted random integers?
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(100, 4), columns=list('ABCD'))
randint works by providing a range, but not an array like randn. So how do I do this with random integers between some range?
",https://stackoverflow.com/questions/32752292/how-to-create-a-dataframe-of-random-integers-with-pandas,191,261252.0,3.0,,,2015-09-24 02:17:00,2025-04-23 11:13:51,2025-04-15 16:35:28,,,python;pandas;dataframe;numpy;random,TheRealFakeNews,8401,2023745,registered,true,32752318,,CC BY-SA 4.0,,624,399,4,1,0,5,true,false,false,true,true,true,57,10,true,0.011,0.0007,4076,2015,9,2,Thursday,false,true,false,false,false,false,false
3877209,How to convert an array of strings to an array of floats in numpy?,"How do I make the following conversion in NumPy?
["1.1", "2.2", "3.2"] ⟶ [1.1, 2.2, 3.2]
",https://stackoverflow.com/questions/3877209/how-to-convert-an-array-of-strings-to-an-array-of-floats-in-numpy,191,575932.0,6.0,,,2010-10-06 21:57:33,2023-10-24 20:05:48,2023-10-24 20:05:48,,,python;numpy;type-conversion,Meh,7206,212865,registered,true,3877247,,CC BY-SA 4.0,2019-07-06 00:28:14,192,122,1,0,0,3,true,false,false,true,true,true,66,14,true,0.01,0.0003,5890,2010,10,21,Wednesday,false,true,false,false,false,false,false
19900202,How to determine whether a column/variable is numeric or not in Pandas/NumPy?,"Is there a better way to determine whether a variable in Pandas and/or NumPy is numeric or not ?
I have a self defined dictionary with dtypes as keys and numeric / not as values.
",https://stackoverflow.com/questions/19900202/how-to-determine-whether-a-column-variable-is-numeric-or-not-in-pandas-numpy,190,236623.0,11.0,,,2013-11-11 06:32:11,2024-08-14 08:50:59,2018-04-11 18:48:07,,,python;pandas;numpy,user2808117,4957,2808117,registered,true,,,CC BY-SA 3.0,,286,181,7,0,0,3,false,false,false,true,true,true,77,12,true,0.046,0.0008,4758,2013,11,6,Monday,false,true,false,false,false,false,false
26248654,How to return 0 with divide by zero,"I'm trying to perform an element wise divide in python, but if a zero is encountered, I need the quotient to just be zero.
For example:
array1 = np.array([0, 1, 2])
array2 = np.array([0, 1, 1])
array1 / array2 # should be np.array([0, 1, 2])
I could always just use a for-loop through my data, but to really utilize numpy's optimizations, I need the divide function to return 0 upon divide by zero errors instead of ignoring the error.
Unless I'm missing something, it doesn't seem numpy.seterr() can return values upon errors. Does anyone have any other suggestions on how I could get the best out of numpy while setting my own divide by zero error handling?
",https://stackoverflow.com/questions/26248654/how-to-return-0-with-divide-by-zero,189,211326.0,9.0,,,2014-10-08 03:13:05,2023-07-14 20:57:27,2019-05-07 06:31:36,,,python;arrays;numpy;error-handling;divide-by-zero,hlin117,22608,2014591,registered,true,37977222,,CC BY-SA 4.0,,815,666,1,1,0,5,true,false,false,true,true,true,35,8,false,0.043,0.0009,4427,2014,10,3,Wednesday,false,true,false,false,false,false,false
49768306,Pytorch tensor to numpy array,"I have a pytorch Tensor of shape [4, 3, 966, 1296]. I want to convert it to numpy array using the following code:
imgs = imgs.numpy()[:, ::-1, :, :]
How does that code work?
",https://stackoverflow.com/questions/49768306/pytorch-tensor-to-numpy-array,189,619450.0,8.0,,,2018-04-11 06:49:22,2025-02-03 19:40:36,2022-03-28 12:30:23,,,python;numpy;pytorch,DukeLover,2507,1249184,registered,true,49768500,,CC BY-SA 4.0,,252,175,4,0,0,3,true,false,false,true,true,true,29,5,false,0.013,0.0003,3146,2018,4,6,Wednesday,false,true,false,false,false,false,false
66322049,Could not install packages due to an OSError: [WinError 2] No such file or directory,"I try to use pip to install numpy, and I receive the following error message:
Python: Could not install packages due to an OSError: [Errno 2] No such file or directory
'c:\python39\Scripts\f2py.exe' -> 'c:\python39\Scripts\f2py.exe.deleteme'
I'm not sure about an older version of numpy installed first.
I ran just command prompt, not a one with admin privileges.
Can anyone help? Thanks.
",https://stackoverflow.com/questions/66322049/could-not-install-packages-due-to-an-oserror-winerror-2-no-such-file-or-direc,187,404495.0,29.0,,,2021-02-22 19:16:55,2025-09-15 03:13:37,2021-02-22 21:50:41,,,python;numpy,Kristina,4732,6284785,registered,true,,,CC BY-SA 4.0,,616,395,0,1,1,2,false,false,false,true,true,true,84,15,false,0.072,0.0005,2098,2021,2,19,Monday,false,true,false,false,false,false,false
34667282,"How do I use numpy.where()? What should I pass, and what does the result mean?","I tried reading the documentation for numpy.where(), but I'm still confused.
What should I pass for the condition, x and y values? When I pass only condition, what does the result mean and how can I use it? What about when I pass all three?
I found How does python numpy.where() work? but it didn't answer my question because it seems to be about the implementation rather than about how to use it. Numpy where() on a 2D matrix also didn't explain things for me; I'm looking for a step-by-step explanation, rather than a how-to guide for a specific case.
Please include examples with both 1D and 2D source data.
",https://stackoverflow.com/questions/34667282/how-do-i-use-numpy-where-what-should-i-pass-and-what-does-the-result-mean,187,213346.0,2.0,,,2016-01-07 23:51:25,2023-01-30 23:18:23,2023-01-30 23:18:23,2016-01-08 10:38:21,Needs more focus,python;numpy;scipy,Alex Dalyac,7074,2880212,registered,true,34667386,,,,938,612,5,3,0,3,true,true,false,true,true,true,78,15,true,0.009,0.0009,3971,2016,1,23,Thursday,false,true,false,false,false,false,false
22646463,'and' (boolean) vs '&' (bitwise) - Why difference in behavior with lists vs numpy arrays?,"What explains the difference in behavior of boolean and bitwise operations on lists vs NumPy arrays?
I'm confused about the appropriate use of & vs and in Python, illustrated in the following examples.
mylist1 = [True, True, True, False, True]
mylist2 = [False, True, False, True, False]
>>> len(mylist1) == len(mylist2)
True
# ---- Example 1 ----
>>> mylist1 and mylist2
[False, True, False, True, False]
# I would have expected [False, True, False, False, False]
# ---- Example 2 ----
>>> mylist1 & mylist2
TypeError: unsupported operand type(s) for &: 'list' and 'list'
# Why not just like example 1?
>>> import numpy as np
# ---- Example 3 ----
>>> np.array(mylist1) and np.array(mylist2)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
# Why not just like Example 4?
# ---- Example 4 ----
>>> np.array(mylist1) & np.array(mylist2)
array([False, True, False, False, False], dtype=bool)
# This is the output I was expecting!
This answer and this answer helped me understand that and is a boolean operation but & is a bitwise operation.
I read about bitwise operations to better understand the concept, but I am struggling to use that information to make sense of my above 4 examples.
Example 4 led me to my desired output, so that is fine, but I am still confused about when/how/why I should use and vs &. Why do lists and NumPy arrays behave differently with these operators?
Can anyone help me understand the difference between boolean and bitwise operations to explain why they handle lists and NumPy arrays differently?
",https://stackoverflow.com/questions/22646463/and-boolean-vs-bitwise-why-difference-in-behavior-with-lists-vs-nump,187,126309.0,8.0,,,2014-03-25 21:18:23,2023-05-21 17:09:36,2019-08-30 15:18:16,,,python;numpy;bit-manipulation;boolean-expression;ampersand,rysqui,2807,2098573,registered,true,22647006,,CC BY-SA 4.0,2019-07-06 00:15:51,2273,1684,7,5,0,5,true,false,false,true,true,true,109,15,true,0.063,0.0015,4624,2014,3,21,Tuesday,false,true,false,false,false,false,false
17394882,How can I add new dimensions to a Numpy array?,"I'm starting off with a numpy array of an image.
In[1]:img = cv2.imread('test.jpg')
The shape is what you might expect for a 640x480 RGB image.
In[2]:img.shape
Out[2]: (480, 640, 3)
However, this image that I have is a frame of a video, which is 100 frames long. Ideally, I would like to have a single array that contains all the data from this video such that img.shape returns (480, 640, 3, 100).
What is the best way to add the next frame -- that is, the next set of image data, another 480 x 640 x 3 array -- to my initial array?
",https://stackoverflow.com/questions/17394882/how-can-i-add-new-dimensions-to-a-numpy-array,186,430194.0,13.0,,,2013-06-30 21:10:55,2022-11-22 20:04:09,2022-08-08 11:15:19,,,python;arrays;numpy,Chris,10153,1481457,registered,true,,,CC BY-SA 4.0,,643,541,4,0,0,3,false,false,false,true,true,true,46,10,true,0.03,0.0004,4892,2013,6,21,Sunday,true,true,false,false,false,false,false
40034993,How to get element-wise matrix multiplication (Hadamard product) in numpy?,"I have two matrices
a = np.matrix([[1,2], [3,4]])
b = np.matrix([[5,6], [7,8]])
and I want to get the element-wise product, [[1*5,2*6], [3*7,4*8]], which equals
matrix([[5, 12], [21, 32]])
I have tried np.dot(a,b) and a*b but both give the result matrix([[19, 22], [43, 50]])
which is the matrix product, not the element-wise product. How can I get the the element-wise product (aka Hadamard product) using built-in functions?
",https://stackoverflow.com/questions/40034993/how-to-get-element-wise-matrix-multiplication-hadamard-product-in-numpy,186,531759.0,5.0,,,2016-10-14 04:35:47,2024-02-15 23:07:34,2024-02-15 23:07:34,,,python;numpy;matrix;matrix-multiplication;elementwise-operations,Malintha,4818,2651924,registered,true,40035266,,CC BY-SA 4.0,,594,429,6,0,0,5,true,false,false,true,true,true,74,10,true,0.009,0.0003,3690,2016,10,4,Friday,false,true,false,false,false,false,false
26998223,What is the difference between contiguous and non-contiguous arrays?,"In the numpy manual about the reshape() function, it says
>>> a = np.zeros((10, 2))
# A transpose make the array non-contiguous
>>> b = a.T
# Taking a view makes it possible to modify the shape without modifying the
# initial object.
>>> c = b.view()
>>> c.shape = (20)
AttributeError: incompatible shape for a non-contiguous array
My questions are:
- What are continuous and noncontiguous arrays? Is it similar to the contiguous memory block in C like What is a contiguous memory block?
- Is there any performance difference between these two? When should we use one or the other?
- Why does transpose make the array non-contiguous?
- Why does
c.shape = (20) throws an error incompatible shape for a non-contiguous array?
Thanks for your answer!
",https://stackoverflow.com/questions/26998223/what-is-the-difference-between-contiguous-and-non-contiguous-arrays,185,137053.0,2.0,,,2014-11-18 15:45:08,2017-05-05 20:42:24,2017-05-23 12:26:14,,,python;arrays;numpy;memory,jdeng,3194,2825506,registered,true,26999092,,CC BY-SA 3.0,,1094,784,3,2,0,4,true,false,false,true,true,true,68,9,true,0.015,0.0013,4386,2014,11,15,Tuesday,false,true,false,false,false,false,false
9619199,best way to preserve numpy arrays on disk,"I am looking for a fast way to preserve large numpy arrays. I want to save them to the disk in a binary format, then read them back into memory relatively fastly. cPickle is not fast enough, unfortunately.
I found numpy.savez and numpy.load. But the weird thing is, numpy.load loads a npy file into ""memory-map"". That means regular manipulating of arrays really slow. For example, something like this would be really slow:
#!/usr/bin/python
import numpy as np;
import time;
from tempfile import TemporaryFile
n = 10000000;
a = np.arange(n)
b = np.arange(n) * 10
c = np.arange(n) * -0.5
file = TemporaryFile()
np.savez(file,a = a, b = b, c = c);
file.seek(0)
t = time.time()
z = np.load(file)
print ""loading time = "", time.time() - t
t = time.time()
aa = z['a']
bb = z['b']
cc = z['c']
print ""assigning time = "", time.time() - t;
more precisely, the first line will be really fast, but the remaining lines that assign the arrays to obj are ridiculously slow:
loading time = 0.000220775604248
assining time = 2.72940087318
Is there any better way of preserving numpy arrays? Ideally, I want to be able to store multiple arrays in one file.
",https://stackoverflow.com/questions/9619199/best-way-to-preserve-numpy-arrays-on-disk,182,168107.0,7.0,,,2012-03-08 14:28:12,2021-07-20 10:26:50,2016-02-01 16:00:30,,,python;numpy;pickle;binary-data;preserve,CuriousMind,15938,509205,registered,true,9619713,,CC BY-SA 3.0,,1433,1156,3,2,0,5,true,false,false,true,true,true,41,8,false,0.042,0.0011,5371,2012,3,14,Thursday,false,true,false,false,false,false,false
28439701,How to save and load numpy.array() data properly?,"I wonder, how to save and load numpy.array data properly. Currently I'm using the numpy.savetxt() method. For example, if I got an array markers, which looks like this:
![]()
I try to save it by the use of:
numpy.savetxt('markers.txt', markers)
In other script I try to open previously saved file:
markers = np.fromfile(""markers.txt"")
And that's what I get...
![]()
Saved data first looks like this:
0.000000000000000000e+00
0.000000000000000000e+00
0.000000000000000000e+00
0.000000000000000000e+00
0.000000000000000000e+00
0.000000000000000000e+00
0.000000000000000000e+00
0.000000000000000000e+00
0.000000000000000000e+00
0.000000000000000000e+00
But when I save just loaded data by the use of the same method, ie. numpy.savetxt() it looks like this:
1.398043286095131769e-76
1.398043286095288860e-76
1.396426376485745879e-76
1.398043286055061908e-76
1.398043286095288860e-76
1.182950697433698368e-76
1.398043275797188953e-76
1.398043286095288860e-76
1.210894289234927752e-99
1.398040649781712473e-76
What am I doing wrong? PS there are no other ""backstage"" operation which I perform. Just saving and loading, and that's what I get. Thank you in advance.
",https://stackoverflow.com/questions/28439701/how-to-save-and-load-numpy-array-data-properly,182,436905.0,4.0,,,2015-02-10 19:02:18,2021-09-18 10:55:28,2015-02-10 19:11:19,,,python;arrays;numpy,bluevoxel,5458,2652811,registered,true,28440249,,CC BY-SA 3.0,,1531,1164,8,0,2,3,true,false,false,true,true,true,49,8,true,0.009,0.0004,4302,2015,2,19,Tuesday,false,true,false,false,false,false,false
28190534,Windows Scipy Install: No Lapack/Blas Resources Found,"I am trying to install python and a series of packages onto a 64bit windows 7 desktop. I have installed Python 3.4, have Microsoft Visual Studio C++ installed, and have successfully installed numpy, pandas and a few others. I am getting the following error when trying to install scipy;
numpy.distutils.system_info.NotFoundError: no lapack/blas resources found
I am using pip install offline, the install command I am using is;
pip install --no-index --find-links=""S:\python\scipy 0.15.0"" scipy
I have read the posts on here about requiring a compiler which if I understand correctly is the VS C++ compiler. I am using the 2010 version as I am using Python 3.4. This has worked for other packages.
Do I have to use the window binary or is there a way I can get pip install to work?
Many thanks for the help
",https://stackoverflow.com/questions/28190534/windows-scipy-install-no-lapack-blas-resources-found,180,283626.0,17.0,,,2015-01-28 11:00:07,2024-04-12 06:54:08,2016-12-17 03:07:38,,,python;windows;python-3.x;numpy;pip,tjb305,2630,4402407,registered,true,29860484,,CC BY-SA 3.0,,898,815,2,0,0,5,true,false,false,true,true,true,53,7,false,0.06,0.0006,4315,2015,1,11,Wednesday,false,true,false,false,false,false,false
12200580,NumPy function for simultaneous max() and min(),"numpy.amax() will find the max value in an array, and numpy.amin() does the same for the min value. If I want to find both, max and min, I have to call both functions, which requires passing over the (very big) array twice, which seems slow.
Is there a function in the NumPy API that finds both, max and min, with only a single pass through the data?
",https://stackoverflow.com/questions/12200580/numpy-function-for-simultaneous-max-and-min,180,145718.0,15.0,,,2012-08-30 15:39:23,2026-09-30 20:53:47,2026-09-30 20:53:47,,,python;numpy,Stuart Berg,18534,162094,registered,true,80003041,,CC BY-SA 4.0,,618,351,2,2,0,2,true,false,false,true,true,true,47,7,false,0.103,0.0012,5196,2012,8,15,Thursday,false,true,false,false,false,false,false
42190783,What does "three dots" in Python mean when indexing what looks like a number?,"What is the meaning of x[...] below?
a = np.arange(6).reshape(2,3)
for x in np.nditer(a, op_flags=['readwrite']):
x[...] = 2 * x
",https://stackoverflow.com/questions/42190783/what-does-three-dots-in-python-mean-when-indexing-what-looks-like-a-number,180,157751.0,4.0,,,2017-02-12 17:24:28,2025-02-10 05:54:26,2019-10-21 21:22:19,,,python;numpy;iterator,Nan Hua,3804,4927088,registered,true,,,CC BY-SA 4.0,,179,135,2,0,0,3,false,false,false,true,true,true,87,14,true,0.025,0.0011,3569,2017,2,17,Sunday,true,true,false,false,false,false,false
6736590,Fast check for NaN in NumPy,"I'm looking for the fastest way to check for the occurrence of NaN (np.nan) in a NumPy array X. np.isnan(X) is out of the question, since it builds a boolean array of shape X.shape, which is potentially gigantic.
I tried np.nan in X, but that seems not to work because np.nan != np.nan. Is there a fast and memory-efficient way to do this at all?
(To those who would ask ""how gigantic"": I can't tell. This is input validation for library code.)
",https://stackoverflow.com/questions/6736590/fast-check-for-nan-in-numpy,179,281069.0,8.0,,,2011-07-18 17:10:05,2025-06-19 15:24:29,2020-06-06 10:25:22,,,python;performance;numpy;nan,Fred Foo,366168,166749,registered,true,6736970,,CC BY-SA 4.0,,546,447,6,0,0,4,true,false,false,true,true,true,27,6,false,0.028,0.0006,5605,2011,7,17,Monday,false,true,false,false,false,false,false
12645547,"Is there a difference between scipy.pi, numpy.pi, or math.pi?","In a project using SciPy and NumPy, when should one use scipy.pi vs numpy.pi vs just math.pi? Is there a difference between these values?
",https://stackoverflow.com/questions/12645547/is-there-a-difference-between-scipy-pi-numpy-pi-or-math-pi,179,247896.0,3.0,,,2012-09-28 18:36:58,2024-11-15 17:44:25,2023-09-08 18:07:25,,,python;numpy;math;scipy;pi,Douglas B. Staple,11046,1655144,registered,true,12645565,,CC BY-SA 4.0,,184,138,3,0,0,5,true,false,false,true,true,true,61,9,true,0.012,0.0007,5167,2012,9,18,Friday,false,true,false,false,false,false,false
9845292,A tool to convert MATLAB code to Python,"I have a bunch of MATLAB code from my MS thesis which I now want to convert to Python (using numpy/scipy and matplotlib) and distribute as open-source. I know the similarity between MATLAB and Python scientific libraries, and converting them manually will be not more than a fortnight (provided that I work towards it every day for some time). I was wondering if there was already any tool available which can do the conversion.
",https://stackoverflow.com/questions/9845292/a-tool-to-convert-matlab-code-to-python,176,352619.0,2.0,,,2012-03-23 19:22:09,2021-11-18 16:47:03,2013-11-24 10:15:24,2015-12-11 16:47:54,Not suitable for this site,python;matlab;numpy;matplotlib;scipy,Jack_of_All_Trades,11576,1128618,registered,true,17535694,,,,436,429,0,0,0,5,true,true,false,true,true,true,39,8,false,0.006,0.0005,5356,2012,3,19,Friday,false,true,false,false,false,false,false
10148818,Numpy how to iterate over columns of array?,"Suppose I have and m x n array. I want to pass each column of this array to a function to perform some operation on the entire column. How do I iterate over the columns of the array?
For example, I have a 4 x 3 array like
1 99 2
2 14 5
3 12 7
4 43 1
for column in array:
some_function(column)
where column would be ""1,2,3,4"" in the first iteration, ""99,14,12,43"" in the second, and ""2,5,7,1"" in the third.
",https://stackoverflow.com/questions/10148818/numpy-how-to-iterate-over-columns-of-array,175,216734.0,10.0,,,2012-04-13 21:55:04,2022-09-03 18:00:32,2015-05-02 16:06:34,,,python;loops;numpy,User,66807,155268,registered,true,10148855,,CC BY-SA 3.0,,464,419,1,0,0,3,true,false,false,true,true,true,43,8,true,0.046,0.0008,5335,2012,4,21,Friday,false,true,false,false,false,false,false
10593100,How do you do natural logs (e.g. "ln()") with numpy in Python?,"Using numpy, how can I do the following:
ln(x)
Is it equivalent to:
np.log(x)
I apologise for such a seemingly trivial question, but my understanding of the difference between log and ln is that ln is logspace e?
",https://stackoverflow.com/questions/10593100/how-do-you-do-natural-logs-e-g-ln-with-numpy-in-python,175,693378.0,6.0,,,2012-05-15 01:30:59,2021-12-01 20:44:41,2019-08-09 14:32:28,,,python;numpy;logarithm;natural-logarithm,user1220022,12375,1220022,registered,true,10593175,,CC BY-SA 4.0,2022-09-02 17:27:27,327,219,5,0,0,4,true,false,false,true,true,true,72,12,true,0.009,0.0003,5303,2012,5,1,Tuesday,false,true,false,false,false,false,false
4624970,Finding local maxima/minima with Numpy in a 1D numpy array,"Can you suggest a module function from numpy/scipy that can find local maxima/minima in a 1D numpy array? Obviously the simplest approach ever is to have a look at the nearest neighbours, but I would like to have an accepted solution that is part of the numpy distro.
",https://stackoverflow.com/questions/4624970/finding-local-maxima-minima-with-numpy-in-a-1d-numpy-array,174,406306.0,13.0,,,2011-01-07 11:22:09,2022-07-28 13:33:25,2011-01-07 11:41:12,,,python;numpy,Navi,8776,287727,registered,true,4625132,,CC BY-SA 2.5,2019-07-06 00:26:29,275,268,0,0,0,2,true,false,false,true,true,true,58,10,false,0.032,0.0004,5797,2011,1,11,Friday,false,true,false,false,false,false,false
21018654,"Strings in a DataFrame, but dtype is object","Why does Pandas tell me that I have objects, although every item in the selected column is a string — even after explicit conversion.
This is my DataFrame:
<class 'pandas.core.frame.DataFrame'>
Int64Index: 56992 entries, 0 to 56991
Data columns (total 7 columns):
id 56992 non-null values
attr1 56992 non-null values
attr2 56992 non-null values
attr3 56992 non-null values
attr4 56992 non-null values
attr5 56992 non-null values
attr6 56992 non-null values
dtypes: int64(2), object(5)
Five of them are dtype object. I explicitly convert those objects to strings:
for c in df.columns:
if df[c].dtype == object:
print ""convert "", df[c].name, "" to string""
df[c] = df[c].astype(str)
Then, df[""attr2""] still has dtype object, although type(df[""attr2""].ix[0] reveals str, which is correct.
Pandas distinguishes between int64 and float64 and object. What is the logic behind it when there is no dtype str? Why is a str covered by object?
",https://stackoverflow.com/questions/21018654/strings-in-a-dataframe-but-dtype-is-object,174,150355.0,4.0,,,2014-01-09 11:16:23,2021-06-14 17:26:20,2018-12-06 13:26:39,,,python;pandas;numpy;types;series,Xiphias,4814,2265734,registered,true,21020411,,CC BY-SA 4.0,2019-07-07 00:47:10,1257,1031,13,0,0,5,true,false,false,true,true,true,43,8,false,0.027,0.0012,4699,2014,1,11,Thursday,false,true,false,false,false,false,false
10016352,Convert numpy array to tuple,"Note: This is asking for the reverse of the usual tuple-to-array conversion.
I have to pass an argument to a (wrapped c++) function as a nested tuple. For example, the following works
X = MyFunction( ((2,2),(2,-2)) )
whereas the following do not
X = MyFunction( numpy.array(((2,2),(2,-2))) )
X = MyFunction( [[2,2],[2,-2]] )
Unfortunately, the argument I would like to use comes to me as a numpy array. That array always has dimensions 2xN for some N, which may be quite large.
Is there an easy way to convert that to a tuple? I know that I could just loop through, creating a new tuple, but would prefer if there's some nice access the numpy array provides.
If it's not possible to do this as nicely as I hope, what's the prettiest way to do it by looping, or whatever?
",https://stackoverflow.com/questions/10016352/convert-numpy-array-to-tuple,174,359173.0,7.0,,,2012-04-04 17:33:55,2026-05-26 14:19:45,,,,python;numpy,Mike,20543,1194883,registered,true,10016379,,CC BY-SA 3.0,,899,783,2,0,0,2,true,false,false,true,true,false,28,5,false,0.019,0.0005,5344,2012,4,17,Wednesday,false,true,false,false,false,false,false
911871,Detect if a NumPy array contains at least one non-numeric value?,"I need to write a function which will detect if the input contains at least one value which is non-numeric. If a non-numeric value is found I will raise an error (because the calculation should only return a numeric value). The number of dimensions of the input array is not known in advance - the function should give the correct value regardless of ndim. As an extra complication the input could be a single float or numpy.float64 or even something oddball like a zero-dimensional array.
The obvious way to solve this is to write a recursive function which iterates over every iterable object in the array until it finds a non-iterabe. It will apply the numpy.isnan() function over every non-iterable object. If at least one non-numeric value is found then the function will return False immediately. Otherwise if all the values in the iterable are numeric it will eventually return True.
That works just fine, but it's pretty slow and I expect that NumPy has a much better way to do it. What is an alternative that is faster and more numpyish?
Here's my mockup:
def contains_nan( myarray ):
""""""
@param myarray : An n-dimensional array or a single float
@type myarray : numpy.ndarray, numpy.array, float
@returns: bool
Returns true if myarray is numeric or only contains numeric values.
Returns false if at least one non-numeric value exists
Not-A-Number is given by the numpy.isnan() function.
""""""
return True
",https://stackoverflow.com/questions/911871/detect-if-a-numpy-array-contains-at-least-one-non-numeric-value,173,222355.0,5.0,,,2009-05-26 17:43:47,2021-06-01 12:20:23,2010-12-10 11:17:54,,,python;numpy,Salim Fadhley,23216,46411,registered,true,913499,,CC BY-SA 2.5,2019-07-07 00:48:33,1600,1456,3,1,0,2,true,false,false,true,true,true,64,11,true,0.022,0.0008,6388,2009,5,17,Tuesday,false,true,false,false,false,false,false
49037742,Why does it take ages to install Pandas on Alpine Linux,"I've noticed that installing Pandas and Numpy (it's dependency) in a Docker container using the base OS Alpine vs. CentOS or Debian takes much longer. I created a little test below to demonstrate the time difference. Aside from the few seconds Alpine takes to update and download the build dependencies to install Pandas and Numpy, why does the setup.py take around 70x more time than on Debian install?
Is there any way to speed up the install using Alpine as the base image or is there another base image of comparable size to Alpine that is better to use for packages like Pandas and Numpy?
Dockerfile.debian
FROM python:3.6.4-slim-jessie
RUN pip install pandas
Build Debian image with Pandas & Numpy:
[PandasDockerTest] time docker build -t debian-pandas -f Dockerfile.debian . --no-cache
Sending build context to Docker daemon 3.072kB
Step 1/2 : FROM python:3.6.4-slim-jessie
---> 43431c5410f3
Step 2/2 : RUN pip install pandas
---> Running in 2e4c030f8051
Collecting pandas
Downloading pandas-0.22.0-cp36-cp36m-manylinux1_x86_64.whl (26.2MB)
Collecting numpy>=1.9.0 (from pandas)
Downloading numpy-1.14.1-cp36-cp36m-manylinux1_x86_64.whl (12.2MB)
Collecting pytz>=2011k (from pandas)
Downloading pytz-2018.3-py2.py3-none-any.whl (509kB)
Collecting python-dateutil>=2 (from pandas)
Downloading python_dateutil-2.6.1-py2.py3-none-any.whl (194kB)
Collecting six>=1.5 (from python-dateutil>=2->pandas)
Downloading six-1.11.0-py2.py3-none-any.whl
Installing collected packages: numpy, pytz, six, python-dateutil, pandas
Successfully installed numpy-1.14.1 pandas-0.22.0 python-dateutil-2.6.1 pytz-2018.3 six-1.11.0
Removing intermediate container 2e4c030f8051
---> a71e1c314897
Successfully built a71e1c314897
Successfully tagged debian-pandas:latest
docker build -t debian-pandas -f Dockerfile.debian . --no-cache 0.07s user 0.06s system 0% cpu 13.605 total
Dockerfile.alpine
FROM python:3.6.4-alpine3.7
RUN apk --update add --no-cache g++
RUN pip install pandas
Build Alpine image with Pandas & Numpy:
[PandasDockerTest] time docker build -t alpine-pandas -f Dockerfile.alpine . --no-cache
Sending build context to Docker daemon 16.9kB
Step 1/3 : FROM python:3.6.4-alpine3.7
---> 4b00a94b6f26
Step 2/3 : RUN apk --update add --no-cache g++
---> Running in 4b0c32551e3f
fetch http://dl-cdn.alpinelinux.org/alpine/v3.7/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.7/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.7/community/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.7/community/x86_64/APKINDEX.tar.gz
(1/17) Upgrading musl (1.1.18-r2 -> 1.1.18-r3)
(2/17) Installing libgcc (6.4.0-r5)
(3/17) Installing libstdc++ (6.4.0-r5)
(4/17) Installing binutils-libs (2.28-r3)
(5/17) Installing binutils (2.28-r3)
(6/17) Installing gmp (6.1.2-r1)
(7/17) Installing isl (0.18-r0)
(8/17) Installing libgomp (6.4.0-r5)
(9/17) Installing libatomic (6.4.0-r5)
(10/17) Installing pkgconf (1.3.10-r0)
(11/17) Installing mpfr3 (3.1.5-r1)
(12/17) Installing mpc1 (1.0.3-r1)
(13/17) Installing gcc (6.4.0-r5)
(14/17) Installing musl-dev (1.1.18-r3)
(15/17) Installing libc-dev (0.7.1-r0)
(16/17) Installing g++ (6.4.0-r5)
(17/17) Upgrading musl-utils (1.1.18-r2 -> 1.1.18-r3)
Executing busybox-1.27.2-r7.trigger
OK: 184 MiB in 50 packages
Removing intermediate container 4b0c32551e3f
---> be26c3bf4e42
Step 3/3 : RUN pip install pandas
---> Running in 36f6024e5e2d
Collecting pandas
Downloading pandas-0.22.0.tar.gz (11.3MB)
Collecting python-dateutil>=2 (from pandas)
Downloading python_dateutil-2.6.1-py2.py3-none-any.whl (194kB)
Collecting pytz>=2011k (from pandas)
Downloading pytz-2018.3-py2.py3-none-any.whl (509kB)
Collecting numpy>=1.9.0 (from pandas)
Downloading numpy-1.14.1.zip (4.9MB)
Collecting six>=1.5 (from python-dateutil>=2->pandas)
Downloading six-1.11.0-py2.py3-none-any.whl
Building wheels for collected packages: pandas, numpy
Running setup.py bdist_wheel for pandas: started
Running setup.py bdist_wheel for pandas: still running...
Running setup.py bdist_wheel for pandas: still running...
Running setup.py bdist_wheel for pandas: still running...
Running setup.py bdist_wheel for pandas: still running...
Running setup.py bdist_wheel for pandas: still running...
Running setup.py bdist_wheel for pandas: still running...
Running setup.py bdist_wheel for pandas: finished with status 'done'
Stored in directory: /root/.cache/pip/wheels/e8/ed/46/0596b51014f3cc49259e52dff9824e1c6fe352048a2656fc92
Running setup.py bdist_wheel for numpy: started
Running setup.py bdist_wheel for numpy: still running...
Running setup.py bdist_wheel for numpy: still running...
Running setup.py bdist_wheel for numpy: still running...
Running setup.py bdist_wheel for numpy: finished with status 'done'
Stored in directory: /root/.cache/pip/wheels/9d/cd/e1/4d418b16ea662e512349ef193ed9d9ff473af715110798c984
Successfully built pandas numpy
Installing collected packages: six, python-dateutil, pytz, numpy, pandas
Successfully installed numpy-1.14.1 pandas-0.22.0 python-dateutil-2.6.1 pytz-2018.3 six-1.11.0
Removing intermediate container 36f6024e5e2d
---> a93c59e6a106
Successfully built a93c59e6a106
Successfully tagged alpine-pandas:latest
docker build -t alpine-pandas -f Dockerfile.alpine . --no-cache 0.54s user 0.33s system 0% cpu 16:08.47 total
",https://stackoverflow.com/questions/49037742/why-does-it-take-ages-to-install-pandas-on-alpine-linux,173,124239.0,12.0,,,2018-02-28 20:10:17,2023-03-06 07:39:29,,,,pandas;numpy;docker;alpine-linux,moku,4289,3089468,registered,true,49057289,,CC BY-SA 3.0,,5768,5562,4,0,0,4,true,false,false,true,true,false,55,11,false,0.097,0.0014,3188,2018,2,20,Wednesday,false,false,false,false,false,false,false
20528328,Numpy `logical_or` for more than two arguments,"Numpy's logical_or function takes no more than two arrays to compare. How can I find the union of more than two arrays? (The same question could be asked with regard to Numpy's logical_and and obtaining the intersection of more than two arrays.)
",https://stackoverflow.com/questions/20528328/numpy-logical-or-for-more-than-two-arguments,171,98819.0,10.0,,,2013-12-11 19:33:29,2025-05-23 12:53:13,2018-06-22 14:25:48,,,python;arrays;numpy,user3074893,1747,3074893,registered,true,,,CC BY-SA 4.0,,281,248,2,0,0,3,false,false,false,true,true,true,46,7,false,0.101,0.0017,4728,2013,12,19,Wednesday,false,true,false,false,false,false,false
22071987,Generate random array of floats between a range,"I haven't been able to find a function to generate an array of random floats of a given length between a certain range.
I've looked at Random sampling but no function seems to do what I need.
random.uniform comes close but it only returns a single element, not a specific number.
This is what I'm after:
ran_floats = some_function(low=0.5, high=13.3, size=50)
which would return an array of 50 random non-unique floats (ie: repetitions are allowed) uniformly distributed in the range [0.5, 13.3].
Is there such a function?
",https://stackoverflow.com/questions/22071987/generate-random-array-of-floats-between-a-range,171,362383.0,10.0,,,2014-02-27 14:50:23,2022-09-02 11:18:56,2019-03-23 16:18:22,,,python;arrays;random;numpy,Gabriel,43081,1391441,registered,true,22072276,,CC BY-SA 4.0,,794,530,2,2,0,4,true,false,false,true,true,true,47,8,false,0.028,0.0005,4650,2014,2,14,Thursday,false,true,false,false,false,false,false
29550414,How can I split a column of tuples in a Pandas dataframe?,"I have a Pandas dataframe (this is only a little piece)
>>> d1
y norm test y norm train len(y_train) len(y_test) \
0 64.904368 116.151232 1645 549
1 70.852681 112.639876 1645 549
SVR RBF \
0 (35.652207342877873, 22.95533537448393)
1 (39.563683797747622, 27.382483096332511)
LCV \
0 (19.365430594452338, 13.880062435173587)
1 (19.099614489458364, 14.018867136617146)
RIDGE CV \
0 (4.2907610988480362, 12.416745648065584)
1 (4.18864306788194, 12.980833914392477)
RF \
0 (9.9484841581029428, 16.46902345373697)
1 (10.139848213735391, 16.282141345406522)
GB \
0 (0.012816232716538605, 15.950164822266007)
1 (0.012814519804493328, 15.305745202851712)
ET DATA
0 (0.00034337162272515505, 16.284800366214057) j2m
1 (0.00024811554516431878, 15.556506191784194) j2m
>>>
I want to split all the columns that contain tuples. For example, I want to replace the column LCV with the columns LCV-a and LCV-b.
How can I do that?
",https://stackoverflow.com/questions/29550414/how-can-i-split-a-column-of-tuples-in-a-pandas-dataframe,170,167163.0,8.0,,,2015-04-09 22:50:38,2025-03-17 10:45:19,2021-03-19 14:17:37,,,python;numpy;pandas;dataframe;tuples,Donbeo,17767,2411173,registered,true,29550458,,CC BY-SA 4.0,,1339,1255,4,0,0,5,true,false,false,true,true,true,57,12,true,0.048,0.001,4244,2015,4,22,Thursday,false,true,false,false,false,false,false
40659212,"FutureWarning: elementwise comparison failed; returning scalar, but in the future will perform elementwise comparison","I am using Pandas 0.19.1 on Python 3. I am getting a warning on these lines of code. I'm trying to get a list that contains all the row numbers where string Peter is present at column Unnamed: 5.
df = pd.read_excel(xls_path)
myRows = df[df['Unnamed: 5'] == 'Peter'].index.tolist()
It produces a Warning:
""\Python36\lib\site-packages\pandas\core\ops.py:792: FutureWarning: elementwise
comparison failed; returning scalar, but in the future will perform
elementwise comparison
result = getattr(x, name)(y)""
What is this FutureWarning and should I ignore it since it seems to work.
",https://stackoverflow.com/questions/40659212/futurewarning-elementwise-comparison-failed-returning-scalar-but-in-the-futur,170,243694.0,12.0,,,2016-11-17 15:46:33,2022-11-03 18:29:16,2020-05-04 18:13:24,,,python;python-3.x;pandas;numpy;matplotlib,user411103,,,does_not_exist,true,,,CC BY-SA 4.0,,698,590,5,0,0,5,false,false,false,true,false,true,117,14,false,0.049,0.0007,3656,2016,11,15,Thursday,false,true,false,false,false,false,false
18395725,Test if numpy array contains only zeros,"We initialize a numpy array with zeros as bellow:
np.zeros((N,N+1))
But how do we check whether all elements in a given n*n numpy array matrix is zero.
The method just need to return a True if all the values are indeed zero.
",https://stackoverflow.com/questions/18395725/test-if-numpy-array-contains-only-zeros,169,244276.0,8.0,,,2013-08-23 05:55:33,2023-04-01 08:32:16,,,,python;numpy,IUnknown,10035,1483620,registered,true,18395906,,CC BY-SA 3.0,,270,228,1,0,0,2,true,false,false,true,true,false,39,7,false,0.033,0.0007,4838,2013,8,5,Friday,false,true,false,false,false,false,false
21011777,How can I remove Nan from list Python/NumPy,"I have a list that countain values, one of the values I got is 'nan'
countries= [nan, 'USA', 'UK', 'France']
I tried to remove it, but I everytime get an error
cleanedList = [x for x in countries if (math.isnan(x) == True)]
TypeError: a float is required
When I tried this one :
cleanedList = cities[np.logical_not(np.isnan(countries))]
cleanedList = cities[~np.isnan(countries)]
TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
",https://stackoverflow.com/questions/21011777/how-can-i-remove-nan-from-list-python-numpy,169,485533.0,16.0,,,2014-01-09 04:46:59,2024-01-15 04:57:03,2014-01-09 05:02:33,,,python;numpy,user3001937,2143,3001937,registered,true,,,CC BY-SA 3.0,2019-07-12 14:45:34,649,556,3,0,0,2,false,false,false,true,true,true,43,8,false,0.033,0.0003,4699,2014,1,4,Thursday,false,true,false,false,false,false,false
14847457,"How do I find the length (or dimensions, size) of a numpy matrix in python?","For a numpy matrix in python
from numpy import matrix
A = matrix([[1,2],[3,4]])
How can I find the length of a row (or column) of this matrix? Equivalently, how can I know the number of rows or columns?
So far, the only solution I've found is:
len(A)
len(A[:,1])
len(A[1,:])
Which returns 2, 2, and 1, respectively. From this I've gathered that len() will return the number of rows, so I can always us the transpose, len(A.T), for the number of columns. However, this feels unsatisfying and arbitrary, as when reading the line len(A), it isn't immediately obvious that this should return the number of rows. It actually works differently than len([1,2]) would for a 2D python array, as this would return 2.
So, is there a more intuitive way to find the size of a matrix, or is this the best I have?
",https://stackoverflow.com/questions/14847457/how-do-i-find-the-length-or-dimensions-size-of-a-numpy-matrix-in-python,169,664390.0,2.0,,,2013-02-13 06:07:24,2014-02-27 00:39:23,2014-02-04 01:45:08,2013-02-13 12:31:25,exact duplicate,python;matrix;numpy,Kyle Heuton,9896,1748679,registered,true,14847459,,,,942,807,6,0,0,3,true,true,false,true,true,true,75,15,true,0.003,0.0003,5029,2013,2,6,Wednesday,false,true,false,false,false,false,false
36783921,ValueError when checking if variable is None or numpy.array,"I'd like to check if variable is None or numpy.array. I've implemented check_a function to do this.
def check_a(a):
if not a:
print ""please initialize a""
a = None
check_a(a)
a = np.array([1,2])
check_a(a)
But, this code raises ValueError. What is the straight forward way?
ValueError Traceback (most recent call last)
<ipython-input-41-0201c81c185e> in <module>()
6 check_a(a)
7 a = np.array([1,2])
----> 8 check_a(a)
<ipython-input-41-0201c81c185e> in check_a(a)
1 def check_a(a):
----> 2 if not a:
3 print ""please initialize a""
4
5 a = None
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
",https://stackoverflow.com/questions/36783921/valueerror-when-checking-if-variable-is-none-or-numpy-array,169,226458.0,2.0,,,2016-04-22 02:48:01,2021-01-27 00:54:34,2017-10-03 01:47:24,,,python;numpy;is-empty,Light Yagmi,5305,590847,registered,true,36783987,,CC BY-SA 3.0,,846,771,3,0,0,3,true,false,false,true,true,true,59,9,false,0.009,0.0007,3865,2016,4,2,Friday,false,true,false,false,false,false,false
5284646,"Rank items in an array using Python/NumPy, without sorting array twice","I have an array of numbers and I'd like to create another array that represents the rank of each item in the first array. I'm using Python and NumPy.
For example:
array = [4,2,7,1]
ranks = [2,1,3,0]
Here's the best method I've come up with:
array = numpy.array([4,2,7,1])
temp = array.argsort()
ranks = numpy.arange(len(array))[temp.argsort()]
Are there any better/faster methods that avoid sorting the array twice?
",https://stackoverflow.com/questions/5284646/rank-items-in-an-array-using-python-numpy-without-sorting-array-twice,168,159337.0,11.0,,,2011-03-12 18:52:11,2022-06-19 16:11:50,2019-05-28 14:02:38,,,python;sorting;numpy,joshayers,3469,401818,registered,true,5284703,,CC BY-SA 4.0,,500,424,2,0,0,3,true,false,false,true,true,true,70,11,false,0.069,0.0011,5733,2011,3,18,Saturday,true,true,false,false,false,false,false
17901218,Numpy argsort - what is it doing?,"Why is numpy giving this result:
x = numpy.array([1.48,1.41,0.0,0.1])
print x.argsort()
>[2 3 1 0]
when I'd expect it to do this:
[3 2 0 1]
Clearly my understanding of the function is lacking.
",https://stackoverflow.com/questions/17901218/numpy-argsort-what-is-it-doing,168,118011.0,10.0,,,2013-07-27 18:44:55,2021-11-05 03:38:54,,,,python;numpy,user1276273,2013,1276273,registered,true,17901252,,CC BY-SA 3.0,2019-07-06 00:28:47,283,206,1,0,0,2,true,false,false,true,true,false,33,7,true,0.085,0.0014,4865,2013,7,18,Saturday,true,true,false,false,false,false,false
33346591,What is the difference between size and count in pandas?,"That is the difference between groupby(""x"").count and groupby(""x"").size in pandas ?
Does size just exclude nil ?
",https://stackoverflow.com/questions/33346591/what-is-the-difference-between-size-and-count-in-pandas,167,96001.0,6.0,,,2015-10-26 13:08:36,2025-07-22 12:44:04,2019-12-25 12:55:58,,,python;pandas;numpy;nan;difference,Donovan Thomson,2555,2432586,registered,true,33346694,,CC BY-SA 4.0,,154,114,2,0,0,5,true,false,false,true,true,true,56,10,true,0.062,0.0017,4044,2015,10,13,Monday,false,true,false,false,false,false,false
4150171,How to create a density plot,"In R I can create the desired output by doing:
data = c(rep(1.5, 7), rep(2.5, 2), rep(3.5, 8),
rep(4.5, 3), rep(5.5, 1), rep(6.5, 8))
plot(density(data, bw=0.5))
![]()
In python (with matplotlib) the closest I got was with a simple histogram:
import matplotlib.pyplot as plt
data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8
plt.hist(data, bins=6)
plt.show()
![]()
I also tried the normed=True parameter but couldn't get anything other than trying to fit a gaussian to the histogram.
My latest attempts were around scipy.stats and gaussian_kde, following examples on the web, but I've been unsuccessful so far.
",https://stackoverflow.com/questions/4150171/how-to-create-a-density-plot,166,404721.0,6.0,,,2010-11-10 23:39:59,2023-05-28 16:15:56,2023-05-28 16:15:56,,,python;numpy;matplotlib;scipy;kernel-density,unode,9721,125801,registered,true,4152016,,CC BY-SA 4.0,,989,635,4,1,2,5,true,false,false,true,true,true,28,6,false,0.015,0.0004,5855,2010,11,23,Wednesday,false,true,false,false,false,false,false
10540929,figure of imshow() is too small,"I'm trying to visualize a numpy array using imshow() since it's similar to imagesc() in Matlab.
imshow(random.rand(8, 90), interpolation='nearest')
The resulting figure is very small at the center of the grey window, while most of the space is unoccupied. How can I set the parameters to make the figure larger? I tried figsize=(xx,xx) and it's not what I want. Thanks!
![]()
",https://stackoverflow.com/questions/10540929/figure-of-imshow-is-too-small,166,380873.0,4.0,,,2012-05-10 19:31:35,2020-05-03 10:31:11,,,,python;numpy;matplotlib,Ruofeng,2350,1175710,registered,true,10546220,,CC BY-SA 3.0,,470,375,1,0,1,3,true,false,false,true,true,false,31,6,false,0.011,0.0004,5308,2012,5,19,Thursday,false,true,false,false,false,false,false
35723472,How to use sklearn fit_transform with pandas and return dataframe instead of numpy array?,"I want to apply scaling (using StandardScaler() from sklearn.preprocessing) to a pandas dataframe. The following code returns a numpy array, so I lose all the column names and indeces. This is not what I want.
features = df[[""col1"", ""col2"", ""col3"", ""col4""]]
autoscaler = StandardScaler()
features = autoscaler.fit_transform(features)
A ""solution"" I found online is:
features = features.apply(lambda x: autoscaler.fit_transform(x))
It appears to work, but leads to a deprecationwarning:
/usr/lib/python3.5/site-packages/sklearn/preprocessing/data.py:583:
DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17
and will raise ValueError in 0.19. Reshape your data either using
X.reshape(-1, 1) if your data has a single feature or X.reshape(1, -1)
if it contains a single sample.
I therefore tried:
features = features.apply(lambda x: autoscaler.fit_transform(x.reshape(-1, 1)))
But this gives:
Traceback (most recent call last): File ""./analyse.py"", line 91, in
features = features.apply(lambda x: autoscaler.fit_transform(x.reshape(-1, 1))) File
""/usr/lib/python3.5/site-packages/pandas/core/frame.py"", line 3972, in
apply
return self._apply_standard(f, axis, reduce=reduce) File ""/usr/lib/python3.5/site-packages/pandas/core/frame.py"", line 4081, in
_apply_standard
result = self._constructor(data=results, index=index) File ""/usr/lib/python3.5/site-packages/pandas/core/frame.py"", line 226, in
init
mgr = self._init_dict(data, index, columns, dtype=dtype) File ""/usr/lib/python3.5/site-packages/pandas/core/frame.py"", line 363, in
_init_dict
dtype=dtype) File ""/usr/lib/python3.5/site-packages/pandas/core/frame.py"", line 5163, in
_arrays_to_mgr
arrays = _homogenize(arrays, index, dtype) File ""/usr/lib/python3.5/site-packages/pandas/core/frame.py"", line 5477, in
_homogenize
raise_cast_failure=False) File ""/usr/lib/python3.5/site-packages/pandas/core/series.py"", line 2885,
in _sanitize_array
raise Exception('Data must be 1-dimensional') Exception: Data must be 1-dimensional
How do I apply scaling to the pandas dataframe, leaving the dataframe intact? Without copying the data if possible.
",https://stackoverflow.com/questions/35723472/how-to-use-sklearn-fit-transform-with-pandas-and-return-dataframe-instead-of-num,166,238138.0,12.0,,,2016-03-01 12:51:46,2024-12-30 08:11:37,2020-08-24 18:37:17,,,python;numpy;pandas;scikit-learn,Louic,2633,2635175,registered,true,,,CC BY-SA 4.0,,2418,2223,3,0,0,4,false,false,false,true,true,true,89,14,true,0.05,0.0007,3917,2016,3,12,Tuesday,false,true,false,false,false,false,false
7762948,how to load a color image file as a numpy array?,"I have a color image (abc.tiff). I want to load it as a numpy array. How can I do that?
I tried the following using OpenCV version 1:
im = cv.LoadImage("abc.tiff")
a = numpy.asarray(im)
It creates an array with no shape. I assume it is a iplimage object.
",https://stackoverflow.com/questions/7762948/how-to-load-a-color-image-file-as-a-numpy-array,165,518199.0,15.0,,,2011-10-14 04:13:07,2026-05-22 08:59:40,2026-05-22 08:59:40,,,python;numpy;image,Shan,19341,623300,registered,true,7776579,,CC BY-SA 4.0,2026-05-22 09:08:43,344,267,3,0,0,3,true,false,false,true,true,true,48,11,true,0.029,0.0003,5517,2011,10,4,Friday,false,true,false,false,false,false,false
16330831,Most efficient way to find mode in numpy array,"I have a 2D array containing integers (both positive or negative). Each row represents the values over time for a particular spatial site, whereas each column represents values for various spatial sites for a given time.
So if the array is like:
1 3 4 2 2 7
5 2 2 1 4 1
3 3 2 2 1 1
The result should be
1 3 2 2 2 1
Note that when there are multiple values for mode, any one (selected randomly) may be set as mode.
I can iterate over the columns finding mode one at a time but I was hoping numpy might have some in-built function to do that. Or if there is a trick to find that efficiently without looping.
",https://stackoverflow.com/questions/16330831/most-efficient-way-to-find-mode-in-numpy-array,165,388446.0,12.0,,,2013-05-02 05:20:53,2023-06-21 12:05:52,,,,python;numpy;2d;mode,Nik,5785,1306819,registered,true,16331189,,CC BY-SA 3.0,,697,614,2,0,0,4,true,false,false,true,true,false,46,9,false,0.031,0.0004,4951,2013,5,5,Thursday,false,true,false,false,false,false,false
55890813,How to fix 'Object arrays cannot be loaded when allow_pickle=False' for imdb.load_data() function?,"I'm trying to implement the binary classification example using the IMDb dataset in Google Colab. I have implemented this model before. But when I tried to do it again after a few days, it returned a value error: 'Object arrays cannot be loaded when allow_pickle=False' for the load_data() function.
I have already tried solving this, referring to an existing answer for a similar problem: How to fix 'Object arrays cannot be loaded when allow_pickle=False' in the sketch_rnn algorithm.
But it turns out that just adding an allow_pickle argument isn't sufficient.
My code:
from keras.datasets import imdb
(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000)
The error:
ValueError Traceback (most recent call last)
<ipython-input-1-2ab3902db485> in <module>()
1 from keras.datasets import imdb
----> 2 (train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000)
2 frames
/usr/local/lib/python3.6/dist-packages/keras/datasets/imdb.py in load_data(path, num_words, skip_top, maxlen, seed, start_char, oov_char, index_from, **kwargs)
57 file_hash='599dadb1135973df5b59232a0e9a887c')
58 with np.load(path) as f:
---> 59 x_train, labels_train = f['x_train'], f['y_train']
60 x_test, labels_test = f['x_test'], f['y_test']
61
/usr/local/lib/python3.6/dist-packages/numpy/lib/npyio.py in __getitem__(self, key)
260 return format.read_array(bytes,
261 allow_pickle=self.allow_pickle,
--> 262 pickle_kwargs=self.pickle_kwargs)
263 else:
264 return self.zip.read(key)
/usr/local/lib/python3.6/dist-packages/numpy/lib/format.py in read_array(fp, allow_pickle, pickle_kwargs)
690 # The array contained Python objects. We need to unpickle the data.
691 if not allow_pickle:
--> 692 raise ValueError("Object arrays cannot be loaded when "
693 "allow_pickle=False")
694 if pickle_kwargs is None:
ValueError: Object arrays cannot be loaded when allow_pickle=False
",https://stackoverflow.com/questions/55890813/how-to-fix-object-arrays-cannot-be-loaded-when-allow-pickle-false-for-imdb-loa,164,300662.0,27.0,,,2019-04-28 13:39:33,2022-07-05 05:00:51,2020-10-15 16:01:26,,,python;numpy;keras,Kanad,1831,11423025,registered,true,56243777,,CC BY-SA 4.0,,2555,2287,3,1,0,3,true,false,false,true,true,true,106,13,true,0.09,0.0005,2764,2019,4,13,Sunday,true,true,false,false,false,false,false
23435782,NumPy selecting specific column index per row by using a list of indexes,"I'm struggling to select the specific columns per row of a NumPy matrix.
Suppose I have the following matrix which I would call X:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
I also have a list of column indexes per every row which I would call Y:
[1, 0, 2]
I need to get the values:
[2]
[4]
[9]
Instead of a list with indexes Y, I can also produce a matrix with the same shape as X where every column is a bool / int in the range 0-1 value, indicating whether this is the required column.
[0, 1, 0]
[1, 0, 0]
[0, 0, 1]
I know this can be done with iterating over the array and selecting the column values I need. However, this will be executed frequently on big arrays of data and that's why it has to run as fast as it can.
I was thus wondering if there is a better solution?
",https://stackoverflow.com/questions/23435782/numpy-selecting-specific-column-index-per-row-by-using-a-list-of-indexes,164,80930.0,7.0,,,2014-05-02 19:44:12,2022-07-30 16:28:12,2020-12-10 18:25:58,,,python;numpy,Zee,2380,680913,registered,true,23435843,,CC BY-SA 4.0,2018-05-30 15:26:48,1034,768,12,0,0,2,true,false,false,true,true,true,72,13,false,0.086,0.002,4586,2014,5,19,Friday,false,true,false,false,false,false,false
19141432,python numpy machine epsilon,"I am trying to understand what is machine epsilon. According to the Wikipedia, it can be calculated as follows:
def machineEpsilon(func=float):
machine_epsilon = func(1)
while func(1)+func(machine_epsilon) != func(1):
machine_epsilon_last = machine_epsilon
machine_epsilon = func(machine_epsilon) / func(2)
return machine_epsilon_last
However, it is suitable only for double precision numbers. I am interested in modifying it to support also single precision numbers. I read that numpy can be used, particularly numpy.float32 class. Can anybody help with modifying the function?
",https://stackoverflow.com/questions/19141432/python-numpy-machine-epsilon,163,247487.0,3.0,,,2013-10-02 16:03:01,2024-03-10 00:19:35,,,,python;numpy;epsilon,Bob,10923,465137,registered,true,19141711,,CC BY-SA 3.0,,662,611,2,0,0,3,true,false,false,true,true,false,28,4,false,0.012,0.0007,4798,2013,10,16,Wednesday,false,true,false,false,false,false,false
5469286,How to get the index of a maximum element in a NumPy array along one axis,"I have a 2 dimensional NumPy array. I know how to get the maximum values over axes:
>>> a = array([[1,2,3],[4,3,1]])
>>> amax(a,axis=0)
array([4, 3, 3])
How can I get the indices of the maximum elements? I would like as output array([1,1,0]) instead.
",https://stackoverflow.com/questions/5469286/how-to-get-the-index-of-a-maximum-element-in-a-numpy-array-along-one-axis,163,351579.0,6.0,,,2011-03-29 07:35:46,2024-05-12 01:17:18,2020-10-21 12:07:04,,,python;numpy;max;indices,Peter Smit,29087,85514,registered,true,5469326,,CC BY-SA 4.0,,321,270,2,0,0,4,true,false,false,true,true,true,73,16,false,0.017,0.0005,5716,2011,3,7,Tuesday,false,true,false,false,false,false,false
10721915,Shared-memory objects in multiprocessing,"Suppose I have a large in memory numpy array, I have a function func that takes in this giant array as input (together with some other parameters). func with different parameters can be run in parallel. For example:
def func(arr, param):
# do stuff to arr, param
# build array arr
pool = Pool(processes = 6)
results = [pool.apply_async(func, [arr, param]) for param in all_params]
output = [res.get() for res in results]
If I use multiprocessing library, then that giant array will be copied for multiple times into different processes.
Is there a way to let different processes share the same array? This array object is read-only and will never be modified.
What's more complicated, if arr is not an array, but an arbitrary python object, is there a way to share it?
[EDITED]
I read the answer but I am still a bit confused. Since fork() is copy-on-write, we should not invoke any additional cost when spawning new processes in python multiprocessing library. But the following code suggests there is a huge overhead:
from multiprocessing import Pool, Manager
import numpy as np;
import time
def f(arr):
return len(arr)
t = time.time()
arr = np.arange(10000000)
print ""construct array = "", time.time() - t;
pool = Pool(processes = 6)
t = time.time()
res = pool.apply_async(f, [arr,])
res.get()
print ""multiprocessing overhead = "", time.time() - t;
output (and by the way, the cost increases as the size of the array increases, so I suspect there is still overhead related to memory copying):
construct array = 0.0178790092468
multiprocessing overhead = 0.252444982529
Why is there such huge overhead, if we didn't copy the array? And what part does the shared memory save me?
",https://stackoverflow.com/questions/10721915/shared-memory-objects-in-multiprocessing,162,183149.0,4.0,,,2012-05-23 14:20:21,2021-08-09 23:49:22,2017-08-11 14:58:24,,,python;numpy;parallel-processing;multiprocessing;shared-memory,CuriousMind,15938,509205,registered,true,10724332,,CC BY-SA 3.0,,1908,1715,5,0,0,5,true,false,false,true,true,true,40,4,false,0.022,0.0009,5295,2012,5,14,Wednesday,false,true,false,false,false,false,false
6967463,Iterating over a numpy array,"Is there a less verbose alternative to this:
for x in xrange(array.shape[0]):
for y in xrange(array.shape[1]):
do_stuff(x, y)
I came up with this:
for x, y in itertools.product(map(xrange, array.shape)):
do_stuff(x, y)
Which saves one indentation, but is still pretty ugly.
I'm hoping for something that looks like this pseudocode:
for x, y in array.indices:
do_stuff(x, y)
Does anything like that exist?
",https://stackoverflow.com/questions/6967463/iterating-over-a-numpy-array,161,245883.0,4.0,,,2011-08-06 14:27:03,2026-07-10 18:45:23,,,,python;numpy,Ram Rachum,90035,76701,registered,true,6967491,,CC BY-SA 3.0,2019-01-10 00:44:29,542,435,3,0,0,2,true,false,false,true,true,false,28,5,false,0.016,0.0007,5586,2011,8,14,Saturday,true,true,false,false,false,false,false
3302949,Best way to assert for numpy.array equality?,"I want to make some unit-tests for my app, and I need to compare two arrays. Since array.__eq__ returns a new array (so TestCase.assertEqual fails), what is the best way to assert for equality?
Currently I'm using
self.assertTrue((arr1 == arr2).all())
but I don't really like it
",https://stackoverflow.com/questions/3302949/best-way-to-assert-for-numpy-array-equality,161,116392.0,9.0,,,2010-07-21 19:18:48,2023-09-23 20:33:19,2018-11-08 20:17:53,,,python;unit-testing;numpy,maker,1639,315577,registered,true,,,CC BY-SA 4.0,2019-07-07 00:33:58,354,283,3,0,0,3,false,false,false,true,true,true,44,7,true,0.077,0.0014,5967,2010,7,19,Wednesday,false,true,false,false,false,false,false
11114225,Installing SciPy and NumPy using pip,"I'm trying to create required libraries in a package I'm distributing. It requires both the SciPy and NumPy libraries.
While developing, I installed both using
apt-get install scipy
which installed SciPy 0.9.0 and NumPy 1.5.1, and it worked fine.
I would like to do the same using pip install - in order to be able to specify dependencies in a setup.py of my own package.
The problem is, when I try:
pip install 'numpy==1.5.1'
it works fine.
But then
pip install 'scipy==0.9.0'
fails miserably, with
raise self.notfounderror(self.notfounderror.__doc__)
numpy.distutils.system_info.BlasNotFoundError:
Blas (http://www.netlib.org/blas/) libraries not found.
Directories to search for the libraries can be specified in the
numpy/distutils/site.cfg file (section [blas]) or by setting
the BLAS environment variable.
How do I get it to work?
",https://stackoverflow.com/questions/11114225/installing-scipy-and-numpy-using-pip,160,238763.0,8.0,,,2012-06-20 06:48:00,2020-05-10 23:39:33,2015-02-04 18:49:00,,,python;numpy;scipy;pip;apt,eran,15296,1724926,registered,true,14639949,,CC BY-SA 3.0,2016-10-27 07:12:58,1120,857,5,2,0,5,true,false,false,true,true,true,36,6,false,0.034,0.0007,5267,2012,6,6,Wednesday,false,true,false,false,false,false,false
11479064,Multiple linear regression in Python,"I can't seem to find any python libraries that do multiple regression. The only things I find only do simple regression. I need to regress my dependent variable (y) against several independent variables (x1, x2, x3, etc.).
For example, with this data:
print 'y x1 x2 x3 x4 x5 x6 x7'
for t in texts:
print ""{:>7.1f}{:>10.2f}{:>9.2f}{:>9.2f}{:>10.2f}{:>7.2f}{:>7.2f}{:>9.2f}"" /
.format(t.y,t.x1,t.x2,t.x3,t.x4,t.x5,t.x6,t.x7)
(output for above:)
y x1 x2 x3 x4 x5 x6 x7
-6.0 -4.95 -5.87 -0.76 14.73 4.02 0.20 0.45
-5.0 -4.55 -4.52 -0.71 13.74 4.47 0.16 0.50
-10.0 -10.96 -11.64 -0.98 15.49 4.18 0.19 0.53
-5.0 -1.08 -3.36 0.75 24.72 4.96 0.16 0.60
-8.0 -6.52 -7.45 -0.86 16.59 4.29 0.10 0.48
-3.0 -0.81 -2.36 -0.50 22.44 4.81 0.15 0.53
-6.0 -7.01 -7.33 -0.33 13.93 4.32 0.21 0.50
-8.0 -4.46 -7.65 -0.94 11.40 4.43 0.16 0.49
-8.0 -11.54 -10.03 -1.03 18.18 4.28 0.21 0.55
How would I regress these in python, to get the linear regression formula:
Y = a1x1 + a2x2 + a3x3 + a4x4 + a5x5 + a6x6 + +a7x7 + c
",https://stackoverflow.com/questions/11479064/multiple-linear-regression-in-python,160,267181.0,15.0,,,2012-07-13 22:14:40,2022-04-30 12:55:57,2016-09-25 19:11:00,,,python;numpy;statistics;scipy;linear-regression,Zach,4794,1406413,registered,true,11479279,,CC BY-SA 3.0,2019-07-06 00:16:44,1455,1347,2,0,0,5,true,false,false,true,true,true,36,5,false,0.056,0.0006,5244,2012,7,22,Friday,false,true,false,false,false,false,false
17534106,What is the difference between NaN and None?,"I am reading two columns of a csv file using pandas readcsv() and then assigning the values to a dictionary. The columns contain strings of numbers and letters. Occasionally there are cases where a cell is empty. In my opinion, the value read to that dictionary entry should be None but instead nan is assigned. Surely None is more descriptive of an empty cell as it has a null value, whereas nan just says that the value read is not a number.
Is my understanding correct, what IS the difference between None and nan? Why is nan assigned instead of None?
Also, my dictionary check for any empty cells has been using numpy.isnan():
for k, v in my_dict.iteritems():
if np.isnan(v):
But this gives me an error saying that I cannot use this check for v. I guess it is because an integer or float variable, not a string is meant to be used. If this is true, how can I check v for an ""empty cell""/nan case?
",https://stackoverflow.com/questions/17534106/what-is-the-difference-between-nan-and-none,160,191915.0,4.0,,,2013-07-08 19:06:17,2023-07-13 07:31:51,2014-10-02 01:09:33,,,python;numpy;pandas;nan,user1083734,5223,1083734,registered,true,17534682,,CC BY-SA 3.0,,1131,910,14,0,0,4,true,false,false,true,true,true,44,8,true,0.021,0.0008,4884,2013,7,19,Monday,false,true,false,false,false,false,false
9170838,surface plots in matplotlib,"I have a list of 3-tuples representing a set of points in 3D space. I want to plot a surface that covers all these points.
The plot_surface function in the mplot3d package requires as arguments X,Y and Z to be 2d arrays. Is plot_surface the right function to plot surface and how do I transform my data into the required format?
data = [(x1,y1,z1),(x2,y2,z2),.....,(xn,yn,zn)]
",https://stackoverflow.com/questions/9170838/surface-plots-in-matplotlib,159,463459.0,9.0,,,2012-02-07 04:02:45,2023-09-14 17:59:55,2023-09-14 17:59:55,,,python;numpy;matplotlib;surface;matplotlib-3d,Graddy,3018,657215,registered,true,9170879,,CC BY-SA 4.0,2018-04-02 06:34:16,457,380,4,0,0,5,true,false,false,true,true,true,27,4,false,0.019,0.0003,5401,2012,2,4,Tuesday,false,true,false,false,false,false,false
9876290,How do I compute derivative using Numpy?,"How do I calculate the derivative of a function, for example
y = x2+1
using numpy?
Let's say, I want the value of derivative at x = 5...
",https://stackoverflow.com/questions/9876290/how-do-i-compute-derivative-using-numpy,158,715059.0,9.0,,,2012-03-26 16:50:34,2022-02-02 00:06:26,2015-06-02 13:57:48,,,python;math;numpy,DrStrangeLove,11675,275477,registered,true,9877279,,CC BY-SA 3.0,2019-07-07 00:51:45,224,147,1,0,0,3,true,false,false,true,true,true,40,7,true,0.013,0.0002,5353,2012,3,16,Monday,false,true,false,false,false,false,false
25876640,subsampling every nth entry in a numpy array,"I am a beginner with numpy, and I am trying to extract some data from a long numpy array. What I need to do is start from a defined position in my array, and then subsample every nth data point from that position, until the end of my array.
basically if I had
a = [1,2,3,4,1,2,3,4,1,2,3,4....]
I want to subsample this to start at a[1] and then sample every fourth point from there, to produce something like
b = [2,2,2.....]
",https://stackoverflow.com/questions/25876640/subsampling-every-nth-entry-in-a-numpy-array,157,285905.0,2.0,,,2014-09-16 19:11:25,2022-08-22 20:33:53,2016-01-22 14:57:01,,,python;arrays;numpy,Rich Williams,1713,3357245,registered,true,,,CC BY-SA 3.0,,516,434,3,0,0,3,false,false,false,true,true,true,44,8,false,0.007,0.0005,4449,2014,9,19,Tuesday,false,true,false,false,false,false,false
52673285,Performance of Pandas apply vs np.vectorize to create new column from existing columns,"I am using Pandas dataframes and want to create a new column as a function of existing columns. I have not seen a good discussion of the speed difference between df.apply() and np.vectorize(), so I thought I would ask here.
The Pandas apply() function is slow. From what I measured (shown below in some experiments), using np.vectorize() is 25x faster (or more) than using the DataFrame function apply() , at least on my 2016 MacBook Pro. Is this an expected result, and why?
For example, suppose I have the following dataframe with N rows:
N = 10
A_list = np.random.randint(1, 100, N)
B_list = np.random.randint(1, 100, N)
df = pd.DataFrame({'A': A_list, 'B': B_list})
df.head()
# A B
# 0 78 50
# 1 23 91
# 2 55 62
# 3 82 64
# 4 99 80
Suppose further that I want to create a new column as a function of the two columns A and B. In the example below, I'll use a simple function divide(). To apply the function, I can use either df.apply() or np.vectorize():
def divide(a, b):
if b == 0:
return 0.0
return float(a)/b
df['result'] = df.apply(lambda row: divide(row['A'], row['B']), axis=1)
df['result2'] = np.vectorize(divide)(df['A'], df['B'])
df.head()
# A B result result2
# 0 78 50 1.560000 1.560000
# 1 23 91 0.252747 0.252747
# 2 55 62 0.887097 0.887097
# 3 82 64 1.281250 1.281250
# 4 99 80 1.237500 1.237500
If I increase N to real-world sizes like 1 million or more, then I observe that np.vectorize() is 25x faster or more than df.apply().
Below is some complete benchmarking code:
import pandas as pd
import numpy as np
import time
def divide(a, b):
if b == 0:
return 0.0
return float(a)/b
for N in [1000, 10000, 100000, 1000000, 10000000]:
print ''
A_list = np.random.randint(1, 100, N)
B_list = np.random.randint(1, 100, N)
df = pd.DataFrame({'A': A_list, 'B': B_list})
start_epoch_sec = int(time.time())
df['result'] = df.apply(lambda row: divide(row['A'], row['B']), axis=1)
end_epoch_sec = int(time.time())
result_apply = end_epoch_sec - start_epoch_sec
start_epoch_sec = int(time.time())
df['result2'] = np.vectorize(divide)(df['A'], df['B'])
end_epoch_sec = int(time.time())
result_vectorize = end_epoch_sec - start_epoch_sec
print 'N=%d, df.apply: %d sec, np.vectorize: %d sec' % \
(N, result_apply, result_vectorize)
# Make sure results from df.apply and np.vectorize match.
assert(df['result'].equals(df['result2']))
The results are shown below:
N=1000, df.apply: 0 sec, np.vectorize: 0 sec
N=10000, df.apply: 1 sec, np.vectorize: 0 sec
N=100000, df.apply: 2 sec, np.vectorize: 0 sec
N=1000000, df.apply: 24 sec, np.vectorize: 1 sec
N=10000000, df.apply: 262 sec, np.vectorize: 4 sec
If np.vectorize() is in general always faster than df.apply(), then why is np.vectorize() not mentioned more? I only ever see StackOverflow posts related to df.apply(), such as:
pandas create new column based on values from other columns
How do I use Pandas 'apply' function to multiple columns?
How to apply a function to two columns of Pandas dataframe
",https://stackoverflow.com/questions/52673285/performance-of-pandas-apply-vs-np-vectorize-to-create-new-column-from-existing-c,156,105359.0,2.0,,,2018-10-05 21:07:23,2020-09-17 19:54:46,2018-10-06 02:05:52,,,python;arrays;pandas;performance;numpy,stackoverflowuser2010,41665,4561314,registered,true,52674448,,CC BY-SA 4.0,,3931,3156,22,3,0,5,true,false,false,true,true,true,86,13,false,0.019,0.0015,2969,2018,10,21,Friday,false,true,false,false,false,false,false
11858472,String concatenation of two pandas columns,"I have a following DataFrame:
from pandas import *
df = DataFrame({'foo':['a','b','c'], 'bar':[1, 2, 3]})
It looks like this:
bar foo
0 1 a
1 2 b
2 3 c
Now I want to have something like:
bar
0 1 is a
1 2 is b
2 3 is c
How can I achieve this?
I tried the following:
df['foo'] = '%s is %s' % (df['bar'], df['foo'])
but it gives me a wrong result:
>>>print df.ix[0]
bar a
foo 0 a
1 b
2 c
Name: bar is 0 1
1 2
2
Name: 0
Sorry for a dumb question, but this one pandas: combine two columns in a DataFrame wasn't helpful for me.
",https://stackoverflow.com/questions/11858472/string-concatenation-of-two-pandas-columns,155,212903.0,11.0,,,2012-08-08 05:57:33,2022-10-22 03:55:43,2019-01-21 22:32:50,,,python;string;pandas;numpy;dataframe,nat,1601,1583620,registered,true,,,CC BY-SA 4.0,,925,649,6,1,0,5,false,false,false,true,true,true,42,6,false,0.052,0.0007,5218,2012,8,5,Wednesday,false,true,false,false,false,false,false
29206612,Difference between data type 'datetime64[ns]' and '<M8[ns]'?,"I have created a TimeSeries in pandas:
In [346]: from datetime import datetime
In [347]: dates = [datetime(2011, 1, 2), datetime(2011, 1, 5), datetime(2011, 1, 7),
.....: datetime(2011, 1, 8), datetime(2011, 1, 10), datetime(2011, 1, 12)]
In [348]: ts = Series(np.random.randn(6), index=dates)
In [349]: ts
Out[349]:
2011-01-02 0.690002
2011-01-05 1.001543
2011-01-07 -0.503087
2011-01-08 -0.622274
2011-01-10 -0.921169
2011-01-12 -0.726213
I'm following on the example from 'Python for Data Analysis' book.
In the following paragraph, the author checks the index type:
In [353]: ts.index.dtype
Out[353]: dtype('datetime64[ns]')
When I do exactly the same operation in the console I get:
ts.index.dtype
dtype('<M8[ns]')
What is the difference between two types 'datetime64[ns]' and '<M8[ns]' ?
And why do I get a different type?
",https://stackoverflow.com/questions/29206612/difference-between-data-type-datetime64ns-and-m8ns,155,192447.0,2.0,,,2015-03-23 09:17:10,2022-03-04 06:43:36,2015-03-23 09:47:52,,,python;numpy;pandas;datetime64,LLaP,2737,2758414,registered,true,29218694,,CC BY-SA 3.0,,1001,861,5,0,0,4,true,false,false,true,true,true,79,7,true,0.01,0.0008,4261,2015,3,9,Monday,false,true,false,false,false,false,false
35751306,python how to pad numpy array with zeros,"I want to know how I can pad a 2D numpy array with zeros using python 2.6.6 with numpy version 1.5.0. But these are my limitations. Therefore I cannot use np.pad. For example, I want to pad a with zeros such that its shape matches b. The reason why I want to do this is so I can do:
b-a
such that
>>> a
array([[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1.]])
>>> b
array([[ 3., 3., 3., 3., 3., 3.],
[ 3., 3., 3., 3., 3., 3.],
[ 3., 3., 3., 3., 3., 3.],
[ 3., 3., 3., 3., 3., 3.]])
>>> c
array([[1, 1, 1, 1, 1, 0],
[1, 1, 1, 1, 1, 0],
[1, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0]])
The only way I can think of doing this is appending, however this seems pretty ugly. is there a cleaner solution possibly using b.shape?
Edit,
Thank you to MSeiferts answer. I had to clean it up a bit, and this is what I got:
def pad(array, reference_shape, offsets):
"""
array: Array to be padded
reference_shape: tuple of size of ndarray to create
offsets: list of offsets (number of elements must be equal to the dimension of the array)
will throw a ValueError if offsets is too big and the reference_shape cannot handle the offsets
"""
# Create an array of zeros with the reference shape
result = np.zeros(reference_shape)
# Create a list of slices from offset to offset + shape in each dimension
insertHere = [slice(offsets[dim], offsets[dim] + array.shape[dim]) for dim in range(array.ndim)]
# Insert the array in the result at the specified offsets
result[insertHere] = array
return result
",https://stackoverflow.com/questions/35751306/python-how-to-pad-numpy-array-with-zeros,154,382036.0,8.0,,,2016-03-02 15:21:37,2024-06-05 08:11:21,2021-04-05 20:50:34,,,python;arrays;numpy;pad,user2015487,2205,2015487,registered,true,35751427,,CC BY-SA 4.0,,1848,1696,7,0,0,4,true,false,false,true,true,true,40,8,false,0.021,0.0004,3916,2016,3,15,Wednesday,false,true,false,false,false,false,false
19098104,Python OpenCV2 (cv2) wrapper to get image size?,"How to get the size of an image in cv2 wrapper in Python OpenCV (numpy). Is there a correct way to do that other than numpy.shape(). How can I get it in these format dimensions: (width, height) list?
",https://stackoverflow.com/questions/19098104/python-opencv2-cv2-wrapper-to-get-image-size,154,452307.0,3.0,,,2013-09-30 15:29:04,2025-03-16 15:23:34,2020-02-04 07:04:45,,,python;image;opencv;numpy,xercool,4677,1977306,registered,true,19098258,,CC BY-SA 4.0,,233,200,2,0,0,4,true,false,false,true,true,true,47,8,true,0.007,0.0003,4800,2013,9,15,Monday,false,true,false,false,false,false,false
22927181,Selecting specific rows and columns from NumPy array,"I've been going crazy trying to figure out what stupid thing I'm doing wrong here.
I'm using NumPy, and I have specific row indices and specific column indices that I want to select from. Here's the gist of my problem:
import numpy as np
a = np.arange(20).reshape((5,4))
# array([[ 0, 1, 2, 3],
# [ 4, 5, 6, 7],
# [ 8, 9, 10, 11],
# [12, 13, 14, 15],
# [16, 17, 18, 19]])
# If I select certain rows, it works
print a[[0, 1, 3], :]
# array([[ 0, 1, 2, 3],
# [ 4, 5, 6, 7],
# [12, 13, 14, 15]])
# If I select certain rows and a single column, it works
print a[[0, 1, 3], 2]
# array([ 2, 6, 14])
# But if I select certain rows AND certain columns, it fails
print a[[0,1,3], [0,2]]
# Traceback (most recent call last):
# File ""<stdin>"", line 1, in <module>
# ValueError: shape mismatch: objects cannot be broadcast to a single shape
Why is this happening? Surely I should be able to select the 1st, 2nd, and 4th rows, and 1st and 3rd columns? The result I'm expecting is:
a[[0,1,3], [0,2]] => [[0, 2],
[4, 6],
[12, 14]]
",https://stackoverflow.com/questions/22927181/selecting-specific-rows-and-columns-from-numpy-array,154,326415.0,4.0,,,2014-04-08 03:52:52,2024-02-20 17:58:04,2018-05-25 10:24:26,,,python;arrays;numpy;multidimensional-array;numpy-slicing,Mike C,2059,534080,registered,true,22927889,,CC BY-SA 4.0,2019-07-07 20:08:56,1214,1145,2,0,0,5,true,false,false,true,true,true,52,8,false,0.012,0.0005,4610,2014,4,3,Tuesday,false,true,false,false,false,false,false
38013778,Is there any numpy group by function?,"Is there any function in numpy to group this array down below by the first column?
I couldn't find any good answer over the internet..
>>> a
array([[ 1, 275],
[ 1, 441],
[ 1, 494],
[ 1, 593],
[ 2, 679],
[ 2, 533],
[ 2, 686],
[ 3, 559],
[ 3, 219],
[ 3, 455],
[ 4, 605],
[ 4, 468],
[ 4, 692],
[ 4, 613]])
Wanted output:
array([[[275, 441, 494, 593]],
[[679, 533, 686]],
[[559, 219, 455]],
[[605, 468, 692, 613]]], dtype=object)
",https://stackoverflow.com/questions/38013778/is-there-any-numpy-group-by-function,153,167604.0,12.0,,,2016-06-24 12:45:15,2023-10-31 10:13:53,2016-08-31 16:36:51,,,python;arrays;numpy,John Dow,1539,6508887,registered,true,,,CC BY-SA 3.0,,636,567,2,0,0,3,false,false,false,true,true,true,37,7,true,0.072,0.0009,3802,2016,6,12,Friday,false,true,false,false,false,false,false
3685265,How to write a multidimensional array to a text file?,"In another question, other users offered some help if I could supply the array I was having trouble with. However, I even fail at a basic I/O task, such as writing an array to a file.
Can anyone explain what kind of loop I would need to write a 4x11x14 numpy array to file?
This array consist of four 11 x 14 arrays, so I should format it with a nice newline, to make the reading of the file easier on others.
Edit: So I've tried the numpy.savetxt function. Strangely, it gives the following error:
TypeError: float argument required, not numpy.ndarray
I assume that this is because the function doesn't work with multidimensional arrays? Any solutions as I would like them within one file?
",https://stackoverflow.com/questions/3685265/how-to-write-a-multidimensional-array-to-a-text-file,152,361197.0,14.0,,,2010-09-10 14:13:21,2023-08-28 14:58:39,2010-09-11 14:30:43,,,python;file-io;numpy,Ivo Flipse,10282,77595,registered,true,3685339,,CC BY-SA 2.5,2019-07-06 00:29:17,790,697,1,0,0,3,true,false,false,true,true,true,53,10,true,0.039,0.0004,5916,2010,9,14,Friday,false,true,false,false,false,false,false
12569452,How to identify numpy types in python?,"How can one reliably determine if an object has a numpy type?
I realize that this question goes against the philosophy of duck typing, but idea is to make sure a function (which uses scipy and numpy) never returns a numpy type unless it is called with a numpy type. This comes up in the solution to another question, but I think the general problem of determining if an object has a numpy type is far enough away from that original question that they should be separated.
",https://stackoverflow.com/questions/12569452/how-to-identify-numpy-types-in-python,151,218768.0,6.0,,,2012-09-24 16:49:46,2019-02-05 02:33:31,2017-05-23 12:34:47,,,python;numpy;duck-typing;dynamic-typing,Douglas B. Staple,11046,1655144,registered,true,12570040,,CC BY-SA 3.0,,591,474,0,1,0,4,true,false,false,true,true,true,38,7,true,0.027,0.0007,5171,2012,9,16,Monday,false,true,false,false,false,false,false
11124578,Automatically import modules when entering the python or ipython interpreter,"I find myself typing import numpy as np almost every single time I fire up the python interpreter. How do I set up the python or ipython interpreter so that numpy is automatically imported?
",https://stackoverflow.com/questions/11124578/automatically-import-modules-when-entering-the-python-or-ipython-interpreter,151,55511.0,9.0,,,2012-06-20 17:04:51,2024-07-17 07:46:23,2015-09-12 13:27:45,,,python;numpy;ipython,user545424,16331,545424,registered,true,11124610,,CC BY-SA 3.0,,210,190,1,0,0,3,true,false,false,true,true,true,76,10,false,0.162,0.0027,5267,2012,6,17,Wednesday,false,true,false,false,false,false,false
809362,How to calculate cumulative normal distribution?,"I am looking for a function in Numpy or Scipy (or any rigorous Python library) that will give me the cumulative normal distribution function in Python.
",https://stackoverflow.com/questions/809362/how-to-calculate-cumulative-normal-distribution,150,274629.0,8.0,,,2009-04-30 22:13:11,2025-01-29 21:07:24,2019-10-13 19:59:58,,,python;numpy;scipy;statistics,toma,,,does_not_exist,true,,,CC BY-SA 4.0,,159,152,0,0,0,4,false,false,false,true,false,true,48,6,true,0.029,0.0005,6414,2009,4,22,Thursday,false,true,false,false,false,false,false
6163334,binning data in python with scipy/numpy,"is there a more efficient way to take an average of an array in prespecified bins? for example, i have an array of numbers and an array corresponding to bin start and end positions in that array, and I want to just take the mean in those bins? I have code that does it below but i am wondering how it can be cut down and improved. thanks.
from scipy import *
from numpy import *
def get_bin_mean(a, b_start, b_end):
ind_upper = nonzero(a >= b_start)[0]
a_upper = a[ind_upper]
a_range = a_upper[nonzero(a_upper < b_end)[0]]
mean_val = mean(a_range)
return mean_val
data = rand(100)
bins = linspace(0, 1, 10)
binned_data = []
n = 0
for n in range(0, len(bins)-1):
b_start = bins[n]
b_end = bins[n+1]
binned_data.append(get_bin_mean(data, b_start, b_end))
print binned_data
",https://stackoverflow.com/questions/6163334/binning-data-in-python-with-scipy-numpy,150,288117.0,7.0,,,2011-05-28 17:43:00,2025-08-21 23:36:38,,,,python;numpy;scipy;scientific-computing,user248237,,,does_not_exist,true,6163403,,CC BY-SA 3.0,,847,816,1,0,0,4,true,false,false,true,false,false,39,6,false,0.024,0.0005,5656,2011,5,17,Saturday,true,true,false,false,false,false,false
12877189,float64 with pandas to_csv,"I'm reading a CSV with float numbers like this:
Bob,0.085
Alice,0.005
And import into a dataframe, and write this dataframe to a new place
df = pd.read_csv(orig)
df.to_csv(pandasfile)
Now this pandasfile has:
Bob,0.085000000000000006
Alice,0.0050000000000000001
What happen? maybe I have to cast to a different type like float32 or something?
Im using pandas 0.9.0 and numpy 1.6.2.
",https://stackoverflow.com/questions/12877189/float64-with-pandas-to-csv,149,162423.0,3.0,,,2012-10-13 21:31:34,2022-05-02 13:11:17,2012-10-15 10:14:28,,,python;numpy;pandas,avances123,2364,472866,registered,true,12882439,,CC BY-SA 3.0,,547,393,4,0,0,3,true,false,false,true,true,true,26,4,false,0.018,0.0009,5152,2012,10,21,Saturday,true,true,false,false,false,false,false
18689512,Efficiently checking if arbitrary object is NaN in Python / numpy / pandas?,"My numpy arrays use np.nan to designate missing values. As I iterate over the data set, I need to detect such missing values and handle them in special ways.
Naively I used numpy.isnan(val), which works well unless val isn't among the subset of types supported by numpy.isnan(). For example, missing data can occur in string fields, in which case I get:
>>> np.isnan('some_string')
Traceback (most recent call last):
File ""<stdin>"", line 1, in <module>
TypeError: Not implemented for this type
Other than writing an expensive wrapper that catches the exception and returns False, is there a way to handle this elegantly and efficiently?
",https://stackoverflow.com/questions/18689512/efficiently-checking-if-arbitrary-object-is-nan-in-python-numpy-pandas,149,258363.0,3.0,,,2013-09-08 23:05:11,2021-02-19 21:40:59,2013-09-08 23:11:07,,,python;numpy;pandas,Dun Peal,18059,916907,registered,true,18689712,,CC BY-SA 3.0,,774,664,6,0,0,3,true,false,false,true,true,true,75,13,true,0.012,0.0006,4822,2013,9,23,Sunday,true,true,false,false,false,false,false
33356442,When should I use hstack/vstack vs append vs concatenate vs column_stack?,"Simple question: what is the advantage of each of these methods. It seems that given the right parameters (and ndarray shapes) they all work seemingly equivalently. Do some work in place? Have better performance? Which functions should I use when?
",https://stackoverflow.com/questions/33356442/when-should-i-use-hstack-vstack-vs-append-vs-concatenate-vs-column-stack,148,112191.0,5.0,,,2015-10-26 22:02:44,2024-12-20 03:15:39,2020-12-23 00:41:56,,,python;numpy,Stefan Sullivan,1737,5340003,registered,true,33357435,,CC BY-SA 4.0,,255,248,0,0,0,2,true,false,false,true,true,true,73,11,true,0.045,0.0013,4044,2015,10,22,Monday,false,true,false,false,false,false,false
12987624,"Confusion between numpy, scipy, matplotlib and pylab","Numpy, scipy, matplotlib, and pylab are common terms among they who use python for scientific computation.
I just learn a bit about pylab, and I got confused.
Whenever I want to import numpy, I can always do:
import numpy as np
I just consider, that once I do
from pylab import *
the numpy will be imported as well (with np alias). So basically the second one does more things compared to the first one.
There are few things I want to ask:
- Is it right that pylab is just a wrapper for numpy, scipy and matplotlib?
- As np is the numpy alias in pylab, what is the scipy and matplotlib alias in pylab? (as far as I know, plt is alias of matplotlib.pyplot, but I don't know the alias for the matplotlib itself)
",https://stackoverflow.com/questions/12987624/confusion-between-numpy-scipy-matplotlib-and-pylab,148,85148.0,3.0,,,2012-10-20 10:44:33,2019-09-15 01:06:37,2016-12-14 18:58:16,,,python;numpy;matplotlib;scipy,goFrendiAsgard,4104,755319,registered,true,12987916,,CC BY-SA 3.0,,840,717,3,0,0,4,true,false,false,true,true,true,52,7,false,0.035,0.0017,5145,2012,10,10,Saturday,true,true,false,false,false,false,false
11686720,Is there a numpy builtin to reject outliers from a list,"Is there a numpy builtin to do something like the following? That is, take a list d and return a list filtered_d with any outlying elements removed based on some assumed distribution of the points in d.
import numpy as np
def reject_outliers(data):
m = 2
u = np.mean(data)
s = np.std(data)
filtered = [e for e in data if (u - 2 * s < e < u + 2 * s)]
return filtered
>>> d = [2,4,5,1,6,5,40]
>>> filtered_d = reject_outliers(d)
>>> print filtered_d
[2,4,5,1,6,5]
I say 'something like' because the function might allow for varying distributions (poisson, gaussian, etc.) and varying outlier thresholds within those distributions (like the m I've used here).
",https://stackoverflow.com/questions/11686720/is-there-a-numpy-builtin-to-reject-outliers-from-a-list,147,205640.0,15.0,,,2012-07-27 11:19:17,2023-05-22 14:30:58,,,,python;numpy,aaren,5805,1157089,registered,true,11686764,,CC BY-SA 3.0,,805,715,5,0,0,2,true,false,false,true,true,false,55,11,false,0.073,0.0007,5230,2012,7,11,Friday,false,true,false,false,false,false,false
7569553,"Working with TIFFs (import, export) in Python using numpy","I need a python method to open and import TIFF images into numpy arrays so I can analyze and modify the pixel data and then save them as TIFFs again. (They are basically light intensity maps in greyscale, representing the respective values per pixel)
I couldn't find any documentation on PIL methods concerning TIFF. I tried to figure it out, but only got ""bad mode"" or ""file type not supported"" errors.
What do I need to use here?
",https://stackoverflow.com/questions/7569553/working-with-tiffs-import-export-in-python-using-numpy,146,453743.0,12.0,,,2011-09-27 13:01:27,2023-04-18 16:45:36,2020-02-14 20:26:44,,,python;numpy;python-imaging-library;tiff,Jakob,2025,874113,registered,true,7572079,,CC BY-SA 4.0,,455,434,0,0,0,4,true,false,false,true,true,true,57,9,false,0.026,0.0003,5534,2011,9,13,Tuesday,false,true,false,false,false,false,false
3890621,how does multiplication differ for NumPy Matrix vs Array classes?,"The numpy docs recommend using array instead of matrix for working with matrices. However, unlike octave (which I was using till recently), * doesn't perform matrix multiplication, you need to use the function matrixmultipy(). I feel this makes the code very unreadable.
Does anybody share my views, and has found a solution?
",https://stackoverflow.com/questions/3890621/how-does-multiplication-differ-for-numpy-matrix-vs-array-classes,146,255309.0,8.0,,,2010-10-08 12:50:47,2019-04-11 03:55:25,2014-12-13 07:24:22,,,python;arrays;numpy;matrix;matrix-multiplication,elexhobby,2678,470229,registered,true,25476540,,CC BY-SA 3.0,,341,327,0,0,0,5,true,false,false,true,true,true,65,10,true,0.031,0.0006,5888,2010,10,12,Friday,false,true,false,false,false,false,false
893657,How do I calculate r-squared using Python and Numpy?,"I'm using Python and Numpy to calculate a best fit polynomial of arbitrary degree. I pass a list of x values, y values, and the degree of the polynomial I want to fit (linear, quadratic, etc.).
This much works, but I also want to calculate r (coefficient of correlation) and r-squared(coefficient of determination). I am comparing my results with Excel's best-fit trendline capability, and the r-squared value it calculates. Using this, I know I am calculating r-squared correctly for linear best-fit (degree equals 1). However, my function does not work for polynomials with degree greater than 1.
Excel is able to do this. How do I calculate r-squared for higher-order polynomials using Numpy?
Here's my function:
import numpy
# Polynomial Regression
def polyfit(x, y, degree):
results = {}
coeffs = numpy.polyfit(x, y, degree)
# Polynomial Coefficients
results['polynomial'] = coeffs.tolist()
correlation = numpy.corrcoef(x, y)[0,1]
# r
results['correlation'] = correlation
# r-squared
results['determination'] = correlation**2
return results
",https://stackoverflow.com/questions/893657/how-do-i-calculate-r-squared-using-python-and-numpy,145,506364.0,13.0,,,2009-05-21 15:55:54,2024-02-17 22:06:16,2009-05-22 17:40:30,,,python;math;statistics;numpy;curve-fitting,Travis Beale,5708,103091,registered,true,895063,,CC BY-SA 2.5,2019-07-07 00:49:24,1156,1104,1,0,0,5,true,false,false,true,true,true,52,9,true,0.026,0.0003,6393,2009,5,15,Thursday,false,true,false,false,false,false,false
57237352,What does "unsqueeze" do in Pytorch?,"The PyTorch documentation says:
Returns a new tensor with a dimension of size one inserted at the specified position. [...]
>>> x = torch.tensor([1, 2, 3, 4])
>>> torch.unsqueeze(x, 0)
tensor([[ 1, 2, 3, 4]])
>>> torch.unsqueeze(x, 1)
tensor([[ 1],
[ 2],
[ 3],
[ 4]])
",https://stackoverflow.com/questions/57237352/what-does-unsqueeze-do-in-pytorch,145,160032.0,7.0,,,2019-07-28 01:43:43,2025-05-15 11:01:35,2024-04-16 09:54:29,,,python;numpy;machine-learning;deep-learning;pytorch,user6549804,,,does_not_exist,true,57237378,,CC BY-SA 4.0,,482,325,1,1,0,5,true,false,false,true,false,true,46,6,true,0.044,0.0009,2673,2019,7,1,Sunday,true,true,false,false,false,false,false
7894791,Use numpy array in shared memory for multiprocessing,"I would like to use a numpy array in shared memory for use with the multiprocessing module. The difficulty is using it like a numpy array, and not just as a ctypes array.
from multiprocessing import Process, Array
import scipy
def f(a):
a[0] = -a[0]
if __name__ == '__main__':
# Create the array
N = int(10)
unshared_arr = scipy.rand(N)
arr = Array('d', unshared_arr)
print ""Originally, the first two elements of arr = %s""%(arr[:2])
# Create, start, and finish the child processes
p = Process(target=f, args=(arr,))
p.start()
p.join()
# Printing out the changed values
print ""Now, the first two elements of arr = %s""%arr[:2]
This produces output such as:
Originally, the first two elements of arr = [0.3518653236697369, 0.517794725524976]
Now, the first two elements of arr = [-0.3518653236697369, 0.517794725524976]
The array can be accessed in a ctypes manner, e.g. arr[i] makes sense. However, it is not a numpy array, and I cannot perform operations such as -1*arr, or arr.sum(). I suppose a solution would be to convert the ctypes array into a numpy array. However (besides not being able to make this work), I don't believe it would be shared anymore.
It seems there would be a standard solution to what has to be a common problem.
",https://stackoverflow.com/questions/7894791/use-numpy-array-in-shared-memory-for-multiprocessing,145,116075.0,6.0,,,2011-10-25 19:34:31,2023-09-21 00:13:02,2018-01-11 07:34:27,,,python;numpy;multiprocessing;shared,Ian Langmore,2959,993872,registered,true,,,CC BY-SA 3.0,,1416,1301,5,0,0,4,false,false,false,true,true,true,52,8,false,0.052,0.0012,5506,2011,10,19,Tuesday,false,true,false,false,false,false,false
12525722,Normalize data in pandas,"Suppose I have a pandas data frame df:
I want to calculate the column wise mean of a data frame.
This is easy:
df.apply(average)
then the column wise range max(col) - min(col). This is easy again:
df.apply(max) - df.apply(min)
Now for each element I want to subtract its column's mean and divide by its column's range. I am not sure how to do that
Any help/pointers are much appreciated.
",https://stackoverflow.com/questions/12525722/normalize-data-in-pandas,144,268384.0,5.0,,,2012-09-21 07:04:23,2019-08-21 23:29:58,2017-12-04 03:46:39,,,python;pandas;numpy,jason,3522,218900,registered,true,12525836,,CC BY-SA 3.0,2019-07-03 22:19:59,505,402,3,0,0,3,true,false,false,true,true,true,24,4,false,0.019,0.0005,5174,2012,9,7,Friday,false,true,false,false,false,false,false
8505651,Non-repetitive random number in numpy,"How can I generate non-repetitive random numbers in numpy?
list = np.random.random_integers(20,size=(10))
",https://stackoverflow.com/questions/8505651/non-repetitive-random-number-in-numpy,144,184501.0,6.0,,,2011-12-14 13:56:15,2022-01-17 13:17:13,2019-12-06 23:02:15,,,random;numpy;numbers;non-repetitive,Academia,4144,1038382,registered,true,8505754,,CC BY-SA 4.0,,139,108,1,0,0,4,true,false,false,true,true,true,37,5,false,0.033,0.0008,5456,2011,12,13,Wednesday,false,false,false,false,false,false,false
22388519,Problems with pip install numpy - RuntimeError: Broken toolchain: cannot link a simple C program,"I'm trying to install numpy (and scipy and matplotlib) into a virturalenv.
I keep getting these errors though:
RuntimeError: Broken toolchain: cannot link a simple C program
----------------------------------------
Cleaning up...
Command python setup.py egg_info failed with error code 1
I have the command line tools for xcode installed
$ which gcc
/usr/bin/gcc
$ which cc
/usr/bin/cc
I'm on Mac OSX 10.9
Using a brew installed python
Edit
Yes, trying to install with pip.
The whole traceback is huge (>400 lines)
Here is a section of it:
C compiler: cc -fno-strict-aliasing -fno-common -dynamic -arch x86_64 -arch i386 -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -mno-fused-madd -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -arch x86_64 -arch i386 -pipe
compile options: '-Inumpy/core/src/private -Inumpy/core/src -Inumpy/core -Inumpy/core/src/npymath -Inumpy/core/src/multiarray -Inumpy/core/src/umath -Inumpy/core/src/npysort -Inumpy/core/include -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c'
cc: _configtest.c
clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command-line-argument-hard-error-in-future]
clang: note: this will be a hard error (cannot be downgraded to a warning) in the future
clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command-line-argument-hard-error-in-future]
clang: note: this will be a hard error (cannot be downgraded to a warning) in the future
failure.
removing: _configtest.c _configtest.o
Traceback (most recent call last):
File ""<string>"", line 17, in <module>
File ""/Users/bdhammel/Documents/research_programming/julia_env/build/numpy/setup.py"", line 192, in <module>
setup_package()
File ""/Users/bdhammel/Documents/research_programming/julia_env/build/numpy/setup.py"", line 185, in setup_package
configuration=configuration )
File ""/Users/bdhammel/Documents/research_programming/julia_env/build/numpy/numpy/distutils/core.py"", line 169, in setup
return old_setup(**new_attr)
File ""/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/core.py"", line 152, in setup
dist.run_commands()
File ""/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/dist.py"", line 953, in run_commands
self.run_command(cmd)
File ""/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/dist.py"", line 972, in run_command
cmd_obj.run()
File ""/Users/bdhammel/Documents/research_programming/julia_env/build/numpy/numpy/distutils/command/egg_info.py"", line 10, in run
self.run_command(""build_src"")
File ""/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/cmd.py"", line 326, in run_command
self.distribution.run_command(command)
File ""/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/dist.py"", line 972, in run_command
cmd_obj.run()
File ""/Users/bdhammel/Documents/research_programming/julia_env/build/numpy/numpy/distutils/command/build_src.py"", line 153, in run
self.build_sources()
File ""/Users/bdhammel/Documents/research_programming/julia_env/build/numpy/numpy/distutils/command/build_src.py"", line 164, in build_sources
self.build_library_sources(*libname_info)
File ""/Users/bdhammel/Documents/research_programming/julia_env/build/numpy/numpy/distutils/command/build_src.py"", line 299, in build_library_sources
sources = self.generate_sources(sources, (lib_name, build_info))
File ""/Users/bdhammel/Documents/research_programming/julia_env/build/numpy/numpy/distutils/command/build_src.py"", line 386, in generate_sources
source = func(extension, build_dir)
File ""numpy/core/setup.py"", line 674, in get_mathlib_info
raise RuntimeError(""Broken toolchain: cannot link a simple C program"")
RuntimeError: Broken toolchain: cannot link a simple C program
",https://stackoverflow.com/questions/22388519/problems-with-pip-install-numpy-runtimeerror-broken-toolchain-cannot-link-a,144,121145.0,13.0,,,2014-03-13 19:06:19,2024-06-05 11:57:31,2014-03-13 19:26:40,,,python;numpy;virtualenv;pip,Ben,7142,1322179,registered,true,22411624,,CC BY-SA 3.0,,4172,4033,3,0,0,4,true,false,false,true,true,true,96,15,false,0.107,0.0012,4636,2014,3,19,Thursday,false,true,false,false,false,false,false
9000164,How to check BLAS/LAPACK linkage in NumPy and SciPy?,"I am builing my numpy/scipy environment based on blas and lapack more or less based on this walk through.
When I am done, how can I check, that my numpy/scipy functions really do use the previously built blas/lapack functionalities?
",https://stackoverflow.com/questions/9000164/how-to-check-blas-lapack-linkage-in-numpy-and-scipy,143,99720.0,5.0,,,2012-01-25 09:15:34,2020-06-15 20:15:13,2019-05-14 21:28:38,,,python;numpy;scipy;lapack;blas,Woltan,14113,572616,registered,true,19350234,,CC BY-SA 4.0,,322,235,0,1,0,5,true,false,false,true,true,true,52,9,true,0.05,0.0014,5414,2012,1,9,Wednesday,false,true,false,false,false,false,false
643699,How can I use numpy.correlate to do autocorrelation?,"I need to do auto-correlation of a set of numbers, which as I understand it is just the correlation of the set with itself.
I've tried it using numpy's correlate function, but I don't believe the result, as it almost always gives a vector where the first number is not the largest, as it ought to be.
So, this question is really two questions:
- What exactly is
numpy.correlate doing?
- How can I use it (or something else) to do auto-correlation?
",https://stackoverflow.com/questions/643699/how-can-i-use-numpy-correlate-to-do-autocorrelation,143,300057.0,14.0,,,2009-03-13 17:07:53,2024-04-23 17:46:35,2019-02-21 18:20:05,,,python;math;numpy;numerical-methods,Ben,69024,11522,registered,true,676302,,CC BY-SA 4.0,2019-07-07 00:32:08,625,450,1,1,0,4,true,false,false,true,true,true,52,8,true,0.047,0.0005,6462,2009,3,17,Friday,false,true,false,false,false,false,false
9482550,Argmax of numpy array returning non-flat indices,"I'm trying to get the indices of the maximum element in a Numpy array.
This can be done using numpy.argmax. My problem is, that I would like to find the biggest element in the whole array and get the indices of that.
numpy.argmax can be either applied along one axis, which is not what I want, or on the flattened array, which is kind of what I want.
My problem is that using numpy.argmax with axis=None returns the flat index when I want the multi-dimensional index.
I could use divmod to get a non-flat index but this feels ugly. Is there any better way of doing this?
",https://stackoverflow.com/questions/9482550/argmax-of-numpy-array-returning-non-flat-indices,143,92269.0,3.0,,,2012-02-28 13:12:04,2018-07-10 19:03:25,2016-10-04 02:57:29,,,python;multidimensional-array;numpy,Andreas Mueller,29038,676634,registered,true,9483964,,CC BY-SA 3.0,,667,574,5,0,0,3,true,false,false,true,true,true,48,7,false,0.033,0.0015,5380,2012,2,13,Tuesday,false,true,false,false,false,false,false
3674409,"How to split/partition a dataset into training and test datasets for, e.g., cross validation?","What is a good way to split a NumPy array randomly into training and testing/validation dataset? Something similar to the cvpartition or crossvalind functions in Matlab.
",https://stackoverflow.com/questions/3674409/how-to-split-partition-a-dataset-into-training-and-test-datasets-for-e-g-cros,142,288221.0,14.0,,,2010-09-09 06:57:34,2023-03-06 20:50:58,2017-10-17 10:33:49,,,python;arrays;optimization;numpy,erik,1423,443143,unregistered,true,3677283,,CC BY-SA 3.0,,203,170,2,0,0,4,true,false,false,true,true,true,93,14,true,0.049,0.0005,5917,2010,9,6,Thursday,false,true,false,false,false,false,false
9141732,How does numpy.histogram() work?,"While reading up on numpy, I encountered the function numpy.histogram().
What is it for and how does it work? In the docs they mention bins: What are they?
Some googling led me to the definition of Histograms in general. I get that. But unfortunately I can't link this knowledge to the examples given in the docs.
",https://stackoverflow.com/questions/9141732/how-does-numpy-histogram-work,141,300068.0,3.0,,,2012-02-04 14:56:40,2024-06-24 23:53:14,2015-08-29 20:52:52,,,python;numpy;histogram,Aufwind,26436,641514,registered,true,9141822,,CC BY-SA 3.0,,524,316,1,2,0,3,true,false,false,true,true,true,32,4,true,0.01,0.0005,5404,2012,2,14,Saturday,true,true,false,false,false,false,false
4389517,In-place type conversion of a NumPy array,"Given a NumPy array of int32, how do I convert it to float32 in place? So basically, I would like to do
a = a.astype(numpy.float32)
without copying the array. It is big.
The reason for doing this is that I have two algorithms for the computation of a. One of them returns an array of int32, the other returns an array of float32 (and this is inherent to the two different algorithms). All further computations assume that a is an array of float32.
Currently I do the conversion in a C function called via ctypes. Is there a way to do this in Python?
",https://stackoverflow.com/questions/4389517/in-place-type-conversion-of-a-numpy-array,141,146743.0,7.0,,,2010-12-08 16:01:46,2021-06-09 09:59:39,2013-07-14 16:14:12,,,python;numpy,Sven Marnach,610048,279627,registered,true,4396247,,CC BY-SA 3.0,,733,560,9,0,0,2,true,false,false,true,true,true,41,7,false,0.048,0.001,5827,2010,12,16,Wednesday,false,true,false,false,false,false,false
31951980,What exactly does numpy.exp() do?,"I'm very confused as to what np.exp() actually does. In the documentation it says that it: ""Calculates the exponential of all elements in the input array."" I'm confused as to what exactly this means. Could someone give me more information to what it actually does?
",https://stackoverflow.com/questions/31951980/what-exactly-does-numpy-exp-do,141,317774.0,3.0,,,2015-08-11 21:08:55,2023-08-15 06:24:30,2019-08-01 01:06:54,,,python;numpy;statistics;exp,bugsyb,6191,3594588,registered,true,,,CC BY-SA 4.0,,272,265,0,0,0,4,false,false,false,true,true,true,33,5,true,0.009,0.0004,4120,2015,8,21,Tuesday,false,true,false,false,false,false,false
15639779,Why does multiprocessing use only a single core after I import numpy?,"I am not sure whether this counts more as an OS issue, but I thought I would ask here in case anyone has some insight from the Python end of things.
I've been trying to parallelise a CPU-heavy for loop using joblib, but I find that instead of each worker process being assigned to a different core, I end up with all of them being assigned to the same core and no performance gain.
Here's a very trivial example...
from joblib import Parallel,delayed
import numpy as np
def testfunc(data):
# some very boneheaded CPU work
for nn in xrange(1000):
for ii in data[0,:]:
for jj in data[1,:]:
ii*jj
def run(niter=10):
data = (np.random.randn(2,100) for ii in xrange(niter))
pool = Parallel(n_jobs=-1,verbose=1,pre_dispatch='all')
results = pool(delayed(testfunc)(dd) for dd in data)
if __name__ == '__main__':
run()
...and here's what I see in htop while this script is running:
![]()
I'm running Ubuntu 12.10 (3.5.0-26) on a laptop with 4 cores. Clearly joblib.Parallel is spawning separate processes for the different workers, but is there any way that I can make these processes execute on different cores?
",https://stackoverflow.com/questions/15639779/why-does-multiprocessing-use-only-a-single-core-after-i-import-numpy,141,52598.0,3.0,,,2013-03-26 14:37:34,2015-07-12 17:56:27,2015-04-16 13:54:21,,,python;linux;numpy;multiprocessing;blas,ali_m,74784,1461210,registered,true,15641148,,CC BY-SA 3.0,,1342,1170,5,0,1,5,true,false,false,true,true,true,69,12,true,0.057,0.0027,4988,2013,3,14,Tuesday,false,true,false,false,false,false,false
7632963,Numpy: find first index of value fast,"How can I find the index of the first occurrence of a number in a Numpy array?
Speed is important to me. I am not interested in the following answers because they scan the whole array and don't stop when they find the first occurrence:
itemindex = numpy.where(array==item)[0][0]
nonzero(array == item)[0][0]
Note 1: none of the answers from that question seem relevant Is there a Numpy function to return the first index of something in an array?
Note 2: using a C-compiled method is preferred to a Python loop.
",https://stackoverflow.com/questions/7632963/numpy-find-first-index-of-value-fast,141,115809.0,15.0,,,2011-10-03 09:03:57,2023-09-10 11:24:38,2017-05-23 11:47:12,,,python;numpy;find,cyborg,10159,907578,registered,true,,,CC BY-SA 3.0,,698,516,1,1,0,3,false,false,false,true,true,true,37,7,false,0.13,0.0012,5528,2011,10,9,Monday,false,true,false,false,false,false,false
64654805,How do you fix "runtimeError: package fails to pass a sanity check" for numpy and pandas?,"This is the error I am getting and, as far as I can tell, there is nothing useful on the error link to fix this.
RuntimeError: The current Numpy installation
('...\\venv\\lib\\site-packages\\numpy\\__init__.py') fails to pass a
sanity check due to a bug in the windows runtime.
See this issue for more information: https://developercommunity.visualstudio.com/content/problem/1207405/fmod-after-an-update-to-windows-2004-is-causing-a.html
I have tried multiple versions of Python (3.8.6 and 3.9.0) and numpy and pandas. I am currently using PyCharm to do all this.
",https://stackoverflow.com/questions/64654805/how-do-you-fix-runtimeerror-package-fails-to-pass-a-sanity-check-for-numpy-an,140,86953.0,9.0,,,2020-11-02 23:37:04,2021-01-08 08:57:13,2020-11-16 09:41:30,,,python;python-3.x;windows;numpy,Reed Collins,1403,14567162,registered,true,64658254,,CC BY-SA 4.0,2020-11-12 22:11:46,786,566,1,1,0,4,true,false,false,true,true,true,99,16,true,0.104,0.0016,2210,2020,11,23,Monday,false,true,false,false,false,false,false
21778118,Counting the number of non-NaN elements in a numpy ndarray in Python,"I need to calculate the number of non-NaN elements in a numpy ndarray matrix. How would one efficiently do this in Python? Here is my simple code for achieving this:
import numpy as np
def numberOfNonNans(data):
count = 0
for i in data:
if not np.isnan(i):
count += 1
return count
Is there a built-in function for this in numpy? Efficiency is important because I'm doing Big Data analysis.
Thnx for any help!
",https://stackoverflow.com/questions/21778118/counting-the-number-of-non-nan-elements-in-a-numpy-ndarray-in-python,140,234424.0,6.0,,,2014-02-14 11:26:25,2024-03-22 09:52:25,2019-01-14 10:23:20,,,python;numpy;matrix;nan,jjepsuomi,4443,1565754,registered,true,21778195,,CC BY-SA 4.0,,495,450,1,0,0,4,true,false,false,true,true,true,68,12,false,0.026,0.0006,4663,2014,2,11,Friday,false,true,false,false,false,false,false
19766757,Replacing Numpy elements if condition is met,"I have a large numpy array that I need to manipulate so that each element is changed to either a 1 or 0 if a condition is met (will be used as a pixel mask later). There are about 8 million elements in the array and my current method takes too long for the reduction pipeline:
for (y,x), value in numpy.ndenumerate(mask_data):
if mask_data[y,x]<3: #Good Pixel
mask_data[y,x]=1
elif mask_data[y,x]>3: #Bad Pixel
mask_data[y,x]=0
Is there a numpy function that would speed this up?
",https://stackoverflow.com/questions/19766757/replacing-numpy-elements-if-condition-is-met,139,308386.0,6.0,,,2013-11-04 11:27:02,2026-04-16 20:17:50,,,,python;arrays;numpy;conditional-statements,ChrisFro,2871,2952205,registered,true,19767068,,CC BY-SA 3.0,,553,515,1,0,0,4,true,false,false,true,true,false,44,7,false,0.019,0.0005,4765,2013,11,11,Monday,false,true,false,false,false,false,false
37754948,How to get the indices list of all NaN value in numpy array?,"Say now I have a numpy array which is defined as,
[[1,2,3,4],
[2,3,NaN,5],
[NaN,5,2,3]]
Now I want to have a list that contains all the indices of the missing values, which is [(1,2),(2,0)] at this case.
Is there any way I can do that?
",https://stackoverflow.com/questions/37754948/how-to-get-the-indices-list-of-all-nan-value-in-numpy-array,139,275891.0,4.0,,,2016-06-10 18:26:38,2023-09-06 09:06:05,,,,python;numpy;scipy,xxx222,3334,5257450,registered,true,37755016,,CC BY-SA 3.0,,298,240,2,0,0,3,true,false,false,true,true,false,60,13,true,0.014,0.0005,3816,2016,6,18,Friday,false,true,false,false,false,false,false
3551242,Numpy index slice without losing dimension information,"I'm using numpy and want to index a row without losing the dimension information.
import numpy as np
X = np.zeros((100,10))
X.shape # >> (100, 10)
xslice = X[10,:]
xslice.shape # >> (10,)
In this example xslice is now 1 dimension, but I want it to be (1,10).
In R, I would use X[10,:,drop=F]. Is there something similar in numpy. I couldn't find it in the documentation and didn't see a similar question asked.
Thanks!
",https://stackoverflow.com/questions/3551242/numpy-index-slice-without-losing-dimension-information,139,81370.0,7.0,,,2010-08-23 20:06:22,2022-08-05 12:28:34,2016-01-11 14:05:47,,,python;numpy,mindmatters,2525,339573,registered,true,3551859,,CC BY-SA 3.0,,491,446,1,0,0,2,true,false,false,true,true,true,54,7,false,0.086,0.0017,5934,2010,8,20,Monday,false,true,false,false,false,false,false
5124376,convert nan value to zero,"I have a 2D numpy array. Some of the values in this array are NaN. I want to perform certain operations using this array. For example consider the array:
[[ 0. 43. 67. 0. 38.]
[ 100. 86. 96. 100. 94.]
[ 76. 79. 83. 89. 56.]
[ 88. NaN 67. 89. 81.]
[ 94. 79. 67. 89. 69.]
[ 88. 79. 58. 72. 63.]
[ 76. 79. 71. 67. 56.]
[ 71. 71. NaN 56. 100.]]
I am trying to take each row, one at a time, sort it in reversed order to get max 3 values from the row and take their average. The code I tried is:
# nparr is a 2D numpy array
for entry in nparr:
sortedentry = sorted(entry, reverse=True)
highest_3_values = sortedentry[:3]
avg_highest_3 = float(sum(highest_3_values)) / 3
This does not work for rows containing NaN. My question is, is there a quick way to convert all NaN values to zero in the 2D numpy array so that I have no problems with sorting and other things I am trying to do.
",https://stackoverflow.com/questions/5124376/convert-nan-value-to-zero,136,450268.0,9.0,,,2011-02-26 01:08:12,2023-03-07 14:04:13,2016-06-17 15:08:18,,,python;numpy;nan,Curious2learn,33976,316357,registered,true,5124409,,CC BY-SA 3.0,2019-07-07 20:11:03,1081,973,5,0,0,3,true,false,false,true,true,true,25,5,false,0.02,0.0003,5747,2011,2,1,Saturday,true,true,false,false,false,false,false
15274696,ImportError in importing from sklearn: cannot import name check_build,"I am getting the following error while trying to import from sklearn:
>>> from sklearn import svm
Traceback (most recent call last):
File ""<pyshell#17>"", line 1, in <module>
from sklearn import svm
File ""C:\Python27\lib\site-packages\sklearn\__init__.py"", line 16, in <module>
from . import check_build
ImportError: cannot import name check_build
I am using python 2.7, scipy-0.12.0b1 superpack, numpy-1.6.0 superpack, scikit-learn-0.11
I have a windows 7 machine
I have checked several answers for this issue but none of them gives a way out of this error.
",https://stackoverflow.com/questions/15274696/importerror-in-importing-from-sklearn-cannot-import-name-check-build,136,373163.0,13.0,,,2013-03-07 15:12:12,2021-09-23 19:02:53,2014-08-10 08:35:45,,,python;numpy;scipy;scikit-learn,ayush singhal,1935,386384,registered,true,26255358,,CC BY-SA 3.0,2019-07-06 00:20:17,645,600,1,0,0,4,true,false,false,true,true,true,69,9,false,0.035,0.0004,5007,2013,3,15,Thursday,false,true,false,false,false,false,false
41925157,LogisticRegression: Unknown label type: 'continuous' using sklearn in python,"I have the following code to test some of most popular ML algorithms of sklearn python library:
import numpy as np
from sklearn import metrics, svm
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC
trainingData = np.array([ [2.3, 4.3, 2.5], [1.3, 5.2, 5.2], [3.3, 2.9, 0.8], [3.1, 4.3, 4.0] ])
trainingScores = np.array( [3.4, 7.5, 4.5, 1.6] )
predictionData = np.array([ [2.5, 2.4, 2.7], [2.7, 3.2, 1.2] ])
clf = LinearRegression()
clf.fit(trainingData, trainingScores)
print(""LinearRegression"")
print(clf.predict(predictionData))
clf = svm.SVR()
clf.fit(trainingData, trainingScores)
print(""SVR"")
print(clf.predict(predictionData))
clf = LogisticRegression()
clf.fit(trainingData, trainingScores)
print(""LogisticRegression"")
print(clf.predict(predictionData))
clf = DecisionTreeClassifier()
clf.fit(trainingData, trainingScores)
print(""DecisionTreeClassifier"")
print(clf.predict(predictionData))
clf = KNeighborsClassifier()
clf.fit(trainingData, trainingScores)
print(""KNeighborsClassifier"")
print(clf.predict(predictionData))
clf = LinearDiscriminantAnalysis()
clf.fit(trainingData, trainingScores)
print(""LinearDiscriminantAnalysis"")
print(clf.predict(predictionData))
clf = GaussianNB()
clf.fit(trainingData, trainingScores)
print(""GaussianNB"")
print(clf.predict(predictionData))
clf = SVC()
clf.fit(trainingData, trainingScores)
print(""SVC"")
print(clf.predict(predictionData))
The first two works ok, but I got the following error in LogisticRegression call:
root@ubupc1:/home/ouhma# python stack.py
LinearRegression
[ 15.72023529 6.46666667]
SVR
[ 3.95570063 4.23426243]
Traceback (most recent call last):
File ""stack.py"", line 28, in <module>
clf.fit(trainingData, trainingScores)
File ""/usr/local/lib/python2.7/dist-packages/sklearn/linear_model/logistic.py"", line 1174, in fit
check_classification_targets(y)
File ""/usr/local/lib/python2.7/dist-packages/sklearn/utils/multiclass.py"", line 172, in check_classification_targets
raise ValueError(""Unknown label type: %r"" % y_type)
ValueError: Unknown label type: 'continuous'
The input data is the same as in the previous calls, so what is going on here?
And by the way, why there is a huge diference in the first prediction of LinearRegression() and SVR() algorithms (15.72 vs 3.95)?
",https://stackoverflow.com/questions/41925157/logisticregression-unknown-label-type-continuous-using-sklearn-in-python,136,393894.0,4.0,,,2017-01-29 19:43:18,2025-01-16 17:57:41,2017-01-29 22:07:07,,,python;numpy;scikit-learn,mllamazares,8264,1709738,registered,true,41925957,,CC BY-SA 3.0,2018-04-28 16:42:51,2822,2694,6,0,0,3,true,false,false,true,true,true,84,9,false,0.01,0.0003,3583,2017,1,19,Sunday,true,true,false,false,false,false,false
8092920,sort eigenvalues and associated eigenvectors after using numpy.linalg.eig in python,"I'm using numpy.linalg.eig to obtain a list of eigenvalues and eigenvectors:
A = someMatrixArray
from numpy.linalg import eig as eigenValuesAndVectors
solution = eigenValuesAndVectors(A)
eigenValues = solution[0]
eigenVectors = solution[1]
I would like to sort my eigenvalues (e.g. from lowest to highest), in a way I know what is the associated eigenvector after the sorting.
I'm not finding any way of doing that with python functions. Is there any simple way or do I have to code my sort version?
",https://stackoverflow.com/questions/8092920/sort-eigenvalues-and-associated-eigenvectors-after-using-numpy-linalg-eig-in-pyt,136,129347.0,3.0,,,2011-11-11 10:53:35,2018-05-28 09:21:19,2014-03-19 09:53:12,,,python;sorting;numpy,Jorge Leitao,20360,931303,registered,true,8093043,,CC BY-SA 3.0,,551,506,1,0,0,3,true,false,false,true,true,true,83,10,false,0.023,0.0011,5489,2011,11,10,Friday,false,true,false,false,false,false,false
37726830,"How to determine if a number is any type of int (core or numpy, signed or not)?","I need to test whether a variable is of type int, or any of np.int*, np.uint*, preferably using a single condition (i.e. no or).
After some tests, I guess that:
isinstance(n, int) will only match int and np.int32 (or np.int64 depending on plateform),
np.issubdtype(type(n), int) seems to match all int and np.int*, but doesn’t match np.uint*.
This leads to two questions: will np.issubdtype match any kind of signed ints? Can determine in a single check whether a number is any kind of signed or unsigned int?
This is about testing for integers, the test should return False for float-likes.
",https://stackoverflow.com/questions/37726830/how-to-determine-if-a-number-is-any-type-of-int-core-or-numpy-signed-or-not,136,72526.0,3.0,,,2016-06-09 13:04:37,2022-06-09 09:20:14,2016-06-09 13:50:54,,,python;numpy;types,Arcturus B,5731,4352108,registered,true,37727662,,CC BY-SA 3.0,,880,600,14,0,0,3,true,false,false,true,true,true,79,17,true,0.041,0.0019,3817,2016,6,13,Thursday,false,true,false,false,false,false,false
25735153,Plotting a fast Fourier transform in Python,"I have access to NumPy and SciPy and want to create a simple FFT of a data set. I have two lists, one that is y values and the other is timestamps for those y values.
What is the simplest way to feed these lists into a SciPy or NumPy method and plot the resulting FFT?
I have looked up examples, but they all rely on creating a set of fake data with some certain number of data points, and frequency, etc. and don't really show how to do it with just a set of data and the corresponding timestamps.
I have tried the following example:
from scipy.fftpack import fft
# Number of samplepoints
N = 600
# Sample spacing
T = 1.0 / 800.0
x = np.linspace(0.0, N*T, N)
y = np.sin(50.0 * 2.0*np.pi*x) + 0.5*np.sin(80.0 * 2.0*np.pi*x)
yf = fft(y)
xf = np.linspace(0.0, 1.0/(2.0*T), N/2)
import matplotlib.pyplot as plt
plt.plot(xf, 2.0/N * np.abs(yf[0:N/2]))
plt.grid()
plt.show()
But when I change the argument of fft to my data set and plot it, I get extremely odd results, and it appears the scaling for the frequency may be off. I am unsure.
Here is a pastebin of the data I am attempting to FFT
http://pastebin.com/0WhjjMkb
http://pastebin.com/ksM4FvZS
When I use fft() on the whole thing it just has a huge spike at zero and nothing else.
Here is my code:
## Perform FFT with SciPy
signalFFT = fft(yInterp)
## Get power spectral density
signalPSD = np.abs(signalFFT) ** 2
## Get frequencies corresponding to signal PSD
fftFreq = fftfreq(len(signalPSD), spacing)
## Get positive half of frequencies
i = fftfreq>0
##
plt.figurefigsize = (8, 4)
plt.plot(fftFreq[i], 10*np.log10(signalPSD[i]));
#plt.xlim(0, 100);
plt.xlabel('Frequency [Hz]');
plt.ylabel('PSD [dB]')
Spacing is just equal to xInterp[1]-xInterp[0].
",https://stackoverflow.com/questions/25735153/plotting-a-fast-fourier-transform-in-python,136,485238.0,7.0,,,2014-09-09 00:45:05,2022-09-08 08:35:39,2022-03-06 13:00:46,,,python;numpy;scipy;fft,user3123955,2911,3123955,registered,true,25735274,,CC BY-SA 4.0,2019-07-07 20:11:52,2020,1717,7,2,0,4,true,false,false,true,true,true,43,7,false,0.014,0.0003,4456,2014,9,0,Tuesday,false,true,false,false,false,false,false
44123874,'DataFrame' object has no attribute 'sort',"I face some problem here, in my python package I have install numpy, but I still have this error:
'DataFrame' object has no attribute 'sort'
Anyone can give me some idea..
This is my code :
final.loc[-1] =['', 'P','Actual']
final.index = final.index + 1 # shifting index
final = final.sort()
final.columns=[final.columns,final.iloc[0]]
final = final.iloc[1:].reset_index(drop=True)
final.columns.names = (None, None)
",https://stackoverflow.com/questions/44123874/dataframe-object-has-no-attribute-sort,135,220601.0,2.0,,,2017-05-23 00:14:45,2021-09-22 06:15:32,2021-09-22 06:15:32,,,python;pandas;numpy;dataframe,Shi Jie Tio,2529,7892936,registered,true,44123892,,CC BY-SA 4.0,2019-01-25 06:13:39,528,421,2,0,0,4,true,false,false,true,true,true,58,6,false,0.009,0.0006,3469,2017,5,0,Tuesday,false,true,false,false,false,false,false
5951135,How to save a list as numpy array in python?,"Is possible to construct a NumPy array from a python list?
",https://stackoverflow.com/questions/5951135/how-to-save-a-list-as-numpy-array-in-python,135,302553.0,9.0,,,2011-05-10 13:51:38,2022-12-18 21:00:31,2020-09-04 07:28:24,,,python;list;numpy,Hossein,42659,313245,registered,true,5951187,,CC BY-SA 4.0,,66,59,0,0,0,3,true,false,false,true,true,true,44,10,true,0.03,0.0004,5674,2011,5,13,Tuesday,false,true,false,false,false,false,false
38152389,Coalesce values from 2 columns into a single column in a pandas dataframe,"I'm looking for a method that behaves similarly to coalesce in T-SQL. I have 2 columns (column A and B) that are sparsely populated in a pandas dataframe. I'd like to create a new column using the following rules:
- If the value in column A is not null, use that value for the new column C
- If the value in column A is null, use the value in column B for the new column C
Like I mentioned, this can be accomplished in MS SQL Server via the coalesce function. I haven't found a good pythonic method for this; does one exist?
",https://stackoverflow.com/questions/38152389/coalesce-values-from-2-columns-into-a-single-column-in-a-pandas-dataframe,133,186944.0,9.0,,,2016-07-01 19:03:34,2022-08-22 19:20:24,2018-01-10 22:33:50,,,python;pandas;numpy;dataframe,Sevyns,3332,4812246,registered,true,38152458,,CC BY-SA 3.0,,618,525,0,0,0,4,true,false,false,true,true,true,73,13,false,0.048,0.0007,3795,2016,7,19,Friday,false,true,false,false,false,false,false
18696122,Change values on matplotlib imshow() graph axis,"Say I have some input data:
data = np.random.normal(loc=100, scale=10, size=(500,1,32))
hist = np.ones((32, 20)) # initialise hist
for z in range(32):
hist[z], edges = np.histogram(data[:, 0, z], bins=np.arange(80, 122, 2))
I can plot it using imshow():
plt.imshow(hist, cmap='Reds')
getting:
![]()
However, the x-axis values do not match the input data (i.e. mean of 100, range from 80 to 122). Therefore, I'd like to change the x-axis to show the values in edges.
I have tried:
ax = plt.gca()
ax.set_xlabel([80,122]) # range of values in edges
...
# this shifts the plot so that nothing is visible
and
ax.set_xticklabels(edges)
...
# this labels the axis but does not centre around the mean:
![]()
Any ideas on how I can change the axis values to reflect the input data I am using?
",https://stackoverflow.com/questions/18696122/change-values-on-matplotlib-imshow-graph-axis,133,312001.0,3.0,,,2013-09-09 10:23:20,2023-09-28 02:08:43,2023-02-28 07:22:49,,,python;numpy;matplotlib;plot;imshow,Lee,31478,1461850,registered,true,18696354,,CC BY-SA 4.0,,1238,782,6,0,2,5,true,false,false,true,true,true,47,7,false,0.01,0.0004,4821,2013,9,10,Monday,false,true,false,false,false,false,false
16992713,Translate every element in numpy array according to key,"I am trying to translate every element of a numpy.array according to a given key:
For example:
a = np.array([[1,2,3],
[3,2,4]])
my_dict = {1:23, 2:34, 3:36, 4:45}
I want to get:
array([[ 23., 34., 36.],
[ 36., 34., 45.]])
I can see how to do it with a loop:
def loop_translate(a, my_dict):
new_a = np.empty(a.shape)
for i,row in enumerate(a):
new_a[i,:] = map(my_dict.get, row)
return new_a
Is there a more efficient and/or pure numpy way?
Edit:
I timed it, and np.vectorize method proposed by DSM is considerably faster for larger arrays:
In [13]: def loop_translate(a, my_dict):
....: new_a = np.empty(a.shape)
....: for i,row in enumerate(a):
....: new_a[i,:] = map(my_dict.get, row)
....: return new_a
....:
In [14]: def vec_translate(a, my_dict):
....: return np.vectorize(my_dict.__getitem__)(a)
....:
In [15]: a = np.random.randint(1,5, (4,5))
In [16]: a
Out[16]:
array([[2, 4, 3, 1, 1],
[2, 4, 3, 2, 4],
[4, 2, 1, 3, 1],
[2, 4, 3, 4, 1]])
In [17]: %timeit loop_translate(a, my_dict)
10000 loops, best of 3: 77.9 us per loop
In [18]: %timeit vec_translate(a, my_dict)
10000 loops, best of 3: 70.5 us per loop
In [19]: a = np.random.randint(1, 5, (500,500))
In [20]: %timeit loop_translate(a, my_dict)
1 loops, best of 3: 298 ms per loop
In [21]: %timeit vec_translate(a, my_dict)
10 loops, best of 3: 37.6 ms per loop
In [22]: %timeit loop_translate(a, my_dict)
",https://stackoverflow.com/questions/16992713/translate-every-element-in-numpy-array-according-to-key,133,82999.0,9.0,,,2013-06-07 20:49:12,2024-08-06 21:59:36,2013-06-07 21:36:15,,,python;numpy,Akavall,87022,1078084,registered,true,16992783,,CC BY-SA 3.0,,1700,1512,6,0,0,2,true,false,false,true,true,true,55,9,false,0.108,0.0016,4915,2013,6,20,Friday,false,true,false,false,false,false,false
19676538,Numpy array assignment with copy,"For example, if we have a numpy array A, and we want a numpy array B with the same elements.
What is the difference between the following (see below) methods? When is additional memory allocated, and when is it not?
B = A
B[:] = A (same as B[:]=A[:]?)
numpy.copy(B, A)
",https://stackoverflow.com/questions/19676538/numpy-array-assignment-with-copy,133,86119.0,3.0,,,2013-10-30 07:44:25,2018-12-07 22:30:33,2018-12-07 22:30:33,,,python;arrays;numpy,mrgloom,21918,1179925,registered,true,19676762,,CC BY-SA 4.0,,427,273,8,0,0,3,true,false,false,true,true,true,32,5,false,0.035,0.0015,4770,2013,10,7,Wednesday,false,true,false,false,false,false,false
35084071,Concat DataFrame Reindexing only valid with uniquely valued Index objects,"I am trying to concat the following dataframes:
df1
price side timestamp
timestamp
2016-01-04 00:01:15.631331072 0.7286 2 1451865675631331
2016-01-04 00:01:15.631399936 0.7286 2 1451865675631400
2016-01-04 00:01:15.631860992 0.7286 2 1451865675631861
2016-01-04 00:01:15.631866112 0.7286 2 1451865675631866
and:
df2
bid bid_size offer offer_size
timestamp
2016-01-04 00:00:31.331441920 0.7284 4000000 0.7285 1000000
2016-01-04 00:00:53.631324928 0.7284 4000000 0.7290 4000000
2016-01-04 00:01:03.131234048 0.7284 5000000 0.7286 4000000
2016-01-04 00:01:12.131444992 0.7285 1000000 0.7286 4000000
2016-01-04 00:01:15.631364096 0.7285 4000000 0.7290 4000000
With
data = pd.concat([df1,df2], axis=1)
But I get the follwing output:
InvalidIndexError Traceback (most recent call last)
<ipython-input-38-2e88458f01d7> in <module>()
----> 1 data = pd.concat([df1,df2], axis=1)
2 data = data.fillna(method='pad')
3 data = data.fillna(method='bfill')
4 data['timestamp'] = data.index.values#converting to datetime
5 data['timestamp'] = pd.to_datetime(data['timestamp'])#converting to datetime
/usr/local/lib/python2.7/site-packages/pandas/tools/merge.pyc in concat(objs, axis, join, join_axes, ignore_index, keys, levels, names, verify_integrity, copy)
810 keys=keys, levels=levels, names=names,
811 verify_integrity=verify_integrity,
--> 812 copy=copy)
813 return op.get_result()
814
/usr/local/lib/python2.7/site-packages/pandas/tools/merge.pyc in __init__(self, objs, axis, join, join_axes, keys, levels, names, ignore_index, verify_integrity, copy)
947 self.copy = copy
948
--> 949 self.new_axes = self._get_new_axes()
950
951 def get_result(self):
/usr/local/lib/python2.7/site-packages/pandas/tools/merge.pyc in _get_new_axes(self)
1013 if i == self.axis:
1014 continue
-> 1015 new_axes[i] = self._get_comb_axis(i)
1016 else:
1017 if len(self.join_axes) != ndim - 1:
/usr/local/lib/python2.7/site-packages/pandas/tools/merge.pyc in _get_comb_axis(self, i)
1039 raise TypeError("Cannot concatenate list of %s" % types)
1040
-> 1041 return _get_combined_index(all_indexes, intersect=self.intersect)
1042
1043 def _get_concat_axis(self):
/usr/local/lib/python2.7/site-packages/pandas/core/index.pyc in _get_combined_index(indexes, intersect)
6120 index = index.intersection(other)
6121 return index
-> 6122 union = _union_indexes(indexes)
6123 return _ensure_index(union)
6124
/usr/local/lib/python2.7/site-packages/pandas/core/index.pyc in _union_indexes(indexes)
6149
6150 if hasattr(result, 'union_many'):
-> 6151 return result.union_many(indexes[1:])
6152 else:
6153 for other in indexes[1:]:
/usr/local/lib/python2.7/site-packages/pandas/tseries/index.pyc in union_many(self, others)
959 else:
960 tz = this.tz
--> 961 this = Index.union(this, other)
962 if isinstance(this, DatetimeIndex):
963 this.tz = tz
/usr/local/lib/python2.7/site-packages/pandas/core/index.pyc in union(self, other)
1553 result.extend([x for x in other._values if x not in value_set])
1554 else:
-> 1555 indexer = self.get_indexer(other)
1556 indexer, = (indexer == -1).nonzero()
1557
/usr/local/lib/python2.7/site-packages/pandas/core/index.pyc in get_indexer(self, target, method, limit, tolerance)
1890
1891 if not self.is_unique:
-> 1892 raise InvalidIndexError('Reindexing only valid with uniquely'
1893 ' valued Index objects')
1894
InvalidIndexError: Reindexing only valid with uniquely valued Index objects
I have removed additional columns and removed duplicates and NA where there could be a conflict - but I simply do not know what's wrong.
",https://stackoverflow.com/questions/35084071/concat-dataframe-reindexing-only-valid-with-uniquely-valued-index-objects,132,422372.0,17.0,,,2016-01-29 12:00:42,2025-02-27 08:55:11,2021-03-13 04:27:57,,,python;numpy;pandas,noidea,1479,4986357,registered,true,35088066,,CC BY-SA 4.0,,4503,4358,4,0,0,3,true,false,false,true,true,true,73,10,false,0.04,0.0003,3949,2016,1,12,Friday,false,true,false,false,false,false,false
30399534,Shift elements in a numpy array,"This question contains its own answer at the bottom. Use preallocated arrays.
Following-up from this question years ago, is there a canonical "shift" function in numpy? I don't see anything from the documentation.
Here's a simple version of what I'm looking for:
def shift(xs, n):
if n >= 0:
return np.r_[np.full(n, np.nan), xs[:-n]]
else:
return np.r_[xs[-n:], np.full(-n, np.nan)]
Using this is like:
In [76]: xs
Out[76]: array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])
In [77]: shift(xs, 3)
Out[77]: array([ nan, nan, nan, 0., 1., 2., 3., 4., 5., 6.])
In [78]: shift(xs, -3)
Out[78]: array([ 3., 4., 5., 6., 7., 8., 9., nan, nan, nan])
This question came from my attempt to write a fast rolling_product yesterday. I needed a way to "shift" a cumulative product and all I could think of was to replicate the logic in np.roll().
So np.concatenate() is much faster than np.r_[]. This version of the function performs a lot better:
def shift(xs, n):
if n >= 0:
return np.concatenate((np.full(n, np.nan), xs[:-n]))
else:
return np.concatenate((xs[-n:], np.full(-n, np.nan)))
An even faster version simply pre-allocates the array:
def shift(xs, n):
e = np.empty_like(xs)
if n >= 0:
e[:n] = np.nan
e[n:] = xs[:-n]
else:
e[n:] = np.nan
e[:n] = xs[-n:]
return e
The above proposal is the answer. Use preallocated arrays.
",https://stackoverflow.com/questions/30399534/shift-elements-in-a-numpy-array,132,216420.0,14.0,,,2015-05-22 14:36:42,2025-08-30 09:29:16,2022-02-07 12:51:00,,,python;numpy,chrisaycock,38192,478288,registered,true,42642326,,CC BY-SA 4.0,,1943,1490,7,3,0,2,true,false,false,true,true,true,31,6,false,0.065,0.0006,4201,2015,5,14,Friday,false,true,false,false,false,false,false
36000993,Numpy isnan() fails on an array of floats (from pandas dataframe apply),"I have an array of floats (some normal numbers, some nans) that is coming out of an apply on a pandas dataframe.
For some reason, numpy.isnan is failing on this array, however as shown below, each element is a float, numpy.isnan runs correctly on each element, the type of the variable is definitely a numpy array.
What's going on?!
set([type(x) for x in tester])
Out[59]: {float}
tester
Out[60]:
array([-0.7000000000000001, nan, nan, nan, nan, nan, nan, nan, nan, nan,
nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan,
nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan,
nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan,
nan, nan], dtype=object)
set([type(x) for x in tester])
Out[61]: {float}
np.isnan(tester)
Traceback (most recent call last):
File ""<ipython-input-62-e3638605b43c>"", line 1, in <module>
np.isnan(tester)
TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
set([np.isnan(x) for x in tester])
Out[65]: {False, True}
type(tester)
Out[66]: numpy.ndarray
",https://stackoverflow.com/questions/36000993/numpy-isnan-fails-on-an-array-of-floats-from-pandas-dataframe-apply,132,188298.0,5.0,,,2016-03-15 01:14:18,2021-04-08 01:50:18,,,,python;arrays;numpy;pandas,tim654321,2268,4294553,registered,true,36001191,,CC BY-SA 3.0,,1207,1162,1,0,0,4,true,false,false,true,true,false,71,12,false,0.027,0.0007,3903,2016,3,1,Tuesday,false,true,false,false,false,false,false
41446833,What is the difference between i = i + 1 and i += 1 in a 'for' loop?,"I found out a curious thing today and was wondering if somebody could shed some light into what the difference is here?
import numpy as np
A = np.arange(12).reshape(4,3)
for a in A:
a = a + 1
B = np.arange(12).reshape(4,3)
for b in B:
b += 1
After running each for loop, A has not changed, but B has had one added to each element. I actually use the B version to write to a initialized NumPy array within a for loop.
",https://stackoverflow.com/questions/41446833/what-is-the-difference-between-i-i-1-and-i-1-in-a-for-loop,131,342525.0,6.0,,,2017-01-03 15:27:00,2019-05-01 15:57:13,2017-01-03 19:01:40,2017-01-04 19:52:17,Duplicate,python;loops;numpy;operators,Dammi,1277,2758652,registered,true,41446882,,,,533,430,6,0,0,4,true,true,false,true,true,true,76,18,true,0.018,0.0004,3609,2017,1,15,Tuesday,false,true,false,false,false,false,false
13869173,Numpy: find index of the elements within range,"I have a numpy array of numbers, for example,
a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])
I would like to find all the indexes of the elements within a specific range. For instance, if the range is (6, 10), the answer should be (3, 4, 5). Is there a built-in function to do this?
",https://stackoverflow.com/questions/13869173/numpy-find-index-of-the-elements-within-range,130,257374.0,12.0,,,2012-12-13 21:56:38,2021-03-26 14:21:23,2020-03-30 10:14:19,,,python;numpy,zzzbbx,10217,464277,registered,true,13869233,,CC BY-SA 4.0,2019-07-07 20:08:42,327,289,1,0,0,2,true,false,false,true,true,true,46,8,false,0.047,0.0005,5091,2012,12,21,Thursday,false,true,false,false,false,false,false
25169297,NumPy: Logarithm with base n,"From the numpy documentation on logarithms, I have found functions to take the logarithm with base e, 2, and 10:
import numpy as np
np.log(np.e**3) #3.0
np.log2(2**3) #3.0
np.log10(10**3) #3.0
However, how do I take the logarithm with base n (e.g. 42) in numpy?
",https://stackoverflow.com/questions/25169297/numpy-logarithm-with-base-n,130,163020.0,2.0,,,2014-08-06 20:09:39,2023-02-26 01:10:23,2023-02-24 06:17:34,,,python;math;numpy;logarithm,dwitvliet,7729,2801037,registered,true,25169298,,CC BY-SA 4.0,,805,265,1,4,0,4,true,false,false,true,true,true,28,5,false,0.012,0.0008,4490,2014,8,20,Wednesday,false,true,false,false,false,false,false
32208359,Is there a multi-dimensional version of arange/linspace in numpy?,"I would like a list of 2d NumPy arrays (x,y) , where each x is in {-5, -4.5, -4, -3.5, ..., 3.5, 4, 4.5, 5} and the same for y.
I could do
x = np.arange(-5, 5.1, 0.5)
y = np.arange(-5, 5.1, 0.5)
and then iterate through all possible pairs, but I'm sure there's a nicer way...
I would like something back that looks like:
[[-5, -5],
[-5, -4.5],
[-5, -4],
...
[5, 5]]
but the order does not matter.
",https://stackoverflow.com/questions/32208359/is-there-a-multi-dimensional-version-of-arange-linspace-in-numpy,130,163105.0,13.0,,,2015-08-25 15:41:25,2024-05-26 07:09:06,2019-05-14 17:10:12,,,python;numpy;cartesian-product,Hilemonstoer,1467,5265046,registered,true,32208788,,CC BY-SA 4.0,,493,410,2,0,0,3,true,false,false,true,true,true,65,9,true,0.08,0.0008,4106,2015,8,15,Tuesday,false,true,false,false,false,false,false
2413522,Weighted standard deviation in NumPy,"numpy.average() has a weights option, but numpy.std() does not. Does anyone have suggestions for a workaround?
",https://stackoverflow.com/questions/2413522/weighted-standard-deviation-in-numpy,129,99897.0,7.0,,,2010-03-09 23:53:36,2024-04-02 23:52:33,2018-12-12 17:35:02,,,python;numpy;statsmodels;standard-deviation;weighted,YGA,10184,54873,registered,true,2415343,,CC BY-SA 4.0,,145,112,2,0,0,5,true,false,false,true,true,true,36,5,false,0.07,0.0013,6101,2010,3,23,Tuesday,false,true,false,false,false,false,false
7701429,Efficient evaluation of a function at every cell of a NumPy array,"Given NumPy array A, what is the fastest/most efficient way to apply the same function f() to every cell?
I assign to A(i,j) by f(A(i,j)). Function f() doesn't have binary output, so masking operations won't help. Is double loop iteration through every cell the optimal solution?
",https://stackoverflow.com/questions/7701429/efficient-evaluation-of-a-function-at-every-cell-of-a-numpy-array,129,123060.0,6.0,,,2011-10-09 04:21:10,2023-09-24 00:00:17,2023-09-24 00:00:17,,,python;arrays;numpy;performance;vectorization,Peter,1551,986040,registered,true,,,CC BY-SA 4.0,,377,280,5,0,0,5,false,false,false,true,true,true,65,12,false,0.049,0.001,5522,2011,10,4,Sunday,true,true,false,false,false,false,false
18079029,Index of element in NumPy array,"In Python we can get the index of a value in an array by using .index().
But with a NumPy array, when I try to do:
decoding.index(i)
I get:
AttributeError: 'numpy.ndarray' object has no attribute 'index'
How could I do this on a NumPy array?
",https://stackoverflow.com/questions/18079029/index-of-element-in-numpy-array,128,516738.0,6.0,,,2013-08-06 11:32:25,2020-10-29 15:44:23,2020-10-29 15:44:23,2020-10-31 17:13:45,Duplicate,python;arrays;numpy;indexing;indexof,Marc Ortiz,2442,1262638,registered,true,18079151,,,,342,245,2,0,0,5,true,true,false,true,true,true,31,6,false,0.012,0.0002,4855,2013,8,11,Tuesday,false,true,false,false,false,false,false
23189506,Maximum allowed value for a numpy data type,"I am working with numpy arrays of a range of data types (uint8, uint16, int16, etc.). I would like to be able to check whether a number can be represented within the limits of an array for a given datatype. I am imagining something that looks like:
>>> im.dtype
dtype('uint16')
>>> dtype_max(im.dtype)
65535
>>> dtype_min(im.dtype)
0
Does something like this exist? By the way, I feel like this has to have been asked before, but my search came up empty, and all of the ""similar questions"" appear to be unrelated.
Edit: Of course, now that I've asked, one of the ""related"" questions does have the answer. Oops.
",https://stackoverflow.com/questions/23189506/maximum-allowed-value-for-a-numpy-data-type,128,91124.0,2.0,,,2014-04-21 01:28:22,2018-05-23 20:08:51,2014-04-21 01:56:59,,,python;numpy,jdmcbr,6566,897640,registered,true,23189557,,CC BY-SA 3.0,,688,643,1,0,0,2,true,false,false,true,true,true,43,8,false,0.022,0.0014,4597,2014,4,1,Monday,false,true,false,false,false,false,false
6148207,Linear regression with matplotlib / numpy,"I'm trying to generate a linear regression on a scatter plot I have generated, however my data is in list format, and all of the examples I can find of using polyfit require using arange. arange doesn't accept lists though. I have searched high and low about how to convert a list to an array and nothing seems clear. Am I missing something?
Following on, how best can I use my list of integers as inputs to the polyfit?
Here is the polyfit example I am following:
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(data)
y = np.arange(data)
m, b = np.polyfit(x, y, 1)
plt.plot(x, y, 'yo', x, m*x+b, '--k')
plt.show()
",https://stackoverflow.com/questions/6148207/linear-regression-with-matplotlib-numpy,127,497563.0,10.0,,,2011-05-27 05:32:22,2024-09-22 04:41:57,2022-04-29 07:16:03,,,python;numpy;matplotlib;linear-regression;curve-fitting,user771224,,,does_not_exist,true,6148315,,CC BY-SA 4.0,,733,636,5,0,0,5,true,false,false,true,false,true,41,6,false,0.02,0.0003,5657,2011,5,5,Friday,false,true,false,false,false,false,false
18215317,extracting days from a numpy.timedelta64 value,"I am using pandas/python and I have two date time series s1 and s2, that have been generated using the 'to_datetime' function on a field of the df containing dates/times.
When I subtract s1 from s2
s3 = s2 - s1
I get a series, s3, of type
timedelta64[ns]
0 385 days, 04:10:36
1 57 days, 22:54:00
2 642 days, 21:15:23
3 615 days, 00:55:44
4 160 days, 22:13:35
5 196 days, 23:06:49
6 23 days, 22:57:17
7 2 days, 22:17:31
8 622 days, 01:29:25
9 79 days, 20:15:14
10 23 days, 22:46:51
11 268 days, 19:23:04
12 NaT
13 NaT
14 583 days, 03:40:39
How do I look at 1 element of the series:
s3[10]
I get something like this:
numpy.timedelta64(2069211000000000,'ns')
How do I extract days from s3 and maybe keep them as integers(not so interested in hours/mins etc.)?
",https://stackoverflow.com/questions/18215317/extracting-days-from-a-numpy-timedelta64-value,127,232809.0,5.0,,,2013-08-13 17:17:13,2025-01-29 03:09:03,2022-12-18 22:41:30,,,python;numpy;pandas,user7289,34698,213216,registered,true,18215499,,CC BY-SA 4.0,,1036,842,1,0,0,3,true,false,false,true,true,true,46,6,false,0.021,0.0005,4848,2013,8,17,Tuesday,false,true,false,false,false,false,false
18522216,Multiplying across in a numpy array,"I'm trying to multiply each of the terms in a 2D array by the corresponding terms in a 1D array. This is very easy if I want to multiply every column by the 1D array, as shown in the numpy.multiply function. But I want to do the opposite, multiply each term in the row.
In other words I want to multiply:
[1,2,3] [0]
[4,5,6] * [1]
[7,8,9] [2]
and get
[0,0,0]
[4,5,6]
[14,16,18]
but instead I get
[0,2,6]
[0,5,12]
[0,8,18]
Does anyone know if there's an elegant way to do that with numpy?
Thanks a lot,
Alex
",https://stackoverflow.com/questions/18522216/multiplying-across-in-a-numpy-array,127,188913.0,8.0,,,2013-08-29 22:53:00,2024-03-03 11:39:07,,,,python;arrays;numpy,Alex S,4934,728286,registered,true,18522281,,CC BY-SA 3.0,,706,520,3,1,0,3,true,false,false,true,true,false,35,6,false,0.042,0.0007,4832,2013,8,22,Thursday,false,true,false,false,false,false,false
34226400,Find the index of the k smallest values of a numpy array,"In order to find the index of the smallest value, we can use argmin:
import numpy as np
A = np.array([1, 7, 9, 2, 0.1, 17, 17, 1.5])
print(A.argmin()) # 4 because A[4] = 0.1
But how can I find the indices of the k-smallest values?
I'm looking for something like:
A.argmin(numberofvalues=3)
# [4, 0, 7] because A[4] <= A[0] <= A[7] <= all other A[i]
Note: in my use case A has between ~ 10 000 and 100 000 values, and I'm interested for only the indices of the k=10 smallest values. k will never be > 10.
",https://stackoverflow.com/questions/34226400/find-the-index-of-the-k-smallest-values-of-a-numpy-array,127,170263.0,5.0,,,2015-12-11 14:59:17,2024-07-26 21:50:16,2024-07-26 21:50:16,,,python;numpy,Basj,48120,1422096,registered,true,34226816,,CC BY-SA 4.0,,641,526,3,0,0,2,true,false,false,true,true,true,56,12,false,0.029,0.0007,3998,2015,12,14,Friday,false,true,false,false,false,false,false
11169418,NumPy style arrays for C++?,"Are there any C++ (or C) libs that have NumPy-like arrays with support for slicing, vectorized operations, adding and subtracting contents element-by-element, etc.?
",https://stackoverflow.com/questions/11169418/numpy-style-arrays-for-c,127,113659.0,13.0,,,2012-06-23 12:15:45,2021-09-10 10:40:36,2021-08-21 04:13:07,2020-12-05 03:19:45,Not suitable for this site,c++;arrays;python-3.x;numpy;dynamic-arrays,Llamageddon,3626,867814,registered,true,11169765,,,,172,165,0,0,0,5,true,true,false,true,true,true,27,5,true,0.114,0.0011,5264,2012,6,12,Saturday,true,false,false,false,false,false,false
17079279,how is axis indexed in numpy's array?,"From Numpy's tutorial, axis can be indexed with integers, like 0 is for column, 1 is for row, but I don't grasp why they are indexed this way? And How do I figure out each axis' index when coping with multidimensional array?
",https://stackoverflow.com/questions/17079279/how-is-axis-indexed-in-numpys-array,126,148158.0,5.0,,,2013-06-13 04:30:56,2025-01-24 13:25:25,2022-12-06 21:01:14,2023-09-22 23:04:18,Duplicate,python;numpy,Alcott,18825,888051,registered,true,17079437,,,,379,225,2,1,0,2,true,true,false,true,true,true,41,7,true,0.034,0.0009,4909,2013,6,4,Thursday,false,true,false,false,false,false,false
5328556,Histogram Matplotlib,"So I have a little problem. I have a data set in scipy that is already in the histogram format, so I have the center of the bins and the number of events per bin. How can I now plot is as a histogram. I tried just doing
bins, n=hist()
but it didn't like that. Any recommendations?
",https://stackoverflow.com/questions/5328556/histogram-matplotlib,125,193602.0,7.0,,,2011-03-16 16:38:32,2021-08-31 08:11:47,2019-09-07 05:50:36,,,python;numpy;matplotlib;scipy;histogram,madtowneast,2410,662888,registered,true,5328669,,CC BY-SA 4.0,2019-03-21 02:01:20,323,285,1,0,0,5,true,false,false,true,true,true,20,2,false,0.036,0.0006,5729,2011,3,16,Wednesday,false,true,false,false,false,false,false
32034237,How does NumPy's transpose() method permute the axes of an array?,"In [28]: arr = np.arange(16).reshape((2, 2, 4))
In [29]: arr
Out[29]:
array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7]],
[[ 8, 9, 10, 11],
[12, 13, 14, 15]]])
In [32]: arr.transpose((1, 0, 2))
Out[32]:
array([[[ 0, 1, 2, 3],
[ 8, 9, 10, 11]],
[[ 4, 5, 6, 7],
[12, 13, 14, 15]]])
When we pass a tuple of integers to the transpose() function, what happens?
To be specific, this is a 3D array: how does NumPy transform the array when I pass the tuple of axes (1, 0 ,2)? Can you explain which row or column these integers refer to? And what are axis numbers in the context of NumPy?
",https://stackoverflow.com/questions/32034237/how-does-numpys-transpose-method-permute-the-axes-of-an-array,125,140647.0,6.0,,,2015-08-16 10:51:07,2022-02-12 16:50:57,2017-12-09 16:57:25,,,python;arrays;numpy;transpose,Frank Hu,1255,5232126,registered,true,32034565,,CC BY-SA 3.0,2020-04-26 17:42:26,702,638,3,0,0,4,true,false,false,true,true,true,69,11,true,0.043,0.0009,4115,2015,8,10,Sunday,true,true,false,false,false,false,false
33859531,RuntimeError: module compiled against API version a but this version of numpy is 9,"Code:
import numpy as np
import cv
Console:
>>> runfile('/Users/isaiahnields/.spyder2/temp.py', wdir='/Users/isaiahnields/.spyder2')
RuntimeError: module compiled against API version a but this version of numpy is 9
Traceback (most recent call last):
File ""<stdin>"", line 1, in <module>
File ""/Applications/Spyder-Py2.app/Contents/Resources/lib/python2.7/spyderlib/widgets/externalshell/sitecustomize.py"", line 685, in runfile
execfile(filename, namespace)
File ""/Applications/Spyder-Py2.app/Contents/Resources/lib/python2.7/spyderlib/widgets/externalshell/sitecustomize.py"", line 78, in execfile
builtins.execfile(filename, *where)
File ""/Users/isaiahnields/.spyder2/temp.py"", line 9, in <module>
import cv
File ""/Applications/Spyder-Py2.app/Contents/Resources/lib/python2.7/cv.py"", line 1, in <module>
from cv2.cv import *
ImportError: numpy.core.multiarray failed to import
>>>
System Info: OS X El Capitan, Macbook Air, 1.3 GHz Intel Core i5, 8 GB 1600 HMz DDR3
I have already attempted updating numpy. I had to add cv.py to the python2.7 folder in Spyder-Py2 is there something else I need to add?
",https://stackoverflow.com/questions/33859531/runtimeerror-module-compiled-against-api-version-a-but-this-version-of-numpy-is,125,280208.0,21.0,,,2015-11-22 20:03:46,2024-11-12 01:11:55,2015-11-22 21:13:13,,,python;python-2.7;opencv;numpy,Zay Nields,1261,5592653,registered,true,,,CC BY-SA 3.0,,1230,1154,2,0,0,4,false,false,false,true,true,true,82,14,false,0.075,0.0004,4017,2015,11,20,Sunday,true,true,false,false,false,false,false
17578115,Pass percentiles to pandas agg function,"I want to pass the numpy percentile() function through pandas' agg() function as I do below with various other numpy statistics functions.
Right now I have a dataframe that looks like this:
AGGREGATE MY_COLUMN
A 10
A 12
B 5
B 9
A 84
B 22
And my code looks like this:
grouped = dataframe.groupby('AGGREGATE')
column = grouped['MY_COLUMN']
column.agg([np.sum, np.mean, np.std, np.median, np.var, np.min, np.max])
The above code works, but I want to do something like
column.agg([np.sum, np.mean, np.percentile(50), np.percentile(95)])
I.e., specify various percentiles to return from agg().
How should this be done?
",https://stackoverflow.com/questions/17578115/pass-percentiles-to-pandas-agg-function,124,154678.0,19.0,,,2013-07-10 18:22:46,2026-03-06 06:00:21,2021-10-02 14:07:09,,,python;pandas;numpy;aggregate,slizb,6290,1700913,registered,true,17578653,,CC BY-SA 4.0,,832,679,6,0,0,4,true,false,false,true,true,true,39,6,false,0.123,0.0008,4882,2013,7,18,Wednesday,false,true,false,false,false,false,false
14639496,How to create a numpy array of arbitrary length strings?,"I'm a complete rookie to Python, but it seems like a given string is able to be (effectively) arbitrary length. i.e. you can take a string str and keeping adding to it: str += ""some stuff..."". Is there a way to make an array of such strings?
When I try this, each element only stores a single character
strArr = numpy.empty(10, dtype='string')
for i in range(0,10)
strArr[i] = ""test""
On the other hand, I know I can initialize an array of certain length strings, i.e.
strArr = numpy.empty(10, dtype='s256')
which can store 10 strings of up to 256 characters.
",https://stackoverflow.com/questions/14639496/how-to-create-a-numpy-array-of-arbitrary-length-strings,124,255114.0,3.0,,,2013-02-01 03:58:21,2024-06-09 21:04:17,2019-03-07 06:36:58,,,python;arrays;string;numpy,DilithiumMatrix,18847,230468,registered,true,14639568,,CC BY-SA 4.0,,674,572,4,0,0,4,true,false,false,true,true,true,56,10,true,0.012,0.0005,5041,2013,2,3,Friday,false,true,false,false,false,false,false
8904694,How to normalize a 2-dimensional numpy array in python less verbose?,"Given a 3 times 3 numpy array
a = numpy.arange(0,27,3).reshape(3,3)
# array([[ 0, 3, 6],
# [ 9, 12, 15],
# [18, 21, 24]])
To normalize the rows of the 2-dimensional array I thought of
row_sums = a.sum(axis=1) # array([ 9, 36, 63])
new_matrix = numpy.zeros((3,3))
for i, (row, row_sum) in enumerate(zip(a, row_sums)):
new_matrix[i,:] = row / row_sum
There must be a better way, isn't there?
Perhaps to clearify: By normalizing I mean, the sum of the entrys per row must be one. But I think that will be clear to most people.
",https://stackoverflow.com/questions/8904694/how-to-normalize-a-2-dimensional-numpy-array-in-python-less-verbose,123,291176.0,12.0,,,2012-01-18 03:12:41,2023-01-19 23:01:52,2012-01-18 03:18:23,,,python;arrays;syntax;numpy;normalization,Aufwind,26436,641514,registered,true,8904762,,CC BY-SA 3.0,,628,552,2,0,0,5,true,false,false,true,true,true,68,11,true,0.041,0.0004,5421,2012,1,3,Wednesday,false,true,false,false,false,false,false
18250298,How to check if a value is in the list in selection from pandas data frame?,"Looks ugly:
df_cut = df_new[
(
(df_new['l_ext']==31) |
(df_new['l_ext']==22) |
(df_new['l_ext']==30) |
(df_new['l_ext']==25) |
(df_new['l_ext']==64)
)
]
Does not work:
df_cut = df_new[(df_new['l_ext'] in [31, 22, 30, 25, 64])]
Is there an elegant and working solution of the above ""problem""?
",https://stackoverflow.com/questions/18250298/how-to-check-if-a-value-is-in-the-list-in-selection-from-pandas-data-frame,123,259317.0,2.0,,,2013-08-15 09:55:32,2021-10-29 20:23:45,,2023-02-15 20:25:46,Duplicate,python;select;numpy;pandas;dataframe,Roman,132560,245549,registered,true,18250457,,,2021-10-29 20:25:42,470,401,2,0,0,5,true,true,false,true,true,false,75,16,true,0.008,0.0005,4846,2013,8,9,Thursday,false,true,false,false,false,false,false
11453141,How to remove all rows in a numpy.ndarray that contain non-numeric values,"I read in a dataset as a numpy.ndarray and some of the values are missing (either by just not being there, being NaN, or by being a string written "NA").
I want to clean out all rows containing any entry like this. How do I do that with a numpy ndarray?
",https://stackoverflow.com/questions/11453141/how-to-remove-all-rows-in-a-numpy-ndarray-that-contain-non-numeric-values,123,94796.0,2.0,,,2012-07-12 13:41:52,2025-03-16 01:05:41,2025-03-16 01:05:41,,,python;arrays;numpy;filter;nan,zebra,6591,1084573,registered,true,11453235,,CC BY-SA 4.0,,318,265,3,0,0,5,true,false,false,true,true,true,73,12,false,0.021,0.0013,5245,2012,7,13,Thursday,false,true,false,false,false,false,false
8218608,"savefig without frames, axes, only content","In numpy/scipy I have an image stored in an array. I can display it, I want to save it using savefig without any borders, axes, labels, titles,... Just pure image, nothing else.
I want to avoid packages like PyPNG or scipy.misc.imsave, they are sometimes problematic (they do not always install well), only basic savefig() for me
",https://stackoverflow.com/questions/8218608/savefig-without-frames-axes-only-content,122,159454.0,13.0,,,2011-11-21 21:13:47,2025-03-27 17:37:11,2025-03-27 17:35:29,,,python;numpy;matplotlib;scipy;savefig,Jakub M.,34257,497208,registered,true,8218887,,CC BY-SA 4.0,,405,330,4,0,0,5,true,false,false,true,true,true,42,6,false,0.082,0.0008,5479,2011,11,21,Monday,false,true,false,false,false,false,false
9721884,Convert 2d numpy array into list of lists,"I use an external module (libsvm), which does not support numpy arrays, only tuples, lists and dicts. But my data is in a 2d numpy array. How can I convert it the pythonic way, aka without loops.
>>> import numpy
>>> array = numpy.ones((2,4))
>>> data_list = list(array)
>>> data_list
[array([ 1., 1., 1., 1.]), array([ 1., 1., 1., 1.])]
>>> type(data_list[0])
<type 'numpy.ndarray'> # <= what I don't want
# non pythonic way using for loop
>>> newdata=list()
>>> for line in data_list:
... line = list(line)
... newdata.append(line)
>>> type(newdata[0])
<type 'list'> # <= what I want
",https://stackoverflow.com/questions/9721884/convert-2d-numpy-array-into-list-of-lists,122,140548.0,1.0,,,2012-03-15 14:31:14,2019-11-01 13:55:41,2013-05-12 21:30:47,2015-02-10 19:56:27,Duplicate,python;arrays;list;numpy;multidimensional-array,Framester,36179,380038,registered,true,9721957,,,,801,697,1,1,0,5,true,true,false,true,true,true,41,8,false,0.007,0.0009,5364,2012,3,14,Thursday,false,true,false,false,false,false,false
49883177,How does Lru_cache (from functools) Work?,"Especially when using recursive code there are massive improvements with lru_cache. I do understand that a cache is a space that stores data that has to be served fast and saves the computer from recomputing.
How does the Python lru_cache from functools work internally?
I'm Looking for a specific answer, does it use dictionaries like the rest of Python? Does it only store the return value?
I know that Python is heavily built on top of dictionaries, however, I couldn't find a specific answer to this question.
",https://stackoverflow.com/questions/49883177/how-does-lru-cache-from-functools-work,122,101610.0,3.0,,,2018-04-17 16:29:15,2023-03-28 14:47:33,2023-03-28 14:47:33,,,python;python-3.x;numpy;caching;lru,innicoder,2732,6929467,registered,true,49883466,,CC BY-SA 4.0,,632,514,3,0,0,5,true,false,false,true,true,true,41,6,true,0.03,0.0012,3140,2018,4,16,Tuesday,false,true,false,false,false,false,false
5347065,Interleaving two NumPy arrays efficiently,"Assume the following arrays are given:
a = array([1, 3, 5])
b = array([2, 4, 6])
How would one interleave them efficiently so that one gets a third array like the following?
c = array([1, 2, 3, 4, 5, 6])
It can be assumed that length(a) == length(b).
",https://stackoverflow.com/questions/5347065/interleaving-two-numpy-arrays-efficiently,121,65877.0,14.0,,,2011-03-18 01:20:51,2025-03-01 16:50:58,2023-08-07 11:21:26,,,python;arrays;numpy,D R,22670,134397,registered,true,5347492,,CC BY-SA 4.0,,335,253,3,0,0,3,true,false,false,true,true,true,41,5,false,0.213,0.0018,5727,2011,3,1,Friday,false,true,false,false,false,false,false
20928136,Input and output numpy arrays to h5py,"I have a Python code whose output is a
sized matrix, whose entries are all of the type float. If I save it with the extension .dat the file size is of the order of 500 MB. I read that using h5py reduces the file size considerably. So, let's say I have the 2D numpy array named A. How do I save it to an h5py file?
Also, how do I read the same file and put it as a numpy array in a different code, as I need to do manipulations with the array?
",https://stackoverflow.com/questions/20928136/input-and-output-numpy-arrays-to-h5py,121,154326.0,2.0,,,2014-01-04 23:41:12,2020-01-12 17:51:58,2014-11-29 13:52:56,,,python;arrays;numpy;h5py,lovespeed,5085,611301,registered,true,,,CC BY-SA 3.0,,581,444,4,0,1,4,false,false,false,true,true,true,37,7,false,0.013,0.0008,4704,2014,1,23,Saturday,true,true,false,false,false,false,false
25773245,Ambiguity in Pandas Dataframe / Numpy Array "axis" definition,"I've been very confused about how python axes are defined, and whether they refer to a DataFrame's rows or columns. Consider the code below:
>>> df = pd.DataFrame([[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]], columns=[""col1"", ""col2"", ""col3"", ""col4""])
>>> df
col1 col2 col3 col4
0 1 1 1 1
1 2 2 2 2
2 3 3 3 3
So if we call df.mean(axis=1), we'll get a mean across the rows:
>>> df.mean(axis=1)
0 1
1 2
2 3
However, if we call df.drop(name, axis=1), we actually drop a column, not a row:
>>> df.drop(""col4"", axis=1)
col1 col2 col3
0 1 1 1
1 2 2 2
2 3 3 3
Can someone help me understand what is meant by an ""axis"" in pandas/numpy/scipy?
A side note, DataFrame.mean just might be defined wrong. It says in the documentation for DataFrame.mean that axis=1 is supposed to mean a mean over the columns, not the rows...
",https://stackoverflow.com/questions/25773245/ambiguity-in-pandas-dataframe-numpy-array-axis-definition,121,37933.0,8.0,,,2014-09-10 19:11:14,2024-12-07 14:28:32,2017-01-02 16:06:26,,,python;arrays;pandas;numpy;dataframe,hlin117,22608,2014591,registered,true,25774395,,CC BY-SA 3.0,,1244,960,8,1,0,5,true,false,false,true,true,true,71,9,false,0.211,0.0032,4455,2014,9,19,Wednesday,false,true,false,false,false,false,false
18646076,Add numpy array as column to Pandas data frame,"I have a Pandas data frame object of shape (X,Y) that looks like this:
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
and a numpy sparse matrix (CSC) of shape (X,Z) that looks something like this
[[0, 1, 0],
[0, 0, 1],
[1, 0, 0]]
How can I add the content from the matrix to the data frame in a new named column such that the data frame will end up like this:
[[1, 2, 3, [0, 1, 0]],
[4, 5, 6, [0, 0, 1]],
[7, 8, 9, [1, 0, 0]]]
Notice the data frame now has shape (X, Y+1) and rows from the matrix are elements in the data frame.
",https://stackoverflow.com/questions/18646076/add-numpy-array-as-column-to-pandas-data-frame,121,370254.0,5.0,,,2013-09-05 21:15:01,2023-07-11 20:22:20,,,,python;numpy;pandas,Mihai Damian,11452,64167,registered,true,18646275,,CC BY-SA 3.0,2019-07-07 20:13:26,625,525,3,0,0,3,true,false,false,true,true,false,46,9,false,0.014,0.0003,4825,2013,9,21,Thursday,false,true,false,false,false,false,false
27710245,Is there an analysis speed or memory usage advantage to using HDF5 for large array storage (instead of flat binary files)?,"I am processing large 3D arrays, which I often need to slice in various ways to do a variety of data analysis. A typical ""cube"" can be ~100GB (and will likely get larger in the future)
It seems that the typical recommended file format for large datasets in python is to use HDF5 (either h5py or pytables). My question is: is there any speed or memory usage benefit to using HDF5 to store and analyze these cubes over storing them in simple flat binary files? Is HDF5 more appropriate for tabular data, as opposed to large arrays like what I am working with? I see that HDF5 can provide nice compression, but I am more interested in processing speed and dealing with memory overflow.
I frequently want to analyze only one large subset of the cube. One drawback of both pytables and h5py is it seems is that when I take a slice of the array, I always get a numpy array back, using up memory. However, if I slice a numpy memmap of a flat binary file, I can get a view, which keeps the data on disk. So, it seems that I can more easily analyze specific sectors of my data without overrunning my memory.
I have explored both pytables and h5py, and haven't seen the benefit of either so far for my purpose.
",https://stackoverflow.com/questions/27710245/is-there-an-analysis-speed-or-memory-usage-advantage-to-using-hdf5-for-large-arr,120,54544.0,2.0,,,2014-12-30 18:00:27,2024-02-29 20:35:40,,,,python;numpy;hdf5;pytables;h5py,Caleb,4161,1361752,registered,true,27713489,,CC BY-SA 3.0,,1233,1205,0,0,0,5,true,false,false,true,true,false,122,21,true,0.037,0.0022,4344,2014,12,18,Tuesday,false,true,false,false,false,false,false
7596612,Benchmarking (python vs. c++ using BLAS) and (numpy),"I would like to write a program that makes extensive use of BLAS and LAPACK linear algebra functionalities. Since performance is an issue I did some benchmarking and would like know, if the approach I took is legitimate.
I have, so to speak, three contestants and want to test their performance with a simple matrix-matrix multiplication. The contestants are:
- Numpy, making use only of the functionality of
dot.
- Python, calling the BLAS functionalities through a shared object.
- C++, calling the BLAS functionalities through a shared object.
Scenario
I implemented a matrix-matrix multiplication for different dimensions i. i runs from 5 to 500 with an increment of 5 and the matricies m1 and m2 are set up like this:
m1 = numpy.random.rand(i,i).astype(numpy.float32)
m2 = numpy.random.rand(i,i).astype(numpy.float32)
1. Numpy
The code used looks like this:
tNumpy = timeit.Timer(""numpy.dot(m1, m2)"", ""import numpy; from __main__ import m1, m2"")
rNumpy.append((i, tNumpy.repeat(20, 1)))
2. Python, calling BLAS through a shared object
With the function
_blaslib = ctypes.cdll.LoadLibrary(""libblas.so"")
def Mul(m1, m2, i, r):
no_trans = c_char(""n"")
n = c_int(i)
one = c_float(1.0)
zero = c_float(0.0)
_blaslib.sgemm_(byref(no_trans), byref(no_trans), byref(n), byref(n), byref(n),
byref(one), m1.ctypes.data_as(ctypes.c_void_p), byref(n),
m2.ctypes.data_as(ctypes.c_void_p), byref(n), byref(zero),
r.ctypes.data_as(ctypes.c_void_p), byref(n))
the test code looks like this:
r = numpy.zeros((i,i), numpy.float32)
tBlas = timeit.Timer(""Mul(m1, m2, i, r)"", ""import numpy; from __main__ import i, m1, m2, r, Mul"")
rBlas.append((i, tBlas.repeat(20, 1)))
3. c++, calling BLAS through a shared object
Now the c++ code naturally is a little longer so I reduce the information to a minimum.
I load the function with
void* handle = dlopen(""libblas.so"", RTLD_LAZY);
void* Func = dlsym(handle, ""sgemm_"");
I measure the time with gettimeofday like this:
gettimeofday(&start, NULL);
f(&no_trans, &no_trans, &dim, &dim, &dim, &one, A, &dim, B, &dim, &zero, Return, &dim);
gettimeofday(&end, NULL);
dTimes[j] = CalcTime(start, end);
where j is a loop running 20 times. I calculate the time passed with
double CalcTime(timeval start, timeval end)
{
double factor = 1000000;
return (((double)end.tv_sec) * factor + ((double)end.tv_usec) - (((double)start.tv_sec) * factor + ((double)start.tv_usec))) / factor;
}
Results
The result is shown in the plot below:
![]()
Questions
- Do you think my approach is fair, or are there some unnecessary overheads I can avoid?
- Would you expect that the result would show such a huge discrepancy between the c++ and python approach? Both are using shared objects for their calculations.
- Since I would rather use python for my program, what could I do to increase the performance when calling BLAS or LAPACK routines?
Download
The complete benchmark can be downloaded here. (J.F. Sebastian made that link possible^^)
",https://stackoverflow.com/questions/7596612/benchmarking-python-vs-c-using-blas-and-numpy,120,49416.0,5.0,,,2011-09-29 11:23:25,2021-12-18 02:04:40,2011-10-21 11:42:06,,,c++;python;numpy;benchmarking;blas,Woltan,14113,572616,registered,true,7614252,,CC BY-SA 3.0,,3706,3074,14,1,1,5,true,false,false,true,true,true,52,8,false,0.101,0.0024,5532,2011,9,11,Thursday,false,true,false,false,false,false,false
40378427,numpy: formal definition of "array_like" objects?,"In numpy, the constructors of many objects accept an ""array_like"" as first argument. Is there a definition of a such object, either as an abstract meta class, or documentation of the methods is should contain??
",https://stackoverflow.com/questions/40378427/numpy-formal-definition-of-array-like-objects,120,91442.0,6.0,,,2016-11-02 11:07:51,2024-10-06 00:25:46,2016-11-02 11:54:49,,,python;numpy,blue note,29625,3208297,registered,true,40380014,,CC BY-SA 3.0,,218,211,0,0,0,2,true,false,false,true,true,true,59,6,true,0.066,0.0013,3671,2016,11,11,Wednesday,false,true,false,false,false,false,false
22994423,Difference between np.random.seed() and np.random.RandomState(),"I know that to seed the randomness of numpy.random, and be able to reproduce it, I should us:
import numpy as np
np.random.seed(1234)
but what does
np.random.RandomState()
do?
",https://stackoverflow.com/questions/22994423/difference-between-np-random-seed-and-np-random-randomstate,119,116678.0,6.0,,,2014-04-10 17:00:30,2023-01-10 19:12:23,2014-04-10 17:11:25,,,python;numpy;random,eran,15296,1724926,registered,true,22994890,,CC BY-SA 3.0,,231,180,2,0,0,3,true,false,false,true,true,true,63,5,false,0.051,0.001,4608,2014,4,17,Thursday,false,true,false,false,false,false,false
32589829,How to get value counts for multiple columns at once in Pandas DataFrame?,"Given a Pandas DataFrame that has multiple columns with categorical values (0 or 1), is it possible to conveniently get the value_counts for every column at the same time?
For example, suppose I generate a DataFrame as follows:
import numpy as np
import pandas as pd
np.random.seed(0)
df = pd.DataFrame(np.random.randint(0, 2, (10, 4)), columns=list('abcd'))
I can get a DataFrame like this:
a b c d
0 0 1 1 0
1 1 1 1 1
2 1 1 1 0
3 0 1 0 0
4 0 0 0 1
5 0 1 1 0
6 0 1 1 1
7 1 0 1 0
8 1 0 1 1
9 0 1 1 0
How do I conveniently get the value counts for every column and obtain the following conveniently?
a b c d
0 6 3 2 6
1 4 7 8 4
My current solution is:
pieces = []
for col in df.columns:
tmp_series = df[col].value_counts()
tmp_series.name = col
pieces.append(tmp_series)
df_value_counts = pd.concat(pieces, axis=1)
But there must be a simpler way, like stacking, pivoting, or groupby?
",https://stackoverflow.com/questions/32589829/how-to-get-value-counts-for-multiple-columns-at-once-in-pandas-dataframe,118,196417.0,16.0,,,2015-09-15 15:21:57,2024-03-01 18:26:41,,,,python;numpy;pandas,Xin,4602,1449228,registered,true,32589877,,CC BY-SA 3.0,,1107,969,4,0,0,3,true,false,false,true,true,false,73,13,true,0.081,0.0006,4085,2015,9,15,Tuesday,false,true,false,false,false,false,false
8905501,Extract upper or lower triangular part of a numpy matrix,"I have a matrix A and I want 2 matrices U and L such that U contains the upper triangular elements of A (all elements above and not including diagonal) and similarly for L(all elements below and not including diagonal). Is there a numpy method to do this?
e.g
A = array([[ 4., 9., -3.],
[ 2., 4., -2.],
[-2., -3., 7.]])
U = array([[ 0., 9., -3.],
[ 0., 0., -2.],
[ 0., 0., 0.]])
L = array([[ 0., 0., 0.],
[ 2., 0., 0.],
[-2., -3., 0.]])
",https://stackoverflow.com/questions/8905501/extract-upper-or-lower-triangular-part-of-a-numpy-matrix,118,167070.0,3.0,,,2012-01-18 05:13:11,2022-05-06 16:15:48,2022-04-19 12:57:16,,,python;numpy;machine-learning,pratikm ,4344,748865,registered,true,8905529,,CC BY-SA 4.0,,634,518,7,0,0,3,true,false,false,true,true,true,56,10,false,0.018,0.0007,5421,2012,1,5,Wednesday,false,true,false,false,false,false,false
7922487,How to transform numpy.matrix or array to scipy sparse matrix,"For SciPy sparse matrix, one can use todense() or toarray() to transform to NumPy matrix or array. What are the functions to do the inverse?
I searched, but got no idea what keywords should be the right hit.
",https://stackoverflow.com/questions/7922487/how-to-transform-numpy-matrix-or-array-to-scipy-sparse-matrix,118,191063.0,4.0,,,2011-10-27 21:14:08,2020-11-26 06:39:20,2016-07-31 01:48:59,,,python;numpy;scipy;sparse-matrix,Flake,4497,927877,registered,true,7922642,,CC BY-SA 3.0,2019-07-07 20:10:41,249,209,2,0,0,4,true,false,false,true,true,true,61,10,false,0.021,0.0006,5504,2011,10,21,Thursday,false,true,false,false,false,false,false
43977463,"ValueError: could not broadcast input array from shape (224,224,3) into shape (224,224)","I have a list say, temp_list with following properties :
len(temp_list) = 9260
temp_list[0].shape = (224,224,3)
Now, when I am converting into numpy array,
x = np.array(temp_list)
I am getting the error :
ValueError: could not broadcast input array from shape (224,224,3) into shape (224,224)
Can someone help me here?
",https://stackoverflow.com/questions/43977463/valueerror-could-not-broadcast-input-array-from-shape-224-224-3-into-shape-2,118,602544.0,11.0,,,2017-05-15 10:43:46,2025-07-12 01:00:42,,,,python;numpy,neel,9209,1215889,registered,true,43977626,,CC BY-SA 3.0,2023-03-12 11:22:05,442,342,3,0,0,2,true,false,false,true,true,false,87,12,false,0.018,0.0002,3477,2017,5,10,Monday,false,true,false,false,false,false,false
19580102,inverting image in Python with OpenCV,"I want to load a color image, convert it to grayscale, and then invert the data in the file.
What I need: to iterate over the array in OpenCV and change every single value with this formula (it might be wrong but it seems reasonable for me):
img[x,y] = abs(img[x,y] - 255)
but I don't understand why doesn't it works:
def inverte(imagem, name):
imagem = abs(imagem - 255)
cv2.imwrite(name, imagem)
def inverte2(imagem, name):
for x in np.nditer(imagem, op_flags=['readwrite']):
x = abs(x - 255)
cv2.imwrite(name, imagem)
if __name__ == '__main__':
nome = str(sys.argv[1])
image = cv2.imread(nome)
gs_imagem = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
inverte(gs_imagem, ""invertida.png"")
inverte2(gs_imagem, ""invertida2.png"")
I don't want to do an explicit loop (I am trying to be more pythonic). I can see that in one image that got a white background it turned black, but only this it doesn't looks like the other colors are having much (if any) change.
",https://stackoverflow.com/questions/19580102/inverting-image-in-python-with-opencv,117,345996.0,7.0,,,2013-10-25 02:25:45,2024-10-08 18:58:18,2016-05-11 20:02:07,,,python;arrays;opencv;numpy;image-processing,Mansueli,7194,2188186,registered,true,19712018,,CC BY-SA 3.0,,1086,1010,2,0,0,5,true,false,false,true,true,true,37,6,false,0.02,0.0003,4775,2013,10,2,Friday,false,true,false,false,false,false,false
1730600,Principal component analysis in Python,"I'd like to use principal component analysis (PCA) for dimensionality reduction. Does numpy or scipy already have it, or do I have to roll my own using numpy.linalg.eigh?
I don't just want to use singular value decomposition (SVD) because my input data are quite high-dimensional (~460 dimensions), so I think SVD will be slower than computing the eigenvectors of the covariance matrix.
I was hoping to find a premade, debugged implementation that already makes the right decisions for when to use which method, and which maybe does other optimizations that I don't know about.
",https://stackoverflow.com/questions/1730600/principal-component-analysis-in-python,117,107761.0,11.0,,,2009-11-13 17:04:31,2019-04-04 13:21:26,,,,python;numpy;scipy;pca,Vebjorn Ljosa,18098,17498,registered,true,1730690,,CC BY-SA 2.5,2019-07-06 00:19:00,721,581,1,1,0,4,true,false,false,true,true,false,38,5,false,0.102,0.0011,6217,2009,11,17,Friday,false,true,false,false,false,false,false
1721802,What is the equivalent of MATLAB's repmat in NumPy,"I would like to execute the equivalent of the following MATLAB code using NumPy: repmat([1; 1], [1 1 1]). How would I accomplish this?
",https://stackoverflow.com/questions/1721802/what-is-the-equivalent-of-matlabs-repmat-in-numpy,117,132521.0,7.0,,,2009-11-12 12:20:32,2022-12-06 20:01:24,2014-09-10 01:58:34,,,python;matlab;numpy,vernomcrp,3599,188912,registered,true,1724410,,CC BY-SA 3.0,2019-07-06 00:32:59,156,136,1,0,0,3,true,false,false,true,true,true,54,9,false,0.053,0.0009,6218,2009,11,12,Thursday,false,true,false,false,false,false,false
16774849,Mean Squared Error in Numpy?,"Is there a method in numpy for calculating the Mean Squared Error between two matrices?
I've tried searching but found none. Is it under a different name?
If there isn't, how do you overcome this? Do you write it yourself or use a different lib?
",https://stackoverflow.com/questions/16774849/mean-squared-error-in-numpy,116,348182.0,7.0,,,2013-05-27 13:59:14,2024-06-30 21:50:31,2013-08-04 21:00:36,,,python;arrays;numpy;mean;mean-square-error,TheMeaningfulEngineer,16559,1214214,registered,true,18047482,,CC BY-SA 3.0,,269,248,0,0,0,5,true,false,false,true,true,true,28,5,true,0.02,0.0003,4926,2013,5,13,Monday,false,true,false,false,false,false,false
26850355,Converting list to numpy array,"I have managed to load images in a folder using the command line sklearn: load_sample_images()
I would now like to convert it to a numpy.ndarray format with float32 datatype
I was able to convert it to np.ndarray using : np.array(X), however np.array(X, dtype=np.float32) and np.asarray(X).astype('float32') give me the error:
ValueError: setting an array element with a sequence.
Is there a way to work around this?
from sklearn_theano.datasets import load_sample_images
import numpy as np
kinect_images = load_sample_images()
X = kinect_images.images
X_new = np.array(X) # works
X_new = np.array(X[1], dtype=np.float32) # works
X_new = np.array(X, dtype=np.float32) # does not work
",https://stackoverflow.com/questions/26850355/converting-list-to-numpy-array,116,357323.0,2.0,,,2014-11-10 18:22:18,2026-10-02 22:19:00,2025-01-13 18:32:57,,,python;arrays;list;numpy;type-conversion,Priya Narayanan,1337,4096101,registered,true,,,CC BY-SA 4.0,,937,694,9,0,0,5,false,false,false,true,true,true,30,5,false,0.006,0.0003,4394,2014,11,18,Monday,false,true,false,false,false,false,false
14406567,Partition array into N chunks with Numpy,"There is this How do you split a list into evenly sized chunks?
for splitting an array into chunks. Is there anyway to do this more efficiently for giant arrays using Numpy?
",https://stackoverflow.com/questions/14406567/partition-array-into-n-chunks-with-numpy,115,211536.0,7.0,,,2013-01-18 19:50:27,2022-08-16 02:34:12,2021-04-21 06:25:29,,,python;arrays;numpy;numpy-ndarray,Eiyrioü von Kauyf,4791,997301,registered,true,14406661,,CC BY-SA 4.0,,297,174,0,1,0,4,true,false,false,true,true,true,40,7,false,0.033,0.0005,5055,2013,1,19,Friday,false,true,false,false,false,false,false
30053329,Elegant way to create empty pandas DataFrame with NaN of type float,"I want to create a Pandas DataFrame filled with NaNs. During my research I found an answer:
import pandas as pd
df = pd.DataFrame(index=range(0,4),columns=['A'])
This code results in a DataFrame filled with NaNs of type ""object"". So they cannot be used later on for example with the interpolate() method. Therefore, I created the DataFrame with this complicated code (inspired by this answer):
import pandas as pd
import numpy as np
dummyarray = np.empty((4,1))
dummyarray[:] = np.nan
df = pd.DataFrame(dummyarray)
This results in a DataFrame filled with NaN of type ""float"", so it can be used later on with interpolate(). Is there a more elegant way to create the same result?
",https://stackoverflow.com/questions/30053329/elegant-way-to-create-empty-pandas-dataframe-with-nan-of-type-float,115,179663.0,6.0,,,2015-05-05 12:44:09,2023-08-02 19:20:32,2017-05-23 12:26:17,,,python;pandas;numpy;dataframe;nan,mjd,1273,4866038,registered,true,30053507,,CC BY-SA 3.0,,1012,687,4,2,0,5,true,false,false,true,true,true,67,12,false,0.033,0.0006,4218,2015,5,12,Tuesday,false,true,false,false,false,false,false
36998260,Prepend element to numpy array,"I have the following numpy array
import numpy as np
X = np.array([[5.], [4.], [3.], [2.], [1.]])
I want to insert [6.] at the beginning.
I've tried:
X = X.insert(X, 0)
how do I insert into X?
",https://stackoverflow.com/questions/36998260/prepend-element-to-numpy-array,114,169372.0,5.0,,,2016-05-03 07:33:14,2023-02-16 08:27:09,,,,python;numpy;insert,piRSquared,296006,2336654,registered,true,36998277,,CC BY-SA 3.0,,281,199,3,0,0,3,true,false,false,true,true,false,30,5,false,0.03,0.0007,3854,2016,5,7,Tuesday,false,true,false,false,false,false,false
5836335,Consistently create same random numpy array,"I am waiting for another developer to finish a piece of code that will return an np array of shape (100,2000) with values of either -1,0, or 1.
In the meantime, I want to randomly create an array of the same characteristics so I can get a head start on my development and testing. The thing is that I want this randomly created array to be the same each time, so that I'm not testing against an array that keeps changing its value each time I re-run my process.
I can create my array like this, but is there a way to create it so that it's the same each time. I can pickle the object and unpickle it, but wondering if there's another way.
r = np.random.randint(3, size=(100, 2000)) - 1
",https://stackoverflow.com/questions/5836335/consistently-create-same-random-numpy-array,113,105197.0,6.0,,,2011-04-29 19:10:40,2021-11-18 14:46:24,2018-04-13 22:19:48,,,python;random;numpy,Idr,6291,717636,registered,true,5836372,,CC BY-SA 3.0,,735,690,1,0,0,3,true,false,false,true,true,true,43,6,false,0.057,0.0011,5685,2011,4,19,Friday,false,true,false,false,false,false,false
10335090,Replace negative values in an numpy array,"Is there a simple way of replacing all negative values in an array with 0?
I'm having a complete block on how to do it using a NumPy array.
E.g.
a = array([1, 2, 3, -4, 5])
I need to return
[1, 2, 3, 0, 5]
a < 0 gives:
[False, False, False, True, False]
This is where I'm stuck - how to use this array to modify the original array.
",https://stackoverflow.com/questions/10335090/replace-negative-values-in-an-numpy-array,113,147804.0,6.0,,,2012-04-26 14:03:09,2022-01-31 13:58:30,2020-10-05 05:15:05,,,python;numpy,bph,11416,1041868,registered,true,10335159,,CC BY-SA 4.0,,465,338,4,0,0,2,true,false,false,true,true,true,41,7,false,0.041,0.0008,5322,2012,4,14,Thursday,false,true,false,false,false,false,false
1642730,How to delete columns in numpy.array,"I would like to delete selected columns in a numpy.array . This is what I do:
n [397]: a = array([[ NaN, 2., 3., NaN],
.....: [ 1., 2., 3., 9]])
In [398]: print a
[[ NaN 2. 3. NaN]
[ 1. 2. 3. 9.]]
In [399]: z = any(isnan(a), axis=0)
In [400]: print z
[ True False False True]
In [401]: delete(a, z, axis = 1)
Out[401]:
array([[ 3., NaN],
[ 3., 9.]])
In this example my goal is to delete all the columns that contain NaN's. I expect the last command
to result in:
array([[2., 3.],
[2., 3.]])
How can I do that?
",https://stackoverflow.com/questions/1642730/how-to-delete-columns-in-numpy-array,113,306986.0,8.0,,,2009-10-29 10:21:34,2019-04-10 07:30:55,2011-02-17 20:57:57,,,python;numpy;scipy,Boris Gorelik,32215,17523,registered,true,5034558,,CC BY-SA 2.5,,643,574,2,0,0,3,true,false,false,true,true,true,36,6,false,0.026,0.0004,6232,2009,10,10,Thursday,false,true,false,false,false,false,false
3767409,"'invalid value encountered in double_scalars' warning, possibly numpy","As I run my code I get these warnings, always in groups of four, sporadically. I have tried to locate the source by placing debug messages before and after certain statements to pin-point its origin.
Warning: invalid value encountered in double_scalars
Warning: invalid value encountered in double_scalars
Warning: invalid value encountered in double_scalars
Warning: invalid value encountered in double_scalars
Is this is a Numpy warning, and what is a double scalar?
From Numpy I use
min(), argmin(), mean() and random.randn()
I also use Matplotlib
",https://stackoverflow.com/questions/3767409/invalid-value-encountered-in-double-scalars-warning-possibly-numpy,113,368487.0,9.0,,,2010-09-22 08:11:21,2025-05-18 10:55:20,2016-03-02 16:46:25,,,python;numpy;warnings;matplotlib,Theodor,5706,441337,registered,true,3767475,,CC BY-SA 3.0,2019-03-23 00:59:26,634,558,2,0,0,4,true,false,false,true,true,true,77,8,false,0.024,0.0003,5904,2010,9,8,Wednesday,false,true,false,false,false,false,false
29688168,"mean, nanmean and warning: Mean of empty slice","Say I construct three numpy arrays:
a = np.array([1, 2, 3])
b = np.array([np.NaN, np.NaN, 3])
c = np.array([np.NaN, np.NaN, np.NaN])
Now I find that np.mean returns nan for both b and c:
>>> np.mean(a)
2.0
>>> np.mean(b)
nan
>>> np.mean(c)
nan
Since numpy 1.8 (released 20 April 2016), we've been blessed with nanmean, which ignores nan values:
>>> np.nanmean(a)
2.0
>>> np.nanmean(b)
3.0
>>> np.nanmean(c)
nan
C:\python-3.4.3\lib\site-packages\numpy\lib\nanfunctions.py:598: RuntimeWarning: Mean of empty slice
warnings.warn("Mean of empty slice", RuntimeWarning)
So, nanmean is great, but it has the odd and undesirable behaviour of raising a warning when the array has nothing but nan values.
How can I get the behaviour of nanmean without that warning? I don't like warnings, and I don't like suppressing them manually.
",https://stackoverflow.com/questions/29688168/mean-nanmean-and-warning-mean-of-empty-slice,113,188727.0,2.0,,,2015-04-17 00:22:06,2023-03-13 18:11:04,2023-03-13 18:11:04,,,python;numpy;warnings,Michael B. Currie,14846,1832942,registered,true,29688390,,CC BY-SA 4.0,,1225,894,11,1,0,3,true,false,false,true,true,true,46,8,false,0.011,0.0006,4236,2015,4,0,Friday,false,true,false,false,false,false,false
17316880,reading v 7.3 mat file in python,"I am trying to read a matlab file with the following code
import scipy.io
mat = scipy.io.loadmat('test.mat')
and it gives me the following error
raise NotImplementedError('Please use HDF reader for matlab v7.3 files')
NotImplementedError: Please use HDF reader for matlab v7.3 files
so could anyone please had the same problem and could please any sample code
thanks
",https://stackoverflow.com/questions/17316880/reading-v-7-3-mat-file-in-python,112,146617.0,10.0,,,2013-06-26 09:53:15,2023-07-10 11:18:57,2022-08-12 09:52:33,,,python;numpy;matlab;io;mat-file,Shan,19341,623300,registered,true,,,CC BY-SA 4.0,2018-06-03 08:06:50,450,374,2,0,0,5,false,false,false,true,true,true,32,7,false,0.068,0.0008,4896,2013,6,9,Wednesday,false,true,false,false,false,false,false
5963269,How to make a great R reproducible example,"When discussing performance with colleagues, teaching, sending a bug report or searching for guidance on mailing lists and here on Stack Overflow, a reproducible example is often asked and always helpful.
What are your tips for creating an excellent example? How do you paste data structures from r in a text format? What other information should you include?
Are there other tricks in addition to using dput(), dump() or structure()? When should you include library() or require() statements? Which reserved words should one avoid, in addition to c, df, data, etc.?
How does one make a great r reproducible example?
",https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example,2462,497150.0,23.0,,,2011-05-11 11:12:02,2026-02-06 06:32:46,2018-08-19 17:12:16,,,r;r-faq,Andrie,180454,602276,registered,true,5963610,,CC BY-SA 4.0,2014-05-31 02:51:05,1015,627,8,3,0,2,true,false,false,true,true,true,42,8,false,0.046,0.005,5673,2011,5,11,Wednesday,false,false,false,false,false,false,false
1299871,"How to join (merge) data frames (inner, outer, left, right)","Given two data frames:
df1 = data.frame(CustomerId = c(1:6), Product = c(rep("Toaster", 3), rep("Radio", 3)))
df2 = data.frame(CustomerId = c(2, 4, 6), State = c(rep("Alabama", 2), rep("Ohio", 1)))
df1
# CustomerId Product
# 1 Toaster
# 2 Toaster
# 3 Toaster
# 4 Radio
# 5 Radio
# 6 Radio
df2
# CustomerId State
# 2 Alabama
# 4 Alabama
# 6 Ohio
How can I do database style, i.e., sql style, joins? That is, how do I get:
- An inner join of
df1 and df2:
Return only the rows in which the left table has matching keys in the right table.
- An outer join of
df1 and df2:
Returns all rows from both tables, and joins records from the left which have matching keys in the right table.
- A left outer join (or simply left join) of
df1 and df2
Return all rows from the left table, and any rows with matching keys from the right table.
- A right outer join of
df1 and df2
Return all rows from the right table, and any rows with matching keys from the left table.
Extra credit:
How can I do a SQL style select statement?
",https://stackoverflow.com/questions/1299871/how-to-join-merge-data-frames-inner-outer-left-right,1572,1928503.0,14.0,,,2009-08-19 13:18:11,2025-02-03 08:58:50,2025-02-03 08:58:50,,,r;join;merge;dataframe;r-faq,Dan Goldstein,25069,23929,registered,true,1300618,,CC BY-SA 4.0,2016-04-20 13:14:23,1831,1153,9,5,0,5,true,false,false,true,true,true,59,10,false,0.007,0.0008,6303,2009,8,13,Wednesday,false,false,false,false,false,false,false
1296646,Sort (order) data frame rows by multiple columns,"I want to sort a data frame by multiple columns. For example, with the data frame below I would like to sort by column 'z' (descending) then by column 'b' (ascending):
dd <- data.frame(b = factor(c("Hi", "Med", "Hi", "Low"),
levels = c("Low", "Med", "Hi"), ordered = TRUE),
x = c("A", "D", "A", "C"), y = c(8, 3, 9, 9),
z = c(1, 1, 1, 2))
dd
b x y z
1 Hi A 8 1
2 Med D 3 1
3 Hi A 9 1
4 Low C 9 2
",https://stackoverflow.com/questions/1296646/sort-order-data-frame-rows-by-multiple-columns,1511,1400632.0,21.0,,,2009-08-18 21:33:18,2024-07-16 04:37:34,2021-12-07 17:45:34,,,r;sorting;dataframe;r-faq,Christopher DuBois,43650,84458,registered,true,1296745,,CC BY-SA 4.0,2017-09-05 08:09:53,566,535,1,0,0,4,true,false,false,true,true,true,48,8,false,0.015,0.0011,6304,2009,8,21,Tuesday,false,false,false,false,false,false,false
3505701,"Grouping functions (tapply, by, aggregate) and the *apply family","Whenever I want to do something ""map""py in R, I usually try to use a function in the apply family.
However, I've never quite understood the differences between them -- how {sapply, lapply, etc.} apply the function to the input/grouped input, what the output will look like, or even what the input can be -- so I often just go through them all until I get what I want.
Can someone explain how to use which one when?
My current (probably incorrect/incomplete) understanding is...
sapply(vec, f): input is a vector. output is a vector/matrix, where element i is f(vec[i]), giving you a matrix if f has a multi-element output
lapply(vec, f): same as sapply, but output is a list?
apply(matrix, 1/2, f): input is a matrix. output is a vector, where element i is f(row/col i of the matrix)
tapply(vector, grouping, f): output is a matrix/array, where an element in the matrix/array is the value of f at a grouping g of the vector, and g gets pushed to the row/col names
by(dataframe, grouping, f): let g be a grouping. apply f to each column of the group/dataframe. pretty print the grouping and the value of f at each column.
aggregate(matrix, grouping, f): similar to by, but instead of pretty printing the output, aggregate sticks everything into a dataframe.
Side question: I still haven't learned plyr or reshape -- would plyr or reshape replace all of these entirely?
",https://stackoverflow.com/questions/3505701/grouping-functions-tapply-by-aggregate-and-the-apply-family,1157,445947.0,12.0,,,2010-08-17 18:31:12,2023-07-02 07:19:54,2022-09-25 16:39:28,,,r;vectorization;apply;r-faq,grautur,30575,231588,registered,true,7141669,,CC BY-SA 4.0,2016-02-02 17:54:01,1787,1376,23,0,0,4,true,false,false,true,true,true,64,9,false,0.027,0.0026,5940,2010,8,18,Tuesday,false,false,false,false,false,false,false
4862178,Remove rows with all or some NAs (missing values) in data.frame,"I'd like to remove the lines in this data frame that:
a) contain NAs across all columns. Below is my example data frame.
gene hsap mmul mmus rnor cfam
1 ENSG00000208234 0 NA NA NA NA
2 ENSG00000199674 0 2 2 2 2
3 ENSG00000221622 0 NA NA NA NA
4 ENSG00000207604 0 NA NA 1 2
5 ENSG00000207431 0 NA NA NA NA
6 ENSG00000221312 0 1 2 3 2
Basically, I'd like to get a data frame such as the following.
gene hsap mmul mmus rnor cfam
2 ENSG00000199674 0 2 2 2 2
6 ENSG00000221312 0 1 2 3 2
b) contain NAs in only some columns, so I can also get this result:
gene hsap mmul mmus rnor cfam
2 ENSG00000199674 0 2 2 2 2
4 ENSG00000207604 0 NA NA 1 2
6 ENSG00000221312 0 1 2 3 2
",https://stackoverflow.com/questions/4862178/remove-rows-with-all-or-some-nas-missing-values-in-data-frame,1099,2467966.0,20.0,,,2011-02-01 11:52:31,2024-11-13 07:32:34,2018-08-12 12:32:28,,,r;dataframe;filter;missing-data;r-faq,Benoit B.,12134,525563,registered,true,4862502,,CC BY-SA 4.0,2017-02-05 14:33:04,1016,856,5,0,0,5,true,false,false,true,true,true,63,11,false,0.008,0.0004,5772,2011,2,11,Tuesday,false,false,false,false,false,false,false
4605206,Drop data frame columns by name,"I have a number of columns that I would like to remove from a data frame. I know that we can delete them individually using something like:
df$x <- NULL
But I was hoping to do this with fewer commands.
Also, I know that I could drop columns using integer indexing like this:
df <- df[ -c(1, 3:6, 12) ]
But I am concerned that the relative position of my variables may change.
Given how powerful R is, I figured there might be a better way than dropping each column one by one.
",https://stackoverflow.com/questions/4605206/drop-data-frame-columns-by-name,1055,2010456.0,25.0,,,2011-01-05 14:34:29,2022-08-26 17:16:08,2017-01-29 11:06:18,,,r;dataframe;r-faq,Btibert3,40506,155406,registered,true,4605405,,CC BY-SA 3.0,2017-08-23 19:20:04,574,491,2,0,0,3,true,false,false,true,true,true,31,6,false,0.012,0.0005,5799,2011,1,14,Wednesday,false,false,false,false,false,false,false
8161836,How do I replace NA values with zeros in an R dataframe?,"I have a data frame and some columns have NA values.
How do I replace these NA values with zeroes?
",https://stackoverflow.com/questions/8161836/how-do-i-replace-na-values-with-zeros-in-an-r-dataframe,996,2245240.0,30.0,,,2011-11-17 03:45:44,2025-02-17 14:12:33,2023-05-08 08:58:41,,,r;dataframe;r-faq,Renato Dinhani,37214,734984,registered,true,8166616,,CC BY-SA 4.0,2016-07-29 23:42:41,140,100,2,0,0,3,true,false,false,true,true,true,56,12,true,0.013,0.0004,5483,2011,11,3,Thursday,false,false,false,false,false,false,false
1741820,What are the differences between "=" and "<-" assignment operators?,"What are the differences between the assignment operators = and <- in R?
I know that operators are slightly different, as this example shows
x <- y <- 5
x = y = 5
x = y <- 5
x <- y = 5
# Error in (x <- y) = 5 : could not find function ""<-<-""
But is this the only difference?
",https://stackoverflow.com/questions/1741820/what-are-the-differences-between-and-assignment-operators,976,401532.0,9.0,,,2009-11-16 12:14:51,2025-11-20 14:36:53,2022-06-15 16:16:28,,,r;assignment-operator;r-faq,csgillespie,60907,203420,registered,true,51564252,,CC BY-SA 4.0,2016-12-19 18:45:51,376,305,3,0,0,3,true,false,false,true,true,true,90,10,true,0.022,0.0024,6214,2009,11,12,Monday,false,false,false,false,false,false,false
1330989,Rotating and spacing axis labels in ggplot2,"I have a plot where the x-axis is a factor whose labels are long. While probably not an ideal visualization, for now I'd like to simply rotate these labels to be vertical. I've figured this part out with the code below, but as you can see, the labels aren't totally visible.
data(diamonds)
diamonds$cut <- paste("Super Dee-Duper",as.character(diamonds$cut))
q <- qplot(cut,carat,data=diamonds,geom="boxplot")
q + opts(axis.text.x=theme_text(angle=-90))
",https://stackoverflow.com/questions/1330989/rotating-and-spacing-axis-labels-in-ggplot2,929,1778120.0,8.0,,,2009-08-25 21:05:24,2024-02-29 08:48:27,2024-02-29 08:48:27,,,r;ggplot2;label;boxplot,Christopher DuBois,43650,84458,registered,true,1331400,,CC BY-SA 4.0,2019-07-23 12:38:25,666,483,1,1,1,4,true,false,false,true,true,true,43,7,false,0.004,0.0005,6297,2009,8,21,Tuesday,false,false,false,false,false,false,false
21435339,data.table vs dplyr: can one do something well the other can't or does poorly?,"Overview
I'm relatively familiar with data.table, not so much with dplyr. I've read through some dplyr vignettes and examples that have popped up on SO, and so far my conclusions are that:
data.table and dplyr are comparable in speed, except when there are many (i.e. >10-100K) groups, and in some other circumstances (see benchmarks below)
dplyr has more accessible syntax
dplyr abstracts (or will) potential DB interactions
- There are some minor functionality differences (see "Examples/Usage" below)
In my mind 2. doesn't bear much weight because I am fairly familiar with data.table, though I understand that for users new to both it will be a big factor. I would like to avoid an argument about which is more intuitive, as that is irrelevant for my specific question asked from the perspective of someone already familiar with data.table. I also would like to avoid a discussion about how "more intuitive" leads to faster analysis (certainly true, but again, not what I'm most interested about here).
Question
What I want to know is:
- Are there analytical tasks that are a lot easier to code with one or the other package for people familiar with the packages (i.e. some combination of keystrokes required vs. required level of esotericism, where less of each is a good thing).
- Are there analytical tasks that are performed substantially (i.e. more than 2x) more efficiently in one package vs. another.
One recent SO question got me thinking about this a bit more, because up until that point I didn't think dplyr would offer much beyond what I can already do in data.table. Here is the dplyr solution (data at end of Q):
dat %.%
group_by(name, job) %.%
filter(job != "Boss" | year == min(year)) %.%
mutate(cumu_job2 = cumsum(job2))
Which was much better than my hack attempt at a data.table solution. That said, good data.table solutions are also pretty good (thanks Jean-Robert, Arun, and note here I favored single statement over the strictly most optimal solution):
setDT(dat)[,
.SD[job != "Boss" | year == min(year)][, cumjob := cumsum(job2)],
by=list(id, job)
]
The syntax for the latter may seem very esoteric, but it actually is pretty straightforward if you're used to data.table (i.e. doesn't use some of the more esoteric tricks).
Ideally what I'd like to see is some good examples were the dplyr or data.table way is substantially more concise or performs substantially better.
Examples
Usage
dplyr does not allow grouped operations that return arbitrary number of rows (from eddi's question, note: this looks like it will be implemented in dplyr 0.5, also, @beginneR shows a potential work-around using do in the answer to @eddi's question).
data.table supports rolling joins (thanks @dholstius) as well as overlap joins
data.table internally optimises expressions of the form DT[col == value] or DT[col %in% values] for speed through automatic indexing which uses binary search while using the same base R syntax. See here for some more details and a tiny benchmark.
dplyr offers standard evaluation versions of functions (e.g. regroup, summarize_each_) that can simplify the programmatic use of dplyr (note programmatic use of data.table is definitely possible, just requires some careful thought, substitution/quoting, etc, at least to my knowledge)
Benchmarks
- I ran my own benchmarks and found both packages to be comparable in "split apply combine" style analysis, except when there are very large numbers of groups (>100K) at which point
data.table becomes substantially faster.
- @Arun ran some benchmarks on joins, showing that
data.table scales better than dplyr as the number of groups increase (updated with recent enhancements in both packages and recent version of R). Also, a benchmark when trying to get unique values has data.table ~6x faster.
- (Unverified) has
data.table 75% faster on larger versions of a group/apply/sort while dplyr was 40% faster on the smaller ones (another SO question from comments, thanks danas).
- Matt, the main author of
data.table, has benchmarked grouping operations on data.table, dplyr and python pandas on up to 2 billion rows (~100GB in RAM).
- An older benchmark on 80K groups has
data.table ~8x faster
Data
This is for the first example I showed in the question section.
dat <- structure(list(id = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L), name = c("Jane", "Jane", "Jane", "Jane",
"Jane", "Jane", "Jane", "Jane", "Bob", "Bob", "Bob", "Bob", "Bob",
"Bob", "Bob", "Bob"), year = c(1980L, 1981L, 1982L, 1983L, 1984L,
1985L, 1986L, 1987L, 1985L, 1986L, 1987L, 1988L, 1989L, 1990L,
1991L, 1992L), job = c("Manager", "Manager", "Manager", "Manager",
"Manager", "Manager", "Boss", "Boss", "Manager", "Manager", "Manager",
"Boss", "Boss", "Boss", "Boss", "Boss"), job2 = c(1L, 1L, 1L,
1L, 1L, 1L, 0L, 0L, 1L, 1L, 1L, 0L, 0L, 0L, 0L, 0L)), .Names = c("id",
"name", "year", "job", "job2"), class = "data.frame", row.names = c(NA,
-16L))
",https://stackoverflow.com/questions/21435339/data-table-vs-dplyr-can-one-do-something-well-the-other-cant-or-does-poorly,921,173355.0,5.0,,,2014-01-29 15:21:45,2023-10-16 10:40:22,2023-08-02 11:02:18,,,r;data.table;dplyr,BrodieG,52917,2725969,registered,true,27718317,,CC BY-SA 4.0,2015-01-12 09:47:27,7835,5391,42,13,0,3,true,false,false,true,true,true,82,14,true,0.029,0.0053,4679,2014,1,15,Wednesday,false,false,false,false,false,false,false
12675147,How can we make xkcd style graphs?,"Apparently, folk have figured out how to make xkcd style graphs in Mathematica and in LaTeX. Can we do it in R? Ggplot2-ers? A geom_xkcd and/or theme_xkcd?
I guess in base graphics, par(xkcd=TRUE)? How do I do it?
![]()
As a first stab (and as much more elegantly shown below) in ggplot2, adding the jitter argument to a line makes for a great hand-drawn look. So -
ggplot(mapping=aes(x=seq(1,10,.1), y=seq(1,10,.1))) +
geom_line(position=""jitter"", color=""red"", size=2) + theme_bw()
It makes for a nice example - but the axes and fonts appear trickier. Fonts appear solved (below), though. Is the only way to deal with axes to blank them out and draw them in by hand? Is there a more elegant solution? In particular, in ggplot2, can element_line in the new theme system be modified to take a jitter-like argument?
",https://stackoverflow.com/questions/12675147/how-can-we-make-xkcd-style-graphs,772,96380.0,7.0,,,2012-10-01 14:22:51,2019-10-04 15:55:04,2019-10-04 15:55:04,,,r;ggplot2;plot,jebyrnes,9396,190352,registered,true,16597217,,CC BY-SA 4.0,2019-07-23 12:36:57,1370,821,1,3,1,3,true,false,false,true,true,true,34,7,true,0.073,0.008,5164,2012,10,14,Monday,false,false,false,false,false,false,false
25721884,How should I deal with "package 'xxx' is not available (for R version x.y.z)" warning?,"I tried to install a package, using
install.packages(""foobarbaz"")
but received the warning
Warning message:
package 'foobarbaz' is not available (for R version x.y.z)
Why doesn't R think that the package is available?
See also these questions referring to specific instances of this problem:
My package doesn't work for R 2.15.2
package 'Rbbg' is not available (for R version 2.15.2)
package is not available (for R version 2.15.2)
package doMC NOT available for R version 3.0.0 warning in install.packages
Dependency ‘Rglpk’ is not available for package ‘fPortfolio’
What to do when a package is not available for our R version?
Is the bigvis package for R not available for R version 3.0.1?
package ‘syncwave’/‘mvcwt’ is not available (for R version 3.0.2)
package ‘diamonds’ is not available (for R version 3.0.0)
Is the plyr package for R not available for R version 3.0.2?
Package bigmemory not installing on R 64 3.0.2
package "makeR" is not available (for version 3.0.2)
package ‘RTN’ is not available (for R version 3.0.1)
Trouble Installing geoR package
package ‘twitterR’ is not available (for R version 3.1.0)
How to install 'Rcpp, package? I got "package is not available"
package ‘dataset’ is not available (for R version 3.1.1)
"package ‘rhipe’ is not available (for R version 3.1.2)"
",https://stackoverflow.com/questions/25721884/how-should-i-deal-with-package-xxx-is-not-available-for-r-version-x-y-z-wa,723,1082500.0,19.0,,,2014-09-08 10:11:07,2025-10-06 15:33:58,2020-03-03 13:43:06,,,r;installation;repository;package;r-faq,Richie Cotton,121999,134830,registered,true,25721890,,CC BY-SA 4.0,2015-12-23 18:33:57,3519,1356,2,18,0,5,true,false,false,true,true,true,104,15,true,0.018,0.0007,4457,2014,9,10,Monday,false,false,false,false,false,false,false
3418128,How to convert a factor to integer\numeric without loss of information?,"When I convert a factor to a numeric or integer, I get the underlying level codes, not the values as numbers.
f <- factor(sample(runif(5), 20, replace = TRUE))
## [1] 0.0248644019011408 0.0248644019011408 0.179684827337041
## [4] 0.0284090070053935 0.363644931698218 0.363644931698218
## [7] 0.179684827337041 0.249704354675487 0.249704354675487
## [10] 0.0248644019011408 0.249704354675487 0.0284090070053935
## [13] 0.179684827337041 0.0248644019011408 0.179684827337041
## [16] 0.363644931698218 0.249704354675487 0.363644931698218
## [19] 0.179684827337041 0.0284090070053935
## 5 Levels: 0.0248644019011408 0.0284090070053935 ... 0.363644931698218
as.numeric(f)
## [1] 1 1 3 2 5 5 3 4 4 1 4 2 3 1 3 5 4 5 3 2
as.integer(f)
## [1] 1 1 3 2 5 5 3 4 4 1 4 2 3 1 3 5 4 5 3 2
I have to resort to paste to get the real values:
as.numeric(paste(f))
## [1] 0.02486440 0.02486440 0.17968483 0.02840901 0.36364493 0.36364493
## [7] 0.17968483 0.24970435 0.24970435 0.02486440 0.24970435 0.02840901
## [13] 0.17968483 0.02486440 0.17968483 0.36364493 0.24970435 0.36364493
## [19] 0.17968483 0.02840901
Is there a better way to convert a factor to numeric?
",https://stackoverflow.com/questions/3418128/how-to-convert-a-factor-to-integer-numeric-without-loss-of-information,716,1162974.0,14.0,,,2010-08-05 18:53:32,2023-08-04 10:05:27,2018-04-01 11:06:59,,,r;casting;r-faq,Adam SO,10011,409828,registered,true,3418192,,CC BY-SA 3.0,2013-07-09 13:53:44,1263,1181,3,0,0,3,true,false,false,true,true,true,71,11,true,0.012,0.0006,5952,2010,8,18,Thursday,false,false,false,false,false,false,false
19226816,How can I view the source code for a function?,"I want to look at the source code for a function to see how it works. I know I can print a function by typing its name at the prompt:
> t
function (x)
UseMethod(""t"")
<bytecode: 0x2332948>
<environment: namespace:base>
In this case, what does UseMethod(""t"") mean? How do I find the source code that's actually being used by, for example: t(1:10)?
Is there a difference between when I see UseMethod and when I see standardGeneric and showMethods, as with with?
> with
standardGeneric for ""with"" defined from package ""base""
function (data, expr, ...)
standardGeneric(""with"")
<bytecode: 0x102fb3fc0>
<environment: 0x102fab988>
Methods may be defined for arguments: data
Use showMethods(""with"") for currently available ones.
In other cases, I can see that R functions are being called, but I can't find the source code for those functions.
> ts.union
function (..., dframe = FALSE)
.cbind.ts(list(...), .makeNamesTs(...), dframe = dframe, union = TRUE)
<bytecode: 0x36fbf88>
<environment: namespace:stats>
> .cbindts
Error: object '.cbindts' not found
> .makeNamesTs
Error: object '.makeNamesTs' not found
How do I find functions like .cbindts and .makeNamesTs?
In still other cases, there's a bit of R code, but most of work seems to be done somewhere else.
> matrix
function (data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL)
{
if (is.object(data) || !is.atomic(data))
data <- as.vector(data)
.Internal(matrix(data, nrow, ncol, byrow, dimnames, missing(nrow),
missing(ncol)))
}
<bytecode: 0x134bd10>
<environment: namespace:base>
> .Internal
function (call) .Primitive("".Internal"")
> .Primitive
function (name) .Primitive("".Primitive"")
How do I find out what the .Primitive function does? Similarly, some functions call .C, .Call, .Fortran, .External, or .Internal. How can I find the source code for those?
",https://stackoverflow.com/questions/19226816/how-can-i-view-the-source-code-for-a-function,703,464006.0,14.0,,,2013-10-07 13:58:00,2024-06-05 09:42:01,2023-02-14 16:48:29,,,r;function;debugging;r-faq,Joshua Ulrich,177612,271616,registered,true,19226817,,CC BY-SA 4.0,,2272,1945,18,0,0,4,true,false,false,true,true,true,46,10,true,0.03,0.0015,4793,2013,10,13,Monday,false,false,false,false,false,false,false
2564258,Plot two graphs in a same plot,"I would like to plot y1 and y2 in the same plot.
x <- seq(-2, 2, 0.05)
y1 <- pnorm(x)
y2 <- pnorm(x, 1, 1)
plot(x, y1, type = ""l"", col = ""red"")
plot(x, y2, type = ""l"", col = ""green"")
But when I do it like this, they are not plotted in the same plot together.
In Matlab one can do hold on, but does anyone know how to do this in R?
",https://stackoverflow.com/questions/2564258/plot-two-graphs-in-a-same-plot,694,1895803.0,17.0,,,2010-04-01 23:28:14,2023-02-23 16:32:15,2023-02-23 16:32:15,,,r;plot;ggplot2;r-faq,Sandra Schlichting,26376,256439,registered,true,2564276,,CC BY-SA 4.0,2017-07-31 13:47:41,403,345,2,0,0,4,true,false,false,true,true,true,30,7,false,0.009,0.0004,6078,2010,4,23,Thursday,false,false,false,false,false,false,false
1169456,The difference between bracket [ ] and double bracket [[ ]] for accessing the elements of a list or dataframe,"R provides two different methods for accessing the elements of a list or data.frame: [] and [[]].
What is the difference between the two, and when should I use one over the other?
",https://stackoverflow.com/questions/1169456/the-difference-between-bracket-and-double-bracket-for-accessing-the-el,692,350238.0,11.0,,,2009-07-23 03:33:18,2022-01-11 18:51:07,2022-01-11 18:51:07,,,r;list;dataframe;extract;r-faq,Sharpie,17743,135870,registered,true,1169495,,CC BY-SA 4.0,2016-04-20 13:12:51,220,180,2,0,0,5,true,false,false,true,true,true,109,20,false,0.031,0.002,6330,2009,7,3,Thursday,false,false,false,false,false,false,false
6979917,How to unload a package without restarting R,"I'd like to unload a package without having to restart R (mostly because restarting R as I try out different, conflicting packages is getting frustrating, but conceivably this could be used in a program to use one function and then another--although namespace referencing is probably a better idea for that use).
?library doesn't show any options that would unload a package.
There is a suggestion that detach can unload package, but the following both fail:
detach(vegan)
Error in detach(vegan) : invalid name argument
detach(""vegan"")
Error in detach(""vegan"") : invalid name argument
So how do I unload a package?
",https://stackoverflow.com/questions/6979917/how-to-unload-a-package-without-restarting-r,690,616270.0,12.0,,,2011-08-08 09:12:44,2022-05-27 09:13:55,2019-04-03 16:38:18,,,r;package;r-faq,Ari B. Friedman,73197,636656,registered,true,6979989,,CC BY-SA 4.0,2019-07-23 12:40:44,972,632,8,1,0,3,true,false,false,true,true,true,44,8,false,0.019,0.0011,5584,2011,8,9,Monday,false,false,false,false,false,false,false
18306362,Run R script from command line,"I have a file, called a.r, it has a chmod of 755,
sayHello <- function(){
print('hello')
}
sayHello()
How can I run this via command-line?
",https://stackoverflow.com/questions/18306362/run-r-script-from-command-line,680,1184713.0,7.0,,,2013-08-19 04:23:21,2022-10-13 19:20:19,2016-03-31 09:10:07,,,r;command-line,Sait,19928,547820,registered,true,18306656,,CC BY-SA 3.0,2016-03-08 17:20:51,213,149,3,0,0,2,true,false,false,true,true,true,30,6,false,0.006,0.0006,4842,2013,8,4,Monday,false,false,false,false,false,false,false
5595512,What is the difference between require() and library()?,"What is the difference between require() and library()?
",https://stackoverflow.com/questions/5595512/what-is-the-difference-between-require-and-library,676,187150.0,8.0,,,2011-04-08 13:09:14,2024-03-29 00:59:20,2020-07-29 20:10:18,,,r;package;r-faq,Marco,9674,584879,registered,true,28422554,,CC BY-SA 4.0,2017-01-12 15:39:50,89,56,2,0,0,3,true,false,false,true,true,true,55,8,true,0.043,0.0036,5706,2011,4,13,Friday,false,false,false,false,false,false,false
4227223,Convert a list to a data frame,"I have a nested list of data. Its length is 132 and each item is a list of length 20. Is there a quick way to convert this structure into a data frame that has 132 rows and 20 columns of data?
Here is some sample data to work with:
l <- replicate(
132,
as.list(sample(letters, 20)),
simplify = FALSE
)
",https://stackoverflow.com/questions/4227223/convert-a-list-to-a-data-frame,650,1283531.0,27.0,,,2010-11-19 16:40:52,2024-03-13 15:08:40,2020-11-11 20:02:10,,,r;list;dataframe,Btibert3,40506,155406,registered,true,4227273,,CC BY-SA 4.0,2017-09-29 18:44:51,359,312,1,0,0,3,true,false,false,true,true,true,30,7,false,0.021,0.0005,5846,2010,11,16,Friday,false,false,false,false,false,false,false
1169248,Test if a vector contains a given element,"How to check if a vector contains a given value?
",https://stackoverflow.com/questions/1169248/test-if-a-vector-contains-a-given-element,643,980048.0,8.0,,,2009-07-23 02:20:53,2022-07-16 18:43:31,2018-05-09 09:33:59,,,r;vector;r-faq,medriscoll,27595,2002705,registered,true,1169262,,CC BY-SA 4.0,2017-05-18 05:18:25,56,49,0,0,0,3,true,false,false,true,true,true,41,8,false,0.008,0.0007,6330,2009,7,2,Thursday,false,false,false,false,false,false,false
1195826,Drop unused factor levels in a subsetted data frame,"I have a data frame containing a factor. When I create a subset of this dataframe using subset or another indexing function, a new data frame is created. However, the factor variable retains all of its original levels, even when/if they do not exist in the new dataframe.
This causes problems when doing faceted plotting or using functions that rely on factor levels.
What is the most succinct way to remove levels from a factor in the new dataframe?
Here's an example:
df <- data.frame(letters=letters[1:5],
numbers=seq(1:5))
levels(df$letters)
## [1] ""a"" ""b"" ""c"" ""d"" ""e""
subdf <- subset(df, numbers <= 3)
## letters numbers
## 1 a 1
## 2 b 2
## 3 c 3
# all levels are still there!
levels(subdf$letters)
## [1] ""a"" ""b"" ""c"" ""d"" ""e""
",https://stackoverflow.com/questions/1195826/drop-unused-factor-levels-in-a-subsetted-data-frame,611,459313.0,16.0,,,2009-07-28 18:21:47,2021-12-29 00:53:13,2020-06-29 23:26:17,,,r;dataframe;r-factor;r-faq,medriscoll,27595,2002705,registered,true,1197154,,CC BY-SA 4.0,2017-03-17 22:51:01,903,812,4,0,0,4,true,false,false,true,true,true,51,9,false,0.035,0.0013,6325,2009,7,18,Tuesday,false,false,false,false,false,false,false
10689055,Create an empty data.frame,"I'm trying to initialize a data.frame without any rows. Basically, I want to specify the data types for each column and name them, but not have any rows created as a result.
The best I've been able to do so far is something like:
df <- data.frame(Date=as.Date(""01/01/2000"", format=""%m/%d/%Y""),
File="""", User="""", stringsAsFactors=FALSE)
df <- df[-1,]
Which creates a data.frame with a single row containing all of the data types and column names I wanted, but also creates a useless row which then needs to be removed.
Is there a better way to do this?
",https://stackoverflow.com/questions/10689055/create-an-empty-data-frame,609,1252170.0,17.0,,,2012-05-21 16:35:18,2020-08-05 07:01:44,2018-08-29 10:31:22,,,r;dataframe;r-faq,Jeff Allen,17585,1133019,registered,true,10689206,,CC BY-SA 4.0,2021-12-03 12:02:44,633,581,1,0,0,3,true,false,false,true,true,true,26,4,false,0.014,0.0005,5297,2012,5,16,Monday,false,false,false,false,false,false,false
11103189,How can I find out which package version is loaded in R?,"I am in a process of figuring out how to use my university cluster. It has 2 versions of R installed. System wide R 2.11 (Debian 6.0) and R 2.14.2 in non-standard location.
I am trying to use MPI together with snow. The code I am trying to run is the following
library(snow)
library(Rmpi)
cl <- makeMPIcluster(mpi.universe.size()-1)
stopCluster(cl)
mpi.quit()
It works without the problems on R 2.11. (I launch the script with mpirun -H localhost,n1,n2,n3,n4 -n 1 R --slave -f code.R). Now when I try to do it with R 2.14.2, I get the following message:
Error: This is R 2.11.1, package 'snow' needs >= 2.12.1
In addition: Warning message:
So it seems that R loads the package snow version compiled for R 2.11. I've installed snow under R 2.14 into my home folder and I added the following lines to my code:
.libPaths("/soft/R/lib/R/library")
.libPaths("~/R/x86_64-pc-linux-gnu-library/2.11")
print(.libPaths())
print(sessionInfo())
print(version)
And the output before the error confirms that I am indeed running R 2.14.2 and my R packages folder is first in search path. But I still get the error.
So my question is how do I determine which version of package is loaded in R? I can see with installed.packages all the packages which are installed, so maybe there is some function which lists similar information for loaded packages?
",https://stackoverflow.com/questions/11103189/how-can-i-find-out-which-package-version-is-loaded-in-r,584,759211.0,13.0,,,2012-06-19 14:30:29,2026-10-01 15:04:57,2026-08-01 21:16:01,,,r;package;version,mpiktas,11568,144297,registered,true,11103209,,CC BY-SA 4.0,,1544,1365,5,0,0,3,true,false,false,true,true,true,56,12,true,0.017,0.0008,5268,2012,6,14,Tuesday,false,false,false,false,false,false,false
1727772,Quickly reading very large tables as dataframes,"I have very large tables (30 million rows) that I would like to load as a dataframes in R. read.table() has a lot of convenient features, but it seems like there is a lot of logic in the implementation that would slow things down. In my case, I am assuming I know the types of the columns ahead of time, the table does not contain any column headers or row names, and does not have any pathological characters that I have to worry about.
I know that reading in a table as a list using scan() can be quite fast, e.g.:
datalist <- scan('myfile',sep='\t',list(url='',popularity=0,mintime=0,maxtime=0)))
But some of my attempts to convert this to a dataframe appear to decrease the performance of the above by a factor of 6:
df <- as.data.frame(scan('myfile',sep='\t',list(url='',popularity=0,mintime=0,maxtime=0))))
Is there a better way of doing this? Or quite possibly completely different approach to the problem?
",https://stackoverflow.com/questions/1727772/quickly-reading-very-large-tables-as-dataframes,577,288799.0,12.0,,,2009-11-13 07:53:33,2021-12-18 20:19:47,2018-06-03 12:36:27,,,r;import;dataframe;r-faq,eytan,6095,162436,registered,true,1728422,,CC BY-SA 4.0,2017-07-05 10:23:17,1032,930,4,0,0,4,true,false,false,true,true,true,47,7,false,0.042,0.002,6217,2009,11,7,Friday,false,false,false,false,false,false,false
14622421,How to change legend title in ggplot,"I have the following plot like below. It was created with this command:
library(ggplot2)
df <- data.frame(cond = factor(rep(c("A", "B"), each = 200)),
rating = c(rnorm(200), rnorm(200, mean=.8)))
ggplot(df, aes(x=rating, fill=cond)) +
geom_density(alpha = .3) +
xlab("NEW RATING TITLE") +
ylab("NEW DENSITY TITLE")
Now, I want to modify the legend title from cond into NEW LEGEND TITLE.
So, I just added the following line add the end of the above code:
+labs(colour="NEW LEGEND TITLE")
But it doesn't work. What's the right way to do it?
![]()
",https://stackoverflow.com/questions/14622421/how-to-change-legend-title-in-ggplot,553,1538713.0,14.0,,,2013-01-31 09:31:10,2024-07-12 09:24:00,2022-01-05 21:31:01,,,r;plot;ggplot2,neversaint,64786,67405,registered,true,14622513,,CC BY-SA 4.0,2021-01-09 18:20:31,822,616,2,0,1,3,true,false,false,true,true,true,36,7,false,0.009,0.0004,5042,2013,1,9,Thursday,false,false,false,false,false,false,false
1358003,Tricks to manage the available memory in an R session,"What tricks do people use to manage the available memory of an interactive R session? I use the functions below [based on postings by Petr Pikal and David Hinds to the r-help list in 2004] to list (and/or sort) the largest objects and to occassionally rm() some of them. But by far the most effective solution was ... to run under 64-bit Linux with ample memory.
Any other nice tricks folks want to share? One per post, please.
# improved list of objects
.ls.objects <- function (pos = 1, pattern, order.by,
decreasing=FALSE, head=FALSE, n=5) {
napply <- function(names, fn) sapply(names, function(x)
fn(get(x, pos = pos)))
names <- ls(pos = pos, pattern = pattern)
obj.class <- napply(names, function(x) as.character(class(x))[1])
obj.mode <- napply(names, mode)
obj.type <- ifelse(is.na(obj.class), obj.mode, obj.class)
obj.size <- napply(names, object.size)
obj.dim <- t(napply(names, function(x)
as.numeric(dim(x))[1:2]))
vec <- is.na(obj.dim)[, 1] & (obj.type != ""function"")
obj.dim[vec, 1] <- napply(names, length)[vec]
out <- data.frame(obj.type, obj.size, obj.dim)
names(out) <- c(""Type"", ""Size"", ""Rows"", ""Columns"")
if (!missing(order.by))
out <- out[order(out[[order.by]], decreasing=decreasing), ]
if (head)
out <- head(out, n)
out
}
# shorthand
lsos <- function(..., n=10) {
.ls.objects(..., order.by=""Size"", decreasing=TRUE, head=TRUE, n=n)
}
",https://stackoverflow.com/questions/1358003/tricks-to-manage-the-available-memory-in-an-r-session,550,144846.0,28.0,,,2009-08-31 15:26:13,2021-07-08 15:33:19,2015-07-10 12:52:37,,,memory-management;r,Dirk is no longer here,370396,143305,registered,true,1359679,,CC BY-SA 3.0,,1626,1575,2,0,0,2,true,false,false,true,true,true,53,10,false,0.193,0.0038,6291,2009,8,15,Monday,false,false,false,false,false,false,false
12193779,How to use the tryCatch() function?,"I want to write code using tryCatch to deal with errors downloading data from the web.
url <- c(
"http://stat.ethz.ch/R-manual/R-devel/library/base/html/connections.html",
"http://en.wikipedia.org/wiki/Xz")
y <- mapply(readLines, con=url)
These two statements run successfully. Below, I create a non-exist web address:
url <- c("xxxxx", "http://en.wikipedia.org/wiki/Xz")
url[1] does not exist. How does one write a tryCatch loop (function) so that:
- When the URL is wrong, the output will be: "web URL is wrong, can't get".
- When the URL is wrong, the code does not stop, but continues to download until the end of the list of URLs?
",https://stackoverflow.com/questions/12193779/how-to-use-the-trycatch-function,549,607411.0,6.0,,,2012-08-30 09:27:17,2025-03-31 13:32:16,2023-11-14 13:30:21,,,r;exception;try-catch;r-faq,Dd Pp,6047,1631694,registered,true,12195574,,CC BY-SA 4.0,2019-12-19 03:19:11,838,703,5,0,0,4,true,false,false,true,true,true,35,6,true,0.01,0.0009,5196,2012,8,9,Thursday,false,false,false,false,false,false,false
4216753,Folder management with r : Check existence of directory and create it if it doesn't exist,"I often find myself writing R scripts that generate a lot of output. I find it cleaner to put this output into its own directory(s). What I've written below will check for the existence of a directory and move into it, or create the directory and then move into it. Is there a better way to approach this?
mainDir <- "c:/path/to/main/dir"
subDir <- "outputDirectory"
if (file.exists(subDir)){
setwd(file.path(mainDir, subDir))
} else {
dir.create(file.path(mainDir, subDir))
setwd(file.path(mainDir, subDir))
}
",https://stackoverflow.com/questions/4216753/folder-management-with-r-check-existence-of-directory-and-create-it-if-it-does,538,457966.0,11.0,,,2010-11-18 15:53:45,2024-04-03 06:36:18,2023-02-08 20:31:13,,,r;directory;path;filesystems,Chase,69571,415635,registered,true,4216864,,CC BY-SA 4.0,,587,556,1,0,0,4,true,false,false,true,true,true,93,16,false,0.024,0.0012,5847,2010,11,15,Thursday,false,false,false,false,false,false,false
2547402,How to find the statistical mode?,"In R, mean() and median() are standard functions which do what you'd expect. mode() tells you the internal storage mode of the object, not the value that occurs the most in its argument. But is there is a standard library function that implements the statistical mode for a vector (or list)?
",https://stackoverflow.com/questions/2547402/how-to-find-the-statistical-mode,525,444711.0,38.0,,,2010-03-30 17:55:07,2025-09-17 06:32:43,2020-08-20 13:47:20,,,r;statistics;r-faq,Nick,22425,5222,registered,true,8189441,,CC BY-SA 4.0,2016-11-10 16:04:31,339,293,3,0,0,3,true,false,false,true,true,true,33,6,true,0.085,0.0012,6080,2010,3,17,Tuesday,false,false,false,false,false,false,false
1660124,How to sum a variable by group,"I have a data frame with two columns. First column contains categories such as ""First"", ""Second"", ""Third"", and the second column has numbers that represent the number of times I saw the specific groups from ""Category"".
For example:
Category Frequency
First 10
First 15
First 5
Second 2
Third 14
Third 20
Second 3
I want to sort the data by Category and sum all the Frequencies:
Category Frequency
First 30
Second 5
Third 34
How would I do this in R?
",https://stackoverflow.com/questions/1660124/how-to-sum-a-variable-by-group,521,1036965.0,19.0,,,2009-11-02 09:01:28,2024-03-12 09:06:04,2020-04-28 11:16:55,,,r;dataframe;aggregate;r-faq,boo-urns,10414,177541,registered,true,1661144,,CC BY-SA 4.0,2015-09-10 13:47:08,608,532,2,0,0,4,true,false,false,true,true,true,30,7,false,0.018,0.0005,6228,2009,11,9,Monday,false,false,false,false,false,false,false
2851327,Combine a list of data frames into one data frame by row,"I have code that at one place ends up with a list of data frames which I really want to convert to a single big data frame.
I got some pointers from an earlier question which was trying to do something similar but more complex.
Here's an example of what I am starting with (this is grossly simplified for illustration):
listOfDataFrames <- vector(mode = ""list"", length = 100)
for (i in 1:100) {
listOfDataFrames[[i]] <- data.frame(a=sample(letters, 500, rep=T),
b=rnorm(500), c=rnorm(500))
}
I am currently using this:
df <- do.call(""rbind"", listOfDataFrames)
",https://stackoverflow.com/questions/2851327/combine-a-list-of-data-frames-into-one-data-frame-by-row,515,392042.0,11.0,,,2010-05-17 17:38:24,2025-11-26 18:42:04,2021-02-24 16:53:48,,,r;list;dataframe;r-faq,JD Long,61014,37751,registered,true,49017065,,CC BY-SA 4.0,,784,614,2,1,0,4,true,false,false,true,true,true,56,12,false,0.028,0.0013,6032,2010,5,17,Monday,false,false,false,false,false,false,false
1474081,How do I install an R package from source?,"A friend sent me along this great tutorial on webscraping The New York Times with R. I would really love to try it. However, the first step is to install a package called [RJSONIO][2] from source.
I know R reasonably well, but I have no idea how to install a package from source.
I'm running macOS (OS X).
",https://stackoverflow.com/questions/1474081/how-do-i-install-an-r-package-from-source,504,720168.0,8.0,,,2009-09-24 20:51:30,2025-04-07 05:46:46,2024-02-06 08:35:30,,,r;install.packages;r-faq,Madjoro,,,does_not_exist,true,,,CC BY-SA 4.0,2015-08-04 16:50:38,460,306,0,1,0,3,false,false,false,true,false,true,42,9,true,0.011,0.0007,6267,2009,9,20,Thursday,false,false,false,false,false,false,false
5812493,How to add leading zeros?,"I have a set of data which looks something like this:
anim <- c(25499,25500,25501,25502,25503,25504)
sex <- c(1,2,2,1,2,1)
wt <- c(0.8,1.2,1.0,2.0,1.8,1.4)
data <- data.frame(anim,sex,wt)
data
anim sex wt anim2
1 25499 1 0.8 2
2 25500 2 1.2 2
3 25501 2 1.0 2
4 25502 1 2.0 2
5 25503 2 1.8 2
6 25504 1 1.4 2
I would like a zero to be added before each animal id:
data
anim sex wt anim2
1 025499 1 0.8 2
2 025500 2 1.2 2
3 025501 2 1.0 2
4 025502 1 2.0 2
5 025503 2 1.8 2
6 025504 1 1.4 2
And for interest sake, what if I need to add two or three zeros before the animal id's?
",https://stackoverflow.com/questions/5812493/how-to-add-leading-zeros,503,463545.0,8.0,,,2011-04-28 01:10:47,2018-10-17 06:08:40,2018-10-17 06:08:40,,,r;formatting;number-formatting;r-faq,baz,7197,438498,registered,true,5816779,,CC BY-SA 4.0,2018-05-04 10:39:50,746,677,2,0,0,4,true,false,false,true,true,true,25,5,true,0.017,0.0011,5686,2011,4,1,Thursday,false,false,false,false,false,false,false
6081439,Changing column names of a data frame,"I have a data frame called ""newprice"" (see below) and I want to change the column names in my program in R.
> newprice
Chang. Chang. Chang.
1 100 36 136
2 120 -33 87
3 150 14 164
In fact this is what am doing:
names(newprice)[1]<-paste(""premium"")
names(newprice)[2]<-paste(""change"")
names(newprice)[3]<-paste(""newprice"")
I have not put this in a loop because I want each column name to be different as you see.
When I paste my program into R console this is the output it gives me:
> names(newprice)[1]<-paste(“premium”)
Error: unexpected input in ""names(newprice)[1]<-paste(“""
> names(newprice)[2]<-paste(“change”)
Error: unexpected input in ""names(newprice)[2]<-paste(“""
> names(newprice)[3]<-paste(“newpremium”)
Error: unexpected input in ""names(newprice)[3]<-paste(“""
I have equally tried using the c() function-for example c(""premium""), instead of the paste() function, but to no avail.
Could someone help me to figure this out?
",https://stackoverflow.com/questions/6081439/changing-column-names-of-a-data-frame,494,2009183.0,19.0,,,2011-05-21 11:31:23,2023-03-26 21:11:39,2019-04-11 21:03:22,,,r;dataframe;rename,Son,5465,747389,registered,true,,,CC BY-SA 4.0,2015-01-29 00:42:09,1189,1036,6,0,0,3,false,false,false,true,true,true,37,7,false,0.009,0.0002,5663,2011,5,11,Saturday,true,false,false,false,false,false,false
1923273,Counting the number of elements with the values of x in a vector,"I have a vector of numbers:
numbers <- c(4,23,4,23,5,43,54,56,657,67,67,435,
453,435,324,34,456,56,567,65,34,435)
How can I have R count the number of times a value x appears in the vector?
",https://stackoverflow.com/questions/1923273/counting-the-number-of-elements-with-the-values-of-x-in-a-vector,493,1668968.0,21.0,,,2009-12-17 17:21:36,2023-11-24 10:32:25,2016-10-04 11:29:19,,,r;vector;count;r-faq,RQuestions,4933,233979,registered,true,1923297,,CC BY-SA 3.0,2016-04-12 10:44:17,252,205,1,0,0,4,true,false,false,true,true,true,64,13,false,0.013,0.0003,6183,2009,12,17,Thursday,false,false,false,false,false,false,false
7201341,How can two strings be concatenated?,"How can I concatenate (merge, combine) two values?
For example I have:
tmp = cbind(""GAD"", ""AB"")
tmp
# [,1] [,2]
# [1,] ""GAD"" ""AB""
My goal is to concatenate the two values in ""tmp"" to one string:
tmp_new = ""GAD,AB""
Which function can do this for me?
",https://stackoverflow.com/questions/7201341/how-can-two-strings-be-concatenated,489,1008230.0,12.0,,,2011-08-26 07:25:35,2021-10-23 16:47:10,2018-09-19 19:34:35,,,r;string-concatenation;r-faq,Hans,5595,913573,registered,true,,,CC BY-SA 4.0,2017-10-30 16:11:11,331,262,2,0,0,3,false,false,false,true,true,true,36,6,true,0.012,0.0005,5566,2011,8,7,Friday,false,false,false,false,false,false,false
7531868,How to rename a single column in a data.frame?,"I know if I have a data frame with more than 1 column, then I can use
colnames(x) <- c("col1","col2")
to rename the columns. How to do this if it's just one column?
Meaning a vector or data frame with only one column.
Example:
trSamp <- data.frame(sample(trainer$index, 10000))
head(trSamp )
# sample.trainer.index..10000.
# 1 5907862
# 2 2181266
# 3 7368504
# 4 1949790
# 5 3475174
# 6 6062879
ncol(trSamp)
# [1] 1
class(trSamp)
# [1] "data.frame"
class(trSamp[1])
# [1] "data.frame"
class(trSamp[,1])
# [1] "numeric"
colnames(trSamp)[2] <- "newname2"
# Error in names(x) <- value :
# 'names' attribute [2] must be the same length as the vector [1]
",https://stackoverflow.com/questions/7531868/how-to-rename-a-single-column-in-a-data-frame,481,1483727.0,21.0,,,2011-09-23 16:08:34,2024-02-20 09:39:29,2022-01-05 21:31:47,,,r,screechOwl,28327,914308,registered,true,7532464,,CC BY-SA 4.0,,925,856,2,0,0,1,true,false,false,true,true,true,46,9,true,0.014,0.0003,5538,2011,9,16,Friday,false,false,false,false,false,false,false
15376075,Cluster analysis in R: determine the optimal number of clusters,"How can I choose the best number of clusters to do a k-means analysis. After plotting a subset of below data, how many clusters will be appropriate? How can I perform cluster dendro analysis?
n = 1000
kk = 10
x1 = runif(kk)
y1 = runif(kk)
z1 = runif(kk)
x4 = sample(x1,length(x1))
y4 = sample(y1,length(y1))
randObs <- function()
{
ix = sample( 1:length(x4), 1 )
iy = sample( 1:length(y4), 1 )
rx = rnorm( 1, x4[ix], runif(1)/8 )
ry = rnorm( 1, y4[ix], runif(1)/8 )
return( c(rx,ry) )
}
x = c()
y = c()
for ( k in 1:n )
{
rPair = randObs()
x = c( x, rPair[1] )
y = c( y, rPair[2] )
}
z <- rnorm(n)
d <- data.frame( x, y, z )
",https://stackoverflow.com/questions/15376075/cluster-analysis-in-r-determine-the-optimal-number-of-clusters,465,290159.0,8.0,,,2013-03-13 02:39:40,2023-01-10 01:53:21,2023-01-10 01:53:21,,,r;cluster-analysis;k-means,user2153893,4697,2153893,registered,true,,,CC BY-SA 4.0,2014-03-27 16:55:41,699,668,1,0,0,3,false,false,false,true,true,true,63,10,false,0.028,0.0016,5001,2013,3,2,Wednesday,false,false,false,false,false,false,false
2470248,Write lines of text to a file in R,"In the R scripting language, how do I write lines of text, e.g., the following two lines
Hello
World
to a file named "output.txt"?
",https://stackoverflow.com/questions/2470248/write-lines-of-text-to-a-file-in-r,463,494796.0,14.0,,,2010-03-18 13:51:59,2026-02-23 15:03:18,2022-01-05 21:32:26,,,file-io;r,amarillion,24997,3306,registered,true,2470277,,CC BY-SA 4.0,,180,142,1,0,0,2,true,false,false,true,true,true,34,9,false,0.028,0.0009,6092,2010,3,13,Thursday,false,false,false,false,false,false,false
10085806,Extracting specific columns from a data frame,"I have an R data frame with 6 columns, and I want to create a new data frame that only has three of the columns.
Assuming my data frame is df, and I want to extract columns A, B, and E, this is the only command I can figure out:
data.frame(df$A,df$B,df$E)
Is there a more compact way of doing this?
",https://stackoverflow.com/questions/10085806/extracting-specific-columns-from-a-data-frame,463,1832628.0,12.0,,,2012-04-10 02:24:04,2024-04-23 20:06:41,2024-04-23 20:06:41,,,r;dataframe;r-faq,Aren Cambre,6740,425477,registered,true,29736003,,,2020-04-16 22:34:44,397,300,5,0,0,3,true,false,false,true,true,true,45,7,false,0.007,0.0003,5338,2012,4,2,Tuesday,false,false,false,false,false,false,false
1249548,Side-by-side plots with ggplot2,"I would like to place two plots side by side using the ggplot2 package, i.e. do the equivalent of par(mfrow=c(1,2)).
For example, I would like to have the following two plots show side-by-side with the same scale.
x <- rnorm(100)
eps <- rnorm(100,0,.2)
qplot(x,3*x+eps)
qplot(x,2*x+eps)
Do I need to put them in the same data.frame?
qplot(displ, hwy, data=mpg, facets = . ~ year) + geom_smooth()
",https://stackoverflow.com/questions/1249548/side-by-side-plots-with-ggplot2,459,737255.0,14.0,,,2009-08-08 18:16:43,2022-08-21 16:25:13,2021-12-20 16:48:23,,,r;ggplot2;visualization;r-faq,Christopher DuBois,43650,84458,registered,true,3935554,,CC BY-SA 4.0,2024-06-12 16:26:09,560,408,3,1,0,4,true,false,false,true,true,true,31,4,false,0.019,0.0006,6314,2009,8,18,Saturday,true,false,false,false,false,false,false
4090169,Elegant way to check for missing packages and install them?,"I seem to be sharing a lot of code with coauthors these days. Many of them are novice/intermediate R users and don't realize that they have to install packages they don't already have.
Is there an elegant way to call installed.packages(), compare that to the ones I am loading and install if missing?
",https://stackoverflow.com/questions/4090169/elegant-way-to-check-for-missing-packages-and-install-them,459,281192.0,36.0,,,2010-11-03 18:08:54,2025-12-21 01:41:50,2017-03-07 10:57:36,,,r;package;r-faq,Maiasaura,33216,313163,registered,true,4090208,,CC BY-SA 3.0,2017-03-07 10:57:43,329,302,1,0,0,3,true,false,false,true,true,true,59,10,true,0.128,0.0016,5862,2010,11,18,Wednesday,false,false,false,false,false,false,false
8273313,Sample random rows in dataframe,"I am struggling to find the appropriate function that would return a specified number of rows picked up randomly without replacement from a data frame in R language? Can anyone help me out?
",https://stackoverflow.com/questions/8273313/sample-random-rows-in-dataframe,458,725950.0,14.0,,,2011-11-25 19:08:40,2025-01-08 00:20:20,2020-06-16 04:36:13,,,r;dataframe;random;r-faq,nikhil,9463,502867,registered,true,8273355,,CC BY-SA 4.0,,197,190,0,0,0,4,true,false,false,true,true,true,31,5,false,0.019,0.0006,5475,2011,11,19,Friday,false,false,false,false,false,false,false
9860090,Why is `[` better than `subset`?,"When I need to filter a data.frame, i.e., extract rows that meet certain conditions, I prefer to use the subset function:
subset(airquality, Month == 8 & Temp > 90)
Rather than the [ function:
airquality[airquality$Month == 8 & airquality$Temp > 90, ]
There are two main reasons for my preference:
I find the code reads better, from left to right. Even people who know nothing about R could tell what the subset statement above is doing.
Because columns can be referred to as variables in the select expression, I can save a few keystrokes. In my example above, I only had to type airquality once with subset, but three times with [.
So I was living happy, using subset everywhere because it is shorter and reads better, even advocating its beauty to my fellow R coders. But yesterday my world broke apart. While reading the subset documentation, I notice this section:
Warning
This is a convenience function intended for use interactively. For programming it is better to use the standard subsetting functions like [, and in particular the non-standard evaluation of argument subset can have unanticipated consequences.
Could someone help clarify what the authors mean?
First, what do they mean by "for use interactively"? I know what an interactive session is, as opposed to a script run in BATCH mode but I don't see what difference it should make.
Then, could you please explain "the non-standard evaluation of argument subset" and why it is dangerous, maybe provide an example?
",https://stackoverflow.com/questions/9860090/why-is-better-than-subset,449,112081.0,2.0,,,2012-03-25 12:27:32,2016-11-15 08:02:47,2020-06-20 09:12:55,,,r;filter;subset;r-faq,flodel,89425,1201032,registered,true,9863081,,CC BY-SA 4.0,2019-07-23 12:43:02,1837,1525,11,0,0,4,true,false,false,true,true,true,32,6,true,0.018,0.004,5354,2012,3,12,Sunday,true,false,false,false,false,false,false
5577727,Is there an R function for finding the index of an element in a vector?,"In R, I have an element x and a vector v. I want to find the first index of an element in v that is equal to x. I know that one way to do this is: which(x == v)[[1]], but that seems excessively inefficient. Is there a more direct way to do it?
For bonus points, is there a function that works if x is a vector? That is, it should return a vector of indices indicating the position of each element of x in v.
",https://stackoverflow.com/questions/5577727/is-there-an-r-function-for-finding-the-index-of-an-element-in-a-vector,448,845769.0,5.0,,,2011-04-07 07:55:57,2026-01-12 16:19:47,2011-04-07 08:04:16,,,r;indexing;match;vectorization,Ryan C. Thompson,42550,125921,registered,true,5577776,,CC BY-SA 2.5,2020-10-20 06:52:41,527,409,8,0,0,4,true,false,false,true,true,true,71,15,true,0.006,0.0005,5707,2011,4,7,Thursday,false,false,false,false,false,false,false
3606697,How to set limits for axes in ggplot2 R plots?,"I plot the following:
library(ggplot2)
carrots <- data.frame(length = rnorm(500000, 10000, 10000))
cukes <- data.frame(length = rnorm(50000, 10000, 20000))
carrots$veg <- 'carrot'
cukes$veg <- 'cuke'
vegLengths <- rbind(carrots, cukes)
ggplot(vegLengths, aes(length, fill = veg)) +
geom_density(alpha = 0.2)
Now say, I only want to plot the region between x=-5000 to 5000, instead of the entire range.
How can I do that?
",https://stackoverflow.com/questions/3606697/how-to-set-limits-for-axes-in-ggplot2-r-plots,447,806153.0,2.0,,,2010-08-31 07:03:24,2022-01-05 21:27:31,2022-01-05 21:27:31,,,r;plot;ggplot2,David B,30158,377031,registered,true,3606798,,CC BY-SA 4.0,,515,444,3,0,0,3,true,false,false,true,true,true,46,10,true,0.002,0.0006,5926,2010,8,7,Tuesday,false,false,false,false,false,false,false
2261079,How can I trim leading and trailing white space?,"I am having some trouble with leading and trailing white space in a data.frame.
For example, I look at a specific row in a data.frame based on a certain condition:
> myDummy[myDummy$country == c("Austria"),c(1,2,3:7,19)]
[1] codeHelper country dummyLI dummyLMI dummyUMI
[6] dummyHInonOECD dummyHIOECD dummyOECD
<0 rows> (or 0-length row.names)
I was wondering why I didn't get the expected output since the country Austria obviously existed in my data.frame. After looking through my code history and trying to figure out what went wrong I tried:
> myDummy[myDummy$country == c("Austria "),c(1,2,3:7,19)]
codeHelper country dummyLI dummyLMI dummyUMI dummyHInonOECD dummyHIOECD
18 AUT Austria 0 0 0 0 1
dummyOECD
18 1
All I have changed in the command is an additional white space after Austria.
Further annoying problems obviously arise. For example, when I like to merge two frames based on the country column. One data.frame uses "Austria " while the other frame has "Austria". The matching doesn't work.
- Is there a nice way to 'show' the white space on my screen so that I am aware of the problem?
- And can I remove the leading and trailing white space in R?
So far I used to write a simple Perl script which removes the whites pace, but it would be nice if I can somehow do it inside R.
",https://stackoverflow.com/questions/2261079/how-can-i-trim-leading-and-trailing-white-space,428,415971.0,15.0,,,2010-02-14 12:44:02,2022-09-26 20:55:54,2022-01-05 21:27:13,,,r;whitespace;trim;removing-whitespace;r-faq,mropa,11952,258334,registered,true,2261149,,CC BY-SA 4.0,,1717,1456,8,1,0,5,true,false,false,true,true,true,48,9,true,0.036,0.001,6124,2010,2,12,Sunday,true,false,false,false,false,false,false
11134812,How to find the length of a string in R,"How to find the length of a string (i.e., number of characters in a string) without splitting it in R? I know how to find the length of a list but not of a string.
And what about Unicode strings? How do I find the length (in bytes) and the number of characters (runes, symbols) in a Unicode string?
Related Question:
",https://stackoverflow.com/questions/11134812/how-to-find-the-length-of-a-string-in-r,416,443973.0,6.0,,,2012-06-21 09:01:40,2022-01-05 21:26:11,2022-01-05 21:26:11,,,r;string;unicode;string-length,Igor Chubin,65429,1458569,registered,true,11134861,,CC BY-SA 4.0,,572,398,0,1,0,4,true,false,false,true,true,true,39,10,false,0.014,0.0009,5266,2012,6,9,Thursday,false,false,false,false,false,false,false
10128617,Test if characters are in a string,"I'm trying to determine if a string is a subset of another string. For example:
chars <- "test"
value <- "es"
I want to return TRUE if "value" appears as part of the string "chars". In the following scenario, I would want to return false:
chars <- "test"
value <- "et"
",https://stackoverflow.com/questions/10128617/test-if-characters-are-in-a-string,413,872185.0,9.0,,,2012-04-12 17:24:08,2022-09-18 16:27:33,2022-09-18 16:27:33,,,r;regex;string;r-faq,mike,24051,862345,registered,true,10128682,,CC BY-SA 4.0,,446,345,5,0,0,4,true,false,false,true,true,true,34,7,false,0.01,0.0005,5336,2012,4,17,Thursday,false,false,false,false,false,false,false
40675778,Center Plot title in ggplot2,"This simple code (and all my scripts from this morning) has started giving me an off center title in ggplot2:
Ubuntu version: 16.04
R studio version: Version 0.99.896
R version: 3.3.2
GGPLOT2 version: 2.2.0
I have freshly installed the above this morning to try and fix this...
dat <- data.frame(
time = factor(c("Lunch","Dinner"), levels=c("Lunch","Dinner")),
total_bill = c(14.89, 17.23)
)
# Add title, narrower bars, fill color, and change axis labels
ggplot(data=dat, aes(x=time, y=total_bill, fill=time)) +
geom_bar(colour="black", fill="#DD8888", width=.8, stat="identity") +
guides(fill=FALSE) +
xlab("Time of day") + ylab("Total bill") +
ggtitle("Average bill for 2 people")
",https://stackoverflow.com/questions/40675778/center-plot-title-in-ggplot2,409,776444.0,5.0,,,2016-11-18 11:18:31,2023-03-17 07:42:28,2021-02-10 04:33:10,,,r;ggplot2;center;ggtitle,Christopher John,4510,4495143,registered,true,41487043,,CC BY-SA 4.0,,1015,803,2,1,1,4,true,false,false,true,true,true,28,5,false,0.006,0.0005,3655,2016,11,11,Friday,false,false,false,false,false,false,false
35618260,Remove legend ggplot 2.2,"I'm trying to keep the legend of one layer (smooth) and remove the legend of the other (point). I have tried shutting off the legends with guides(colour = FALSE) and geom_point(aes(color = vs), show.legend = FALSE).
Edit: As this question and its answers are popular, a reproducible example seems in order:
library(ggplot2)
ggplot(data = mtcars, aes(x = mpg, y = disp, group = gear)) +
geom_point(aes(color = vs)) +
geom_point(aes(shape = factor(cyl))) +
geom_line(aes(linetype = factor(gear))) +
geom_smooth(aes(fill = factor(gear), color = gear)) +
theme_bw()
",https://stackoverflow.com/questions/35618260/remove-legend-ggplot-2-2,407,747978.0,4.0,,,2016-02-25 04:19:15,2024-02-06 05:20:41,2018-11-26 05:04:58,,,r;ggplot2;legend,Guy,4185,2942785,registered,true,,,CC BY-SA 4.0,,799,570,3,1,1,3,false,false,false,true,true,true,24,4,false,0.005,0.0005,3922,2016,2,4,Thursday,false,false,false,false,false,false,false
2851015,Convert data.frame columns from factors to characters,"I have a data frame. Let's call him bob:
> head(bob)
phenotype exclusion
GSM399350 3- 4- 8- 25- 44+ 11b- 11c- 19- NK1.1- Gr1- TER119-
GSM399351 3- 4- 8- 25- 44+ 11b- 11c- 19- NK1.1- Gr1- TER119-
GSM399352 3- 4- 8- 25- 44+ 11b- 11c- 19- NK1.1- Gr1- TER119-
GSM399353 3- 4- 8- 25+ 44+ 11b- 11c- 19- NK1.1- Gr1- TER119-
GSM399354 3- 4- 8- 25+ 44+ 11b- 11c- 19- NK1.1- Gr1- TER119-
GSM399355 3- 4- 8- 25+ 44+ 11b- 11c- 19- NK1.1- Gr1- TER119-
I'd like to concatenate the rows of this data frame (this will be another question). But look:
> class(bob$phenotype)
[1] ""factor""
Bob's columns are factors. So, for example:
> as.character(head(bob))
[1] ""c(3, 3, 3, 6, 6, 6)"" ""c(3, 3, 3, 3, 3, 3)""
[3] ""c(29, 29, 29, 30, 30, 30)""
I don't begin to understand this, but I guess these are indices into the levels of the factors of the columns (of the court of king caractacus) of bob? Not what I need.
Strangely I can go through the columns of bob by hand, and do
bob$phenotype <- as.character(bob$phenotype)
which works fine. And, after some typing, I can get a data.frame whose columns are characters rather than factors. So my question is: how can I do this automatically? How do I convert a data.frame with factor columns into a data.frame with character columns without having to manually go through each column?
Bonus question: why does the manual approach work?
",https://stackoverflow.com/questions/2851015/convert-data-frame-columns-from-factors-to-characters,405,775860.0,18.0,,,2010-05-17 16:52:02,2020-08-20 10:13:49,2013-01-10 22:26:57,,,r;dataframe,Mike Dewar,11165,270572,registered,true,2851213,,CC BY-SA 3.0,2016-02-03 14:03:26,1633,1436,8,0,0,2,true,false,false,true,true,true,53,7,false,0.023,0.0005,6032,2010,5,16,Monday,false,false,false,false,false,false,false
5208679,Order Bars in ggplot2 bar graph,"I am trying to make a bar graph where the largest bar would be nearest to the y axis and the shortest bar would be furthest. So this is kind of like the Table I have
Name Position
1 James Goalkeeper
2 Frank Goalkeeper
3 Jean Defense
4 Steve Defense
5 John Defense
6 Tim Striker
So I am trying to build a bar graph that would show the number of players according to position
p <- ggplot(theTable, aes(x = Position)) + geom_bar(binwidth = 1)
but the graph shows the goalkeeper bar first then the defense, and finally the striker one. I would want the graph to be ordered so that the defense bar is closest to the y axis, the goalkeeper one, and finally the striker one.
Thanks
",https://stackoverflow.com/questions/5208679/order-bars-in-ggplot2-bar-graph,403,611212.0,16.0,,,2011-03-06 04:20:48,2023-03-15 15:48:08,2016-10-08 17:32:18,,,r;ggplot2;r-faq,Julio Diaz,9537,590942,registered,true,5210833,,CC BY-SA 3.0,,781,712,2,0,0,3,true,false,false,true,true,true,31,6,false,0.026,0.0007,5739,2011,3,4,Sunday,true,false,false,false,false,false,false
5620885,How does one reorder columns in a data frame?,"How would one change this input (with the sequence: time, in, out, files):
Time In Out Files
1 2 3 4
2 3 4 5
To this output (with the sequence: time, out, in, files)?
Time Out In Files
1 3 2 4
2 4 3 5
Here's the dummy R data:
table <- data.frame(Time=c(1,2), In=c(2,3), Out=c(3,4), Files=c(4,5))
table
## Time In Out Files
##1 1 2 3 4
##2 2 3 4 5
",https://stackoverflow.com/questions/5620885/how-does-one-reorder-columns-in-a-data-frame,399,921770.0,12.0,,,2011-04-11 11:55:13,2022-06-14 07:09:35,2019-06-03 06:08:24,,,r;sorting;dataframe;r-faq,Catherine,5427,691390,unregistered,true,,,CC BY-SA 4.0,2017-07-06 14:37:37,537,440,3,0,0,4,false,false,false,true,true,true,45,9,true,0.013,0.0004,5703,2011,4,11,Monday,false,false,false,false,false,false,false
5890584,How to reshape data from long to wide format,"I'm having trouble rearranging the following data frame:
set.seed(45)
dat1 <- data.frame(
name = rep(c(""firstName"", ""secondName""), each=4),
numbers = rep(1:4, 2),
value = rnorm(8)
)
dat1
name numbers value
1 firstName 1 0.3407997
2 firstName 2 -0.7033403
3 firstName 3 -0.3795377
4 firstName 4 -0.7460474
5 secondName 1 -0.8981073
6 secondName 2 -0.3347941
7 secondName 3 -0.5013782
8 secondName 4 -0.1745357
I want to reshape it so that each unique ""name"" variable is a rowname, with the ""values"" as observations along that row and the ""numbers"" as colnames. Sort of like this:
name 1 2 3 4
1 firstName 0.3407997 -0.7033403 -0.3795377 -0.7460474
5 secondName -0.8981073 -0.3347941 -0.5013782 -0.1745357
I've looked at melt and cast and a few other things, but none seem to do the job.
",https://stackoverflow.com/questions/5890584/how-to-reshape-data-from-long-to-wide-format,393,544975.0,15.0,,,2011-05-04 22:27:50,2026-05-01 07:59:18,2019-03-30 14:25:31,,,r;reshape;r-faq,Steve,6077,230850,registered,true,5890979,,CC BY-SA 4.0,2021-02-18 07:18:33,1015,920,4,0,0,3,true,false,false,true,true,true,44,9,false,0.028,0.0007,5680,2011,5,22,Wednesday,false,false,false,false,false,false,false
36733638,Representing Parametric Survival Model in 'Counting Process' form in JAGS,"I'm trying to build a survival model in JAGS that allows for time-varying covariates. I'd like it to be a parametric model — for example, assuming survival follows the Weibull distribution (but I'd like to allow the hazard to vary, so exponential is too simple). So, this is essentially a Bayesian version of what can be done in the flexsurv package, which allows for time-varying covariates in parametric models.
Therefore, I want to be able to enter the data in a 'counting-process' form, where each subject has multiple rows, each corresponding to a time interval in which their covariates remained constant (as described in this pdf or here. This is the (start, stop] formulation that the survival or flexurv packages allow.
Unfortunately, every explanation of how to perform survival analysis in JAGS seems to assume one row per subject.
I attempted to take this simpler approach and extend it to the counting process format, but the model does not correctly estimate the distribution.
A Failed Attempt:
Here's an example. First we generate some data:
library('dplyr')
library('survival')
## Make the Data: -----
set.seed(3)
n_sub <- 1000
current_date <- 365*2
true_shape <- 2
true_scale <- 365
dat <- data_frame(person = 1:n_sub,
true_duration = rweibull(n = n_sub, shape = true_shape, scale = true_scale),
person_start_time = runif(n_sub, min= 0, max= true_scale*2),
person_censored = (person_start_time + true_duration) > current_date,
person_duration = ifelse(person_censored, current_date - person_start_time, true_duration)
)
person person_start_time person_censored person_duration
(int) (dbl) (lgl) (dbl)
1 1 11.81416 FALSE 487.4553
2 2 114.20900 FALSE 168.7674
3 3 75.34220 FALSE 356.6298
4 4 339.98225 FALSE 385.5119
5 5 389.23357 FALSE 259.9791
6 6 253.71067 FALSE 259.0032
7 7 419.52305 TRUE 310.4770
Then we split the data into 2 observations per subject. I'm just splitting each subject at time = 300 (unless they didn't make it to time=300, in which they get just one observation).
## Split into multiple observations per person: --------
cens_point <- 300 # <----- try changing to 0 for no split; if so, model correctly estimates
dat_split <- dat %>%
group_by(person) %>%
do(data_frame(
split = ifelse(.$person_duration > cens_point, cens_point, .$person_duration),
START = c(0, split[1]),
END = c(split[1], .$person_duration),
TINTERVAL = c(split[1], .$person_duration - split[1]),
CENS = c(ifelse(.$person_duration > cens_point, 1, .$person_censored), .$person_censored), # <— edited original post here due to bug; but problem still present when fixing bug
TINTERVAL_CENS = ifelse(CENS, NA, TINTERVAL),
END_CENS = ifelse(CENS, NA, END)
)) %>%
filter(TINTERVAL != 0)
person split START END TINTERVAL CENS TINTERVAL_CENS
(int) (dbl) (dbl) (dbl) (dbl) (dbl) (dbl)
1 1 300.0000 0 300.0000 300.00000 1 NA
2 1 300.0000 300 487.4553 187.45530 0 187.45530
3 2 168.7674 0 168.7674 168.76738 1 NA
4 3 300.0000 0 300.0000 300.00000 1 NA
5 3 300.0000 300 356.6298 56.62979 0 56.62979
6 4 300.0000 0 300.0000 300.00000 1 NA
Now we can set up the JAGS model.
## Set-Up JAGS Model -------
dat_jags <- as.list(dat_split)
dat_jags$N <- length(dat_jags$TINTERVAL)
inits <- replicate(n = 2, simplify = FALSE, expr = {
list(TINTERVAL_CENS = with(dat_jags, ifelse(CENS, TINTERVAL + 1, NA)),
END_CENS = with(dat_jags, ifelse(CENS, END + 1, NA)) )
})
model_string <-
"
model {
# set priors on reparameterized version, as suggested
# here: https://sourceforge.net/p/mcmc-jags/discussion/610036/thread/d5249e71/?limit=25#8c3b
log_a ~ dnorm(0, .001)
log(a) <- log_a
log_b ~ dnorm(0, .001)
log(b) <- log_b
nu <- a
lambda <- (1/b)^a
for (i in 1:N) {
# Estimate Subject-Durations:
CENS[i] ~ dinterval(TINTERVAL_CENS[i], TINTERVAL[i])
TINTERVAL_CENS[i] ~ dweibull( nu, lambda )
}
}
"
library('runjags')
param_monitors <- c('a', 'b', 'nu', 'lambda')
fit_jags <- run.jags(model = model_string,
burnin = 1000, sample = 1000,
monitor = param_monitors,
n.chains = 2, data = dat_jags, inits = inits)
# estimates:
fit_jags
# actual:
c(a=true_shape, b=true_scale)
Depending on where the split point is, the model estimates very different parameters for the underlying distribution. It only gets the parameters right if the data isn't split into the counting process form. It seems like this is not the way to format the data for this kind of problem.
If I am missing an assumption and my problem is less related to JAGS and more related to how I'm formulating the problem, suggestions are very welcome. I might be despairing that time-varying covariates can't be used in parametric survival models (and can only be used in models like the Cox model, which assumes constant hazards and which doesn't actually estimate the underlying distribution)— however, as I mentioned above, the flexsurvreg package in R does accommodate the (start, stop] formulation in parametric models.
If anyone knows how to build a model like this in another language (e.g. STAN instead of JAGS) that would be appreciated too.
Edit:
Chris Jackson provides some helpful advice via email:
I think the T() construct for truncation in JAGS is needed here. Essentially for each period (t[i], t[i+1]) where a person is alive but the covariate is constant, the survival time is left-truncated at the start of the period, and possibly also right-censored at the end. So you'd write something like y[i] ~ dweib(shape, scale[i])T(t[i], )
I tried implementing this suggestion as follows:
model {
# same as before
log_a ~ dnorm(0, .01)
log(a) <- log_a
log_b ~ dnorm(0, .01)
log(b) <- log_b
nu <- a
lambda <- (1/b)^a
for (i in 1:N) {
# modified to include left-truncation
CENS[i] ~ dinterval(END_CENS[i], END[i])
END_CENS[i] ~ dweibull( nu, lambda )T(START[i],)
}
}
Unfortunately this doesn't quite do the trick. With the old code, the model was mostly getting the scale parameter right, but doing a very bad job on the shape parameter. With this new code, it gets very close to the correct shape parameter, but consistently over-estimates the scale parameter. I have noticed that the degree of over-estimation is correlated with how late the split point comes. If the split-point is early (cens_point = 50), there's not really any over-estimation; if it's late (cens_point = 350), there is a lot.
I thought maybe the problem could be related to 'double-counting' the observations: if we see a censored observation at t=300, then from that same person, an uncensored observation at t=400, it seems intuitive to me that this person is contributing two data-points to our inference about the Weibull parameters when really they should just be contributing one point. I, therefore, tried in",https://stackoverflow.com/questions/36733638/representing-parametric-survival-model-in-counting-process-form-in-jags,393,10765.0,1.0,,,2016-04-20 04:08:21,2022-01-05 21:29:35,2022-01-05 21:29:35,,,r;survival-analysis;jags;stan;weibull,jwdink,4865,3291744,registered,true,,,CC BY-SA 4.0,2021-04-18 17:14:27,8467,7800,14,3,0,5,false,false,false,true,true,true,81,10,false,0.093,0.0365,3867,2016,4,4,Wednesday,false,false,false,false,false,false,false
5831794,Opposite of %in%: exclude rows with values specified in a vector,"
A categorical variable V1 in a data frame D1 can have values represented by the letters from A to Z. I want to create a subset D2, which excludes some values, say, B, N and T. Basically, I want a command which is the opposite of %in%
D2 = subset(D1, V1 %in% c("B", "N", "T"))
",https://stackoverflow.com/questions/5831794/opposite-of-in-exclude-rows-with-values-specified-in-a-vector,388,556256.0,13.0,,,2011-04-29 12:06:07,2022-06-13 23:16:48,2021-03-23 20:47:59,,,r;dataframe;subset,user702432,12288,702432,registered,true,5831829,,CC BY-SA 4.0,2022-01-02 12:36:40,351,307,2,0,0,3,true,false,false,true,true,true,64,11,false,0.023,0.0007,5685,2011,4,12,Friday,false,false,false,false,false,false,false
9368900,How to check if object (variable) is defined in R?,"I'd like to check if some variable is defined in R - without getting an error. How can I do this?
My attempts (not successful):
> is.na(ooxx)
Error: object 'ooxx' not found
> is.finite(ooxx)
Error: object 'ooxx' not found
Thanks!
",https://stackoverflow.com/questions/9368900/how-to-check-if-object-variable-is-defined-in-r,386,255454.0,7.0,,,2012-02-20 21:46:47,2021-05-18 15:24:14,2016-06-01 14:16:23,,,r,Tomas,60384,684229,registered,true,9368953,,CC BY-SA 3.0,,285,240,1,0,0,1,true,false,false,true,true,true,50,10,true,0.027,0.0015,5388,2012,2,21,Monday,false,false,false,false,false,false,false
7963898,Extracting the last n characters from a string in R,"How can I get the last n characters from a string in R?
Is there a function like SQL's RIGHT?
",https://stackoverflow.com/questions/7963898/extracting-the-last-n-characters-from-a-string-in-r,386,579470.0,16.0,,,2011-11-01 08:11:19,2024-01-23 16:48:49,2015-02-02 11:31:26,,,r;string;substring,Brani,6814,299077,registered,true,7963963,,CC BY-SA 3.0,2024-07-12 21:37:01,101,94,0,0,0,3,true,false,false,true,true,true,51,10,false,0.028,0.0007,5499,2011,11,8,Tuesday,false,false,false,false,false,false,false
5234117,How to drop columns by name in a data frame,"I have a large data set and I would like to read specific columns or drop all the others.
data <- read.dta(""file.dta"")
I select the columns that I'm not interested in:
var.out <- names(data)[!names(data) %in% c(""iden"", ""name"", ""x_serv"", ""m_serv"")]
and than I'd like to do something like:
for(i in 1:length(var.out)) {
paste(""data$"", var.out[i], sep="""") <- NULL
}
to drop all the unwanted columns. Is this the optimal solution?
",https://stackoverflow.com/questions/5234117/how-to-drop-columns-by-name-in-a-data-frame,384,680456.0,13.0,,,2011-03-08 14:56:26,2024-06-14 07:52:06,2013-09-30 12:34:32,,,r;dataframe;subset,leroux,3979,649996,registered,true,5234201,,CC BY-SA 3.0,2022-10-26 13:22:22,548,448,3,0,0,3,true,false,false,true,true,true,43,10,false,0.019,0.0006,5737,2011,3,14,Tuesday,false,false,false,false,false,false,false
5352099,How can I disable scientific notation?,"I have a dataframe with a column of p-values, and I want to make a selection on these p-values.
> pvalues_anova
[1] 9.693919e-01 9.781728e-01 9.918415e-01 9.716883e-01 1.667183e-02
[6] 9.952762e-02 5.386854e-01 9.997699e-01 8.714044e-01 7.211856e-01
[11] 9.536330e-01 9.239667e-01 9.645590e-01 9.478572e-01 6.243775e-01
[16] 5.608563e-01 1.371190e-04 9.601970e-01 9.988648e-01 9.698365e-01
[21] 2.795891e-06 1.290176e-01 7.125751e-01 5.193604e-01 4.835312e-04
Selection way:
anovatest<- results[ - which(results$pvalues_anova < 0.8) ,]
The function works really fine if I use it in R. But if I run it in another application (galaxy), the numbers which don't have e-01 e.g. 4.835312e-04 are not thrown out.
Is there another way to notate p-values, like 0.0004835312 instead of 4.835312e-04?
",https://stackoverflow.com/questions/5352099/how-can-i-disable-scientific-notation,384,424255.0,6.0,,,2011-03-18 12:40:54,2023-05-24 10:59:00,2022-06-23 22:00:24,,,r;formatting;scientific-notation,Samantha,3925,665742,unregistered,true,,,CC BY-SA 4.0,2017-07-18 09:15:18,929,801,6,0,0,3,false,false,false,true,true,true,38,6,true,0.014,0.0009,5727,2011,3,12,Friday,false,false,false,false,false,false,false
14260340,Function to clear the console in R and RStudio,"I am wondering if there is a function to clear the console in R and, in particular, RStudio I am looking for a function that I can type into the console, and not a keyboard shortcut.
Someone has already provided such a function in this StackExchange post from 2010. Unfortunately, this depends on the RCom package and will not run on Mac OS X.
",https://stackoverflow.com/questions/14260340/function-to-clear-the-console-in-r-and-rstudio,375,611392.0,14.0,,,2013-01-10 14:37:49,2023-02-10 16:23:28,2018-03-16 23:16:50,,,r,Berk U.,7238,568249,registered,true,16084793,,CC BY-SA 3.0,2016-11-30 16:06:39,450,345,0,1,0,1,true,false,false,true,true,true,46,9,false,0.023,0.0006,5063,2013,1,14,Thursday,false,false,false,false,false,false,false
652136,How can I remove an element from a list?,"I have a list and I want to remove a single element from it. How can I do this?
I've tried looking up what I think the obvious names for this function would be in the reference manual and I haven't found anything appropriate.
",https://stackoverflow.com/questions/652136/how-can-i-remove-an-element-from-a-list,375,736577.0,21.0,,,2009-03-16 20:59:36,2025-11-24 21:10:23,2021-03-04 00:38:26,,,r;list;indexing;r-faq,David Locke,18145,1447,registered,true,652180,,CC BY-SA 4.0,2015-07-20 16:02:42,242,228,0,0,0,4,true,false,false,true,true,true,40,9,true,0.029,0.0005,6459,2009,3,20,Monday,false,false,false,false,false,false,false
3443687,Formatting Decimal places in R,"I have a number, for example 1.128347132904321674821 that I would like to show as only two decimal places when output to screen (or written to a file). How does one do that?
x <- 1.128347132904321674821
EDIT:
The use of:
options(digits=2)
Has been suggested as a possible answer. Is there a way to specify this within a script for one-time use? When I add it to my script it doesn't seem to do anything different and I'm not interested in a lot of re-typing to format each number (I'm automating a very large report).
--
Answer: round(x, digits=2)
",https://stackoverflow.com/questions/3443687/formatting-decimal-places-in-r,375,954564.0,16.0,,,2010-08-09 19:57:41,2024-11-11 18:02:07,2019-09-17 19:23:33,,,r;formatting;rounding;r-faq,Brandon Bertelsen,44888,170352,registered,true,12135122,,CC BY-SA 4.0,2015-10-13 08:22:33,655,565,2,0,0,4,true,false,false,true,true,true,30,5,false,0.017,0.0004,5948,2010,8,19,Monday,false,false,false,false,false,false,false
3777174,Plotting two variables as lines using ggplot2 on the same graph,"A very newbish question, but say I have data like this:
test_data <-
data.frame(
var0 = 100 + c(0, cumsum(runif(49, -20, 20))),
var1 = 150 + c(0, cumsum(runif(49, -10, 10))),
date = seq(as.Date(""2002-01-01""), by=""1 month"", length.out=100)
)
How can I plot both time series var0 and var1 on the same graph, with date on the x-axis, using ggplot2? Bonus points if you make var0 and var1 different colours, and can include a legend!
I'm sure this is very simple, but I can't find any examples out there.
",https://stackoverflow.com/questions/3777174/plotting-two-variables-as-lines-using-ggplot2-on-the-same-graph,374,669055.0,5.0,,,2010-09-23 09:53:40,2022-11-19 12:05:34,2018-05-02 11:37:25,,,r;ggplot2;graph;time-series;r-faq,fmark,59043,103225,registered,true,3780353,,CC BY-SA 4.0,2018-03-09 10:20:52,648,525,7,0,0,5,true,false,false,true,true,true,63,11,false,0.007,0.0006,5903,2010,9,9,Thursday,false,false,false,false,false,false,false
6262203,Measuring function execution time in R,"Is there a standardized way in R of measuring execution time of function?
Obviously I can take system.time before and after execution and then take the difference of those, but I would like to know if there is some standardized way or function (would like to not invent the wheel).
I seem to remember that I have once used something like below:
somesysfunction(""myfunction(with,arguments)"")
> Start time : 2001-01-01 00:00:00 # output of somesysfunction
> ""Result"" ""of"" ""myfunction"" # output of myfunction
> End time : 2001-01-01 00:00:10 # output of somesysfunction
> Total Execution time : 10 seconds # output of somesysfunction
",https://stackoverflow.com/questions/6262203/measuring-function-execution-time-in-r,373,333340.0,16.0,,,2011-06-07 07:55:52,2025-08-13 04:01:49,2017-05-30 15:58:26,,,r;time;profiling,dns,3721,787038,unregistered,true,,,CC BY-SA 3.0,,722,660,2,0,0,3,false,false,false,true,true,true,38,6,false,0.048,0.0011,5646,2011,6,7,Tuesday,false,false,false,false,false,false,false
1743698,Evaluate expression given as a string,"I'm curious to know if R can use its eval() function to perform calculations provided by e.g. a string.
This is a common case:
eval(""5+5"")
However, instead of 10 I get:
[1] ""5+5""
Any solution?
",https://stackoverflow.com/questions/1743698/evaluate-expression-given-as-a-string,372,270225.0,8.0,,,2009-11-16 17:39:31,2022-07-11 23:19:52,2017-02-28 10:54:03,,,r;eval;r-faq,Federico Giorgi,10825,209467,registered,true,1743796,,CC BY-SA 3.0,2019-02-05 08:01:31,289,200,3,0,0,3,true,false,false,true,true,true,37,6,false,0.03,0.0014,6214,2009,11,17,Monday,false,false,false,false,false,false,false
77434,How to access the last value in a vector?,"Suppose I have a vector that is nested in a dataframe with one or two levels. Is there a quick and dirty way to access the last value, without using the length() function? Something ala PERL's $# special var?
So I would like something like:
dat$vec1$vec2[$#]
instead of:
dat$vec1$vec2[length(dat$vec1$vec2)]
",https://stackoverflow.com/questions/77434/how-to-access-the-last-value-in-a-vector,368,527249.0,13.0,,,2008-09-16 21:40:29,2024-11-18 22:48:08,2023-01-01 14:54:35,,,r;dataframe;vector,user14008,3671,14008,registered,true,,,CC BY-SA 4.0,,407,312,4,0,0,3,false,false,false,true,true,true,41,9,true,0.025,0.0007,6640,2008,9,21,Tuesday,false,false,false,false,false,false,false
3099219,ggplot with 2 y axes on each side and different scales,"I need to plot a bar chart showing counts and a line chart showing rate all in one chart, I can do both of them separately, but when I put them together, I scale of the first layer (i.e. the geom_bar) is overlapped by the second layer (i.e. the geom_line).
Can I move the axis of the geom_line to the right?
",https://stackoverflow.com/questions/3099219/ggplot-with-2-y-axes-on-each-side-and-different-scales,364,612172.0,19.0,,,2010-06-23 05:52:19,2024-04-18 13:36:40,2019-05-27 19:58:38,,,r;ggplot2;r-faq,lokheart,24935,373908,registered,true,3117319,,CC BY-SA 4.0,2016-11-19 21:38:12,362,309,3,0,0,3,true,false,false,true,true,true,54,11,false,0.031,0.0006,5995,2010,6,5,Wednesday,false,false,false,false,false,false,false
2098368,Concatenate a vector of strings/character,"If I have a vector of type character, how can I concatenate the values into string? Here's how I would do it with paste():
sdata = c('a', 'b', 'c')
paste(sdata[1], sdata[2], sdata[3], sep ='')
yielding ""abc"".
But of course, that only works if I know the length of sdata ahead of time.
",https://stackoverflow.com/questions/2098368/concatenate-a-vector-of-strings-character,363,431384.0,8.0,,,2010-01-20 01:00:37,2024-09-03 22:38:36,2018-11-06 10:45:53,,,r;string;r-faq,Nick,22425,5222,registered,true,2098442,,CC BY-SA 4.0,,365,289,2,0,0,3,true,false,false,true,true,true,41,5,false,0.019,0.0008,6149,2010,1,1,Wednesday,false,false,false,false,false,false,false
7144118,How can I save a plot as an image on the disk?,"I plot a simple linear regression using R.
I would like to save that image as PNG or JPEG. Is it possible to do it automatically? (via code)
There are two different questions: First, I am already looking at the plot on my monitor and I would like to save it as is. Second, I have not yet generated the plot, but I would like to directly save it to disk when I execute my plotting code.
",https://stackoverflow.com/questions/7144118/how-can-i-save-a-plot-as-an-image-on-the-disk,362,507007.0,11.0,,,2011-08-22 07:06:34,2023-10-30 17:45:52,2023-10-30 17:33:00,,,r;plot;ggplot2;lattice;r-faq,blakc05,3799,904945,unregistered,true,7144203,,CC BY-SA 4.0,2024-10-10 17:33:17,479,386,0,1,0,5,true,false,false,true,true,true,46,12,true,0.022,0.0007,5570,2011,8,7,Monday,false,false,false,false,false,false,false
8091303,Simultaneously merge multiple data.frames in a list,"I have a list of many data.frames that I want to merge. The issue here is that each data.frame differs in terms of the number of rows and columns, but they all share the key variables (which I've called ""var1"" and ""var2"" in the code below). If the data.frames were identical in terms of columns, I could merely rbind, for which plyr's rbind.fill would do the job, but that's not the case with these data.
Because the merge command only works on 2 data.frames, I turned to the Internet for ideas. I got this one from here, which worked perfectly in R 2.7.2, which is what I had at the time:
merge.rec <- function(.list, ...){
if(length(.list)==1) return(.list[[1]])
Recall(c(list(merge(.list[[1]], .list[[2]], ...)), .list[-(1:2)]), ...)
}
And I would call the function like so:
df <- merge.rec(my.list, by.x = c(""var1"", ""var2""),
by.y = c(""var1"", ""var2""), all = T, suffixes=c("""", """"))
But in any R version after 2.7.2, including 2.11 and 2.12, this code fails with the following error:
Error in match.names(clabs, names(xi)) :
names do not match previous names
(Incidently, I see other references to this error elsewhere with no resolution).
Is there any way to solve this?
",https://stackoverflow.com/questions/8091303/simultaneously-merge-multiple-data-frames-in-a-list,355,300621.0,9.0,,,2011-11-11 08:16:54,2022-12-01 15:48:24,2017-05-23 12:18:22,,,r;list;merge;dataframe;r-faq,bshor,5079,170408,registered,true,34393416,,CC BY-SA 3.0,,1723,1220,7,3,0,5,true,false,false,true,true,true,51,7,false,0.03,0.0012,5489,2011,11,8,Friday,false,false,false,false,false,false,false
4350440,Split data frame string column into multiple columns,"I'd like to take data of the form
before = data.frame(attr = c(1,30,4,6), type=c('foo_and_bar','foo_and_bar_2'))
attr type
1 1 foo_and_bar
2 30 foo_and_bar_2
3 4 foo_and_bar
4 6 foo_and_bar_2
and use split() on the column ""type"" from above to get something like this:
attr type_1 type_2
1 1 foo bar
2 30 foo bar_2
3 4 foo bar
4 6 foo bar_2
I came up with something unbelievably complex involving some form of apply that worked, but I've since misplaced that. It seemed far too complicated to be the best way. I can use strsplit as below, but then unclear how to get that back into 2 columns in the data frame.
> strsplit(as.character(before$type),'_and_')
[[1]]
[1] ""foo"" ""bar""
[[2]]
[1] ""foo"" ""bar_2""
[[3]]
[1] ""foo"" ""bar""
[[4]]
[1] ""foo"" ""bar_2""
Thanks for any pointers. I've not quite groked R lists just yet.
",https://stackoverflow.com/questions/4350440/split-data-frame-string-column-into-multiple-columns,352,639196.0,18.0,,,2010-12-03 22:29:15,2025-01-22 14:24:43,2018-06-03 07:37:08,,,r;string;dataframe;split;r-faq,jkebinger,4174,315062,registered,true,4351918,,CC BY-SA 4.0,2019-04-18 12:07:36,1043,891,7,0,0,5,true,false,false,true,true,true,52,8,false,0.028,0.0006,5832,2010,12,22,Friday,false,false,false,false,false,false,false
35090883,Remove all of x axis labels in ggplot,"I need to remove everything on the x-axis including the labels and tick marks so that only the y-axis is labeled. How would I do this?
In the image below I would like 'clarity' and all of the tick marks and labels removed so that just the axis line is there.
Sample ggplot
data(diamonds)
ggplot(data = diamonds, mapping = aes(x = clarity)) + geom_bar(aes(fill = cut))
ggplot Chart:
Desired chart:
",https://stackoverflow.com/questions/35090883/remove-all-of-x-axis-labels-in-ggplot,350,847166.0,1.0,,,2016-01-29 17:50:22,2018-05-31 04:34:07,2018-05-31 04:34:07,2016-01-29 17:55:37,Duplicate,r;ggplot2,Vedda,7545,4104728,registered,true,35090981,,,,814,408,1,2,2,2,true,true,false,true,true,true,37,8,false,0.001,0.0004,3949,2016,1,17,Friday,false,false,false,false,false,false,false
2050790,How to correctly use lists?,"Brief background: Many (most?) contemporary programming languages in widespread use have at least a handful of ADTs [abstract data types] in common, in particular,
string (a sequence comprised of characters)
list (an ordered collection of values), and
map-based type (an unordered array that maps keys to values)
In the R programming language, the first two are implemented as character and vector, respectively.
When I began learning R, two things were obvious almost from the start: list is the most important data type in R (because it is the parent class for the R data.frame), and second, I just couldn't understand how they worked, at least not well enough to use them correctly in my code.
For one thing, it seemed to me that R's list data type was a straightforward implementation of the map ADT (dictionary in Python, NSMutableDictionary in Objective C, hash in Perl and Ruby, object literal in Javascript, and so forth).
For instance, you create them just like you would a Python dictionary, by passing key-value pairs to a constructor (which in Python is dict not list):
x = list(""ev1""=10, ""ev2""=15, ""rv""=""Group 1"")
And you access the items of an R List just like you would those of a Python dictionary, e.g., x['ev1']. Likewise, you can retrieve just the 'keys' or just the 'values' by:
names(x) # fetch just the 'keys' of an R list
# [1] ""ev1"" ""ev2"" ""rv""
unlist(x) # fetch just the 'values' of an R list
# ev1 ev2 rv
# ""10"" ""15"" ""Group 1""
x = list(""a""=6, ""b""=9, ""c""=3)
sum(unlist(x))
# [1] 18
but R lists are also unlike other map-type ADTs (from among the languages I've learned anyway). My guess is that this is a consequence of the initial spec for S, i.e., an intention to design a data/statistics DSL [domain-specific language] from the ground-up.
three significant differences between R lists and mapping types in other languages in widespread use (e.g,. Python, Perl, JavaScript):
first, lists in R are an ordered collection, just like vectors, even though the values are keyed (ie, the keys can be any hashable value not just sequential integers). Nearly always, the mapping data type in other languages is unordered.
second, lists can be returned from functions even though you never passed in a list when you called the function, and even though the function that returned the list doesn't contain an (explicit) list constructor (Of course, you can deal with this in practice by wrapping the returned result in a call to unlist):
x = strsplit(LETTERS[1:10], """") # passing in an object of type 'character'
class(x) # returns 'list', not a vector of length 2
# [1] list
A third peculiar feature of R's lists: it doesn't seem that they can be members of another ADT, and if you try to do that then the primary container is coerced to a list. E.g.,
x = c(0.5, 0.8, 0.23, list(0.5, 0.2, 0.9), recursive=TRUE)
class(x)
# [1] list
my intention here is not to criticize the language or how it is documented; likewise, I'm not suggesting there is anything wrong with the list data structure or how it behaves. All I'm after is to correct is my understanding of how they work so I can correctly use them in my code.
Here are the sorts of things I'd like to better understand:
What are the rules which determine when a function call will return a list (e.g., strsplit expression recited above)?
If I don't explicitly assign names to a list (e.g., list(10,20,30,40)) are the default names just sequential integers beginning with 1? (I assume, but I am far from certain that the answer is yes, otherwise we wouldn't be able to coerce this type of list to a vector w/ a call to unlist.)
Why do these two different operators, [], and [[]], return the same result?
x = list(1, 2, 3, 4)
both expressions return ""1"":
x[1]
x[[1]]
why do these two expressions not return the same result?
x = list(1, 2, 3, 4)
x2 = list(1:4)
Please don't point me to the R Documentation (?list, R-intro)--I have read it carefully and it does not help me answer the type of questions I recited just above.
(lastly, I recently learned of and began using an R Package (available on CRAN) called hash which implements conventional map-type behavior via an S4 class; I can certainly recommend this Package.)
",https://stackoverflow.com/questions/2050790/how-to-correctly-use-lists,349,221895.0,13.0,,,2010-01-12 17:08:50,2022-06-15 16:15:53,2022-06-15 16:15:53,,,r;list;data-structures;language-features;abstract-data-type,doug,70368,66549,registered,true,2051159,,CC BY-SA 4.0,,5619,4292,43,3,0,5,true,false,false,true,true,true,27,5,true,0.059,0.0016,6157,2010,1,17,Tuesday,false,false,false,false,false,false,false
11936339,Replace specific characters within strings,"I would like to remove specific characters from strings within a vector, similar to the Find and Replace feature in Excel.
Here are the data I start with:
group <- data.frame(c(""12357e"", ""12575e"", ""197e18"", ""e18947"")
I start with just the first column; I want to produce the second column by removing the e's:
group group.no.e
12357e 12357
12575e 12575
197e18 19718
e18947 18947
",https://stackoverflow.com/questions/11936339/replace-specific-characters-within-strings,347,815340.0,8.0,,,2012-08-13 14:26:09,2024-02-06 12:03:23,2019-02-21 00:14:32,,,r;regex;replace;gsub;string-substitution,Luke,4949,1554937,registered,true,11936385,,CC BY-SA 4.0,2024-10-08 22:25:50,506,415,3,0,0,5,true,false,false,true,true,true,42,5,false,0.01,0.0004,5213,2012,8,14,Monday,false,false,false,false,false,false,false
6558921,Difference between Boolean operators && and & and between || and | in R,"According to the R language definition, the difference between & and && (correspondingly | and ||) is that the former is vectorized while the latter is not.
According to the help text, I read the difference akin to the difference between an ""And"" and ""AndAlso"" (correspondingly ""Or"" and ""OrElse"")...
Meaning:
That not all evaluations if they don't have to be (i.e. A or B or C is always true if A is true, so stop evaluating if A is true)
Could someone shed light here?
Also, is there an AndAlso and OrElse in R?
",https://stackoverflow.com/questions/6558921/difference-between-boolean-operators-and-and-between-and-in-r,347,394813.0,4.0,,,2011-07-02 18:48:35,2023-12-18 07:59:34,2023-03-29 14:37:32,,,r;logical-operators;boolean-operations;or-operator;and-operator,Suraj,36954,356790,registered,true,6559049,,CC BY-SA 4.0,,800,527,4,2,0,5,true,false,false,true,true,true,83,14,false,0.01,0.0009,5621,2011,7,18,Saturday,true,false,false,false,false,false,false
7549694,Add regression line equation and R^2 on graph,"I wonder how to add regression line equation and R^2 on the ggplot. My code is:
library(ggplot2)
df <- data.frame(x = c(1:100))
df$y <- 2 + 3 * df$x + rnorm(100, sd = 40)
p <- ggplot(data = df, aes(x = x, y = y)) +
geom_smooth(method = ""lm"", se=FALSE, color=""black"", formula = y ~ x) +
geom_point()
p
Any help will be highly appreciated.
",https://stackoverflow.com/questions/7549694/add-regression-line-equation-and-r2-on-graph,340,532080.0,10.0,,,2011-09-26 00:52:09,2023-03-30 14:08:39,2023-03-30 14:08:39,,,r;ggplot2;linear-regression;r-faq;ggpmisc,MYaseen208,24196,707145,registered,true,7549819,,CC BY-SA 4.0,2013-10-03 22:25:38,426,375,2,0,0,5,true,false,false,true,true,true,45,8,false,0.019,0.0006,5535,2011,9,0,Monday,false,false,false,false,false,false,false
3402371,Combine two data frames by rows (rbind) when they have different sets of columns,"Is it possible to row bind two data frames that don't have the same set of columns? I am hoping to retain the columns that do not match after the bind.
",https://stackoverflow.com/questions/3402371/combine-two-data-frames-by-rows-rbind-when-they-have-different-sets-of-columns,340,539815.0,17.0,,,2010-08-04 03:25:45,2026-01-16 07:40:49,2017-06-20 07:54:11,,,r;dataframe;r-faq,Btibert3,40506,155406,registered,true,3402488,,CC BY-SA 3.0,2018-03-21 11:12:57,162,155,0,0,0,3,true,false,false,true,true,true,80,14,false,0.031,0.0006,5953,2010,8,3,Wednesday,false,false,false,false,false,false,false
11433432,How to import multiple .csv files at once?,"Suppose we have a folder containing multiple data.csv files, each containing the same number of variables but each from different times.
Is there a way in R to import them all simultaneously rather than having to import them all individually?
My problem is that I have around 2000 data files to import and having to import them individually just by using the code:
read.delim(file=""filename"", header=TRUE, sep=""\t"")
is not very efficient.
",https://stackoverflow.com/questions/11433432/how-to-import-multiple-csv-files-at-once,335,555030.0,16.0,,,2012-07-11 13:10:50,2024-12-07 21:21:20,2021-10-13 19:28:24,,,r;r-faq,Jojo,5251,1517860,registered,true,11433532,,CC BY-SA 4.0,2016-10-31 08:26:03,489,444,1,0,0,2,true,false,false,true,true,true,42,8,true,0.029,0.0006,5246,2012,7,13,Wednesday,false,false,false,false,false,false,false
13656699,Update R using RStudio,"How can I update R via RStudio?
",https://stackoverflow.com/questions/13656699/update-r-using-rstudio,334,748963.0,10.0,,,2012-12-01 05:29:34,2021-01-26 13:05:43,2020-05-08 20:13:42,,,r;rstudio,AdamNYC,20573,927667,registered,true,13656802,,CC BY-SA 4.0,2016-06-07 07:24:36,39,32,0,0,0,2,true,false,false,true,true,true,22,4,false,0.013,0.0004,5103,2012,12,5,Saturday,true,false,false,false,false,false,false
6286313,Remove an entire column from a data.frame in R,"Does anyone know how to remove an entire column from a data.frame in R? For example if I am given this data.frame:
> head(data)
chr genome region
1 chr1 hg19_refGene CDS
2 chr1 hg19_refGene exon
3 chr1 hg19_refGene CDS
4 chr1 hg19_refGene exon
5 chr1 hg19_refGene CDS
6 chr1 hg19_refGene exon
and I want to remove the 2nd column.
",https://stackoverflow.com/questions/6286313/remove-an-entire-column-from-a-data-frame-in-r,332,1397754.0,10.0,,,2011-06-08 23:02:38,2024-12-24 09:18:26,2022-11-07 09:14:04,,,r;dataframe;r-faq,Nanami,3478,787279,registered,true,6286336,,CC BY-SA 4.0,2013-07-09 13:54:45,398,360,1,0,0,3,true,false,false,true,true,true,46,9,false,0.007,0.0002,5645,2011,6,23,Wednesday,false,false,false,false,false,false,false
22850026,Filter rows which contain a certain string,"I have to filter a data frame using as a criterion those rows in which is contained the string RTB.
I'm using dplyr.
d.del <- df %>%
group_by(TrackingPixel) %>%
summarise(MonthDelivery = as.integer(sum(Revenue))) %>%
arrange(desc(MonthDelivery))
I know I can use the function filter in dplyr, but I don't exactly know how to tell it to check for the content of a string.
In particular, I want to check the content in the column TrackingPixel. If the string contains the label RTB, I want to remove the row from the result.
",https://stackoverflow.com/questions/22850026/filter-rows-which-contain-a-certain-string,329,781856.0,5.0,,,2014-04-03 22:15:15,2025-10-23 02:17:39,2025-10-23 02:17:39,,,r;filter;dplyr,Gianluca,6747,2092449,registered,true,,,CC BY-SA 4.0,,672,542,7,0,0,3,false,false,false,true,true,true,42,7,false,0.006,0.0004,4615,2014,4,22,Thursday,false,false,false,false,false,false,false
2288485,How to convert a data frame column to numeric type?,"How do you convert a data frame column to a numeric type?
",https://stackoverflow.com/questions/2288485/how-to-convert-a-data-frame-column-to-numeric-type,327,1525330.0,19.0,,,2010-02-18 12:17:58,2024-02-28 12:04:24,2015-10-10 05:54:38,,,r;dataframe;type-conversion,acroa,3329,236703,unregistered,true,2293313,,CC BY-SA 3.0,2018-02-05 16:23:27,65,58,0,0,0,3,true,false,false,true,true,true,51,10,true,0.012,0.0002,6120,2010,2,12,Thursday,false,false,false,false,false,false,false
23449319,YAML current date in rmarkdown,"I'm wondering if there's a trick to put the current date in the YAML front-matter of a .rmd document to be processed by knitr and the rmarkdown package. I used to have the following line at the top of my wiki pages,
_baptiste, `r format(Sys.time(), ""%d %B, %Y"")`_
and it would get converted to baptiste, 03 May, 2014 in the html output. Now, I would like to take advantage of the advanced pandoc wrapper provided by rmarkdown, but having r code in the YAML header doesn't seem to work:
---
title: ""Sample Document""
output:
html_document:
toc: true
theme: united
date: `r format(Sys.time(), ""%d %B, %Y"")`
author: baptiste
---
Error in yaml::yaml.load(front_matter) :
Scanner error: while scanning for the next token at line 6, column 7
found character that cannot start any token at line 6, column 7
Calls: <Anonymous> ... output_format_from_yaml_front_matter ->
parse_yaml_front_matter -> <Anonymous> -> .Call
Any workaround?
",https://stackoverflow.com/questions/23449319/yaml-current-date-in-rmarkdown,322,150824.0,8.0,,,2014-05-03 20:13:29,2022-09-11 13:30:47,,,,r;yaml;knitr;r-markdown,baptiste,77412,471093,registered,true,23529410,,CC BY-SA 3.0,,1109,979,6,0,0,4,true,false,false,true,true,false,30,5,false,0.053,0.0021,4585,2014,5,20,Saturday,true,false,false,false,false,false,false
3472980,How to change facet labels?,"I have used the following ggplot command:
ggplot(survey, aes(x = age)) + stat_bin(aes(n = nrow(h3), y = ..count.. / n), binwidth = 10)
+ scale_y_continuous(formatter = ""percent"", breaks = c(0, 0.1, 0.2))
+ facet_grid(hospital ~ .)
+ theme(panel.background = theme_blank())
to produce
![]()
I'd like to change the facet labels, however, to something shorter (like Hosp 1, Hosp 2...) because they are too long now and look cramped (increasing the height of the graph is not an option, it would take too much space in the document). I looked at the facet_grid help page but cannot figure out how.
",https://stackoverflow.com/questions/3472980/how-to-change-facet-labels,319,476339.0,24.0,,,2010-08-13 00:05:40,2024-04-20 17:04:28,2019-04-11 12:40:40,,,r;ggplot2;symbols;facet;plotmath,wishihadabettername,14911,277434,registered,true,3473306,,CC BY-SA 4.0,,845,600,4,1,1,5,true,false,false,true,true,true,27,5,true,0.05,0.0007,5944,2010,8,0,Friday,false,false,false,false,false,false,false
12328056,How do I delete rows in a data frame?,"I have a data frame named ""mydata"" that looks like this this:
A B C D
1. 5 4 4 4
2. 5 4 4 4
3. 5 4 4 4
4. 5 4 4 4
5. 5 4 4 4
6. 5 4 4 4
7. 5 4 4 4
I'd like to delete row 2,4,6. For example, like this:
A B C D
1. 5 4 4 4
3. 5 4 4 4
5. 5 4 4 4
7. 5 4 4 4
",https://stackoverflow.com/questions/12328056/how-do-i-delete-rows-in-a-data-frame,319,1995933.0,11.0,,,2012-09-08 04:37:33,2026-11-06 20:56:39,2026-11-06 20:56:39,,,r;dataframe;row;r-faq,R newbie,3247,1656047,registered,true,,,CC BY-SA 4.0,,392,325,2,0,0,4,false,false,false,true,true,true,37,9,true,0.006,0.0002,5187,2012,9,4,Saturday,true,false,false,false,false,false,false
9508518,Why are these numbers not equal?,"The following code is obviously wrong. What's the problem?
i <- 0.1
i <- i + 0.05
i
## [1] 0.15
if(i==0.15) cat(""i equals 0.15"") else cat(""i does not equal 0.15"")
## i does not equal 0.15
",https://stackoverflow.com/questions/9508518/why-are-these-numbers-not-equal,317,73563.0,7.0,,,2012-02-29 23:46:46,2023-12-29 09:28:02,2018-05-30 19:56:13,,,r;floating-point;floating-accuracy;r-faq,dplanet,5453,1195941,registered,true,9508558,,CC BY-SA 4.0,2019-10-22 10:07:16,228,197,1,0,0,4,true,false,false,true,true,true,32,6,true,0.095,0.0043,5379,2012,2,23,Wednesday,false,false,false,false,false,false,false
14604435,Turning off some legends in a ggplot,"Suppose I have a ggplot with more than one legend.
mov <- subset(movies, length != """")
(p0 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
geom_point()
)
I can turn off the display of all the legends like this:
(p1 <- p0 + theme(legend.position = ""none""))
Passing show_guide = FALSE to geom_point (as per this question) turns off the shape legend.
(p2 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
geom_point(show_guide = FALSE)
)
But what if I want to turn off the colour legend instead? There doesn't seem to be a way of telling show_guide which legend to apply its behaviour to. And there is no show_guide argument for scales or aesthetics.
(p3 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
scale_colour_discrete(show_guide = FALSE) +
geom_point()
)
# Error in discrete_scale
(p4 <- ggplot(mov, aes(year, rating, shape = mpaa)) +
aes(colour = length, show_guide = FALSE) +
geom_point()
)
#draws both legends
This question suggests that the modern (since ggplot2 v0.9.2) way of controlling legends is with the guides function.
I want to be able to do something like
p0 + guides(
colour = guide_legend(show = FALSE)
)
but guide_legend doesn't have a show argument.
How do I specify which legends get displayed?
",https://stackoverflow.com/questions/14604435/turning-off-some-legends-in-a-ggplot,314,287519.0,2.0,,,2013-01-30 12:49:46,2022-02-07 18:05:32,2017-05-23 10:31:37,,,r;ggplot2,Richie Cotton,121999,134830,registered,true,14604540,,CC BY-SA 3.0,,1766,1326,11,2,0,2,true,false,false,true,true,true,36,7,false,0.007,0.0011,5043,2013,1,12,Wednesday,false,false,false,false,false,false,false
7368262,How to properly document S4 class slots using Roxygen2?,"For documenting classes with roxygen(2), specifying a title and description/details appears to be the same as for functions, methods, data, etc. However, slots and inheritance are their own sort of animal. What is the best practice -- current or planned -- for documenting S4 classes in roxygen2?
Due Diligence:
I found mention of an @slot tag in early descriptions of roxygen.
A 2008 R-forge mailing list post
seems to indicate that this is dead,
and there is no support for @slot in roxygen:
Is this true of roxygen2? The previously-mentioned post suggests a user should instead make their own itemized list with LaTeX markup. E.g. a new S4 class that extends the ""character"" class would be coded and documented like this:
#' The title for my S4 class that extends \code{""character""} class.
#'
#' Some details about this class and my plans for it in the body.
#'
#' \describe{
#' \item{myslot1}{A logical keeping track of something.}
#'
#' \item{myslot2}{An integer specifying something else.}
#'
#' \item{myslot3}{A data.frame holding some data.}
#' }
#' @name mynewclass-class
#' @rdname mynewclass-class
#' @exportClass mynewclass
setClass(""mynewclass"",
representation(myslot1=""logical"",
myslot2=""integer"",
myslot3=""data.frame""),
contains = ""character""
)
However, although this works, this \describe , \item approach for documenting the slots seems inconsistent with the rest of roxygen(2), in that there are no @-delimited tags and slots could go undocumented with no objection from roxygenize(). It also says nothing about a consistent way to document inheritance of the class being defined. I imagine dependency still generally works fine (if a particular slot requires a non-base class from another package) using the @import tag.
So, to summarize, what is the current best-practice for roxygen(2) slots?
There seem to be three options to consider at the moment:
- A -- Itemized list (as example above).
- B --
@slot ... but with extra tags/implementation I missed. I was unable to get @slot to work with roxygen / roxygen2 in versions where
it was included as a replacement for the itemized list in the example
above. Again, the example above does work with roxygen(2).
- C -- Some alternative tag for specifying slots, like
@param, that would accomplish the same thing.
I'm borrowing/extending this question from a post I made to the roxygen2 development page on github.
",https://stackoverflow.com/questions/7368262/how-to-properly-document-s4-class-slots-using-roxygen2,314,15118.0,3.0,,,2011-09-09 22:52:16,2022-11-07 23:39:34,2015-07-10 12:53:17,,,class;r;r-s4;slot;roxygen2,Paul 'Joey' McMurdie,7465,935950,registered,true,20484059,,CC BY-SA 3.0,2012-04-05 10:52:03,2931,2452,12,2,0,5,true,false,false,true,true,true,55,9,true,0.198,0.0208,5552,2011,9,22,Friday,false,false,false,false,false,false,false
3318333,Split a vector into chunks,"I have to split a vector into n chunks of equal size in R. I couldn't find any base function to do that. Also Google didn't get me anywhere. Here is what I came up with so far;
x <- 1:10
n <- 3
chunk <- function(x,n) split(x, factor(sort(rank(x)%%n)))
chunk(x,n)
$`0`
[1] 1 2 3
$`1`
[1] 4 5 6 7
$`2`
[1] 8 9 10
",https://stackoverflow.com/questions/3318333/split-a-vector-into-chunks,309,247685.0,23.0,,,2010-07-23 13:01:03,2024-04-26 09:47:29,2020-09-29 16:13:50,,,r;vector,Sebastian,3877,400269,registered,true,,,CC BY-SA 4.0,2019-01-11 04:59:54,356,325,1,0,0,2,false,false,false,true,true,true,26,5,false,0.093,0.0012,5965,2010,7,13,Friday,false,false,false,false,false,false,false
1815606,Determine path of the executing script,"I have a script called foo.R that includes another script other.R, which is in the same directory:
#!/usr/bin/env Rscript
message(""Hello"")
source(""other.R"")
But I want R to find that other.R no matter what the current working directory.
In other words, foo.R needs to know its own path. How can I do that?
",https://stackoverflow.com/questions/1815606/determine-path-of-the-executing-script,308,161430.0,31.0,,,2009-11-29 13:58:32,2026-04-10 14:14:32,2019-06-19 13:49:17,,,r;file;path;rscript;r-faq,Frank,66794,60628,registered,true,,,CC BY-SA 4.0,2016-11-25 13:23:17,421,311,6,0,0,5,false,false,false,true,true,true,38,6,false,0.192,0.0019,6201,2009,11,13,Sunday,true,false,false,false,false,false,false
2151212,How can I read command line parameters from an R script?,"I've got a R script for which I'd like to be able to supply several command-line parameters (rather than hardcode parameter values in the code itself). The script runs on Windows.
I can't find info on how to read parameters supplied on the command-line into my R script. I'd be surprised if it can't be done, so maybe I'm just not using the best keywords in my Google search...
Any pointers or recommendations?
",https://stackoverflow.com/questions/2151212/how-can-i-read-command-line-parameters-from-an-r-script,307,201402.0,10.0,,,2010-01-27 23:40:22,2018-05-01 13:17:37,,,,command-line;r;parameters,monch1962,5301,140823,registered,true,2154190,,CC BY-SA 2.5,,436,415,0,0,0,3,true,false,false,true,true,false,56,11,true,0.05,0.0015,6142,2010,1,23,Wednesday,false,false,false,false,false,false,false
42635310,Remove the kernel on a Jupyter Notebook,"How can I remove a kernel from Jupyter Notebook?
I have an R kernel on my Jupyter Notebook. Recently, the kernel always dies right after I open a new notebook.
",https://stackoverflow.com/questions/42635310/remove-the-kernel-on-a-jupyter-notebook,304,340696.0,8.0,,,2017-03-06 20:51:15,2024-03-10 09:14:06,2024-03-10 08:56:23,,,r;jupyter-notebook,zesla,12025,6379348,registered,true,42647666,,CC BY-SA 4.0,,174,160,0,0,0,2,true,false,false,true,true,true,39,7,false,0.023,0.0009,3547,2017,3,20,Monday,false,false,false,false,false,false,false
6190051,How can I remove all objects but one from the workspace in R?,"I have a workspace with lots of objects and I would like to remove all but one. Ideally I would like to avoid having to type rm(obj.1, obj.2... obj.n). Is it possible to indicate remove all objects but these ones?
",https://stackoverflow.com/questions/6190051/how-can-i-remove-all-objects-but-one-from-the-workspace-in-r,302,252532.0,14.0,,,2011-05-31 15:39:13,2021-04-06 20:32:15,2017-09-28 11:30:15,,,r,DQdlM,10354,686481,registered,true,6190319,,CC BY-SA 3.0,2017-04-05 14:18:46,250,217,2,0,0,1,true,false,false,true,true,true,61,13,true,0.055,0.0012,5653,2011,5,15,Tuesday,false,false,false,false,false,false,false
26003574,Use dynamic name for new column/variable in `dplyr`,"I want to use dplyr::mutate() to create multiple new columns in a data frame. The column names and their contents should be dynamically generated.
Example data from iris:
library(dplyr)
iris <- as_tibble(iris)
I've created a function to mutate my new columns from the Petal.Width variable:
multipetal <- function(df, n) {
varname <- paste("petal", n , sep=".")
df <- mutate(df, varname = Petal.Width * n) ## problem arises here
df
}
Now I create a loop to build my columns:
for(i in 2:5) {
iris <- multipetal(df=iris, n=i)
}
However, since mutate thinks varname is a literal variable name, the loop only creates one new variable (called varname) instead of four (called petal.2 - petal.5).
How can I get mutate() to use my dynamic name as variable name?
",https://stackoverflow.com/questions/26003574/use-dynamic-name-for-new-column-variable-in-dplyr,302,245741.0,10.0,,,2014-09-23 19:51:15,2023-03-16 16:41:51,2022-02-17 14:29:12,,,r;dplyr;r-faq,Timm S.,5465,2123452,registered,true,26003971,,CC BY-SA 4.0,,962,809,6,0,0,3,true,false,false,true,true,true,51,8,false,0.041,0.0012,4442,2014,9,19,Tuesday,false,false,false,false,false,false,false
13515893,Set margin size when converting from Markdown to PDF with pandoc,"I have created an RMarkdown file in RStudio and managed to knit it with knitr into an HTML and .md file. Next, I used pandoc to convert the .md file into a PDF file (I get an error if I try and convert from the .html file). However, the PDF that is produced have massive margins (like this http://johnmacfarlane.net/pandoc/demo/example13.pdf). How can I get pandoc to produce something with smaller margins? I have looked through the pandoc user guide, but haven't found anything useful.
",https://stackoverflow.com/questions/13515893/set-margin-size-when-converting-from-markdown-to-pdf-with-pandoc,295,194052.0,4.0,,,2012-11-22 15:31:31,2026-05-22 21:16:28,2014-02-26 21:34:13,,,r;latex;markdown;knitr;pandoc,mchangun,10582,1583516,registered,true,13516042,,CC BY-SA 3.0,2023-07-26 02:27:40,582,492,0,1,0,5,true,false,false,true,true,true,64,11,false,0.021,0.0015,5112,2012,11,15,Thursday,false,false,false,false,false,false,false
9397664,Force R not to use exponential notation (e.g. e+10)?,"Can I force R to use regular numbers instead of using the e+10-like notation? I have:
1.810032e+09
# and
4
within the same vector and want to see:
1810032000
# and
4
I am creating output for an old fashioned program and I have to write a text file using cat.
That works fine so far but I simply can't use the e+10 notation there.
",https://stackoverflow.com/questions/9397664/force-r-not-to-use-exponential-notation-e-g-e10,294,420321.0,4.0,,,2012-02-22 15:24:33,2022-10-04 06:27:49,2022-07-16 18:05:17,2024-09-21 02:25:25,Duplicate,r;default;number-formatting;scientific-notation,Matt Bannert,28424,366256,registered,true,9397821,,,2018-02-13 07:40:40,447,339,5,0,0,4,true,true,false,true,true,true,52,9,true,0.01,0.0007,5386,2012,2,15,Wednesday,false,false,false,false,false,false,false
11335836,Increase number of axis ticks,"I'm generating plots for some data, but the number of ticks is too small, I need more precision on the reading.
Is there some way to increase the number of axis ticks in ggplot2?
I know I can tell ggplot to use a vector as axis ticks, but what I want is to increase the number of ticks, for all data. In other words, I want the tick number to be calculated from the data.
Possibly ggplot do this internally with some algorithm, but I couldn't find how it does it, to change according to what I want.
",https://stackoverflow.com/questions/11335836/increase-number-of-axis-ticks,293,465936.0,6.0,,,2012-07-04 22:00:58,2021-10-02 04:47:45,2017-03-21 08:35:12,,,r;ggplot2,João Daniel,9006,1096545,registered,true,11335933,,CC BY-SA 3.0,,540,503,0,0,0,2,true,false,false,true,true,true,29,5,false,0.013,0.0006,5253,2012,7,22,Wednesday,false,false,false,false,false,false,false
15170399,Change R default library path using .libPaths in Rprofile.site fails to work,"I am running R on Windows, not as an administrator. When I install a package, the following command doesn't work:
> install.packages(""zoo"")
Installing package(s) into ‘C:/Program Files/R/R-2.15.2/library’
(as ‘lib’ is unspecified)
Warning in install.packages :
'lib = ""C:/Program Files/R/R-2.15.2/library""' is not writable
To install a package, I have to specify a library location:
install.packages(""zoo"", lib=""C:/software/Rpackages"")
To load a package, I also have to specify the library location:
library(""zoo"", lib.loc=""C:/software/Rpackages"")
All of this is OK, but I wanted to see if I could add C:/software/Rpackages to the library path somehow and thus not have to type it each time.
As I searched online, I found that one way to do this is to edit the Rprofile.site file and to add the line
.libPaths(""C:/software/Rpackages"")
However, after doing this, and starting RStudio, this is the output that I get
> .libPaths()
[1] ""C:/Program Files/R/R-2.15.2/library"" ""C:/Program Files/RStudio/R/library""
The .libPaths command that I added to the Rprofile.site doesn't seem to have had any effect! Why is this the case? Or more importantly, how can I fix the problem so that I can install and load packages without typing in the library location?
Note: if I start RStudio the .libPaths() command seems to work as it is supposed to
.libPaths(""C:/software/Rpackages"")
> .libPaths()
[1] ""C:/software/Rpackages"" ""C:/Program Files/R/R-2.15.2/library""
Isn't that strange?
",https://stackoverflow.com/questions/15170399/change-r-default-library-path-using-libpaths-in-rprofile-site-fails-to-work,291,751663.0,17.0,,,2013-03-02 03:36:02,2026-06-28 16:24:18,2026-06-28 16:24:18,,,r;windows;rstudio;r-faq;library-path,I Like to Code,7421,856624,registered,true,15170774,,CC BY-SA 4.0,2018-11-05 09:50:48,1786,1514,11,0,0,5,true,false,false,true,true,true,76,12,false,0.023,0.0004,5012,2013,3,3,Saturday,true,false,false,false,false,false,false
1189759,"Expert R users, what's in your .Rprofile?","I have always found startup profile files of other people both useful and instructive about the language. Moreover, while I have some customization for Bash and Vim, I have nothing for R.
For example, one thing I always wanted is different colors for input and output text in a window terminal, and maybe even syntax highlighting.
",https://stackoverflow.com/questions/1189759/expert-r-users-whats-in-your-rprofile,290,76767.0,24.0,,,2009-07-27 18:17:42,2022-04-26 18:13:57,2022-04-26 18:13:57,2013-02-11 14:16:32,not constructive,r;terminal;customization;rprofile,gappy,10293,143813,registered,true,1189826,,,,511,331,0,2,0,4,true,true,false,true,true,true,45,7,true,0.313,0.0038,6326,2009,7,18,Monday,false,false,false,false,false,false,false
21370132,What are the main differences between R data files?,"What are the main differences between .RData, .Rda and .Rds files?
- Are there differences in compression, etc.?
- When should each type be used?
- How can one type be converted to another?
",https://stackoverflow.com/questions/21370132/what-are-the-main-differences-between-r-data-files,289,162537.0,2.0,,,2014-01-26 22:29:48,2021-05-20 13:07:02,2021-05-20 13:07:02,,,r;r-faq;rdata;rda,Carlos Cinelli,11707,3216713,registered,true,21370351,,CC BY-SA 4.0,,268,186,3,0,0,4,true,false,false,true,true,true,51,9,true,0.012,0.0018,4682,2014,1,22,Sunday,true,false,false,false,false,false,false
2615128,Where does R store packages?,"The install.packages() function in R is the automatic unzipping utility that gets and install packages in R.
How do I find out what directory R has chosen to store packages?
How can I change the directory in which R stores and accesses packages?
",https://stackoverflow.com/questions/2615128/where-does-r-store-packages,287,364944.0,4.0,,,2010-04-10 21:46:20,2023-01-21 01:43:54,2015-05-29 14:26:55,,,r;package,Milktrader,10048,296155,registered,true,2615147,,CC BY-SA 3.0,2017-05-12 10:29:41,310,249,1,0,0,2,true,false,false,true,true,true,28,5,true,0.011,0.0008,6069,2010,4,21,Saturday,true,false,false,false,false,false,false
21618423,Extract a dplyr tbl column as a vector,"Is there a more succinct way to get one column of a dplyr tbl as a vector, from a tbl with database back-end (i.e. the data frame/table can't be subset directly)?
require(dplyr)
db <- src_sqlite(tempfile(), create = TRUE)
iris2 <- copy_to(db, iris)
iris2$Species
# NULL
That would have been too easy, so
collect(select(iris2, Species))[, 1]
# [1] ""setosa"" ""setosa"" ""setosa"" ""setosa"" etc.
But it seems a bit clumsy.
",https://stackoverflow.com/questions/21618423/extract-a-dplyr-tbl-column-as-a-vector,279,172170.0,8.0,,,2014-02-07 02:55:22,2022-08-05 11:02:49,2016-07-30 22:03:53,,,r;dplyr;lazy-evaluation;collect,nacnudus,6578,937932,registered,true,44542659,,CC BY-SA 3.0,,509,440,2,0,0,4,true,false,false,true,true,true,38,8,false,0.046,0.0016,4670,2014,2,2,Friday,false,false,false,false,false,false,false
17499013,How do I make a list of data frames?,"How do I make a list of data frames and how do I access each of those data frames from the list?
For example, how can I put these data frames in a list ?
d1 <- data.frame(y1 = c(1, 2, 3),
y2 = c(4, 5, 6))
d2 <- data.frame(y1 = c(3, 2, 1),
y2 = c(6, 5, 4))
",https://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames,277,398670.0,10.0,,,2013-07-06 02:16:30,2025-11-25 20:47:42,2018-04-09 15:28:25,,,r;list;dataframe;r-faq,Ben,22041,2146894,registered,true,17499124,,CC BY-SA 3.0,2020-07-06 13:27:22,337,299,1,0,0,4,true,false,false,true,true,true,36,9,true,0.025,0.0007,4886,2013,7,2,Saturday,true,false,false,false,false,false,false
9216138,Find the day of a week,"Let's say that I have a date in R and it's formatted as follows.
date
2012-02-01
2012-02-01
2012-02-02
Is there any way in R to add another column with the day of the week associated with the date? The dataset is really large, so it would not make sense to go through manually and make the changes.
df = data.frame(date=c(""2012-02-01"", ""2012-02-01"", ""2012-02-02""))
So after adding the days, it would end up looking like:
date day
2012-02-01 Wednesday
2012-02-01 Wednesday
2012-02-02 Thursday
Is this possible? Can anyone point me to a package that will allow me to do this?
Just trying to automatically generate the day by the date.
",https://stackoverflow.com/questions/9216138/find-the-day-of-a-week,277,314326.0,7.0,,,2012-02-09 17:54:53,2018-07-08 12:38:05,2018-07-08 12:38:05,,,r;date;r-faq,ATMathew,12986,406278,registered,true,9216316,,CC BY-SA 4.0,,768,668,3,0,0,3,true,false,false,true,true,true,22,6,false,0.022,0.0009,5399,2012,2,17,Thursday,false,false,false,false,false,false,false
8197559,Emulate ggplot2 default color palette,"What function can I use to emulate ggplot2's default color palette for a desired number of colors. For example, an input of 3 would produce a character vector of HEX colors with these colors:
![]()
",https://stackoverflow.com/questions/8197559/emulate-ggplot2-default-color-palette,276,261342.0,5.0,,,2011-11-19 21:37:46,2022-11-16 10:17:53,,,,r;ggplot2,Suraj,36954,356790,registered,true,8197703,,CC BY-SA 3.0,,279,194,0,0,1,2,true,false,false,true,true,false,37,5,false,0.019,0.0011,5481,2011,11,21,Saturday,true,false,false,false,false,false,false
1826519,How to assign from a function which returns more than one value?,"Still trying to get into the R logic... what is the ""best"" way to unpack (on LHS) the results from a function returning multiple values?
I can't do this apparently:
R> functionReturningTwoValues <- function() { return(c(1, 2)) }
R> functionReturningTwoValues()
[1] 1 2
R> a, b <- functionReturningTwoValues()
Error: unexpected ',' in ""a,""
R> c(a, b) <- functionReturningTwoValues()
Error in c(a, b) <- functionReturningTwoValues() : object 'a' not found
must I really do the following?
R> r <- functionReturningTwoValues()
R> a <- r[1]; b <- r[2]
or would the R programmer write something more like this:
R> functionReturningTwoValues <- function() {return(list(first=1, second=2))}
R> r <- functionReturningTwoValues()
R> r$first
[1] 1
R> r$second
[1] 2
--- edited to answer Shane's questions ---
I don't really need giving names to the result value parts. I am applying one aggregate function to the first component and an other to the second component (min and max. if it was the same function for both components I would not need splitting them).
",https://stackoverflow.com/questions/1826519/how-to-assign-from-a-function-which-returns-more-than-one-value,276,339085.0,17.0,,,2009-12-01 14:27:23,2025-09-05 14:54:17,2016-10-30 00:33:07,,,r;return-value;variable-assignment;assign;multiple-results,mariotomo,9888,78912,registered,true,15140507,,CC BY-SA 3.0,,1264,1124,5,0,0,5,true,false,false,true,true,true,64,12,true,0.05,0.0008,6199,2009,12,14,Tuesday,false,false,false,false,false,false,false
13297995,Changing font size and direction of axes text in ggplot2,"I am plotting a graph with a categorical variable on the x axis and a numerical variable on the y axis.
For the x axis, given that there are many data points, the default text formatting causes the label for each tick mark to overlap with other labels. How do I (a) change the font size for my axis text and (b) change the orientation of the text so that the text is perpendicular to the axis?
",https://stackoverflow.com/questions/13297995/changing-font-size-and-direction-of-axes-text-in-ggplot2,274,843869.0,7.0,,,2012-11-08 21:19:27,2024-03-01 09:00:24,2016-09-02 18:04:16,,,r;ggplot2,Anjan,2980,1518427,registered,true,13298150,,CC BY-SA 3.0,,409,395,0,0,0,2,true,false,false,true,true,true,56,10,false,0.008,0.0003,5126,2012,11,21,Thursday,false,false,false,false,false,false,false
23188900,Display / print all rows of a tibble (tbl_df),"tibble (previously tbl_df) is a version of a data frame created by the dplyr data frame manipulation package in R. It prevents long table outputs when accidentally calling the data frame.
Once a data frame has been wrapped by tibble/tbl_df, is there a command to view the whole data frame though (all the rows and columns of the data frame)?
If I use df[1:100,], I will see all 100 rows, but if I use df[1:101,], it will only display the first 10 rows. I would like to easily display all the rows to quickly scroll through them.
Is there either a dplyr command to counteract this or a way to unwrap the data frame?
",https://stackoverflow.com/questions/23188900/display-print-all-rows-of-a-tibble-tbl-df,274,227547.0,7.0,,,2014-04-20 23:55:04,2022-07-16 18:04:48,2022-07-16 18:04:48,,,r;dplyr,Zhe Zhang,2979,3555034,registered,true,27294928,,CC BY-SA 4.0,,738,619,7,0,0,2,true,false,false,true,true,true,45,9,false,0.031,0.0012,4598,2014,4,23,Sunday,true,false,false,false,false,false,false
3541713,How can I plot two histograms together in R?,"I am using R and I have two data frames: carrots and cucumbers. Each data frame has a single numeric column that lists the length of all measured carrots (total: 100k carrots) and cucumbers (total: 50k cucumbers).
I wish to plot two histograms—carrot length and cucumbers lengths—on the same plot. They overlap, so I guess I also need some transparency. I also need to use relative frequencies not absolute numbers since the number of instances in each group is different.
Something like this would be nice, but how can I create it from my two tables?
![]()
",https://stackoverflow.com/questions/3541713/how-can-i-plot-two-histograms-together-in-r,273,575611.0,9.0,,,2010-08-22 13:54:27,2023-10-30 04:35:17,2023-10-30 04:35:17,,,r;plot;histogram,David B,30158,377031,registered,true,3542115,,CC BY-SA 4.0,,651,553,0,0,1,3,true,false,false,true,true,true,44,9,true,0.016,0.0005,5935,2010,8,13,Sunday,true,false,false,false,false,false,false
15215457,Standardize data columns in R,"I have a dataset called spam which contains 58 columns and approximately 3500 rows of data related to spam messages.
I plan on running some linear regression on this dataset in the future, but I'd like to do some pre-processing beforehand and standardize the columns to have zero mean and unit variance.
I've been told the best way to go about this is with R, so I'd like to ask how can i achieve normalization with R? I've already got the data properly loaded and I'm just looking for some packages or methods to perform this task.
",https://stackoverflow.com/questions/15215457/standardize-data-columns-in-r,267,662534.0,16.0,,,2013-03-05 03:45:45,2022-02-22 06:35:31,2014-05-13 09:23:40,,,r;normalization,Hoser,5034,1333854,registered,true,15215483,,CC BY-SA 3.0,,590,539,1,0,0,2,true,false,false,true,true,true,29,5,false,0.024,0.0004,5009,2013,3,3,Tuesday,false,false,false,false,false,false,false
5465314,Tools for making latex tables in R,"On general request, a community wiki on producing latex tables in R. In this post I'll give an overview of the most commonly used packages and blogs with code for producing latex tables from less straight-forward objects. Please feel free to add any I missed, and/or give tips, hints and little tricks on how to produce nicely formatted latex tables with R.
Packages :
- xtable : for standard tables of most simple objects. A nice gallery with examples can be found here.
- memisc : tool for management of survey data, contains some tools for latex tables of (basic) regression model estimates.
- Hmisc contains a function
latex() that creates a tex file containing the object of choice. It is pretty flexible, and can also output longtable latex tables. There's a lot of info in the help file ?latex
- miscFuncs has a neat function 'latextable' that converts matrix data with mixed alphabetic and numeric entries into a LaTeX table and prints them to the console, so they can be copied and pasted into a LaTeX document.
- texreg package (JSS paper) converts statistical model output into LaTeX tables. Merges multiple models. Can cope with about 50 different model types, including network models and multilevel models (lme and lme4).
- reporttools package (JSS paper) is another option for descriptive statistics on continuous, categorical and date variables.
- tables package is perhaps the most general LaTeX table making package in R for descriptive statistics
- stargazer package makes nice comparative statistical model summary tables
Blogs and code snippets
- There is the outreg function of Paul Johnson that gives Stata-like tables in Latex for the output of regressions. This one works great.
- As given in an earlier question, there's a code snippet to adapt the memisc package for lme4 objects.
Related questions :
- Suggestion for R/LaTeX table creation package
- Rreport/LaTeX quality output package
- sorting a table for latex output with xtable
- Any way to produce a LaTeX table from an lme4 mer model fit object?
- R data.frame with stacked specified titles for latex output with xtable
- Automating adding tables fast to latex from R, with a very flexible and interesting syntax using the formula language
",https://stackoverflow.com/questions/5465314/tools-for-making-latex-tables-in-r,267,148804.0,8.0,,,2011-03-28 21:31:11,2017-01-14 22:59:54,2017-05-23 11:47:11,2013-01-24 16:11:01,not a real question,r;latex,Joris Meys,109211,428790,registered,true,,,,,4315,2207,3,19,0,2,false,true,false,true,true,true,34,7,false,0.054,0.0018,5717,2011,3,21,Monday,false,false,false,false,false,false,false
27082601,ggplot2 line chart gives "geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?","With this data frame (""df""):
year pollution
1 1999 346.82000
2 2002 134.30882
3 2005 130.43038
4 2008 88.27546
I try to create a line chart like this:
plot5 <- ggplot(df, aes(year, pollution)) +
geom_point() +
geom_line() +
labs(x = ""Year"", y = ""Particulate matter emissions (tons)"", title = ""Motor vehicle emissions in Baltimore"")
The error I get is:
geom_path: Each group consist of only one observation. Do you need to
adjust the group aesthetic?
The chart appears as a scatter plot even though I want a line chart. I tried to replace geom_line() with geom_line(aes(group = year)) but that didn't work.
In an answer I was told to convert year to a factor variable. I did and the problem persists. This is the output of str(df) and dput(df):
'data.frame': 4 obs. of 2 variables:
$ year : num 1 2 3 4
$ pollution: num [1:4(1d)] 346.8 134.3 130.4 88.3
..- attr(*, ""dimnames"")=List of 1
.. ..$ : chr ""1999"" ""2002"" ""2005"" ""2008""
structure(list(year = c(1, 2, 3, 4), pollution = structure(c(346.82,
134.308821199349, 130.430379885892, 88.275457392443), .Dim = 4L, .Dimnames = list(
c(""1999"", ""2002"", ""2005"", ""2008"")))), .Names = c(""year"",
""pollution""), row.names = c(NA, -4L), class = ""data.frame"")
",https://stackoverflow.com/questions/27082601/ggplot2-line-chart-gives-geom-path-each-group-consist-of-only-one-observation,266,459289.0,7.0,,,2014-11-22 21:10:18,2025-05-16 09:13:52,2022-02-19 18:17:09,,,r;ggplot2;r-faq,megashigger,9173,2469211,registered,true,29019102,,CC BY-SA 4.0,2019-03-20 02:05:38,1466,1275,7,0,0,3,true,false,false,true,true,true,134,20,false,0.015,0.0006,4382,2014,11,21,Saturday,true,false,false,false,false,false,false
2185252,Reshaping data.frame from wide to long format,"I have some trouble to convert my data.frame from a wide table to a long table.
At the moment it looks like this:
Code Country 1950 1951 1952 1953 1954
AFG Afghanistan 20,249 21,352 22,532 23,557 24,555
ALB Albania 8,097 8,986 10,058 11,123 12,246
Now I would like to transform this data.frame into a long data.frame.
Something like this:
Code Country Year Value
AFG Afghanistan 1950 20,249
AFG Afghanistan 1951 21,352
AFG Afghanistan 1952 22,532
AFG Afghanistan 1953 23,557
AFG Afghanistan 1954 24,555
ALB Albania 1950 8,097
ALB Albania 1951 8,986
ALB Albania 1952 10,058
ALB Albania 1953 11,123
ALB Albania 1954 12,246
I have looked at and already tried using the melt() and the reshape() functions
as some people were suggesting in similar questions.
However, so far I only get messy results.
If it is possible I would like to do it with the reshape() function since
it looks a little bit nicer to handle.
",https://stackoverflow.com/questions/2185252/reshaping-data-frame-from-wide-to-long-format,265,386180.0,10.0,,,2010-02-02 15:36:12,2026-05-01 07:21:35,2019-05-15 03:51:07,,,r;dataframe;reshape;r-faq,mropa,11952,258334,registered,true,2185525,,CC BY-SA 4.0,2016-05-02 05:11:47,1211,1057,8,0,0,4,true,false,false,true,true,true,45,7,false,0.026,0.0007,6136,2010,2,15,Tuesday,false,false,false,false,false,false,false
14942681,Change size of axes title and labels in ggplot2,"I have a really simple question, which I am struggling to find the answer to. I hoped someone here might be able to help me.
An example dataframe is presented below:
a <- c(1:10)
b <- c(10:1)
df <- data.frame(a,b)
library(ggplot2)
g = ggplot(data=df) + geom_point(aes(x=a, y=b)) +
xlab(""x axis"")
g
I just want to learn how I change the text size of the axes titles and the axes labels.
",https://stackoverflow.com/questions/14942681/change-size-of-axes-title-and-labels-in-ggplot2,263,841644.0,6.0,,,2013-02-18 18:10:39,2023-09-15 05:01:00,,,,r;ggplot2,KT_1,8606,1073425,registered,true,14942760,,CC BY-SA 3.0,,447,402,1,0,0,2,true,false,false,true,true,false,47,9,false,0.007,0.0003,5024,2013,2,18,Monday,false,false,false,false,false,false,false
9068397,Import text file as single character string,"How do you import a plain text file as single character string in R? I think that this will probably have a very simple answer but when I tried this today I found that I couldn't find a function to do this.
For example, suppose I have a file foo.txt with something I want to textmine.
I tried it with:
scan(""foo.txt"", what=""character"", sep=NULL)
but this still returned a vector. I got it working somewhat with:
paste(scan(""foo.txt"", what=""character"", sep="" ""),collapse="" "")
but that is quite an ugly solution which is probably unstable too.
",https://stackoverflow.com/questions/9068397/import-text-file-as-single-character-string,258,162720.0,9.0,,,2012-01-30 17:54:10,2025-06-19 14:51:01,2012-01-30 18:02:30,,,r,Sacha Epskamp,47922,567015,registered,true,9069670,,CC BY-SA 3.0,,646,550,3,0,0,1,true,false,false,true,true,true,43,7,false,0.055,0.0016,5409,2012,1,17,Monday,false,false,false,false,false,false,false
2436688,"Append an object to a list in R in amortized constant time, O(1)?","If I have some R list mylist, you can append an item obj to it like so:
mylist[[length(mylist)+1]] <- obj
But surely there is some more compact way. When I was new at R, I tried writing lappend() like so:
lappend <- function(lst, obj) {
lst[[length(lst)+1]] <- obj
return(lst)
}
but of course that doesn't work due to R's call-by-name semantics (lst is effectively copied upon call, so changes to lst are not visible outside the scope of lappend(). I know you can do environment hacking in an R function to reach outside the scope of your function and mutate the calling environment, but that seems like a large hammer to write a simple append function.
Can anyone suggest a more beautiful way of doing this? Bonus points if it works for both vectors and lists.
",https://stackoverflow.com/questions/2436688/append-an-object-to-a-list-in-r-in-amortized-constant-time-o1,258,311920.0,17.0,,,2010-03-13 00:14:09,2022-07-30 10:40:30,2016-04-28 18:22:43,,,r;performance;list;append;big-o,Nick,22425,5222,registered,true,2436960,,CC BY-SA 3.0,2012-09-09 19:51:08,943,789,8,0,0,5,true,false,false,true,true,true,65,13,true,0.055,0.0008,6097,2010,3,0,Saturday,true,false,false,false,false,false,false
12925063,Numbering rows within groups in a data frame,"Working with a data frame similar to this:
set.seed(100)
df <- data.frame(cat = c(rep("aaa", 5), rep("bbb", 5), rep("ccc", 5)), val = runif(15))
df <- df[order(df$cat, df$val), ]
df
cat val
1 aaa 0.05638315
2 aaa 0.25767250
3 aaa 0.30776611
4 aaa 0.46854928
5 aaa 0.55232243
6 bbb 0.17026205
7 bbb 0.37032054
8 bbb 0.48377074
9 bbb 0.54655860
10 bbb 0.81240262
11 ccc 0.28035384
12 ccc 0.39848790
13 ccc 0.62499648
14 ccc 0.76255108
15 ccc 0.88216552
I am trying to add a column with numbering within each group. Doing it this way obviously isn't using the powers of R:
df$num <- 1
for (i in 2:(length(df[,1]))) {
if (df[i,"cat"]==df[(i-1),"cat"]) {
df[i,"num"]<-df[i-1,"num"]+1
}
}
df
cat val num
1 aaa 0.05638315 1
2 aaa 0.25767250 2
3 aaa 0.30776611 3
4 aaa 0.46854928 4
5 aaa 0.55232243 5
6 bbb 0.17026205 1
7 bbb 0.37032054 2
8 bbb 0.48377074 3
9 bbb 0.54655860 4
10 bbb 0.81240262 5
11 ccc 0.28035384 1
12 ccc 0.39848790 2
13 ccc 0.62499648 3
14 ccc 0.76255108 4
15 ccc 0.88216552 5
What would be a good way to do this?
",https://stackoverflow.com/questions/12925063/numbering-rows-within-groups-in-a-data-frame,257,195346.0,11.0,,,2012-10-16 23:38:41,2023-06-07 13:57:36,2022-09-15 21:06:33,,,r;dataframe;r-faq;running-count,eli-k,11494,1737251,registered,true,12925090,,CC BY-SA 4.0,2018-05-23 06:52:49,1560,1293,4,0,0,4,true,false,false,true,true,true,44,8,false,0.056,0.0013,5149,2012,10,23,Tuesday,false,false,false,false,false,false,false
743812,Calculating moving average,"I'm trying to use R to calculate the moving average over a series of values in a matrix. There doesn't seem to be a built-in function in R that will allow me to calculate moving averages. Do any packages provide one? Or do I need to write my own?
",https://stackoverflow.com/questions/743812/calculating-moving-average,256,367390.0,19.0,,,2009-04-13 12:52:51,2025-05-25 21:46:58,2021-12-08 13:56:40,,,r;moving-average,Jared,40009,14744,registered,true,743846,,CC BY-SA 4.0,2024-04-15 13:15:33,338,247,0,1,0,2,true,false,false,true,true,true,26,3,false,0.052,0.0007,6431,2009,4,12,Monday,false,false,false,false,false,false,false
24576515,Relative frequencies / proportions with dplyr,"Suppose I want to calculate the proportion of different values within each group. For example, using the mtcars data, how do I calculate the relative frequency of number of gears by am (automatic/manual) in one go with dplyr?
library(dplyr)
data(mtcars)
mtcars <- tbl_df(mtcars)
# count frequency
mtcars %>%
group_by(am, gear) %>%
summarise(n = n())
# am gear n
# 0 3 15
# 0 4 4
# 1 4 8
# 1 5 5
What I would like to achieve:
am gear n rel.freq
0 3 15 0.7894737
0 4 4 0.2105263
1 4 8 0.6153846
1 5 5 0.3846154
",https://stackoverflow.com/questions/24576515/relative-frequencies-proportions-with-dplyr,253,309942.0,11.0,,,2014-07-04 14:31:15,2023-12-25 21:36:39,2017-05-03 07:57:20,,,r;group-by;dplyr;frequency,jenswirf,7365,1110063,registered,true,24576703,,CC BY-SA 3.0,2021-08-31 07:18:37,725,594,4,0,0,4,true,false,false,true,true,true,45,6,false,0.035,0.0008,4523,2014,7,14,Friday,false,false,false,false,false,false,false
15589601,Print string and variable contents on the same line in R,"Is there a way to print text and variable contents on the same line? For example,
wd <- getwd()
print(""Current working dir: "", wd)
I couldn't find anything about the syntax that would allow me to do this.
",https://stackoverflow.com/questions/15589601/print-string-and-variable-contents-on-the-same-line-in-r,251,687709.0,9.0,,,2013-03-23 17:07:06,2023-11-04 12:30:37,,,,r;printing,user2015601,,,does_not_exist,true,15589629,,CC BY-SA 3.0,2015-07-22 08:04:51,249,211,1,0,0,2,true,false,false,true,false,false,56,11,false,0.013,0.0004,4991,2013,3,17,Saturday,true,false,false,false,false,false,false
29511215,How can I convert row names into the first column?,"I have a data frame like this:
df
VALUE ABS_CALL DETECTION P-VALUE
1007_s_at ""957.729231881542"" ""P"" ""0.00486279317241156""
1053_at ""320.632701283368"" ""P"" ""0.0313356324173416""
117_at ""429.842323161046"" ""P"" ""0.0170004527476119""
121_at ""2395.7364289242"" ""P"" ""0.0114473584876183""
1255_g_at ""116.493632746934"" ""A"" ""0.39799368200131""
1294_at ""739.927122116896"" ""A"" ""0.0668649772942343""
I want to convert the row names into the first column. Currently I use something like this to make row names as the first column:
d <- df
names <- rownames(d)
rownames(d) <- NULL
data <- cbind(names,d)
Is there a single line to do this?
",https://stackoverflow.com/questions/29511215/how-can-i-convert-row-names-into-the-first-column,249,489200.0,9.0,,,2015-04-08 09:45:47,2024-05-24 19:56:35,2023-03-23 03:04:42,,,r;dataframe;col;r-rownames,Agaz Wani,5792,4089949,registered,true,29511626,,CC BY-SA 4.0,,816,747,2,0,0,4,true,false,false,true,true,true,50,10,true,0.018,0.0005,4245,2015,4,9,Wednesday,false,false,false,false,false,false,false
15624656,Label points in geom_point,"The data I'm playing with comes from the internet source listed below
nba <- read.csv(""http://datasets.flowingdata.com/ppg2008.csv"", sep="","")
What I want to do, is create a 2D points graph comparing two metrics from this table, with each player representing a dot on the graph. I have the following code:
nbaplot <- ggplot(nba, aes(x= MIN, y= PTS, colour=""green"", label=Name)) +
geom_point()
This gives me the following:
![]()
What I want is a label of player's name right next to the dots. I thought the label function in ggplot's aesthetics would do this for me, but it didn't.
I also tried text() function and the textxy() function from library(calibrate), neither of which appears to work with ggplot.
How can I add name labels to these points?
",https://stackoverflow.com/questions/15624656/label-points-in-geom-point,249,564962.0,3.0,,,2013-03-25 21:00:05,2022-01-06 08:17:45,2018-05-12 05:26:48,,,r;plot;ggplot2;labeling;ggrepel,Green Demon,4238,2092884,registered,true,15625149,,CC BY-SA 4.0,,980,786,5,0,1,5,true,false,false,true,true,true,26,4,false,0.005,0.0004,4989,2013,3,21,Monday,false,false,false,false,false,false,false
45101045,Why use purrr::map instead of lapply?,"Is there any reason why I should use
map(<list-like-object>, function(x) <do stuff>)
instead of
lapply(<list-like-object>, function(x) <do stuff>)
the output should be the same and the benchmarks I made seem to show that lapply is slightly faster (it should be as map needs to evaluate all the non-standard-evaluation input).
So is there any reason why for such simple cases I should actually consider switching to purrr::map? I am not asking here about one's likes or dislikes about the syntax, other functionalities provided by purrr etc., but strictly about comparison of purrr::map with lapply assuming using the standard evaluation, i.e. map(<list-like-object>, function(x) <do stuff>). Is there any advantage that purrr::map has in terms of performance, exception handling etc.? The comments below suggest that it does not, but maybe someone could elaborate a little bit more?
",https://stackoverflow.com/questions/45101045/why-use-purrrmap-instead-of-lapply,248,66808.0,5.0,,,2017-07-14 10:45:36,2026-01-09 03:50:21,2022-08-08 06:14:12,,,r;lapply;purrr,Tim,7634,3986320,registered,true,47123420,,CC BY-SA 4.0,,1093,926,9,0,0,3,true,false,false,true,true,true,37,6,true,0.075,0.0037,3417,2017,7,10,Friday,false,false,false,false,false,false,false
5863097,Selecting only numeric columns from a data frame,"Suppose, you have a data.frame like this:
x <- data.frame(v1=1:20,v2=1:20,v3=1:20,v4=letters[1:20])
How would you select only those columns in x that are numeric?
",https://stackoverflow.com/questions/5863097/selecting-only-numeric-columns-from-a-data-frame,246,324647.0,12.0,,,2011-05-02 22:19:03,2022-05-16 11:30:43,,,,r,Brandon Bertelsen,44888,170352,registered,true,5863165,,CC BY-SA 3.0,,209,171,1,0,0,1,true,false,false,true,true,false,48,8,false,0.037,0.0008,5682,2011,5,22,Monday,false,false,false,false,false,false,false
7706876,Remove NA values from a vector,"I have a huge vector which has a couple of NA values, and I'm trying to find the max value in that vector (the vector is all numbers), but I can't do this because of the NA values.
How can I remove the NA values so that I can compute the max?
",https://stackoverflow.com/questions/7706876/remove-na-values-from-a-vector,246,630357.0,8.0,,,2011-10-09 22:08:07,2023-10-23 19:36:36,2023-10-12 15:04:48,,,r;na;r-faq,CodeGuy,29059,412082,registered,true,7706959,,CC BY-SA 4.0,2016-09-27 22:22:23,297,244,3,0,0,3,true,false,false,true,true,true,30,6,false,0.013,0.0004,5522,2011,10,22,Sunday,true,false,false,false,false,false,false
17082341,How to downgrade an R package (by installing an older version)?,"I am trying to use Rpy2 and ggplot2 but I get an error. After some searching for the error online, I found that the error occurs because there are changes in the ggplot2 package that are not yet reflected in Rpy2 (for example, see this post (Edit: Link is now dead)).
So I now need to install an older version of ggplot2. Here is pseudo-code for what I want:
install.packages(""ggplot2"", version='0.9.1')
But install.packages does not have a version argument. How do I do it?
",https://stackoverflow.com/questions/17082341/how-to-downgrade-an-r-package-by-installing-an-older-version,245,277540.0,8.0,,,2013-06-13 08:16:42,2025-03-13 05:15:57,2025-03-13 05:15:57,,,r;installation;version;r-faq,hirolau,14051,1827631,registered,true,17082609,,CC BY-SA 4.0,2016-04-14 16:52:09,796,480,3,2,0,4,true,false,false,true,true,true,63,11,true,0.029,0.0009,4909,2013,6,8,Thursday,false,false,false,false,false,false,false
9202413,How do you delete a column by name in data.table?,"To get rid of a column named ""foo"" in a data.frame, I can do:
df <- df[-grep('foo', colnames(df))]
However, once df is converted to a data.table object, there is no way to just remove a column.
Example:
df <- data.frame(id = 1:100, foo = rnorm(100))
df2 <- df[-grep('foo', colnames(df))] # works
df3 <- data.table(df)
df3[-grep('foo', colnames(df3))]
But once it is converted to a data.table object, this no longer works.
",https://stackoverflow.com/questions/9202413/how-do-you-delete-a-column-by-name-in-data-table,245,243006.0,8.0,,,2012-02-08 22:20:31,2019-11-10 19:13:13,2016-02-26 21:22:45,,,r;data.table,Maiasaura,33216,313163,registered,true,9202485,,CC BY-SA 3.0,,566,442,6,0,0,2,true,false,false,true,true,true,49,10,true,0.033,0.001,5400,2012,2,22,Wednesday,false,false,false,false,false,false,false
11889625,Annotating text on individual facet in ggplot2,"I want to annotate some text on last facet of the plot with the following code:
library(ggplot2)
p <- ggplot(mtcars, aes(mpg, wt)) + geom_point()
p <- p + facet_grid(. ~ cyl)
p <- p + annotate("text", label = "Test", size = 4, x = 15, y = 5)
print(p)
![]()
But this code annotates the text on every facet. How can I get the annotated text on only one facet?
",https://stackoverflow.com/questions/11889625/annotating-text-on-individual-facet-in-ggplot2,244,187841.0,7.0,,,2012-08-09 18:21:29,2025-01-04 02:09:36,2024-12-19 19:48:22,,,r;ggplot2;facet-wrap;facet-grid;r-faq,MYaseen208,24196,707145,registered,true,11889798,,CC BY-SA 4.0,2016-01-13 18:22:48,508,383,1,0,1,5,true,false,false,true,true,true,46,7,false,0.037,0.0013,5217,2012,8,18,Thursday,false,false,false,false,false,false,false
8175912,Load multiple packages at once,"How can I load a bunch of packages at once with out retyping the require command over and over? I've tried three approaches all of which crash and burn.
Basically, I want to supply a vector of package names to a function that will load them.
x<-c(""plyr"", ""psych"", ""tm"")
require(x)
lapply(x, require)
do.call(""require"", x)
",https://stackoverflow.com/questions/8175912/load-multiple-packages-at-once,243,162845.0,10.0,,,2011-11-17 23:36:23,2022-09-30 18:28:36,2018-03-01 09:37:34,,,r;package,Tyler Rinker,110876,1000343,registered,true,8176099,,CC BY-SA 3.0,2017-06-20 18:37:13,368,330,1,0,0,2,true,false,false,true,true,true,30,5,false,0.061,0.0015,5483,2011,11,23,Thursday,false,false,false,false,false,false,false
11488174,How to select a CRAN mirror in R,"I'm trying to install a package through the R prompt by doing the following:
install.packages('RMySQL')
But the output is as follows:
--- Please select a CRAN mirror for use in this session ---
And nothing else! I can't find a solution to this very basic problem. What am I supposed to type in order to select a CRAN mirror?
EDIT:
OS: Mac-OS X 10.6.8
R Version: 2.15.0
",https://stackoverflow.com/questions/11488174/how-to-select-a-cran-mirror-in-r,242,359640.0,11.0,,,2012-07-14 23:27:00,2023-04-24 12:22:29,2017-01-23 19:58:52,,,r;package;installation;cran,Jim Johnson,2639,1484373,registered,true,11488224,,CC BY-SA 3.0,,463,380,2,0,0,4,true,false,false,true,true,true,32,8,false,0.031,0.0007,5243,2012,7,23,Saturday,true,false,false,false,false,false,false
5587676,pull out p-values and r-squared from a linear regression,"How do you pull out the p-value (for the significance of the coefficient of the single explanatory variable being non-zero) and R-squared value from a simple linear regression model? For example...
x = cumsum(c(0, runif(100, -1, +1)))
y = cumsum(c(0, runif(100, -1, +1)))
fit = lm(y ~ x)
summary(fit)
I know that summary(fit) displays the p-value and R-squared value, but I want to be able to stick these into other variables.
",https://stackoverflow.com/questions/5587676/pull-out-p-values-and-r-squared-from-a-linear-regression,242,408755.0,13.0,,,2011-04-07 21:07:25,2025-04-16 08:47:39,,,,r,grautur,30575,231588,registered,true,5587781,,CC BY-SA 2.5,,490,430,2,0,0,1,true,false,false,true,true,false,56,9,false,0.032,0.0006,5707,2011,4,21,Thursday,false,false,false,false,false,false,false
14976331,Use of ~ (tilde) in R programming Language,"I saw in a tutorial about regression modeling the following command:
myFormula <- Species ~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width
What exactly does this command do, and what is the role of ~ (tilde) in the command?
",https://stackoverflow.com/questions/14976331/use-of-tilde-in-r-programming-language,241,199916.0,3.0,,,2013-02-20 09:27:57,2021-03-23 18:19:28,2021-01-14 08:10:13,,,r;r-faq;r-formula,Ankita,2878,2090489,registered,true,14976479,,CC BY-SA 4.0,,288,237,2,0,0,3,true,false,false,true,true,true,42,8,false,0.015,0.0012,5022,2013,2,9,Wednesday,false,false,false,false,false,false,false
13090838,R - Markdown avoiding package loading messages,"I have been using Knitr via R-Studio, and think it is pretty neat. I have a minor issue though. When I source a file in an R-Chunk, the knitr output includes external comments as follows:
+ FALSE Loading required package: ggplot2
+ FALSE Loading required package: gridExtra
+ FALSE Loading required package: grid
+ FALSE Loading required package: VGAM
+ FALSE Loading required package: splines
+ FALSE Loading required package: stats4
+ FALSE Attaching package: 'VGAM'
+ FALSE The following object(s) are masked from 'package:stats4':
I have tried to set R-chunk options in various ways but still didn't seem to avoid the problem:
```{r echo=FALSE, cache=FALSE, results=FALSE, warning=FALSE, comment=FALSE, warning=FALSE}
source(""C:/Rscripts/source.R"");
```
Is there any way to comment out these messages?
",https://stackoverflow.com/questions/13090838/r-markdown-avoiding-package-loading-messages,240,279077.0,4.0,,,2012-10-26 16:30:43,2018-08-07 21:10:52,2012-10-26 16:36:46,,,r;markdown;knitr;rstudio;r-markdown,Roark,2595,1676238,registered,true,13090913,,CC BY-SA 3.0,2023-07-14 16:58:14,885,816,2,0,0,5,true,false,false,true,true,true,46,7,false,0.014,0.0009,5139,2012,10,16,Friday,false,false,false,false,false,false,false
24459752,Can dplyr package be used for conditional mutating?,"Can the mutate be used when the mutation is conditional (depending on the values of certain column values)?
This example helps showing what I mean.
structure(list(a = c(1, 3, 4, 6, 3, 2, 5, 1), b = c(1, 3, 4,
2, 6, 7, 2, 6), c = c(6, 3, 6, 5, 3, 6, 5, 3), d = c(6, 2, 4,
5, 3, 7, 2, 6), e = c(1, 2, 4, 5, 6, 7, 6, 3), f = c(2, 3, 4,
2, 2, 7, 5, 2)), .Names = c(""a"", ""b"", ""c"", ""d"", ""e"", ""f""), row.names = c(NA,
8L), class = ""data.frame"")
a b c d e f
1 1 1 6 6 1 2
2 3 3 3 2 2 3
3 4 4 6 4 4 4
4 6 2 5 5 5 2
5 3 6 3 3 6 2
6 2 7 6 7 7 7
7 5 2 5 2 6 5
8 1 6 3 6 3 2
I was hoping to find a solution to my problem using the dplyr package (and yes I know this not code that should work, but I guess it makes the purpose clear) for creating a new column g:
library(dplyr)
df <- mutate(df,
if (a == 2 | a == 5 | a == 7 | (a == 1 & b == 4)){g = 2},
if (a == 0 | a == 1 | a == 4 | a == 3 | c == 4) {g = 3})
The result of the code I am looking for should have this result in this particular example:
a b c d e f g
1 1 1 6 6 1 2 3
2 3 3 3 2 2 3 3
3 4 4 6 4 4 4 3
4 6 2 5 5 5 2 NA
5 3 6 3 3 6 2 NA
6 2 7 6 7 7 7 2
7 5 2 5 2 6 5 2
8 1 6 3 6 3 2 3
Does anyone have an idea about how to do this in dplyr? This data frame is just an example, the data frames I am dealing with are much larger. Because of its speed I tried to use dplyr, but perhaps there are other, better ways to handle this problem?
",https://stackoverflow.com/questions/24459752/can-dplyr-package-be-used-for-conditional-mutating,239,400086.0,5.0,,,2014-06-27 19:48:22,2022-06-03 18:09:08,2018-12-02 03:18:10,,,r;if-statement;case-when;dplyr,rdatasculptor,8547,1983395,registered,true,24459900,,CC BY-SA 4.0,,1543,1436,3,0,0,4,true,false,false,true,true,true,51,8,true,0.012,0.0006,4530,2014,6,19,Friday,false,false,false,false,false,false,false
11738823,Explicitly calling return in a function or not,"A while back I got rebuked by Simon Urbanek from the R core team (I believe) for recommending a user to explicitly calling return at the end of a function (his comment was deleted though):
foo = function() {
return(value)
}
instead he recommended:
foo = function() {
value
}
Probably in a situation like this it is required:
foo = function() {
if(a) {
return(a)
} else {
return(b)
}
}
His comment shed some light on why not calling return unless strictly needed is a good thing, but this was deleted.
My question is: Why is not calling return faster or better, and thus preferable?
",https://stackoverflow.com/questions/11738823/explicitly-calling-return-in-a-function-or-not,239,123711.0,9.0,,,2012-07-31 11:12:55,2024-05-03 14:01:33,2017-05-23 11:54:51,,,r,Paul Hiemstra,61315,1033808,registered,true,11834490,,CC BY-SA 3.0,,879,606,6,1,0,1,true,false,false,true,true,true,46,8,false,0.073,0.0019,5226,2012,7,11,Tuesday,false,false,false,false,false,false,false
28370249,"Correct" way to specifiy optional arguments in R functions,"I am interested in what is the ""correct"" way to write functions with optional arguments in R.
Over time, I stumbled upon a few pieces of code that take a different route here, and I couldn't find a proper (official) position on this topic.
Up until now, I have written optional arguments like this:
fooBar <- function(x,y=NULL){
if(!is.null(y)) x <- x+y
return(x)
}
fooBar(3) # 3
fooBar(3,1.5) # 4.5
The function simply returns its argument if only x is supplied. It uses a default NULL value for the second argument and if that argument happens to be not NULL, then the function adds the two numbers.
Alternatively, one could write the function like this (where the second argument needs to be specified by name, but one could also unlist(z) or define z <- sum(...) instead):
fooBar <- function(x,...){
z <- list(...)
if(!is.null(z$y)) x <- x+z$y
return(x)
}
fooBar(3) # 3
fooBar(3,y=1.5) # 4.5
Personally I prefer the first version. However, I can see good and bad with both. The first version is a little less prone to error, but the second one could be used to incorporate an arbitrary number of optionals.
Is there a ""correct"" way to specify optional arguments in R? So far, I have settled on the first approach, but both can occasionally feel a bit ""hacky"".
",https://stackoverflow.com/questions/28370249/correct-way-to-specifiy-optional-arguments-in-r-functions,239,195180.0,7.0,,,2015-02-06 16:23:34,2025-04-29 18:09:06,,,,r;function,SimonG,4951,2068776,registered,true,28370319,,CC BY-SA 3.0,,1456,1301,7,0,0,2,true,false,false,true,true,false,69,9,false,0.036,0.0012,4306,2015,2,16,Friday,false,false,false,false,false,false,false
9689104,"Installing R on Mac - Warning messages: Setting LC_CTYPE failed, using "C"","I would like install R on my laptop Mac OS X version 10.7.3
I downloaded the last version and I double click on it and it was installed, when i start up I get the following error, I searched in internet but I could not solve the problem, any help would be appreciated
the errors are
During startup - Warning messages:
1: Setting LC_CTYPE failed, using ""C""
2: Setting LC_COLLATE failed, using ""C""
3: Setting LC_TIME failed, using ""C""
4: Setting LC_MESSAGES failed, using ""C""
5: Setting LC_PAPER failed, using ""C""
[R.app GUI 1.50 (6126) x86_64-apple-darwin9.8.0]
WARNING: You're using a non-UTF8 locale, therefore only ASCII characters will work.
Please read R for Mac OS X FAQ (see Help) section 9 and adjust your system preferences accordingly.
[History restored from /Users/nemo/.Rapp.history]
",https://stackoverflow.com/questions/9689104/installing-r-on-mac-warning-messages-setting-lc-ctype-failed-using-c,237,190493.0,7.0,,,2012-03-13 17:35:38,2021-02-01 13:42:27,2015-02-12 15:35:49,,,macos;r;installation,user1267127,,,does_not_exist,true,17510093,,CC BY-SA 3.0,2019-01-16 21:31:24,911,827,0,0,0,3,true,false,false,true,false,true,84,12,false,0.037,0.0012,5366,2012,3,17,Tuesday,false,false,false,false,false,false,false
21125222,Determine the data types of a data frame's columns,"I'm using R and have loaded data into a dataframe using read.csv(). How do I determine the data type of each column in the data frame?
",https://stackoverflow.com/questions/21125222/determine-the-data-types-of-a-data-frames-columns,233,677786.0,11.0,,,2014-01-14 22:20:23,2022-01-25 11:05:47,2018-04-05 22:24:51,,,r;dataframe;types,stackoverflowuser2010,41665,4561314,registered,true,21125793,,CC BY-SA 3.0,,155,135,1,0,0,3,true,false,false,true,true,true,54,9,false,0.016,0.0003,4694,2014,1,22,Tuesday,false,false,false,false,false,false,false
10225098,Understanding exactly when a data.table is a reference to (vs a copy of) another data.table,"I'm having a little trouble understanding the pass-by-reference properties of data.table. Some operations seem to 'break' the reference, and I'd like to understand exactly what's happening.
On creating a data.table from another data.table (via <-, then updating the new table by :=, the original table is also altered. This is expected, as per:
?data.table::copy
and stackoverflow: pass-by-reference-the-operator-in-the-data-table-package
Here's an example:
library(data.table)
DT <- data.table(a=c(1,2), b=c(11,12))
print(DT)
# a b
# [1,] 1 11
# [2,] 2 12
newDT <- DT # reference, not copy
newDT[1, a := 100] # modify new DT
print(DT) # DT is modified too.
# a b
# [1,] 100 11
# [2,] 2 12
However, if I insert a non-:= based modification between the <- assignment and the := lines above, DT is now no longer modified:
DT = data.table(a=c(1,2), b=c(11,12))
newDT <- DT
newDT$b[2] <- 200 # new operation
newDT[1, a := 100]
print(DT)
# a b
# [1,] 1 11
# [2,] 2 12
So it seems that the newDT$b[2] <- 200 line somehow 'breaks' the reference. I'd guess that this invokes a copy somehow, but I would like to understand fully how R is treating these operations, to ensure I don't introduce potential bugs in my code.
I'd very much appreciate if someone could explain this to me.
",https://stackoverflow.com/questions/10225098/understanding-exactly-when-a-data-table-is-a-reference-to-vs-a-copy-of-another,233,47440.0,2.0,,,2012-04-19 09:19:30,2018-05-29 09:43:17,2018-05-29 09:43:17,,,r;reference;copy;data.table;assignment-operator,Peter Fine,2953,1013562,registered,true,10226454,,CC BY-SA 4.0,,1709,1354,13,1,0,5,true,false,false,true,true,true,91,15,false,0.042,0.0049,5329,2012,4,9,Thursday,false,false,false,false,false,false,false
13967063,Remove duplicated rows,"I have read a CSV file into an R data.frame. Some of the rows have the same element in one of the columns. I would like to remove rows that are duplicates in that column. For example:
platform_external_dbus 202 16 google 1
platform_external_dbus 202 16 space-ghost.verbum 1
platform_external_dbus 202 16 localhost 1
platform_external_dbus 202 16 users.sourceforge 8
platform_external_dbus 202 16 hughsie 1
I would like only one of these rows since the others have the same data in the first column.
",https://stackoverflow.com/questions/13967063/remove-duplicated-rows,232,675108.0,10.0,,,2012-12-20 07:17:27,2024-07-14 03:58:56,2017-05-23 15:16:15,,,r;duplicates;r-faq,user1897691,2471,1897691,registered,true,13967118,,CC BY-SA 3.0,,756,705,2,0,0,3,true,false,false,true,true,true,22,3,false,0.015,0.0003,5084,2012,12,7,Thursday,false,false,false,false,false,false,false
8790143,Does the ternary operator exist in R?,"As the question asks, is there a control sequence in R similar to C's ternary operator? If so, how do you use it? Thanks!
",https://stackoverflow.com/questions/8790143/does-the-ternary-operator-exist-in-r,232,92739.0,9.0,,,2012-01-09 14:44:25,2022-07-15 13:33:08,2017-05-23 12:17:50,,,r;operators,eykanal,27297,168775,registered,true,8790269,,CC BY-SA 3.0,,185,122,0,1,0,2,true,false,false,true,true,true,37,7,true,0.097,0.0025,5430,2012,1,14,Monday,false,false,false,false,false,false,false
6668963,How to prevent ifelse() from turning Date objects into numeric objects,"I am using the function ifelse() to manipulate a date vector. I expected the result to be of class Date, and was surprised to get a numeric vector instead. Here is an example:
dates <- as.Date(c('2011-01-01', '2011-01-02', '2011-01-03', '2011-01-04', '2011-01-05'))
dates <- ifelse(dates == '2011-01-01', dates - 1, dates)
str(dates)
This is especially surprising because performing the operation across the entire vector returns a Date object.
dates <- as.Date(c('2011-01-01', '2011-01-02', '2011-01-03', '2011-01-04','2011-01-05'))
dates <- dates - 1
str(dates)
Should I be using some other function to operate on Date vectors? If so, what function? If not, how do I force ifelse to return a vector of the same type as the input?
The help page for ifelse indicates that this is a feature, not a bug, but I'm still struggling to find an explanation for what I found to be surprising behavior.
",https://stackoverflow.com/questions/6668963/how-to-prevent-ifelse-from-turning-date-objects-into-numeric-objects,232,60613.0,7.0,,,2011-07-12 18:11:16,2023-10-20 06:47:16,2020-07-05 16:03:32,,,r;date;datetime;if-statement,Zach,30561,345660,registered,true,38093096,,CC BY-SA 4.0,,1082,915,9,0,0,4,true,false,false,true,true,true,70,11,false,0.115,0.0038,5611,2011,7,18,Tuesday,false,false,false,false,false,false,false
16194212,How to suppress warnings globally in an R Script,"I have a long R script that throws some warnings, which I can ignore.
I could use
suppressWarnings(expr)
for single statements. But how can I suppress warnings in R globally? Is there an option for this?
",https://stackoverflow.com/questions/16194212/how-to-suppress-warnings-globally-in-an-r-script,229,306670.0,5.0,,,2013-04-24 14:09:30,2021-07-02 09:07:16,2015-04-07 12:55:37,,,r;warnings,Richi W,3716,1863648,registered,true,16194365,,CC BY-SA 3.0,,246,208,1,0,0,2,true,false,false,true,true,true,48,9,false,0.016,0.0007,4959,2013,4,14,Wednesday,false,false,false,false,false,false,false
7070173,Convert data.frame column to a vector?,"I have a dataframe such as:
a1 = c(1, 2, 3, 4, 5)
a2 = c(6, 7, 8, 9, 10)
a3 = c(11, 12, 13, 14, 15)
aframe = data.frame(a1, a2, a3)
I tried the following to convert one of the columns to a vector, but it doesn't work:
avector <- as.vector(aframe['a2'])
class(avector)
[1] ""data.frame""
This is the only solution I could come up with, but I'm assuming there has to be a better way to do this:
class(aframe['a2'])
[1] ""data.frame""
avector = c()
for(atmp in aframe['a2']) { avector <- atmp }
class(avector)
[1] ""numeric""
Note: My vocabulary above may be off, so please correct me if so. I'm still learning the world of R. Additionally, any explanation of what's going on here is appreciated (i.e. relating to Python or some other language would help!)
",https://stackoverflow.com/questions/7070173/convert-data-frame-column-to-a-vector,227,572722.0,12.0,,,2011-08-15 20:08:35,2022-08-27 09:15:38,2018-09-11 06:34:48,,,r;dataframe;vector;type-conversion,Dolan Antenucci,16092,318870,registered,true,7070330,,CC BY-SA 4.0,,884,767,3,0,0,4,true,false,false,true,true,true,38,6,true,0.021,0.0004,5577,2011,8,20,Monday,false,false,false,false,false,false,false
10758961,How to convert a table to a data frame,"I have a table in R that has str() of this:
table [1:3, 1:4] 0.166 0.319 0.457 0.261 0.248 ...
- attr(*, ""dimnames"")=List of 2
..$ x: chr [1:3] ""Metro >=1 million"" ""Metro <1 million"" ""Non-Metro Counties""
..$ y: chr [1:4] ""q1"" ""q2"" ""q3"" ""q4""
And looks like this when I print it:
y
x q1 q2 q3 q4
Metro >=1 million 0.1663567 0.2612212 0.2670441 0.3053781
Metro <1 million 0.3192857 0.2480012 0.2341030 0.1986102
Non-Metro Counties 0.4570341 0.2044960 0.2121102 0.1263597
I want to get rid of the x and y and convert it to a data frame that looks exactly the same as the above (three rows, four columns), but without the x or y. If I use as.data.frame(mytable), instead I get this:
x y Freq
1 Metro >=1 million q1 0.1663567
2 Metro <1 million q1 0.3192857
3 Non-Metro Counties q1 0.4570341
4 Metro >=1 million q2 0.2612212
5 Metro <1 million q2 0.2480012
6 Non-Metro Counties q2 0.2044960
7 Metro >=1 million q3 0.2670441
8 Metro <1 million q3 0.2341030
9 Non-Metro Counties q3 0.2121102
10 Metro >=1 million q4 0.3053781
11 Metro <1 million q4 0.1986102
12 Non-Metro Counties q4 0.1263597
I probably fundamentally do not understand how tables relate to data frames.
",https://stackoverflow.com/questions/10758961/how-to-convert-a-table-to-a-data-frame,227,348148.0,4.0,,,2012-05-25 17:35:18,2021-03-03 19:33:24,2021-03-03 19:33:24,,,r;dataframe,Victor Van Hee,10029,433386,registered,true,10759011,,CC BY-SA 4.0,2016-11-29 20:47:48,1517,1339,9,0,0,2,true,false,false,true,true,true,38,9,false,0.011,0.0007,5293,2012,5,17,Friday,false,false,false,false,false,false,false
11977102,Order data frame rows according to vector with specific order,"Is there an easier way to ensure that a data frame's rows are ordered according to a ""target"" vector as the one I implemented in the short example below?
df <- data.frame(name = letters[1:4], value = c(rep(TRUE, 2), rep(FALSE, 2)))
df
# name value
# 1 a TRUE
# 2 b TRUE
# 3 c FALSE
# 4 d FALSE
target <- c(""b"", ""c"", ""a"", ""d"")
This somehow seems to be a bit too ""complicated"" to get the job done:
idx <- sapply(target, function(x) {
which(df$name == x)
})
df <- df[idx,]
rownames(df) <- NULL
df
# name value
# 1 b TRUE
# 2 c FALSE
# 3 a TRUE
# 4 d FALSE
",https://stackoverflow.com/questions/11977102/order-data-frame-rows-according-to-vector-with-specific-order,226,223280.0,6.0,,,2012-08-15 20:53:10,2021-01-12 00:41:59,2019-01-24 13:26:37,,,r;sorting;dataframe,JankoWTF,13160,989691,registered,true,11977256,,CC BY-SA 4.0,,675,613,2,0,0,3,true,false,false,true,true,true,61,10,false,0.027,0.001,5211,2012,8,20,Wednesday,false,false,false,false,false,false,false
43820483,Difference between R MarkDown and R NoteBook,"I am trying to understand at a high level what the differences between R Markdown and R NoteBook. I know they are interrelated but I would like to figure out how they are related. My understanding is this:
I know R Notebooks are really R Markdown documents but I am confused about the terminologies.
RStudio new file option has both R Markdown and R NoteBook and selecting either of them opens an R Markdown file but with minor differences. So just trying to figure out why are there two options and what is the difference between the two?
I understand R Notebooks are newly introduced and R Markdown has been there for a while. Part of the confusion could be because I never used R Markdown before R Notebook was introduced so my related or more specific question is
What is R NoteBook doing differently than just using R MarkDown or what new capabilities is R NoteBook bringing?
All my hits on web search are pointing that R Notebook uses R Markdown but I did not find any help on what is specifically different between the two.
",https://stackoverflow.com/questions/43820483/difference-between-r-markdown-and-r-notebook,226,102524.0,9.0,,,2017-05-06 12:30:09,2022-01-11 02:09:28,2019-04-02 20:22:05,,,r;rstudio;knitr;r-markdown;rnotebook,PagMax,8708,5826590,registered,true,48660864,,CC BY-SA 4.0,,1342,1040,6,1,1,5,true,false,false,true,true,true,44,7,false,0.088,0.0022,3486,2017,5,12,Saturday,true,false,false,false,false,false,false
9439256,How can I handle R CMD check "no visible binding for global variable" notes when my ggplot2 syntax is sensible?,"EDIT: Hadley Wickham points out that I misspoke. R CMD check is throwing NOTES, not Warnings. I'm terribly sorry for the confusion. It was my oversight.
The short version
R CMD check throws this note every time I use sensible plot-creation syntax in ggplot2:
no visible binding for global variable [variable name]
I understand why R CMD check does that, but it seems to be criminalizing an entire vein of otherwise sensible syntax. I'm not sure what steps to take to get my package to pass R CMD check and get admitted to CRAN.
The background
Sascha Epskamp previously posted on essentially the same issue. The difference, I think, is that subset()'s manpage says it's designed for interactive use.
In my case, the issue is not over subset() but over a core feature of ggplot2: the data = argument.
An example of code I write that generates these notes
Here's a sub-function in my package that adds points to a plot:
JitteredResponsesByContrast <- function (data) {
return(
geom_point(
aes(
x = x.values,
y = y.values
),
data = data,
position = position_jitter(height = 0, width = GetDegreeOfJitter(jj))
)
)
}
R CMD check, on parsing this code, will say
granovagg.contr : JitteredResponsesByContrast: no visible binding for
global variable 'x.values'
granovagg.contr : JitteredResponsesByContrast: no visible binding for
global variable 'y.values'
Why R CMD check is right
The check is technically correct. x.values and y.values
- Aren't defined locally in the function
JitteredResponsesByContrast()
- Aren't pre-defined in the form
x.values <- [something] either globally or in the caller.
Instead, they're variables within a dataframe that gets defined earlier and passed into the function JitteredResponsesByContrast().
Why ggplot2 makes it difficult to appease R CMD check
ggplot2 seems to encourage the use of a data argument. The data argument, presumably, is why this code will execute
library(ggplot2)
p <- ggplot(aes(x = hwy, y = cty), data = mpg)
p + geom_point()
but this code will produce an object-not-found error:
library(ggplot2)
hwy # a variable in the mpg dataset
Two work-arounds, and why I'm happy with neither
The NULLing out strategy
Matthew Dowle recommends setting the problematic variables to NULL first, which in my case would look like this:
JitteredResponsesByContrast <- function (data) {
x.values <- y.values <- NULL # Setting the variables to NULL first
return(
geom_point(
aes(
x = x.values,
y = y.values
),
data = data,
position = position_jitter(height = 0, width = GetDegreeOfJitter(jj))
)
)
}
I appreciate this solution, but I dislike it for three reasons.
- it serves no additional purpose beyond appeasing
R CMD check.
- it doesn't reflect intent. It raises the expectation that the
aes() call will see our now-NULL variables (it won't), while obscuring the real purpose (making R CMD check aware of variables it apparently wouldn't otherwise know were bound)
- The problems of 1 and 2 multiply because every time you write a function that returns a plot element, you have to add a confusing NULLing statement
The with() strategy
You can use with() to explicitly signal that the variables in question can be found inside some larger environment. In my case, using with() looks like this:
JitteredResponsesByContrast <- function (data) {
with(data, {
geom_point(
aes(
x = x.values,
y = y.values
),
data = data,
position = position_jitter(height = 0, width = GetDegreeOfJitter(jj))
)
}
)
}
This solution works. But, I don't like this solution because it doesn't even work the way I would expect it to. If with() were really solving the problem of pointing the interpreter to where the variables are, then I shouldn't even need the data = argument. But, with() doesn't work that way:
library(ggplot2)
p <- ggplot()
p <- p + with(mpg, geom_point(aes(x = hwy, y = cty)))
p # will generate an error saying `hwy` is not found
So, again, I think this solution has similar flaws to the NULLing strategy:
- I still have to go through every plot element function and wrap the logic in a
with() call
- The
with() call is misleading. I still need to supply a data = argument; all with() is doing is appeasing R CMD check.
Conclusion
The way I see it, there are three options I could take:
- Lobby CRAN to ignore the notes by arguing that they're "spurious" (pursuant to CRAN policy), and do that every time I submit a package
- Fix my code with one of two undesirable strategies (NULLing or
with() blocks)
- Hum really loudly and hope the problem goes away
None of the three make me happy, and I'm wondering what people suggest I (and other package developers wanting to tap into ggplot2) should do.
",https://stackoverflow.com/questions/9439256/how-can-i-handle-r-cmd-check-no-visible-binding-for-global-variable-notes-when,226,34369.0,9.0,,,2012-02-24 23:00:56,2024-11-26 22:09:45,2022-02-21 22:46:29,,,r;ggplot2,briandk,7059,180626,registered,true,9439360,,CC BY-SA 4.0,,6560,4980,34,7,0,2,true,false,false,true,true,true,121,20,true,0.262,0.0066,5384,2012,2,23,Friday,false,false,false,false,false,false,false
21982987,Mean per group in a data.frame,"I have a data.frame and I need to calculate the mean per group (i.e. per Month, below).
Name Month Rate1 Rate2
Aira 1 12 23
Aira 2 18 73
Aira 3 19 45
Ben 1 53 19
Ben 2 22 87
Ben 3 19 45
Cat 1 22 87
Cat 2 67 43
Cat 3 45 32
My desired output is like below, where the values for Rate1 and Rate2 are the group means. Please disregard the value, I have made it up for the example.
Name Rate1 Rate2
Aira 23.21 12.2
Ben 45.23 43.9
Cat 33.22 32.2
",https://stackoverflow.com/questions/21982987/mean-per-group-in-a-data-frame,225,712732.0,8.0,,,2014-02-24 08:56:59,2022-06-23 15:40:20,2020-05-04 13:10:46,2020-05-04 13:20:53,Duplicate,r;aggregate,Ianthe,5749,661951,registered,true,21983076,,,2022-05-11 20:50:47,788,674,6,0,0,2,true,true,false,true,true,true,30,6,false,0.011,0.0003,4653,2014,2,8,Monday,false,false,false,false,false,false,false
3932038,Plot a legend outside of the plotting area in base graphics?,"As the title says: How can I plot a legend outside the plotting area when using base graphics?
I thought about fiddling around with layout and produce an empty plot to only contain the legend, but I would be interested in a way using just the base graph facilities and e.g., par(mar = ) to get some space on the right of the plot for the legend.
Here an example:
plot(1:3, rnorm(3), pch = 1, lty = 1, type = ""o"", ylim=c(-2,2))
lines(1:3, rnorm(3), pch = 2, lty = 2, type=""o"")
legend(1,-1,c(""group A"", ""group B""), pch = c(1,2), lty = c(1,2))
produces:
![]()
But as said, I would like the legend to be outside the plotting area (e.g., to the right of the graph/plot.
",https://stackoverflow.com/questions/3932038/plot-a-legend-outside-of-the-plotting-area-in-base-graphics,225,468623.0,12.0,,,2010-10-14 10:01:44,2024-09-10 00:29:25,,,,r;plot;legend,Henrik,14510,289572,registered,true,3932558,,CC BY-SA 2.5,,840,669,3,0,1,3,true,false,false,true,true,false,60,11,true,0.026,0.0005,5882,2010,10,10,Thursday,false,false,false,false,false,false,false
7263849,What do hjust and vjust do when making a plot using ggplot?,"Every time I make a plot using ggplot, I spend a little while trying different values for hjust and vjust in a line like
+ opts(axis.text.x = theme_text(hjust = 0.5))
to get the axis labels to line up where the axis labels almost touch the axis, and are flush against it (justified to the axis, so to speak). However, I don't really understand what's going on. Often, hjust = 0.5 gives such dramatically different results from hjust = 0.6, for example, that I haven't been able to figure it out just by playing around with different values.
Can anyone point me to a comprehensive explanation of how hjust and vjust options work?
",https://stackoverflow.com/questions/7263849/what-do-hjust-and-vjust-do-when-making-a-plot-using-ggplot,225,269262.0,2.0,,,2011-08-31 21:46:28,2023-03-15 19:44:36,2011-09-01 21:12:28,,,r;plot;ggplot2,William Gunn,3065,156044,registered,true,7267364,,CC BY-SA 3.0,,706,635,3,0,0,3,true,false,false,true,true,true,59,12,true,0.007,0.0008,5561,2011,8,21,Wednesday,false,false,false,false,false,false,false
9950144,Access lapply index names inside FUN,"Is there a way to get the list index name in my lapply() function?
n = names(mylist)
lapply(mylist, function(list.elem) { cat(""What is the name of this list element?\n"" })
I asked before if it's possible to preserve the index names in the lapply() returned list, but I still don't know if there is an easy way to fetch each element name inside the custom function. I would like to avoid to call lapply on the names themselves, I'd rather get the name in the function parameters.
",https://stackoverflow.com/questions/9950144/access-lapply-index-names-inside-fun,225,94183.0,12.0,,,2012-03-30 20:40:07,2019-11-15 10:43:20,2017-05-23 12:02:46,,,r;lapply;names;indices,Robert Kubrick,8883,382271,registered,true,9950217,,CC BY-SA 3.0,,637,482,1,1,0,4,true,false,false,true,true,true,36,6,false,0.127,0.0024,5349,2012,3,20,Friday,false,false,false,false,false,false,false
6919025,How to assign colors to categorical variables in ggplot2 that have stable mapping?,"I've been getting up to speed with R in the last month.
Here is my question:
What is a good way to assign colors to categorical variables in ggplot2 that have stable mapping? I need consistent colors across a set of graphs that have different subsets and different number of categorical variables.
For example,
plot1 <- ggplot(data, aes(xData, yData,color=categoricaldData)) + geom_line()
where categoricalData has 5 levels.
And then
plot2 <- ggplot(data.subset, aes(xData.subset, yData.subset,
color=categoricaldData.subset)) + geom_line()
where categoricalData.subset has 3 levels.
However, a particular level that is in both sets will end up with a different color, which makes it harder to read the graphs together.
Do I need to create a vector of colors in the data frame? Or is there another way to assigns specific colors to categories?
",https://stackoverflow.com/questions/6919025/how-to-assign-colors-to-categorical-variables-in-ggplot2-that-have-stable-mappin,225,339660.0,5.0,,,2011-08-02 21:41:58,2018-04-08 15:19:54,2017-12-01 14:26:26,,,r;ggplot2,wintour,2365,789771,registered,true,6920045,,CC BY-SA 3.0,,1034,897,4,0,0,2,true,false,false,true,true,true,82,13,true,0.015,0.0007,5590,2011,8,21,Tuesday,false,false,false,false,false,false,false
7027288,Error: could not find function ... in R,"
This is meant to be a FAQ question, so please be as complete as possible. The answer is a community answer, so feel free to edit if you think something is missing.
I am using R and tried some.function but I got following error message:
Error: could not find function "some.function"
This question comes up very regularly. When you get this type of error in R, how can you solve it?
",https://stackoverflow.com/questions/7027288/error-could-not-find-function-in-r,223,632991.0,11.0,,,2011-08-11 14:04:19,2023-08-01 23:09:27,2020-06-20 09:12:55,,,r;function;error-handling;r-faq,Joris Meys,109211,428790,registered,true,7027332,,CC BY-SA 4.0,2016-09-28 11:04:00,665,445,2,1,0,4,true,false,false,true,true,true,39,8,false,0.017,0.0004,5581,2011,8,14,Thursday,false,false,false,false,false,false,false
24027605,Determine the number of NA values in a column,"I want to count the number of NA values in a data frame column. Say my data frame is called df, and the name of the column I am considering is col. The way I have come up with is following:
sapply(df$col, function(x) sum(length(which(is.na(x)))))
Is this a good/most efficient way to do this?
",https://stackoverflow.com/questions/24027605/determine-the-number-of-na-values-in-a-column,222,668166.0,17.0,,,2014-06-04 01:29:01,2022-08-27 11:11:42,2016-01-09 18:58:05,,,r;dataframe,user3274289,2596,3274289,registered,true,,,CC BY-SA 3.0,2016-08-19 20:59:11,377,300,4,0,0,2,false,false,false,true,true,true,45,9,false,0.025,0.0003,4553,2014,6,1,Wednesday,false,false,false,false,false,false,false
3695677,How to find common elements from multiple vectors?,"Can anyone tell me how to find the common elements from multiple vectors?
a <- c(1,3,5,7,9)
b <- c(3,6,8,9,10)
c <- c(2,3,4,5,7,9)
I want to get the common elements from the above vectors (ex: 3 and 9)
",https://stackoverflow.com/questions/3695677/how-to-find-common-elements-from-multiple-vectors,218,296679.0,4.0,,,2010-09-12 16:52:59,2025-04-15 19:46:19,2020-01-17 10:39:18,,,r;vector;r-faq,Chares,2923,445665,registered,true,3695700,,CC BY-SA 4.0,2018-03-14 21:19:49,253,215,1,0,0,3,true,false,false,true,true,true,50,8,true,0.013,0.0007,5914,2010,9,16,Sunday,true,false,false,false,false,false,false
22309285,How to use a variable to specify column name in ggplot,"I have a ggplot command
ggplot( rates.by.groups, aes(x=name, y=rate, colour=majr, group=majr) )
inside a function. But I would like to be able to use a parameter of the function to pick out the column to use as colour and group. I.e. I would like something like this
f <- function( column ) {
...
ggplot( rates.by.groups, aes(x=name, y=rate, colour= ??? , group=??? ) )
}
So that the column used in the ggplot is determined by the parameter. E.g. for f(""majr"") we get the effect of
ggplot( rates.by.groups, aes(x=name, y=rate, colour=majr, group=majr) )
but for f(""gender"") we get the effect of
ggplot( rates.by.groups, aes(x=name, y=rate, colour=gender, group=gender) )
Some things I tried:
ggplot( rates.by.groups, aes(x=name, y=rate, colour= columnName , group=columnName ) )
did not work. Nor did
e <- environment()
ggplot( rates.by.groups, aes(x=name, y=rate, colour= columnName , group=columnName ), environment=e )
",https://stackoverflow.com/questions/22309285/how-to-use-a-variable-to-specify-column-name-in-ggplot,218,136114.0,6.0,,,2014-03-10 19:17:51,2022-10-17 18:56:08,2022-10-17 18:56:08,,,r;ggplot2;nse;r-faq,Theodore Norvell,16531,667690,registered,true,22309328,,CC BY-SA 4.0,2018-11-06 08:50:41,1143,957,6,0,0,4,true,false,false,true,true,true,54,11,false,0.044,0.0016,4639,2014,3,19,Monday,false,false,false,false,false,false,false
3057341,How to use R's ellipsis feature when writing your own function?,"The R language has a nifty feature for defining functions that can take a variable number of arguments. For example, the function data.frame takes any number of arguments, and each argument becomes the data for a column in the resulting data table. Example usage:
> data.frame(letters=c("a", "b", "c"), numbers=c(1,2,3), notes=c("do", "re", "mi"))
letters numbers notes
1 a 1 do
2 b 2 re
3 c 3 mi
The function's signature includes an ellipsis, like this:
function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE,
stringsAsFactors = default.stringsAsFactors())
{
[FUNCTION DEFINITION HERE]
}
I would like to write a function that does something similar, taking multiple values and consolidating them into a single return value (as well as doing some other processing). In order to do this, I need to figure out how to "unpack" the ... from the function's arguments within the function. I don't know how to do this. The relevant line in the function definition of data.frame is object <- as.list(substitute(list(...)))[-1L], which I can't make any sense of.
So how can I convert the ellipsis from the function's signature into, for example, a list?
To be more specific, how can I write get_list_from_ellipsis in the code below?
my_ellipsis_function(...) {
input_list <- get_list_from_ellipsis(...)
output_list <- lapply(X=input_list, FUN=do_something_interesting)
return(output_list)
}
my_ellipsis_function(a=1:10,b=11:20,c=21:30)
Edit
It seems there are two possible ways to do this. They are as.list(substitute(list(...)))[-1L] and list(...). However, these two do not do exactly the same thing. (For differences, see examples in the answers.) Can anyone tell me what the practical difference between them is, and which one I should use?
",https://stackoverflow.com/questions/3057341/how-to-use-rs-ellipsis-feature-when-writing-your-own-function,218,72508.0,5.0,,,2010-06-16 21:31:41,2016-07-13 10:13:06,2020-06-20 09:12:55,,,r;function;parameters;ellipsis;variadic,Ryan C. Thompson,42550,125921,registered,true,3083193,,CC BY-SA 4.0,2017-07-27 14:07:07,2129,1909,10,0,0,5,true,false,false,true,true,true,67,11,true,0.069,0.003,6002,2010,6,21,Wednesday,false,false,false,false,false,false,false
28467068,How to add a row to a data frame in R?,"In R, how do you add a new row to a data frame once the data frame has already been initialized?
So far I have this:
df <- data.frame(""hi"", ""bye"")
names(df) <- c(""hello"", ""goodbye"")
#I am trying to add ""hola"" and ""ciao"" as a new row
de <- data.frame(""hola"", ""ciao"")
merge(df, de) # Adds to the same row as new columns
# Unfortunately, I couldn't find an rbind() solution that wouldn't give me an error
Any help would be appreciated
",https://stackoverflow.com/questions/28467068/how-to-add-a-row-to-a-data-frame-in-r,216,852896.0,16.0,,,2015-02-12 00:10:10,2023-09-11 23:07:34,2022-02-01 14:38:02,,,r;dataframe,Rilcon42,9895,1634753,registered,true,28468977,,CC BY-SA 4.0,,529,448,1,0,0,2,true,false,false,true,true,true,38,11,true,0.019,0.0003,4300,2015,2,0,Thursday,false,false,false,false,false,false,false
2643939,Remove columns from dataframe where ALL values are NA,"I have a data frame where some of the columns contain NA values.
How can I remove columns where all rows contain NA values?
",https://stackoverflow.com/questions/2643939/remove-columns-from-dataframe-where-all-values-are-na,216,203874.0,14.0,,,2010-04-15 08:59:52,2025-01-15 15:09:25,2022-09-05 10:56:35,,,r;apply;dataframe,Gnark,4252,162154,registered,true,2644009,,CC BY-SA 4.0,,155,124,0,0,0,3,true,false,false,true,true,true,53,9,false,0.069,0.0011,6064,2010,4,8,Thursday,false,false,false,false,false,false,false
7735647,Replacing NAs with latest non-NA value,"In a data.frame (or data.table), I would like to "fill forward" NAs with the closest previous non-NA value. A simple example, using vectors (instead of a data.frame) is the following:
> y <- c(NA, 2, 2, NA, NA, 3, NA, 4, NA, NA)
I would like a function fill.NAs() that allows me to construct yy such that:
> yy
[1] NA NA NA 2 2 2 2 3 3 3 4 4
I need to repeat this operation for many (total ~1 Tb) small sized data.frames (~30-50 Mb), where a row is NA is all its entries are. What is a good way to approach the problem?
The ugly solution I cooked up uses this function:
last <- function (x){
x[length(x)]
}
fill.NAs <- function(isNA){
if (isNA[1] == 1) {
isNA[1:max({which(isNA==0)[1]-1},1)] <- 0 # first is NAs
# can't be forward filled
}
isNA.neg <- isNA.pos <- isNA.diff <- diff(isNA)
isNA.pos[isNA.diff < 0] <- 0
isNA.neg[isNA.diff > 0] <- 0
which.isNA.neg <- which(as.logical(isNA.neg))
if (length(which.isNA.neg)==0) return(NULL) # generates warnings later, but works
which.isNA.pos <- which(as.logical(isNA.pos))
which.isNA <- which(as.logical(isNA))
if (length(which.isNA.neg)==length(which.isNA.pos)){
replacement <- rep(which.isNA.pos[2:length(which.isNA.neg)],
which.isNA.neg[2:max(length(which.isNA.neg)-1,2)] -
which.isNA.pos[1:max(length(which.isNA.neg)-1,1)])
replacement <- c(replacement, rep(last(which.isNA.pos), last(which.isNA) - last(which.isNA.pos)))
} else {
replacement <- rep(which.isNA.pos[1:length(which.isNA.neg)], which.isNA.neg - which.isNA.pos[1:length(which.isNA.neg)])
replacement <- c(replacement, rep(last(which.isNA.pos), last(which.isNA) - last(which.isNA.pos)))
}
replacement
}
The function fill.NAs is used as follows:
y <- c(NA, 2, 2, NA, NA, 3, NA, 4, NA, NA)
isNA <- as.numeric(is.na(y))
replacement <- fill.NAs(isNA)
if (length(replacement)){
which.isNA <- which(as.logical(isNA))
to.replace <- which.isNA[which(isNA==0)[1]:length(which.isNA)]
y[to.replace] <- y[replacement]
}
Output
> y
[1] NA 2 2 2 2 3 3 3 4 4 4
... which seems to work. But, man, is it ugly! Any suggestions?
",https://stackoverflow.com/questions/7735647/replacing-nas-with-latest-non-na-value,216,147140.0,23.0,,,2011-10-12 05:27:21,2024-05-31 22:05:40,2021-09-16 06:20:08,,,r;data.table;zoo;r-faq,Ryogi,5637,986817,registered,true,7735681,,CC BY-SA 4.0,2017-08-18 12:10:39,2578,2292,12,0,0,4,true,false,false,true,true,true,38,6,false,0.156,0.0015,5519,2011,10,5,Wednesday,false,false,false,false,false,false,false
1699046,For each row in an R dataframe,"I have a dataframe, and for each row in that dataframe I have to do some complicated lookups and append some data to a file.
The dataFrame contains scientific results for selected wells from 96 well plates used in biological research so I want to do something like:
for (well in dataFrame) {
wellName <- well$name # string like ""H1""
plateName <- well$plate # string like ""plate67""
wellID <- getWellID(wellName, plateName)
cat(paste(wellID, well$value1, well$value2, sep="",""), file=outputFile)
}
In my procedural world, I'd do something like:
for (row in dataFrame) {
#look up stuff using data from the row
#write stuff to the file
}
What is the ""R way"" to do this?
",https://stackoverflow.com/questions/1699046/for-each-row-in-an-r-dataframe,216,503416.0,9.0,,,2009-11-09 04:08:53,2020-12-14 23:39:13,2016-01-04 09:11:23,,,r;dataframe;rows,Carl Coryell-Martin,3520,87661,registered,true,1701141,,CC BY-SA 3.0,,777,701,2,0,0,3,true,false,false,true,true,true,30,7,false,0.018,0.0004,6221,2009,11,4,Monday,false,false,false,false,false,false,false
13649473,Add a common Legend for combined ggplots,"I have two ggplots which I align horizontally with grid.arrange. I have looked through a lot of forum posts, but everything I try seem to be commands that are now updated and named something else.
My data looks like this;
# Data plot 1
axis1 axis2
group1 -0.212201 0.358867
group2 -0.279756 -0.126194
group3 0.186860 -0.203273
group4 0.417117 -0.002592
group1 -0.212201 0.358867
group2 -0.279756 -0.126194
group3 0.186860 -0.203273
group4 0.186860 -0.203273
# Data plot 2
axis1 axis2
group1 0.211826 -0.306214
group2 -0.072626 0.104988
group3 -0.072626 0.104988
group4 -0.072626 0.104988
group1 0.211826 -0.306214
group2 -0.072626 0.104988
group3 -0.072626 0.104988
group4 -0.072626 0.104988
#And I run this:
library(ggplot2)
library(gridExtra)
groups=c('group1','group2','group3','group4','group1','group2','group3','group4')
x1=data1[,1]
y1=data1[,2]
x2=data2[,1]
y2=data2[,2]
p1=ggplot(data1, aes(x=x1, y=y1,colour=groups)) + geom_point(position=position_jitter(w=0.04,h=0.02),size=1.8)
p2=ggplot(data2, aes(x=x2, y=y2,colour=groups)) + geom_point(position=position_jitter(w=0.04,h=0.02),size=1.8)
#Combine plots
p3=grid.arrange(
p1 + theme(legend.position=""none""), p2+ theme(legend.position=""none""), nrow=1, widths = unit(c(10.,10), ""cm""), heights = unit(rep(8, 1), ""cm"")))
How would I extract the legend from any of these plots and add it to the bottom/centre of the combined plot?
",https://stackoverflow.com/questions/13649473/add-a-common-legend-for-combined-ggplots,215,299432.0,9.0,,,2012-11-30 16:48:32,2021-03-26 07:52:05,2015-07-16 13:00:13,,,r;ggplot2;legend;gridextra,jO.,3530,1734415,registered,true,13650878,,CC BY-SA 3.0,2021-01-15 09:52:39,1538,1480,2,0,0,4,true,false,false,true,true,true,40,7,false,0.03,0.0007,5104,2012,11,16,Friday,false,false,false,false,false,false,false
24536154,What does %>% mean in R,"I am following this example, the server.R, file is here.
I plan to do a similar filter, but am lost as to what %>% does.
# Apply filters
m <- all_movies %>%
filter(
Reviews >= reviews,
Oscars >= oscars,
Year >= minyear,
Year <= maxyear,
BoxOffice >= minboxoffice,
BoxOffice <= maxboxoffice
) %>%
arrange(Oscars)
",https://stackoverflow.com/questions/24536154/what-does-mean-in-r,215,517315.0,1.0,,,2014-07-02 16:15:33,2018-11-05 10:36:32,2018-05-31 07:53:40,2019-05-21 18:12:29,Duplicate,r;magrittr,ben_says,2543,2970547,registered,true,24536653,,,,562,416,2,1,0,2,true,true,false,true,true,true,26,6,false,0.002,0.0004,4525,2014,7,16,Wednesday,false,false,false,false,false,false,false
27125672,What does %>% function mean in R?,"I have seen the use of %>% (percent greater than percent) function in some packages like dplyr and rvest. What does it mean? Is it a way to write closure blocks in R?
",https://stackoverflow.com/questions/27125672/what-does-function-mean-in-r,215,704488.0,7.0,,,2014-11-25 11:37:19,2025-04-17 10:26:59,2019-05-21 18:09:21,,,r;syntax;dplyr;magrittr;r-faq,alfakini,4767,732973,registered,true,27129032,,CC BY-SA 4.0,2018-09-02 13:18:21,351,171,1,2,0,5,true,false,false,true,true,true,36,7,true,0.01,0.0003,4379,2014,11,11,Tuesday,false,false,false,false,false,false,false
3365657,Is there a way to make R beep/play a sound at the end of a script?,"When I run R scripts I go do something else on a different desktop. If I don't check frequently, I never know when something is finished. Is there a way to invoke a beep (like a system beep) or get R to play a sound or notify growl via some code at the end of my script?
",https://stackoverflow.com/questions/3365657/is-there-a-way-to-make-r-beep-play-a-sound-at-the-end-of-a-script,214,68666.0,22.0,,,2010-07-29 18:08:27,2024-12-24 04:45:43,,,,r,Maiasaura,33216,313163,registered,true,3365670,,CC BY-SA 2.5,,278,271,0,0,0,1,true,false,false,true,true,false,66,16,true,0.32,0.0031,5959,2010,7,18,Thursday,false,false,false,false,false,false,false
13605271,Reasons for using the set.seed function,"Many times I have seen the set.seed function in R, before starting the program. I know it's basically used for the random number generation. Is there any specific need to set this?
",https://stackoverflow.com/questions/13605271/reasons-for-using-the-set-seed-function,213,370675.0,7.0,,,2012-11-28 12:39:04,2021-08-01 07:29:25,2012-11-28 12:56:07,,,r;random,Vignesh,2277,1666632,registered,true,13605506,,CC BY-SA 3.0,2016-08-09 02:31:46,202,182,1,0,0,2,true,false,false,true,true,true,39,6,false,0.019,0.0006,5106,2012,11,12,Wednesday,false,false,false,false,false,false,false
2908822,Speed up the loop operation in R,"I have a big performance problem in R. I wrote a function that iterates over a data.frame object. It simply adds a new column to a data.frame and accumulates something. (simple operation). The data.frame has roughly 850K rows. My PC is still working (about 10h now) and I have no idea about the runtime.
dayloop2 <- function(temp){
for (i in 1:nrow(temp)){
temp[i,10] <- i
if (i > 1) {
if ((temp[i,6] == temp[i-1,6]) & (temp[i,3] == temp[i-1,3])) {
temp[i,10] <- temp[i,9] + temp[i-1,10]
} else {
temp[i,10] <- temp[i,9]
}
} else {
temp[i,10] <- temp[i,9]
}
}
names(temp)[names(temp) == ""V10""] <- ""Kumm.""
return(temp)
}
Any ideas how to speed up this operation?
",https://stackoverflow.com/questions/2908822/speed-up-the-loop-operation-in-r,212,116157.0,10.0,,,2010-05-25 21:55:36,2020-09-13 11:05:57,2018-07-14 19:17:17,,,performance;r;loops;rcpp;r-faq,Kay,2129,350373,unregistered,true,,,CC BY-SA 4.0,,969,892,4,0,0,5,false,false,false,true,true,true,32,7,false,0.086,0.0018,6024,2010,5,21,Tuesday,false,false,false,false,false,false,false
11036989,Replace all 0 values to NA,"I have a dataframe with some numeric columns. Some row has a 0 value which should be considered as null in statistical analysis. What is the fastest way to replace all the 0 value to NULL in R?
",https://stackoverflow.com/questions/11036989/replace-all-0-values-to-na,212,551873.0,11.0,,,2012-06-14 16:03:13,2022-07-10 18:02:26,2020-03-25 10:51:28,,,r;r-faq,Seen,4204,369921,registered,true,11037085,,CC BY-SA 4.0,2020-03-25 10:51:17,203,196,0,0,0,2,true,false,false,true,true,true,26,6,false,0.02,0.0004,5273,2012,6,16,Thursday,false,false,false,false,false,false,false
5992082,How to remove all whitespace from a string?,"So "" xx yy 11 22 33 "" will become ""xxyy112233"". How can I achieve this?
",https://stackoverflow.com/questions/5992082/how-to-remove-all-whitespace-from-a-string,212,463994.0,9.0,,,2011-05-13 12:49:47,2021-07-22 12:41:47,2020-08-04 18:57:46,,,r;regex;string;r-faq,wndrs,9127,293843,registered,true,5992152,,CC BY-SA 4.0,,106,73,2,0,0,4,true,false,false,true,true,true,43,8,true,0.019,0.0005,5671,2011,5,12,Friday,false,false,false,false,false,false,false
5738831,"R: += (plus equals) and ++ (plus plus) equivalent from c++/c#/java, etc.?","Does R have a concept of += (plus equals) or ++ (plus plus) as c++/c#/others do?
",https://stackoverflow.com/questions/5738831/r-plus-equals-and-plus-plus-equivalent-from-c-c-java-etc,211,217253.0,10.0,,,2011-04-21 02:25:34,2023-03-06 18:51:14,2018-01-26 13:04:17,,,r;operators;variable-assignment;increment,Suraj,36954,356790,registered,true,5738907,,CC BY-SA 3.0,,114,81,2,0,0,4,true,false,false,true,true,true,74,12,true,0.046,0.001,5693,2011,4,2,Thursday,false,false,false,false,false,false,false
22959635,Remove duplicated rows using dplyr,"I have a data.frame like this -
set.seed(123)
df = data.frame(x=sample(0:1,10,replace=T),y=sample(0:1,10,replace=T),z=1:10)
> df
x y z
1 0 1 1
2 1 0 2
3 0 1 3
4 1 1 4
5 1 0 5
6 0 1 6
7 1 0 7
8 1 0 8
9 1 0 9
10 0 1 10
I would like to remove duplicate rows based on first two columns. Expected output -
df[!duplicated(df[,1:2]),]
x y z
1 0 1 1
2 1 0 2
4 1 1 4
I am specifically looking for a solution using dplyr package.
",https://stackoverflow.com/questions/22959635/remove-duplicated-rows-using-dplyr,210,247853.0,6.0,,,2014-04-09 10:22:39,2020-05-02 04:52:59,,,,r;dplyr,Nishanth,7228,2202762,registered,true,22960230,,CC BY-SA 3.0,,537,455,3,0,0,2,true,false,false,true,true,false,34,5,false,0.024,0.0008,4609,2014,4,10,Wednesday,false,false,false,false,false,false,false
2548815,Find file name from full file path,"Is there a way to extract the file name from the file full path (part of a file path) without the hassle of manipulating string?
The equivalent in Java would be:
File f = new File (""C:/some_dir/a"")
f.getName() //output a
f.getFullAbsolutePath() //output c:/some_dir/a
",https://stackoverflow.com/questions/2548815/find-file-name-from-full-file-path,210,136782.0,5.0,,,2010-03-30 21:16:37,2024-04-23 03:23:15,2016-09-30 08:15:28,,,file;r;path,defoo,5325,296564,registered,true,2548871,,CC BY-SA 3.0,2016-09-30 08:16:01,309,271,1,0,0,3,true,false,false,true,true,true,34,7,false,0.037,0.0015,6080,2010,3,21,Tuesday,false,false,false,false,false,false,false
17200114,How to split data into training/testing sets using sample function,"I've just started using R and I'm not sure how to incorporate my dataset with the following sample code:
sample(x, size, replace = FALSE, prob = NULL)
I have a dataset that I need to put into a training (75%) and testing (25%) set.
I'm not sure what information I'm supposed to put into the x and size?
Is x the dataset file, and size how many samples I have?
",https://stackoverflow.com/questions/17200114/how-to-split-data-into-training-testing-sets-using-sample-function,209,693120.0,28.0,,,2013-06-19 19:52:48,2022-01-21 15:30:03,2021-04-02 17:38:25,,,r;split;sample,Susie Humby,2081,2497527,registered,true,,,CC BY-SA 4.0,,404,366,1,0,0,3,false,false,false,true,true,true,66,10,false,0.04,0.0003,4903,2013,6,19,Wednesday,false,false,false,false,false,false,false
3695497,Show percent % instead of counts in charts of categorical variables,"I'm plotting a categorical variable and instead of showing the counts for each category value.
I'm looking for a way to get ggplot to display the percentage of values in that category. Of course, it is possible to create another variable with the calculated percentage and plot that one, but I have to do it several dozens of times and I hope to achieve that in one command.
I was experimenting with something like
qplot(mydataf) +
stat_bin(aes(n = nrow(mydataf), y = ..count../n)) +
scale_y_continuous(formatter = ""percent"")
but I must be using it incorrectly, as I got errors.
To easily reproduce the setup, here's a simplified example:
mydata <- c (""aa"", ""bb"", NULL, ""bb"", ""cc"", ""aa"", ""aa"", ""aa"", ""ee"", NULL, ""cc"");
mydataf <- factor(mydata);
qplot (mydataf); #this shows the count, I'm looking to see % displayed.
In the real case, I'll probably use ggplot instead of qplot, but the right way to use stat_bin still eludes me.
I've also tried these four approaches:
ggplot(mydataf, aes(y = (..count..)/sum(..count..))) +
scale_y_continuous(formatter = 'percent');
ggplot(mydataf, aes(y = (..count..)/sum(..count..))) +
scale_y_continuous(formatter = 'percent') + geom_bar();
ggplot(mydataf, aes(x = levels(mydataf), y = (..count..)/sum(..count..))) +
scale_y_continuous(formatter = 'percent');
ggplot(mydataf, aes(x = levels(mydataf), y = (..count..)/sum(..count..))) +
scale_y_continuous(formatter = 'percent') + geom_bar();
but all 4 give:
Error: ggplot2 doesn't know how to deal with data of class factor
The same error appears for the simple case of
ggplot (data=mydataf, aes(levels(mydataf))) +
geom_bar()
so it's clearly something about how ggplot interacts with a single vector. I'm scratching my head, googling for that error gives a single result.
",https://stackoverflow.com/questions/3695497/show-percent-instead-of-counts-in-charts-of-categorical-variables,209,294584.0,9.0,,,2010-09-12 15:58:17,2021-02-08 23:47:18,2020-08-02 10:52:08,,,r;ggplot2,wishihadabettername,14911,277434,registered,true,14511974,,CC BY-SA 4.0,2016-09-26 14:41:51,2256,1811,9,2,0,2,true,false,false,true,true,true,67,11,false,0.031,0.0007,5914,2010,9,15,Sunday,true,false,false,false,false,false,false
2894775,Repeat each row of data.frame the number of times specified in a column,"df <- data.frame(var1 = c('a', 'b', 'c'), var2 = c('d', 'e', 'f'),
freq = 1:3)
What is the simplest way to expand each row the first two columns of the data.frame above, so that each row is repeated the number of times specified in the column 'freq'?
In other words, go from this:
df
var1 var2 freq
1 a d 1
2 b e 2
3 c f 3
To this:
df.expanded
var1 var2
1 a d
2 b e
3 b e
4 c f
5 c f
6 c f
",https://stackoverflow.com/questions/2894775/repeat-each-row-of-data-frame-the-number-of-times-specified-in-a-column,209,124339.0,10.0,,,2010-05-24 04:46:11,2022-10-12 05:19:09,2019-11-05 15:20:31,,,r;dataframe;replicate,wkmor1,7496,325913,registered,true,2894825,,CC BY-SA 4.0,,578,485,3,0,0,3,true,false,false,true,true,true,71,13,false,0.08,0.0017,6025,2010,5,4,Monday,false,false,false,false,false,false,false
13701347,Force the origin to start at 0,"How can I set the origin / interception of the y-axis and x-axis in ggplot2?
The line of the x-axis should be exactly at y=Z.
With Z=0 or another given value.
",https://stackoverflow.com/questions/13701347/force-the-origin-to-start-at-0,209,292986.0,4.0,,,2012-12-04 10:58:38,2022-11-26 17:13:27,2018-06-06 21:21:50,,,r;plot;ggplot2;axes,Jonas Stein,7103,1749675,registered,true,13701732,,CC BY-SA 4.0,2018-02-12 20:56:14,209,162,2,0,0,4,true,false,false,true,true,true,30,7,false,0.014,0.0007,5100,2012,12,10,Tuesday,false,false,false,false,false,false,false
9723208,"Aggregate / summarize multiple variables per group (e.g. sum, mean)","From a data frame, is there a easy way to aggregate (sum, mean, max etc) multiple variables simultaneously?
Below are some sample data:
library(lubridate)
days = 365*2
date = seq(as.Date("2000-01-01"), length = days, by = "day")
year = year(date)
month = month(date)
x1 = cumsum(rnorm(days, 0.05))
x2 = cumsum(rnorm(days, 0.05))
df1 = data.frame(date, year, month, x1, x2)
I would like to simultaneously aggregate the x1 and x2 variables from the df2 data frame by year and month. The following code aggregates the x1 variable, but is it also possible to simultaneously aggregate the x2 variable?
### aggregate variables by year month
df2=aggregate(x1 ~ year+month, data=df1, sum, na.rm=TRUE)
head(df2)
",https://stackoverflow.com/questions/9723208/aggregate-summarize-multiple-variables-per-group-e-g-sum-mean,208,236817.0,10.0,,,2012-03-15 15:44:54,2024-07-12 15:13:20,2023-02-23 19:08:34,,,r;dataframe;data.table;aggregate;r-faq,MikeTP,8018,1215379,registered,true,9723446,,CC BY-SA 4.0,2016-07-27 18:39:19,900,727,10,0,0,5,true,false,false,true,true,true,67,10,false,0.042,0.0009,5364,2012,3,15,Thursday,false,false,false,false,false,false,false
62140483,How to interpret dplyr message `summarise()` regrouping output by 'x' (override with `.groups` argument)?,"I started getting a new message (see post title) when running group_by and summarise() after updating to dplyr development version 0.8.99.9003.
Here is an example to recreate the output:
library(tidyverse)
library(hablar)
df <- read_csv(""year, week, rat_house_females, rat_house_males, mouse_wild_females, mouse_wild_males
2018,10,1,1,1,1
2018,10,1,1,1,1
2018,11,2,2,2,2
2018,11,2,2,2,2
2019,10,3,3,3,3
2019,10,3,3,3,3
2019,11,4,4,4,4
2019,11,4,4,4,4"") %>%
convert(chr(year,week)) %>%
mutate(total_rodents = rowSums(select_if(., is.numeric))) %>%
convert(num(year,week)) %>%
group_by(year,week) %>% summarise(average = mean(total_rodents))
The output tibble is correct, but this message appears:
summarise() regrouping output by 'year' (override with .groups argument)
How should this be interpreted? Why does it report regrouping only by 'year' when I grouped by both year and week? Also, what does it mean to override and why would I want to do that?
I don't think the message indicates a problem because it appears throughout the dplyr vignette:
https://cran.r-project.org/web/packages/dplyr/vignettes/programming.html
I believe it is a new message because it has only appeared on very recent SO questions such as How to melt pairwise.wilcox.test output using dplyr? and R Aggregate over multiple columns (neither of which addresses the regrouping/override message).
Thank you!
",https://stackoverflow.com/questions/62140483/how-to-interpret-dplyr-message-summarise-regrouping-output-by-x-override,208,199719.0,6.0,,,2020-06-01 20:26:57,2023-07-25 21:34:36,2020-06-16 01:34:15,,,r;dplyr;summarize,Susie Derkins,2706,6867362,registered,true,62140681,,CC BY-SA 4.0,,1996,1547,3,3,0,3,true,false,false,true,true,true,113,14,true,0.03,0.001,2364,2020,6,20,Monday,false,false,false,false,false,false,false
6364783,Capitalize the first letter of both words in a two word string,"Let's say that I have a two word string and I want to capitalize
both of them.
name <- c(""zip code"", ""state"", ""final count"")
The Hmisc package has a function capitalize which capitalized the first word, but I'm not sure
how to get the second word capitalized. The help page for capitalize doesn't suggest that it can perform that task.
library(Hmisc)
capitalize(name)
# [1] ""Zip code"" ""State"" ""Final count""
I want to get:
c(""Zip Code"", ""State"", ""Final Count"")
What about three-word strings:
name2 <- c(""I like pizza"")
",https://stackoverflow.com/questions/6364783/capitalize-the-first-letter-of-both-words-in-a-two-word-string,207,141651.0,15.0,,,2011-06-15 21:44:43,2024-01-30 17:07:24,2016-10-06 03:11:31,,,r;string;title-case,ATMathew,12986,406278,registered,true,6364905,,CC BY-SA 3.0,,707,544,7,0,0,3,true,false,false,true,true,true,62,12,false,0.106,0.0015,5638,2011,6,21,Wednesday,false,false,false,false,false,false,false
31528981,Select first and last row from grouped data,"Question
Using dplyr, how do I select the top and bottom observations/rows of grouped data in one statement?
Data & Example
Given a data frame:
df <- data.frame(id=c(1,1,1,2,2,2,3,3,3),
stopId=c("a","b","c","a","b","c","a","b","c"),
stopSequence=c(1,2,3,3,1,4,3,1,2))
I can get the top and bottom observations from each group using slice, but using two separate statements:
firstStop <- df %>%
group_by(id) %>%
arrange(stopSequence) %>%
slice(1) %>%
ungroup
lastStop <- df %>%
group_by(id) %>%
arrange(stopSequence) %>%
slice(n()) %>%
ungroup
Can I combine these two statements into one that selects both top and bottom observations?
",https://stackoverflow.com/questions/31528981/select-first-and-last-row-from-grouped-data,207,183811.0,10.0,,,2015-07-21 01:41:30,2023-03-27 16:25:38,2022-01-05 21:34:09,,,r;dplyr,tospig,8487,4002530,registered,true,31529043,,CC BY-SA 4.0,,975,816,4,0,0,2,true,false,false,true,true,true,43,8,false,0.054,0.0011,4141,2015,7,1,Tuesday,false,false,false,false,false,false,false
15282580,How to generate a number of most distinctive colors in R?,"I am plotting a categorical dataset and want to use distinctive colors to represent different categories. Given a number n, how can I get n number of MOST distinctive colors in R? Thanks.
",https://stackoverflow.com/questions/15282580/how-to-generate-a-number-of-most-distinctive-colors-in-r,207,239362.0,11.0,,,2013-03-07 21:59:01,2023-04-28 13:13:07,2019-04-13 23:32:09,,,r;colors;palette;color-palette;colorbrewer,RNA,155579,489564,registered,true,,,CC BY-SA 4.0,,221,188,2,0,0,5,false,false,false,true,true,true,57,11,true,0.046,0.0009,5007,2013,3,21,Thursday,false,false,false,false,false,false,false
4935479,How to combine multiple conditions to subset a data-frame using "OR"?,"I have a data.frame in R. I want to try two different conditions on two different columns, but I want these conditions to be inclusive. Therefore, I would like to use ""OR"" to combine the conditions. I have used the following syntax before with lot of success when I wanted to use the ""AND"" condition.
my.data.frame <- data[(data$V1 > 2) & (data$V2 < 4), ]
But I don't know how to use an 'OR' in the above.
",https://stackoverflow.com/questions/4935479/how-to-combine-multiple-conditions-to-subset-a-data-frame-using-or,207,738863.0,5.0,,,2011-02-08 16:18:31,2022-10-12 14:49:57,2013-04-08 20:19:57,,,r;conditional-statements;dataframe,Sam,8212,402681,registered,true,4935551,,CC BY-SA 3.0,2017-10-18 09:15:13,462,424,1,0,0,3,true,false,false,true,true,true,79,11,true,0.007,0.0003,5765,2011,2,16,Tuesday,false,false,false,false,false,false,false
18337653,Remove 'a' from legend when using aesthetics and geom_text,"How can I can remove the letter 'a' from the legend generated by this code? If I remove the geom_text, then the 'a' letter will not show in the legend. I want to keep geom_text, though.
ggplot(data = iris, aes(x = Sepal.Length, y=Sepal.Width,
shape = Species, colour = Species)) +
geom_point() +
geom_text(aes(label = Species))
",https://stackoverflow.com/questions/18337653/remove-a-from-legend-when-using-aesthetics-and-geom-text,207,83334.0,8.0,,,2013-08-20 14:29:02,2024-02-05 15:40:15,2021-08-07 23:09:34,,,r;ggplot2;legend;aesthetics,user2700207,2123,2700207,registered,true,18338082,,CC BY-SA 4.0,,419,362,3,0,0,4,true,false,false,true,true,true,66,9,false,0.096,0.0025,4841,2013,8,14,Tuesday,false,false,false,false,false,false,false
4241798,How to increase font size in a plot in R?,"I am confused. What is the right way to increase font size of text in the title, labels and other places of a plot?
For example
x <- rnorm(100)
hist(x, xlim=range(x), xlab= ""Variable Label"",
ylab=""density"", main=""Title of plot"", prob=TRUE, ps=30)
The ps argument does not change font size (but it says in R Help for ?par that it is for ""the point size of text (but not symbols)"".
Also is it possible to separate changing the font size from the plotting function such as hist?
",https://stackoverflow.com/questions/4241798/how-to-increase-font-size-in-a-plot-in-r,206,726005.0,9.0,,,2010-11-22 02:37:18,2022-03-30 22:03:24,2017-02-07 02:56:55,,,r;plot,Tim,101336,156458,registered,true,4241814,,CC BY-SA 3.0,,582,491,4,0,0,2,true,false,false,true,true,true,41,10,true,0.012,0.0003,5843,2010,11,2,Monday,false,false,false,false,false,false,false
3171426,Select rows from one data.frame that are not present in a second data.frame,"I have two data.frames:
a1 <- data.frame(a = 1:5, b=letters[1:5])
a2 <- data.frame(a = 1:3, b=letters[1:3])
I want to find the rows a1 have that a2 doesn't.
Is there a built in function for this type of operation?
(p.s: I did write a solution for it, I am simply curious if someone already made a more crafted code)
Here is my solution:
a1 <- data.frame(a = 1:5, b=letters[1:5])
a2 <- data.frame(a = 1:3, b=letters[1:3])
rows.in.a1.that.are.not.in.a2 <- function(a1,a2)
{
a1.vec <- apply(a1, 1, paste, collapse = "")
a2.vec <- apply(a2, 1, paste, collapse = "")
a1.without.a2.rows <- a1[!a1.vec %in% a2.vec,]
return(a1.without.a2.rows)
}
rows.in.a1.that.are.not.in.a2(a1,a2)
",https://stackoverflow.com/questions/3171426/select-rows-from-one-data-frame-that-are-not-present-in-a-second-data-frame,205,444263.0,14.0,,,2010-07-03 12:04:25,2023-01-16 18:54:26,2023-01-16 18:54:26,,,r;dataframe;merge;compare;set-difference,Tal Galili,25606,256662,registered,true,3172398,,CC BY-SA 4.0,,822,739,2,0,0,5,true,false,false,true,true,true,75,13,false,0.032,0.0005,5985,2010,7,12,Saturday,true,false,false,false,false,false,false
20923209,Problems installing the devtools package,"I wish to use the devtools package. I've run the following commands:
> install.packages(""devtools"", dependencies = TRUE)
....
> library(devtools)
Error in library(devtools) : there is no package called ‘devtools’
What am I doing wrong?
Edit: Here are the results of re-running the install.packages command after restarting the session.
> install.packages(""devtools"", dependencies = TRUE)
Installing package into ‘/home/evanaad/R/x86_64-pc-linux-gnu-library/3.0’
(as ‘lib’ is unspecified)
--- Please select a CRAN mirror for use in this session ---
Warning: dependencies ‘roxygen2’, ‘BiocInstaller’, ‘rstudio’ are not available
also installing the dependencies ‘httr’, ‘RCurl’
trying URL 'http://cran.at.r-project.org/src/contrib/httr_0.2.tar.gz'
Content type 'application/x-gzip' length 50183 bytes (49 Kb)
opened URL
==================================================
downloaded 49 Kb
trying URL 'http://cran.at.r-project.org/src/contrib/RCurl_1.95-4.1.tar.gz'
Content type 'application/x-gzip' length 870915 bytes (850 Kb)
opened URL
==================================================
downloaded 850 Kb
trying URL 'http://cran.at.r-project.org/src/contrib/devtools_1.4.1.tar.gz'
Content type 'application/x-gzip' length 105214 bytes (102 Kb)
opened URL
==================================================
downloaded 102 Kb
* installing *source* package ‘RCurl’ ...
** package ‘RCurl’ successfully unpacked and MD5 sums checked
checking for curl-config... no
Cannot find curl-config
ERROR: configuration failed for package ‘RCurl’
* removing ‘/home/evanaad/R/x86_64-pc-linux-gnu-library/3.0/RCurl’
ERROR: dependency ‘RCurl’ is not available for package ‘httr’
* removing ‘/home/evanaad/R/x86_64-pc-linux-gnu-library/3.0/httr’
ERROR: dependencies ‘httr’, ‘RCurl’ are not available for package ‘devtools’
* removing ‘/home/evanaad/R/x86_64-pc-linux-gnu-library/3.0/devtools’
The downloaded source packages are in
‘/tmp/RtmptvmTrA/downloaded_packages’
Warning messages:
1: In install.packages(""devtools"", dependencies = TRUE) :
installation of package ‘RCurl’ had non-zero exit status
2: In install.packages(""devtools"", dependencies = TRUE) :
installation of package ‘httr’ had non-zero exit status
3: In install.packages(""devtools"", dependencies = TRUE) :
installation of package ‘devtools’ had non-zero exit status
",https://stackoverflow.com/questions/20923209/problems-installing-the-devtools-package,205,240998.0,19.0,,,2014-01-04 16:00:14,2024-06-04 17:00:19,2014-01-04 16:38:26,,,r;package;devtools,Evan Aad,6103,1818935,registered,true,20924082,,CC BY-SA 3.0,2020-03-15 05:32:27,2439,2344,4,0,0,3,true,false,false,true,true,true,40,5,false,0.079,0.0009,4704,2014,1,16,Saturday,true,false,false,false,false,false,false
2190756,How to count TRUE values in a logical vector,"In R, what is the most efficient/idiomatic way to count the number of TRUE values in a logical vector? I can think of two ways:
z <- sample(c(TRUE, FALSE), 1000, rep = TRUE)
sum(z)
# [1] 498
table(z)[""TRUE""]
# TRUE
# 498
Which do you prefer? Is there anything even better?
",https://stackoverflow.com/questions/2190756/how-to-count-true-values-in-a-logical-vector,205,384587.0,9.0,,,2010-02-03 09:03:38,2024-09-24 17:36:41,2016-02-26 21:15:13,,,r,Jyotirmoy Bhattacharya,9647,212593,registered,true,2191824,,CC BY-SA 3.0,,334,283,2,0,0,1,true,false,false,true,true,true,44,9,false,0.023,0.0005,6135,2010,2,9,Wednesday,false,false,false,false,false,false,false
23635662,Editing legend (text) labels in ggplot,"I have spent hours looking in the documentation and on StackOverflow, but no solution seems to solve my problem. When using ggplot I can't get the right text in the legend, even though it's in my dataframe. I have tried scale_colour_manual, scale_fill_manual with different values for labels= such as c("T999", "T888")", "cols".
Here is my code:
T999 <- runif(10, 100, 200)
T888 <- runif(10, 200, 300)
TY <- runif(10, 20, 30)
df <- data.frame(T999, T888, TY)
ggplot(data = df, aes(x=T999, y=TY, pointtype="T999")) +
geom_point(size = 15, colour = "darkblue") +
geom_point(data = df, aes(x=T888, y=TY), colour = 'red', size = 10 ) +
theme(axis.text.x = element_text(size = 20), axis.title.x =element_text(size = 20), axis.text.y = element_text(size = 20)) +
xlab("Txxx") + ylab("TY [°C]") + labs(title="temperatures", size = 15) +
scale_colour_manual(labels = c("T999", "T888"), values = c("darkblue", "red")) + theme(legend.position="topright")
Here is the graphical output of the above code:
Help would be very appreciated!
",https://stackoverflow.com/questions/23635662/editing-legend-text-labels-in-ggplot,204,773450.0,2.0,,,2014-05-13 15:36:37,2023-11-22 06:39:28,2023-04-26 16:26:45,,,r;text;ggplot2;label,user3633161,2143,3633161,registered,true,23637666,,CC BY-SA 4.0,,1491,1221,6,1,1,4,true,false,false,true,true,true,38,6,false,0.003,0.0003,4575,2014,5,15,Tuesday,false,false,false,false,false,false,false
5677885,Ignore outliers in ggplot2 boxplot,"How would I ignore outliers in ggplot2 boxplot? I don't simply want them to disappear (i.e. outlier.size=0), but I want them to be ignored such that the y axis scales to show 1st/3rd percentile. My outliers are causing the ""box"" to shrink so small its practically a line. Are there some techniques to deal with this?
Edit
Here's an example:
y = c(.01, .02, .03, .04, .05, .06, .07, .08, .09, .5, -.6)
qplot(1, y, geom=""boxplot"")
",https://stackoverflow.com/questions/5677885/ignore-outliers-in-ggplot2-boxplot,203,302156.0,9.0,,,2011-04-15 14:00:58,2024-02-27 10:45:41,2016-03-26 01:41:48,,,r;ggplot2,Suraj,36954,356790,registered,true,5678146,,CC BY-SA 3.0,,640,437,1,1,1,2,true,false,false,true,true,true,34,5,false,0.03,0.0007,5699,2011,4,14,Friday,false,false,false,false,false,false,false
11761992,How do I clear only a few specific objects from the workspace?,"I would like to remove some data from the workspace. I know the ""Clear All"" button will remove all data. However, I would like to remove just certain data.
For example, I have these data frames in the data section:
data
data_1
data_2
data_3
I would like to remove data_1, data_2 and data_3, while keeping data.
I tried data_1 <- data_2 <- data_3 <- NULL, which does remove the data (I think), but still keeps it in the workspace area, so it is not fully what I would like to do.
",https://stackoverflow.com/questions/11761992/how-do-i-clear-only-a-few-specific-objects-from-the-workspace,203,582371.0,13.0,,,2012-08-01 14:58:54,2022-03-17 16:08:13,2019-10-16 21:17:47,,,r,Ford,2569,1555702,registered,true,11762024,,CC BY-SA 4.0,,610,493,6,0,0,1,true,false,false,true,true,true,62,12,true,0.022,0.0003,5225,2012,8,14,Wednesday,false,false,false,false,false,false,false
1395270,Determining memory usage of objects?,"I'd like to work out how much RAM is being used by each of my objects inside my current workspace. Is there an easy way to do this?
",https://stackoverflow.com/questions/1395270/determining-memory-usage-of-objects,201,115929.0,9.0,,,2009-09-08 17:36:12,2025-03-28 07:34:47,2014-05-17 00:20:33,,,memory;r,Josh Reich,6637,136862,registered,true,,,CC BY-SA 3.0,,139,132,0,0,0,2,false,false,false,true,true,true,36,5,true,0.078,0.0017,6283,2009,9,17,Tuesday,false,false,false,false,false,false,false
7484325,Prevent row names to be written to file when using write.csv,"Commands:
t <- data.frame(v = 5:1, v2 = 9:5)
write.csv(t, ""t.csv"")
Resulting file:
# """",""v"",""v2""
# ""1"",5,9
# ""2"",4,8
# ""3"",3,7
# ""4"",2,6
# ""5"",1,5
How do I prevent first column with row index from being written to the file?
",https://stackoverflow.com/questions/7484325/prevent-row-names-to-be-written-to-file-when-using-write-csv,201,244294.0,2.0,,,2011-09-20 11:24:23,2019-03-10 07:36:58,2016-02-27 17:10:33,,,r;csv,watbywbarif,7217,378783,registered,true,7484341,,CC BY-SA 3.0,,302,233,2,0,0,2,true,false,false,true,true,true,60,11,false,0.008,0.0008,5541,2011,9,11,Tuesday,false,false,false,false,false,false,false
4357101,promise already under evaluation: recursive default argument reference or earlier problems?,"Here is my R code. The functions are defined as:
f <- function(x, T) {
10 * sin(0.3 * x) * sin(1.3 * x ^ 2) + 0.001 * x ^ 3 + 0.2 * x + 80
}
g <- function(x, T, f=f) {
exp(-f(x) / T)
}
test <- function(g=g, T=1) {
g(1, T)
}
The running error is:
> test()
Error in test() :
promise already under evaluation: recursive default argument reference or earlier problems?
If I substitute the definition of f in that of g, then the error goes away.
I was wondering what the error was? How to correct it if don't substitute the definition of f in that of g? Thanks!
Update:
Thanks! Two questions:
(1) if function test further takes an argument for f, will you add something like test <- function(g.=g, T=1, f..=f){ g.(1,T, f.=f..) } ? In cases with more recursions, is it a good and safe practice adding more .?
(2) if f is a non-function argument, for example g <- function(x, T, f=f){ exp(-f*x/T) } and test <- function(g.=g, T=1, f=f){ g.(1,T, f=f.) }, will using the same name for both formal and actual non-functional arguments a good and safe practice or it may cause some potential trouble?
",https://stackoverflow.com/questions/4357101/promise-already-under-evaluation-recursive-default-argument-reference-or-earlie,201,92977.0,4.0,,,2010-12-05 02:53:51,2022-03-06 21:18:07,2017-01-06 01:42:26,,,r,Tim,101336,156458,registered,true,4357159,,CC BY-SA 3.0,,1402,1139,11,0,0,1,true,false,false,true,true,true,91,11,true,0.043,0.0022,5830,2010,12,2,Sunday,true,false,false,false,false,false,false
15633714,Adding a regression line on a ggplot,"I'm trying hard to add a regression line on a ggplot. I first tried with abline but I didn't manage to make it work. Then I tried this...
data = data.frame(x.plot=rep(seq(1,5),10),y.plot=rnorm(50))
ggplot(data,aes(x.plot,y.plot))+stat_summary(fun.data=mean_cl_normal) +
geom_smooth(method='lm',formula=data$y.plot~data$x.plot)
But it is not working either.
",https://stackoverflow.com/questions/15633714/adding-a-regression-line-on-a-ggplot,200,696509.0,7.0,,,2013-03-26 09:40:05,2024-05-16 19:54:29,2015-07-10 08:23:07,,,r;ggplot2;regression;linear-regression,Remi.b,18399,2051137,registered,true,15654715,,CC BY-SA 3.0,,401,363,1,0,0,4,true,false,false,true,true,true,36,7,false,0.01,0.0003,4988,2013,3,9,Tuesday,false,false,false,false,false,false,false
2453326,Fastest way to find second (third...) highest/lowest value in vector or column,"R offers max and min, but I do not see a really fast way to find another value in the order, apart from sorting the whole vector and then picking a value x from this vector.
Is there a faster way to get the second highest value, for example?
",https://stackoverflow.com/questions/2453326/fastest-way-to-find-second-third-highest-lowest-value-in-vector-or-column,200,273070.0,16.0,,,2010-03-16 09:54:16,2025-09-30 17:45:46,2020-07-22 15:16:51,,,r;vector,jorgusch,2241,235984,registered,true,53144760,,CC BY-SA 4.0,2018-03-20 05:43:27,256,242,0,0,0,2,true,false,false,true,true,true,78,12,false,0.059,0.0007,6094,2010,3,9,Tuesday,false,false,false,false,false,false,false
2628621,How do you use "<<-" (scoping assignment) in R?,"I just finished reading about scoping in the R intro, and am very curious about the <<- assignment.
The manual showed one (very interesting) example for <<-, which I feel I understood. What I am still missing is the context of when this can be useful.
So what I would love to read from you are examples (or links to examples) on when the use of <<- can be interesting/useful. What might be the dangers of using it (it looks easy to loose track of), and any tips you might feel like sharing.
",https://stackoverflow.com/questions/2628621/how-do-you-use-scoping-assignment-in-r,200,98561.0,7.0,,,2010-04-13 10:04:46,2024-12-16 09:07:50,2016-03-15 14:43:59,,,r;scoping;lexical-scope;r-faq,Tal Galili,25606,256662,registered,true,2630222,,CC BY-SA 3.0,2024-12-16 09:08:16,660,512,3,1,0,4,true,false,false,true,true,true,63,9,true,0.071,0.002,6066,2010,4,10,Tuesday,false,false,false,false,false,false,false
55201226,session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium,"I'm trying to run RSelenium using the rsDriver function, but when I run
rD <- rsDriver()
I get a message telling me I need a newer version of Chrome:
> rD <- rsDriver()
checking Selenium Server versions:
BEGIN: PREDOWNLOAD
BEGIN: DOWNLOAD
BEGIN: POSTDOWNLOAD
checking chromedriver versions:
BEGIN: PREDOWNLOAD
BEGIN: DOWNLOAD
BEGIN: POSTDOWNLOAD
checking geckodriver versions:
BEGIN: PREDOWNLOAD
BEGIN: DOWNLOAD
BEGIN: POSTDOWNLOAD
checking phantomjs versions:
BEGIN: PREDOWNLOAD
BEGIN: DOWNLOAD
BEGIN: POSTDOWNLOAD
[1] ""Connecting to remote server""
Selenium message:session not created: This version of ChromeDriver only supports Chrome version 74
(Driver info: chromedriver=74.0.3729.6 (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}),platform=Mac OS X 10.14.3 x86_64)
Could not open chrome browser.
Client error message:
Summary: SessionNotCreatedException
Detail: A new session could not be created.
Further Details: run errorDetails method
Check server log for further details.
The error message appears to say that I need Chrome version 74.0.3729.6, but when I look in Chrome's settings, it tells me that I'm running the latest stable version (73.0.3683.75). Upon further googling, 74.0.3729.6 is a pre-release dev version of Chrome: do I need to install this in order to use ChromeDriver with RSelenium?
I'm not wedded to the idea of using Chrome, but I haven't been able to get rsDriver to use Firefox: when I specify browser = ""firefox"", rsDriver gives me the same error message about ChromeDriver not supporting my version of Chrome.
My session info is:
R version 3.5.2 (2018-12-20)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS Mojave 10.14.3
Matrix products: default
BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libRlapack.dylib
locale:
[1] en_GB.UTF-8/en_GB.UTF-8/en_GB.UTF-8/C/en_GB.UTF-8/en_GB.UTF-8
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] wdman_0.2.4 forcats_0.3.0 stringr_1.3.1 dplyr_0.7.8 purrr_0.2.5 readr_1.3.1 tidyr_0.8.2
[8] tibble_2.0.1 ggplot2_3.1.0 tidyverse_1.2.1 rvest_0.3.2 xml2_1.2.0 RSelenium_1.7.5
",https://stackoverflow.com/questions/55201226/session-not-created-this-version-of-chromedriver-only-supports-chrome-version-7,200,447922.0,24.0,,,2019-03-16 20:31:14,2022-02-20 13:48:33,2019-03-16 20:49:00,,,r;selenium;google-chrome;selenium-chromedriver;rselenium,Matthew Law,2401,6757085,registered,true,55212731,,CC BY-SA 4.0,2019-07-29 01:20:34,2490,2388,4,0,0,5,true,false,false,true,true,true,127,18,false,0.054,0.0004,2807,2019,3,20,Saturday,true,false,false,false,false,false,false
39041115,Fixing a multiple warning "unknown column","I have a persistent multiple warning of ""unknown column"" for all types of commands (e.g., str(x) to installing updates on packages), and not sure how to debug this or fix it.
The warning ""unknown column"" is clearly related to a variable in a tbl_df that I renamed, but the warning comes up in all kinds of commands seemingly unrelated to the tbl_df (e.g., installing updates on a package, str(x) where x is simply a character vector).
",https://stackoverflow.com/questions/39041115/fixing-a-multiple-warning-unknown-column,200,122154.0,10.0,,,2016-08-19 14:07:09,2022-08-20 11:50:01,,,,r;dplyr,ssp3nc3r,3842,6311848,registered,true,,,CC BY-SA 3.0,2019-06-15 18:21:47,452,438,0,0,0,2,false,false,false,true,true,false,52,6,false,0.082,0.0016,3746,2016,8,14,Friday,false,false,false,false,false,false,false
20407773,increase legend font size ggplot2,"Is there a way to increase the font size in ggplot2? I think I need to specify something like legend.key.width = unit(2, ""line"") in the theme function, but that is used to adjust the keys in legends, not the font sizes. Thanks!
",https://stackoverflow.com/questions/20407773/increase-legend-font-size-ggplot2,199,341461.0,4.0,,,2013-12-05 18:26:28,2022-09-12 13:05:37,,,,r;ggplot2,alittleboy,11046,1510531,registered,true,20407883,,CC BY-SA 3.0,,274,228,3,0,0,2,true,false,false,true,true,false,33,5,false,0.012,0.0006,4734,2013,12,18,Thursday,false,false,false,false,false,false,false
22235809,Append value to empty vector in R?,"I'm trying to learn R and I can't figure out how to append to a list.
If this were Python I would . . .
#Python
vector = []
values = ['a','b','c','d','e','f','g']
for i in range(0,len(values)):
vector.append(values[i])
How do you do this in R?
#R Programming
> vector = c()
> values = c('a','b','c','d','e','f','g')
> for (i in 1:length(values))
+ #append value[i] to empty vector
",https://stackoverflow.com/questions/22235809/append-value-to-empty-vector-in-r,199,688102.0,9.0,,,2014-03-06 20:58:19,2022-12-24 15:56:46,2015-06-20 03:46:07,,,r;list;vector;append,O.rka,31085,678572,registered,true,22235924,,CC BY-SA 3.0,,470,401,2,0,0,4,true,false,false,true,true,true,34,7,true,0.013,0.0003,4643,2014,3,20,Thursday,false,false,false,false,false,false,false
8508482,What does .SD stand for in data.table in R,".SD looks useful but I do not really know what I am doing with it. What does it stand for? Why is there a preceding period (full stop). What is happening when I use it?
I read:
.SD is a data.table containing the subset of x's data for each group, excluding the group column(s). It can be used when grouping by i, when grouping by by, keyed by, and _ad hoc_ by
Does that mean that the daughter data.tables is held in memory for the next operation?
",https://stackoverflow.com/questions/8508482/what-does-sd-stand-for-in-data-table-in-r,198,83187.0,3.0,,,2011-12-14 16:59:16,2020-10-19 03:39:12,2017-06-19 14:41:15,,,r;data.table,Farrel,10484,168139,registered,true,8509301,,CC BY-SA 3.0,,597,450,9,0,0,2,true,false,false,true,true,true,42,9,false,0.036,0.0024,5456,2011,12,16,Wednesday,false,false,false,false,false,false,false
5171593,R memory management / cannot allocate vector of size n Mb,"I am running into issues trying to use large objects in R. For example:
> memory.limit(4000)
> a = matrix(NA, 1500000, 60)
> a = matrix(NA, 2500000, 60)
> a = matrix(NA, 3500000, 60)
Error: cannot allocate vector of size 801.1 Mb
> a = matrix(NA, 2500000, 60)
Error: cannot allocate vector of size 572.2 Mb # Can't go smaller anymore
> rm(list=ls(all=TRUE))
> a = matrix(NA, 3500000, 60) # Now it works
> b = matrix(NA, 3500000, 60)
Error: cannot allocate vector of size 801.1 Mb # But that is all there is room for
I understand that this is related to the difficulty of obtaining contiguous blocks of memory (from here):
Error messages beginning cannot
allocate vector of size indicate a
failure to obtain memory, either
because the size exceeded the
address-space limit for a process or,
more likely, because the system was
unable to provide the memory. Note
that on a 32-bit build there may well
be enough free memory available, but
not a large enough contiguous block of
address space into which to map it.
How can I get around this? My main difficulty is that I get to a certain point in my script and R can't allocate 200-300 Mb for an object... I can't really pre-allocate the block because I need the memory for other processing. This happens even when I dilligently remove unneeded objects.
EDIT: Yes, sorry: Windows XP SP3, 4Gb RAM, R 2.12.0:
> sessionInfo()
R version 2.12.0 (2010-10-15)
Platform: i386-pc-mingw32/i386 (32-bit)
locale:
[1] LC_COLLATE=English_Caribbean.1252 LC_CTYPE=English_Caribbean.1252
[3] LC_MONETARY=English_Caribbean.1252 LC_NUMERIC=C
[5] LC_TIME=English_Caribbean.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
",https://stackoverflow.com/questions/5171593/r-memory-management-cannot-allocate-vector-of-size-n-mb,198,697811.0,9.0,,,2011-03-02 18:13:01,2021-03-14 02:36:45,2018-07-06 14:13:07,,,r;matrix;vector;memory-management;r-faq,user483620,,,does_not_exist,true,5174383,,CC BY-SA 4.0,2018-01-08 11:14:56,2003,1788,2,1,0,5,true,false,false,true,false,true,57,11,false,0.013,0.0003,5743,2011,3,18,Wednesday,false,false,false,false,false,false,false
7355187,Error in if/while (condition) {: missing Value where TRUE/FALSE needed,"I received this error message:
Error in if (condition) { : missing value where TRUE/FALSE needed
or
Error in while (condition) { : missing value where TRUE/FALSE needed
What does it mean, and how do I prevent it?
",https://stackoverflow.com/questions/7355187/error-in-if-while-condition-missing-value-where-true-false-needed,198,671883.0,4.0,,,2011-09-08 22:17:56,2022-04-20 11:26:54,2014-12-26 16:32:25,,,r;r-faq,Concerned_Citizen,6913,633426,registered,true,7355280,,CC BY-SA 3.0,2017-01-19 08:31:52,288,219,2,0,0,2,true,false,false,true,true,true,70,10,false,0.006,0.0003,5553,2011,9,22,Thursday,false,false,false,false,false,false,false
9251326,Convert data.frame column format from character to factor,"I would like to change the format (class) of some columns of my data.frame object (mydf) from charactor to factor.
I don't want to do this when I'm reading the text file by read.table() function.
Any help would be appreciated.
",https://stackoverflow.com/questions/9251326/convert-data-frame-column-format-from-character-to-factor,197,535708.0,8.0,,,2012-02-12 18:17:07,2022-01-15 01:37:16,2018-12-06 08:37:47,,,r;dataframe;character;r-faq,Rasoul,3897,1023798,registered,true,9251420,,CC BY-SA 4.0,,294,229,2,0,0,4,true,false,false,true,true,true,57,8,false,0.015,0.0004,5396,2012,2,18,Sunday,true,false,false,false,false,false,false
15059076,Call apply-like function on each row of dataframe with multiple arguments from each row,"I have a dataframe with multiple columns. For each row in the dataframe, I want to call a function on the row, and the input of the function is using multiple columns from that row. For example, let's say I have this data and this testFunc which accepts two args:
> df <- data.frame(x=c(1,2), y=c(3,4), z=c(5,6))
> df
x y z
1 1 3 5
2 2 4 6
> testFunc <- function(a, b) a + b
Let's say I want to apply this testFunc to columns x and z. So, for row 1 I want 1+5, and for row 2 I want 2 + 6. Is there a way to do this without writing a for loop, maybe with the apply function family?
I tried this:
> df[,c('x','z')]
x z
1 1 5
2 2 6
> lapply(df[,c('x','z')], testFunc)
Error in a + b : 'b' is missing
But got error, any ideas?
EDIT: the actual function I want to call is not a simple sum, but it is power.t.test. I used a+b just for example purposes. The end goal is to be able to do something like this (written in pseudocode):
df = data.frame(
delta=c(delta_values),
power=c(power_values),
sig.level=c(sig.level_values)
)
lapply(df, power.t.test(delta_from_each_row_of_df,
power_from_each_row_of_df,
sig.level_from_each_row_of_df
))
where the result is a vector of outputs for power.t.test for each row of df.
",https://stackoverflow.com/questions/15059076/call-apply-like-function-on-each-row-of-dataframe-with-multiple-arguments-from-e,197,325585.0,12.0,,,2013-02-25 02:09:31,2019-02-08 20:42:47,2016-01-29 10:15:45,,,r;dataframe,vasek1,14207,1058521,registered,true,15059131,,CC BY-SA 3.0,,1447,1316,3,0,0,2,true,false,false,true,true,true,87,14,false,0.037,0.0006,5017,2013,2,2,Monday,false,false,false,false,false,false,false
7014387,What's the difference between `1L` and `1`?,"I often seen the symbol 1L (or 2L, 3L, etc) appear in R code. Whats the difference between 1L and 1? 1==1L evaluates to TRUE. Why is 1L used in R code?
",https://stackoverflow.com/questions/7014387/whats-the-difference-between-1l-and-1,197,113113.0,4.0,,,2011-08-10 16:30:45,2017-12-29 23:14:59,,,,r;types,Zach,30561,345660,registered,true,7014671,,CC BY-SA 3.0,,267,156,8,0,0,2,true,false,false,true,true,false,47,7,true,0.035,0.0017,5582,2011,8,16,Wednesday,false,false,false,false,false,false,false
14794599,How to change line width in ggplot?,"Datalink:
the data used
My code:
ccfsisims <- read.csv(file = ""F:/Purdue University/RA_Position/PhD_ResearchandDissert/PhD_Draft/GTAP-CGE/GTAP_NewAggDatabase/NewFiles/GTAP_ConsIndex.csv"", header=TRUE, sep="","", na.string=""NA"", dec=""."", strip.white=TRUE)
ccfsirsts <- as.data.frame(ccfsisims)
ccfsirsts[6:24] <- sapply(ccfsirsts[6:24],as.numeric)
ccfsirsts <- droplevels(ccfsirsts)
ccfsirsts <- transform(ccfsirsts,sres=factor(sres,levels=unique(sres)))
library(ggplot2)
#------------------------------------------------------------------------------------------
#### Plot of food security index for Morocco and Turkey by sector
#------------------------------------------------------------------------------------------
#_Code_Begin...
datamortur <- melt(ccfsirsts[ccfsirsts$region %in% c(""TUR"",""MAR""), ]) # Selecting regions of interest
datamortur1 <- datamortur[datamortur$variable %in% c(""pFSI2""), ] # Selecting the food security index of interest
datamortur2 <- datamortur1[datamortur1$sector %in% c(""wht"",""gro"",""VegtFrut"",""osd"",""OthCrop"",""VegtOil"",""XPrFood""), ] # Selecting food sectors of interest
datamortur3 <- subset(datamortur2, tradlib !=""BASEDATA"") # Eliminating the ""BASEDATA"" scenario results
allfsi.f <- datamortur3
fsi.wht <- allfsi.f[allfsi.f$sector %in% c(""wht""), ]
Figure29 <- ggplot(data=fsi.wht, aes(x=factor(sres),y=value,colour=factor(tradlib)))
Figure29 + geom_line(aes(group=factor(tradlib),size=2)) + facet_grid(regionsFull~., scales=""free_y"", labeller=reg_labeller) + scale_colour_brewer(type = ""div"") +
theme(axis.text.x = element_text(colour = 'black', angle = 90, size = 13, hjust = 0.5, vjust = 0.5),axis.title.x=element_blank()) +
ylab(""FSI (%Change)"") + theme(axis.text.y = element_text(colour = 'black', size = 12), axis.title.y = element_text(size = 12, hjust = 0.5, vjust = 0.2)) +
theme(strip.text.y = element_text(size = 11, hjust = 0.5, vjust = 0.5, face = 'bold'))
My result:
Newresult with aes(size=2):
![]()
My question:
Is there a way to control for line width more precisely to avoid the result in the second plot? I particularly find it document-unfriendly, and more so for publishing purposes to include the plot with the newly defined line width.
best,
ismail
",https://stackoverflow.com/questions/14794599/how-to-change-line-width-in-ggplot,196,638286.0,7.0,,,2013-02-10 04:07:03,2024-02-29 22:03:32,2018-03-07 07:38:58,,,r;ggplot2;line-plot,iouraich,3056,1978243,registered,true,14804381,,CC BY-SA 3.0,,2527,2257,1,1,2,3,true,false,false,true,true,true,35,7,true,0.011,0.0003,5032,2013,2,4,Sunday,true,false,false,false,false,false,false
1686569,Filter data.frame rows by a logical condition,"I want to filter rows from a data.frame based on a logical condition. Let's suppose that I have data frame like
expr_value cell_type
1 5.345618 bj fibroblast
2 5.195871 bj fibroblast
3 5.247274 bj fibroblast
4 5.929771 hesc
5 5.873096 hesc
6 5.665857 hesc
7 6.791656 hips
8 7.133673 hips
9 7.574058 hips
10 7.208041 hips
11 7.402100 hips
12 7.167792 hips
13 7.156971 hips
14 7.197543 hips
15 7.035404 hips
16 7.269474 hips
17 6.715059 hips
18 7.434339 hips
19 6.997586 hips
20 7.619770 hips
21 7.490749 hips
What I want to is to get a new data frame which looks the same but only has the data for one cell_type. E.g. subset / select rows which contains the cell type ""hesc"":
expr_value cell_type
1 5.929771 hesc
2 5.873096 hesc
3 5.665857 hesc
Or either cell type ""bj fibroblast"" or ""hesc"":
expr_value cell_type
1 5.345618 bj fibroblast
2 5.195871 bj fibroblast
3 5.247274 bj fibroblast
4 5.929771 hesc
5 5.873096 hesc
6 5.665857 hesc
Is there any easy way to do this?
I've tried:
expr[expr[2] == 'hesc']
# [1] ""5.929771"" ""5.873096"" ""5.665857"" ""hesc"" ""hesc"" ""hesc""
if the original data frame is called ""expr"", but it gives the results in wrong format as you can see.
",https://stackoverflow.com/questions/1686569/filter-data-frame-rows-by-a-logical-condition,195,422882.0,9.0,,,2009-11-06 09:58:58,2020-06-29 23:22:05,2020-06-29 23:22:05,,,r;dataframe;subset;r-faq,lhahne,6059,101419,registered,true,1686614,,CC BY-SA 4.0,,1658,1507,5,0,0,4,true,false,false,true,true,true,45,7,false,0.021,0.0005,6224,2009,11,9,Friday,false,false,false,false,false,false,false
21644848,Summarizing multiple columns with dplyr?,"I'm struggling a bit with the dplyr-syntax. I have a data frame with different variables and one grouping variable. Now I want to calculate the mean for each column within each group, using dplyr in R.
df <- data.frame(
a = sample(1:5, n, replace = TRUE),
b = sample(1:5, n, replace = TRUE),
c = sample(1:5, n, replace = TRUE),
d = sample(1:5, n, replace = TRUE),
grp = sample(1:3, n, replace = TRUE)
)
df %>% group_by(grp) %>% summarise(mean(a))
This gives me the mean for column ""a"" for each group indicated by ""grp"".
My question is: is it possible to get the means for each column within each group at once? Or do I have to repeat df %>% group_by(grp) %>% summarise(mean(a)) for each column?
What I would like to have is something like
df %>% group_by(grp) %>% summarise(mean(a:d)) # ""mean(a:d)"" does not work
",https://stackoverflow.com/questions/21644848/summarizing-multiple-columns-with-dplyr,195,323631.0,5.0,,,2014-02-08 10:27:10,2023-10-20 03:28:28,2018-02-12 03:03:39,2017-11-06 12:22:30,Duplicate,r;dplyr;aggregate,Daniel,8000,2094622,registered,true,25839767,,,,954,865,3,0,0,3,true,true,false,true,true,true,40,5,true,0.015,0.0006,4669,2014,2,10,Saturday,true,false,false,false,false,false,false
4215154,Count number of occurences for each unique value,"Let's say I have:
v = rep(c(1,2, 2, 2), 25)
Now, I want to count the number of times each unique value appears. unique(v) returns what the unique values are, but not how many they are.
> unique(v)
[1] 1 2
I want something that gives me
length(v[v==1])
[1] 25
length(v[v==2])
[1] 75
but as a more general one-liner :) Something close (but not quite) like this:
#<doesn't work right> length(v[v==unique(v)])
",https://stackoverflow.com/questions/4215154/count-number-of-occurences-for-each-unique-value,194,589748.0,15.0,,,2010-11-18 13:18:48,2024-08-11 12:21:22,2020-06-17 10:40:03,,,r;count;unique,gakera,3707,377562,registered,true,4215196,,CC BY-SA 4.0,2018-01-04 08:08:33,565,428,5,0,0,3,true,false,false,true,true,true,48,8,false,0.025,0.0003,5847,2010,11,13,Thursday,false,false,false,false,false,false,false
13672720,R command for setting working directory to source file location in Rstudio,"I am working out some tutorials in R. Each R code is contained in a specific folder. There are data files and other files in there. I want to open the .r file and source it such that I do not have to change the working directory in Rstudio as shown below:
![]()
Is there a way to specify my working directory automatically in R.
",https://stackoverflow.com/questions/13672720/r-command-for-setting-working-directory-to-source-file-location-in-rstudio,194,247171.0,17.0,,,2012-12-02 19:10:27,2023-08-27 17:59:20,2018-05-10 20:53:36,,,r;automation;working-directory,Stat-R,5338,1247080,registered,true,35842119,,CC BY-SA 4.0,,438,326,1,0,1,3,true,false,false,true,true,true,74,12,false,0.069,0.0008,5102,2012,12,19,Sunday,true,false,false,false,false,false,false
1174799,"How to make execution pause, sleep, wait for X seconds in R?","How do you pause an R script for a specified number of seconds or miliseconds? In many languages, there is a sleep function, but ?sleep references a data set. And ?pause and ?wait don't exist.
The intended purpose is for self-timed animations. The desired solution works without asking for user input.
",https://stackoverflow.com/questions/1174799/how-to-make-execution-pause-sleep-wait-for-x-seconds-in-r,194,172758.0,3.0,,,2009-07-23 22:17:24,2022-11-21 22:08:00,2014-01-17 15:03:00,,,r;animation;statistics,Dan Goldstein,25069,23929,registered,true,1174826,,CC BY-SA 3.0,,369,303,4,0,0,3,true,false,false,true,true,true,60,12,true,0.017,0.0011,6330,2009,7,22,Thursday,false,false,false,false,false,false,false
6528180,"ggplot2 plot without axes, legends, etc","I want to use bioconductor's hexbin (which I can do) to generate a plot that fills the entire (png) display region - no axes, no labels, no background, no nuthin'.
",https://stackoverflow.com/questions/6528180/ggplot2-plot-without-axes-legends-etc,193,251327.0,9.0,,,2011-06-29 22:49:46,2023-06-29 15:22:16,2017-02-09 23:16:19,,,r;ggplot2,user1320487,2169,1320487,registered,true,,,CC BY-SA 3.0,,171,164,0,0,0,2,false,false,false,true,true,true,39,6,false,0.036,0.0008,5624,2011,6,22,Wednesday,false,false,false,false,false,false,false
2617600,Importing data from a JSON file into R,"Is there a way to import data from a JSON file into R? More specifically, the file is an array of JSON objects with string fields, objects, and arrays. The RJSON Package isn't very clear on how to deal with this http://cran.r-project.org/web/packages/rjson/rjson.pdf.
",https://stackoverflow.com/questions/2617600/importing-data-from-a-json-file-into-r,193,320671.0,7.0,,,2010-04-11 15:54:39,2023-01-28 04:32:30,,2020-11-16 16:49:31,Duplicate,json;r,user313967,2083,313967,registered,true,2617823,,,2020-11-16 16:46:59,361,268,0,1,0,2,true,true,false,true,true,false,38,8,false,0.022,0.0006,6068,2010,4,15,Sunday,true,false,false,false,false,false,false
11366964,Is there a way to change the spacing between legend items in ggplot2?,"Is there a way to change the spacing between legend items in ggplot2? I currently have
legend.position =""top""
which automatically produces a horizontal legend. However, the spacing of the items is very close together and I am wondering how to space them farther apart.
",https://stackoverflow.com/questions/11366964/is-there-a-way-to-change-the-spacing-between-legend-items-in-ggplot2,192,221984.0,9.0,,,2012-07-06 17:26:08,2025-03-31 11:27:04,2014-11-17 11:32:31,,,r;ggplot2;legend,overflowname,2213,1475738,registered,true,,,CC BY-SA 3.0,,311,273,1,0,0,3,false,false,false,true,true,true,69,13,true,0.041,0.0009,5251,2012,7,17,Friday,false,false,false,false,false,false,false
1429907,Workflow for statistical analysis and report writing,"Does anyone have any wisdom on workflows for data analysis related to custom report writing? The use-case is basically this:
Client commissions a report that uses data analysis, e.g. a population estimate and related maps for a water district.
The analyst downloads some data, munges the data and saves the result (e.g. adding a column for population per unit, or subsetting the data based on district boundaries).
The analyst analyzes the data created in (2), gets close to her goal, but sees that needs more data and so goes back to (1).
Rinse repeat until the tables and graphics meet QA/QC and satisfy the client.
Write report incorporating tables and graphics.
Next year, the happy client comes back and wants an update. This should be as simple as updating the upstream data by a new download (e.g. get the building permits from the last year), and pressing a ""RECALCULATE"" button, unless specifications change.
At the moment, I just start a directory and ad-hoc it the best I can. I would like a more systematic approach, so I am hoping someone has figured this out... I use a mix of spreadsheets, SQL, ARCGIS, R, and Unix tools.
Thanks!
PS:
Below is a basic Makefile that checks for dependencies on various intermediate datasets (w/ .RData suffix) and scripts (.R suffix). Make uses timestamps to check dependencies, so if you touch ss07por.csv, it will see that this file is newer than all the files / targets that depend on it, and execute the given scripts in order to update them accordingly. This is still a work in progress, including a step for putting into SQL database, and a step for a templating language like sweave. Note that Make relies on tabs in its syntax, so read the manual before cutting and pasting. Enjoy and give feedback!
http://www.gnu.org/software/make/manual/html_node/index.html#Top
R=/home/wsprague/R-2.9.2/bin/R
persondata.RData : ImportData.R ../../DATA/ss07por.csv Functions.R
$R --slave -f ImportData.R
persondata.Munged.RData : MungeData.R persondata.RData Functions.R
$R --slave -f MungeData.R
report.txt: TabulateAndGraph.R persondata.Munged.RData Functions.R
$R --slave -f TabulateAndGraph.R > report.txt
",https://stackoverflow.com/questions/1429907/workflow-for-statistical-analysis-and-report-writing,190,46369.0,14.0,,,2009-09-15 22:14:26,2017-11-11 12:55:40,2015-09-17 16:07:30,,,r;statistics;data-visualization,forkandwait,5237,2554948,registered,true,1434424,,CC BY-SA 3.0,,2480,2187,3,1,0,3,true,false,false,true,true,true,52,7,false,0.302,0.0041,6276,2009,9,22,Tuesday,false,false,false,false,false,false,false
8936099,Returning multiple objects in an R function,"How can I return multiple objects in an R function? In Java, I would make a Class, maybe Person which has some private variables and encapsulates, maybe, height, age, etc.
But in R, I need to pass around groups of data. For example, how can I make an R function return both an list of characters and an integer?
",https://stackoverflow.com/questions/8936099/returning-multiple-objects-in-an-r-function,190,326725.0,6.0,,,2012-01-20 02:30:17,2016-09-07 22:52:10,2016-09-07 22:52:10,2016-08-23 11:32:00,Duplicate,r;function,CodeGuy,29059,412082,registered,true,8936179,,,,367,314,3,0,0,2,true,true,false,true,true,true,43,7,false,0.018,0.0006,5419,2012,1,2,Friday,false,false,false,false,false,false,false
25664007,Reorder bars in geom_bar ggplot2 by value,"I am trying to make a bar-plot where the plot is ordered from the miRNA with the highest value to the miRNA with the lowest. Why does my code not work?
> head(corr.m)
miRNA variable value
1 mmu-miR-532-3p pos 7
2 mmu-miR-1983 pos 75
3 mmu-miR-301a-3p pos 70
4 mmu-miR-96-5p pos 5
5 mmu-miR-139-5p pos 10
6 mmu-miR-5097 pos 47
ggplot(corr.m, aes(x=reorder(miRNA, value), y=value, fill=variable)) +
geom_bar(stat=""identity"")
",https://stackoverflow.com/questions/25664007/reorder-bars-in-geom-bar-ggplot2-by-value,190,294775.0,4.0,,,2014-09-04 11:11:23,2024-10-01 01:38:23,2020-10-05 15:36:40,,,r;ggplot2,user3741035,2565,3741035,registered,true,25664367,,CC BY-SA 4.0,2021-10-28 18:13:50,591,521,4,0,0,2,true,false,false,true,true,true,41,7,false,0.014,0.0006,4461,2014,9,11,Thursday,false,false,false,false,false,false,false
15272916,How can I wait for a keypress in R?,"I want to pause my R script until the user presses a key.
How do I do this?
",https://stackoverflow.com/questions/15272916/how-can-i-wait-for-a-keypress-in-r,190,121292.0,7.0,,,2013-03-07 13:50:42,2025-09-23 21:56:10,2025-09-23 21:56:10,,,r;keypress;wait;readline;readkey,Contango,81346,107409,registered,true,18746519,,CC BY-SA 4.0,,90,76,0,0,0,5,true,false,false,true,true,true,35,9,true,0.058,0.0016,5007,2013,3,13,Thursday,false,false,false,false,false,false,false
4876813,Using R to list all files with a specified extension,"I'm very new to R and am working on updating an R script to iterate through a series of .dbf tables created using ArcGIS and produce a series of graphs.
I have a directory, C:\Scratch, that will contain all of my .dbf files. However, when ArcGIS creates these tables, it also includes a .dbf.xml file. I want to remove these .dbf.xml files from my file list and thus my iteration. I've tried searching and experimenting with regular expressions to no avail. This is the basic expression I'm using (Excluding all of the various experimentation):
files <- list.files(pattern = ""dbf"")
Can anyone give me some direction?
",https://stackoverflow.com/questions/4876813/using-r-to-list-all-files-with-a-specified-extension,189,218793.0,6.0,,,2011-02-02 16:09:41,2023-11-16 11:55:48,2011-02-02 17:33:40,,,r,chawkins,1993,600280,registered,true,4876869,,CC BY-SA 2.5,,669,624,1,0,0,1,true,false,false,true,true,true,52,10,false,0.027,0.0009,5771,2011,2,16,Wednesday,false,false,false,false,false,false,false
25166624,Insert picture/table in R Markdown,"So I want to insert a table AND a picture into R Markdown. In regular word document I can just easily insert a table (5 rows by 2 columns), and for the picture just copy and paste.
How do I insert a 5 row by 2 column table (and also type stuff into them)(and also adjust the table in terms of the 2nd column being wider than the first)?
How do I insert a picture? From my understanding, I should first save the picture as a png, then reference it into my document. Also, I want to automatically adjust the picture to the report, like not taking up more than a page, or less than a page.(Is there a way for me to adjust the size of the picture to my liking)?
If anyone knows anything cool/formatting about R Markdown could you also let me know? I know that # makes a big title for a paragraph, and ** ** bolds things. Thats about all I know though!
",https://stackoverflow.com/questions/25166624/insert-picture-table-in-r-markdown,189,479083.0,4.0,,,2014-08-06 17:34:00,2020-09-19 18:06:29,2018-04-16 11:50:51,2020-09-19 18:17:55,Needs more focus,r;r-markdown,user3784616,2027,3784616,registered,true,25167279,,,,941,851,2,0,0,2,true,true,false,true,true,true,34,5,false,0.008,0.0004,4490,2014,8,17,Wednesday,false,false,false,false,false,false,false
7145826,How to format a number as percentage in R?,"One of the things that used to perplex me as a newby to R was how to format a number as a percentage for printing.
For example, display 0.12345 as 12.345%. I have a number of workarounds for this, but none of these seem to be ""newby friendly"". For example:
set.seed(1)
m <- runif(5)
paste(round(100*m, 2), ""%"", sep="""")
[1] ""26.55%"" ""37.21%"" ""57.29%"" ""90.82%"" ""20.17%""
sprintf(""%1.2f%%"", 100*m)
[1] ""26.55%"" ""37.21%"" ""57.29%"" ""90.82%"" ""20.17%""
Question: Is there a base R function to do this? Alternatively, is there a widely used package that provides a convenient wrapper?
Despite searching for something like this in ?format, ?formatC and ?prettyNum, I have yet to find a suitably convenient wrapper in base R. ??""percent"" didn't yield anything useful. library(sos); findFn(""format percent"") returns 1250 hits - so again not useful. ggplot2 has a function percent but this gives no control over rounding accuracy.
",https://stackoverflow.com/questions/7145826/how-to-format-a-number-as-percentage-in-r,189,397799.0,11.0,,,2011-08-22 10:05:23,2024-03-01 09:58:33,2015-01-03 21:39:02,,,r;formatting,Andrie,180454,602276,registered,true,7146270,,CC BY-SA 3.0,2017-01-12 15:27:29,1124,934,10,0,0,2,true,false,false,true,true,true,42,9,true,0.028,0.0005,5570,2011,8,10,Monday,false,false,false,false,false,false,false
7235657,Fastest way to replace NAs in a large data.table,"I have a large data.table, with many missing values scattered throughout its ~200k rows and 200 columns. I would like to re code those NA values to zeros as efficiently as possible.
I see two options:
1: Convert to a data.frame, and use something like this
2: Some kind of cool data.table sub setting command
I'll be happy with a fairly efficient solution of type 1. Converting to a data.frame and then back to a data.table won't take too long.
",https://stackoverflow.com/questions/7235657/fastest-way-to-replace-nas-in-a-large-data-table,189,118541.0,11.0,,,2011-08-29 20:35:45,2023-08-03 09:57:02,2015-03-25 11:37:30,,,r;performance;dataframe;data.table,Zach,30561,345660,registered,true,7249454,,CC BY-SA 3.0,,721,448,0,2,0,4,true,false,false,true,true,true,48,9,false,0.093,0.0016,5563,2011,8,20,Monday,false,false,false,false,false,false,false
10520772,"In R, how to get an object's name after it is sent to a function?","I am looking for the reverse of get().
Given an object name, I wish to have the character string representing that object extracted directly from the object.
Trivial example with foo being the placeholder for the function I am looking for.
z <- data.frame(x=1:10, y=1:10)
test <- function(a){
mean.x <- mean(a$x)
print(foo(a))
return(mean.x)}
test(z)
Would print:
""z""
My work around, which is harder to implement in my current problem is:
test <- function(a=""z""){
mean.x <- mean(get(a)$x)
print(a)
return(mean.x)}
test(""z"")
",https://stackoverflow.com/questions/10520772/in-r-how-to-get-an-objects-name-after-it-is-sent-to-a-function,189,83507.0,4.0,,,2012-05-09 17:05:40,2025-07-02 21:30:40,2015-11-09 02:30:26,,,r,Etienne Low-Décarie,13563,742447,registered,true,10520832,,CC BY-SA 3.0,,699,566,5,0,0,1,true,false,false,true,true,true,69,15,true,0.048,0.0023,5309,2012,5,17,Wednesday,false,false,false,false,false,false,false
14563989,Force R to stop plotting abbreviated axis labels (scientific notation) - e.g. 1e+00,"In ggplot2 how can I stop axis labels being abbreviated - e.g. 1e+00, 1e+01 along the x axis once plotted? Ideally, I want to force R to display the actual values which in this case would be 1,10.
Any help much appreciated.
",https://stackoverflow.com/questions/14563989/force-r-to-stop-plotting-abbreviated-axis-labels-scientific-notation-e-g-1e,188,197620.0,10.0,,,2013-01-28 14:17:04,2023-03-26 04:43:33,2022-07-05 06:00:40,,,r;graph;ggplot2;axes,JPD,2681,1303502,registered,true,14564102,,CC BY-SA 4.0,,265,225,2,0,0,4,true,false,false,true,true,true,83,13,false,0.051,0.001,5045,2013,1,14,Monday,false,false,false,false,false,false,false
9341635,Check for installed packages before running install.packages(),"I have an R script that is shared with several users on different computers. One of its lines contains the install.packages(""xtable"") command.
The problem is that every time someone runs the script, R spends a great deal of time apparently reinstalling the package (it actually does take some time, since the real case has vector of several packages).
How can I make first check if the packages are installed and then only run install.packages() for the ones that are not?
",https://stackoverflow.com/questions/9341635/check-for-installed-packages-before-running-install-packages,188,235646.0,16.0,,,2012-02-18 13:35:33,2025-03-02 22:02:16,2015-06-13 21:20:37,2017-03-07 10:58:10,Duplicate,r;package,Waldir Leoncio,11601,1169233,registered,true,9341735,,,,522,475,2,0,0,2,true,true,false,true,true,true,62,7,false,0.068,0.0008,5390,2012,2,13,Saturday,true,false,false,false,false,false,false
15625990,How to set size for local image using knitr for markdown?,"I have a local image that I would like to include in an .Rmd file which I will then knit and convert to HTML slides with Pandoc. Per this post, this will insert the local image :

Is there a way to modify this code to also set the image size?
",https://stackoverflow.com/questions/15625990/how-to-set-size-for-local-image-using-knitr-for-markdown,187,169372.0,8.0,,,2013-03-25 22:24:29,2022-01-03 23:42:13,2017-05-23 11:54:50,,,image;r;markdown;knitr;pandoc,Adam Smith,2651,2077901,registered,true,15626317,,CC BY-SA 3.0,,476,278,4,1,0,5,true,false,false,true,true,true,57,11,true,0.047,0.0011,4989,2013,3,22,Monday,false,false,false,false,false,false,false
10801750,What's the difference between lapply and do.call?,"I'm learning R recently and confused by two function: lapplyand do.call. It seems that they're just similar to map function in Lisp. But why are there two functions with such a different name? Why doesn't R just use a function called map?
",https://stackoverflow.com/questions/10801750/whats-the-difference-between-lapply-and-do-call,187,94916.0,7.0,,,2012-05-29 15:03:10,2022-08-14 13:46:00,2018-03-05 15:52:57,,,r;functional-programming,Hanfei Sun,47411,1272683,registered,true,10801883,,CC BY-SA 3.0,,298,239,4,0,0,2,true,false,false,true,true,true,53,7,true,0.074,0.002,5289,2012,5,15,Tuesday,false,false,false,false,false,false,false
21208801,"Group by multiple columns in dplyr, using string vector input","I'm trying to transfer my understanding of plyr into dplyr, but I can't figure out how to group by multiple columns.
# make data with weird column names that can't be hard coded
data = data.frame(
asihckhdoydkhxiydfgfTgdsx = sample(LETTERS[1:3], 100, replace=TRUE),
a30mvxigxkghc5cdsvxvyv0ja = sample(LETTERS[1:3], 100, replace=TRUE),
value = rnorm(100)
)
# get the columns we want to average within
columns = names(data)[-3]
# plyr - works
ddply(data, columns, summarize, value=mean(value))
# dplyr - raises error
data %.%
group_by(columns) %.%
summarise(Value = mean(value))
#> Error in eval(expr, envir, enclos) : index out of bounds
What am I missing to translate the plyr example into a dplyr-esque syntax?
Edit 2017: Dplyr has been updated, so a simpler solution is available. See the currently selected answer.
",https://stackoverflow.com/questions/21208801/group-by-multiple-columns-in-dplyr-using-string-vector-input,187,125907.0,10.0,,,2014-01-18 19:26:51,2021-06-23 14:07:13,2019-06-16 11:11:46,,,r;dplyr;r-faq,sharoz,6407,529799,registered,true,44954739,,CC BY-SA 4.0,,900,838,1,0,0,3,true,false,false,true,true,true,61,10,false,0.079,0.0015,4690,2014,1,19,Saturday,true,false,false,false,false,false,false
11561856,"Add new row to dataframe, at specific row-index, not appended?","The following code combines a vector with a dataframe:
newrow = c(1:4)
existingDF = rbind(existingDF,newrow)
However this code always inserts the new row at the end of the dataframe.
How can I insert the row at a specified point within the dataframe? For example, lets say the dataframe has 20 rows, how can I insert the new row between rows 10 and 11?
",https://stackoverflow.com/questions/11561856/add-new-row-to-dataframe-at-specific-row-index-not-appended,187,449598.0,6.0,,,2012-07-19 13:24:44,2025-07-22 11:29:30,2016-11-15 16:24:10,,,r;dataframe;insert,luciano,14030,1130279,registered,true,11562428,,CC BY-SA 3.0,2017-04-11 11:58:52,402,357,1,0,0,3,true,false,false,true,true,true,62,10,true,0.013,0.0004,5238,2012,7,13,Thursday,false,false,false,false,false,false,false
28873057,Sum across multiple columns with dplyr,"My question involves summing up values across multiple columns of a data frame and creating a new column corresponding to this summation using dplyr. The data entries in the columns are binary(0,1). I am thinking of a row-wise analog of the summarise_each or mutate_each function of dplyr. Below is a minimal example of the data frame:
library(dplyr)
df=data.frame(
x1=c(1,0,0,NA,0,1,1,NA,0,1),
x2=c(1,1,NA,1,1,0,NA,NA,0,1),
x3=c(0,1,0,1,1,0,NA,NA,0,1),
x4=c(1,0,NA,1,0,0,NA,0,0,1),
x5=c(1,1,NA,1,1,1,NA,1,0,1))
> df
x1 x2 x3 x4 x5
1 1 1 0 1 1
2 0 1 1 0 1
3 0 NA 0 NA NA
4 NA 1 1 1 1
5 0 1 1 0 1
6 1 0 0 0 1
7 1 NA NA NA NA
8 NA NA NA 0 1
9 0 0 0 0 0
10 1 1 1 1 1
I could use something like:
df <- df %>% mutate(sumrow= x1 + x2 + x3 + x4 + x5)
but this would involve writing out the names of each of the columns. I have like 50 columns.
In addition, the column names change at different iterations of the loop in which I want to implement this
operation so I would like to try avoid having to give any column names.
How can I do that most efficiently?
Any assistance would be greatly appreciated.
",https://stackoverflow.com/questions/28873057/sum-across-multiple-columns-with-dplyr,186,331743.0,9.0,,,2015-03-05 08:19:33,2024-04-17 17:38:08,,,,r;dplyr,amo,3260,3484470,registered,true,32734549,,CC BY-SA 3.0,,1304,1176,6,0,0,2,true,false,false,true,true,false,38,6,false,0.027,0.0006,4279,2015,3,8,Thursday,false,false,false,false,false,false,false
7597559,grep using a character vector with multiple patterns,"I am trying to use grep to test whether a vector of strings are present in an another vector or not, and to output the values that are present (the matching patterns).
I have a data frame like this:
FirstName Letter
Alex A1
Alex A6
Alex A7
Bob A1
Chris A9
Chris A6
I have a vector of strings patterns to be found in the ""Letter"" columns, for example: c(""A1"", ""A9"", ""A6"").
I would like to check whether the any of the strings in the pattern vector is present in the ""Letter"" column. If they are, I would like the output of unique values.
The problem is, I don't know how to use grep with multiple patterns. I tried:
matches <- unique (
grep(""A1| A9 | A6"", myfile$Letter, value=TRUE, fixed=TRUE)
)
But it gives me 0 matches which is not true, any suggestions?
",https://stackoverflow.com/questions/7597559/grep-using-a-character-vector-with-multiple-patterns,186,365305.0,11.0,,,2011-09-29 12:48:52,2022-07-16 18:01:21,2017-02-08 10:53:11,,,r;regex,user971102,3135,971102,registered,true,,,CC BY-SA 3.0,,939,810,5,0,0,2,false,false,false,true,true,true,52,8,false,0.03,0.0005,5532,2011,9,12,Thursday,false,false,false,false,false,false,false
3681647,ggplot: How to increase spacing between faceted plots?,"I have several faceted histograms (obtained with the command below) which are nicely plotted one under the other. I would like to increase the spacing between them, however, they are tight.
I looked at the doc but didn't find a parameter for this.
qplot (Happiness.Level, Number.of.Answers, data=mydata, geom=""histogram"") + facet_grid (Location ~ .)
",https://stackoverflow.com/questions/3681647/ggplot-how-to-increase-spacing-between-faceted-plots,186,143491.0,2.0,,,2010-09-10 01:03:34,2021-01-07 17:25:02,2020-02-14 05:29:06,,,r;ggplot2,wishihadabettername,14911,277434,registered,true,3682851,,CC BY-SA 4.0,,465,355,1,1,0,2,true,false,false,true,true,true,54,8,true,0.014,0.0013,5916,2010,9,1,Friday,false,false,false,false,false,false,false
17215789,Extract a substring according to a pattern,"Suppose I have a list of string:
string = c(""G1:E001"", ""G2:E002"", ""G3:E003"")
Now I hope to get a vector of string that contains only the parts after the colon "":"", i.e substring = c(E001,E002,E003).
Is there a convenient way in R to do this? Using substr?
",https://stackoverflow.com/questions/17215789/extract-a-substring-according-to-a-pattern,185,361112.0,9.0,,,2013-06-20 14:06:24,2023-06-22 06:51:17,2020-04-02 09:29:18,,,regex;r;substr,alittleboy,11046,1510531,registered,true,17215890,,CC BY-SA 4.0,2020-04-02 09:29:34,331,260,3,0,0,3,true,false,false,true,true,true,42,7,false,0.025,0.0005,4902,2013,6,14,Thursday,false,false,false,false,false,false,false
2641653,Pass a data.frame column name to a function,"I'm trying to write a function to accept a data.frame (x) and a column from it. The function performs some calculations on x and later returns another data.frame. I'm stuck on the best-practices method to pass the column name to the function.
The two minimal examples fun1 and fun2 below produce the desired result, being able to perform operations on x$column, using max() as an example. However, both rely on the seemingly (at least to me) inelegant
- call to
substitute() and possibly eval()
- the need to pass the column name as a character vector.
fun1 <- function(x, column){
do.call(""max"", list(substitute(x[a], list(a = column))))
}
fun2 <- function(x, column){
max(eval((substitute(x[a], list(a = column)))))
}
df <- data.frame(B = rnorm(10))
fun1(df, ""B"")
fun2(df, ""B"")
I would like to be able to call the function as fun(df, B), for example. Other options I have considered but have not tried:
- Pass
column as an integer of the column number. I think this would avoid substitute(). Ideally, the function could accept either.
with(x, get(column)), but, even if it works, I think this would still require substitute
- Make use of
formula() and match.call(), neither of which I have much experience with.
Subquestion: Is do.call() preferred over eval()?
",https://stackoverflow.com/questions/2641653/pass-a-data-frame-column-name-to-a-function,185,209384.0,8.0,,,2010-04-14 23:04:18,2023-01-03 18:31:31,2016-03-15 14:37:45,,,r;dataframe;r-faq,kmm,6340,168137,registered,true,2641674,,CC BY-SA 3.0,,1639,1287,18,0,0,3,true,false,false,true,true,true,43,8,false,0.038,0.0009,6065,2010,4,23,Wednesday,false,false,false,false,false,false,false
1236620,Global variables in R,"I am poking into the manuals, I wanted to ask the community:
How can we set global variables inside a function?
",https://stackoverflow.com/questions/1236620/global-variables-in-r,185,191698.0,3.0,,,2009-08-06 02:03:00,2020-08-19 12:44:48,2018-11-22 09:54:41,,,r;global-variables;variable-assignment,Alphaneo,12755,70702,registered,true,1236721,,CC BY-SA 4.0,2017-12-22 11:10:45,119,112,0,0,0,3,true,false,false,true,true,true,21,4,false,0.016,0.001,6316,2009,8,2,Thursday,false,false,false,false,false,false,false
10349206,Add legend to ggplot2 line plot,"I have a question about legends in ggplot2. I managed to plot three lines in the same graph and want to add a legend with the three colors used. This is the code used
library(ggplot2)
## edit from original post - removed lines that downloaded data from broken link. Data snippet now below.
## Here a subset as used by [Brian Diggs in their answer](https://stackoverflow.com/a/10355844/7941188)
datos <- structure(list(fecha = structure(c(1317452400, 1317538800, 1317625200, 1317711600, 1317798000, 1317884400, 1317970800, 1318057200, 1318143600, 1318230000, 1318316400, 1318402800, 1318489200, 1318575600, 1318662000, 1318748400, 1318834800, 1318921200, 1319007600, 1319094000), class = c("POSIXct", "POSIXt"), tzone = ""), TempMax = c(26.58, 27.78, 27.9, 27.44, 30.9, 30.44, 27.57, 25.71, 25.98, 26.84, 33.58, 30.7, 31.3, 27.18, 26.58, 26.18, 25.19, 24.19, 27.65, 23.92), TempMedia = c(22.88, 22.87, 22.41, 21.63, 22.43, 22.29, 21.89, 20.52, 19.71, 20.73, 23.51, 23.13, 22.95, 21.95, 21.91, 20.72, 20.45, 19.42, 19.97, 19.61), TempMin = c(
19.34, 19.14, 18.34, 17.49, 16.75, 16.75, 16.88, 16.82, 14.82, 16.01, 16.88, 17.55, 16.75, 17.22, 19.01,
16.95, 17.55, 15.21, 14.22, 16.42
)), .Names = c(
"fecha", "TempMax",
"TempMedia", "TempMin"
), row.names = c(NA, 20L), class = "data.frame")
ggplot(data = datos, aes(x = fecha, y = TempMax, colour = "1")) +
geom_line(colour = "red") +
geom_line(aes(x = fecha, y = TempMedia, colour = "2"), colour = "green") +
geom_line(aes(x = fecha, y = TempMin, colour = "2"), colour = "blue") +
scale_y_continuous(limits = c(-10, 40)) +
scale_colour_manual(values = c("red", "green", "blue")) +
labs(title = "TITULO", x = NULL, y = "Temperatura (C)")
![]()
I'd like to add a legend with the three colours used and the name of the variable (TempMax,TempMedia and TempMin). I have tried
scale_colour_manual, but can't find the exact way.
",https://stackoverflow.com/questions/10349206/add-legend-to-ggplot2-line-plot,185,414970.0,4.0,,,2012-04-27 10:45:25,2022-11-19 17:49:46,2022-11-19 17:43:22,,,r;ggplot2;legend;r-faq,pacomet,5171,709777,registered,true,10349375,,CC BY-SA 4.0,,2229,2083,2,0,1,4,true,false,false,true,true,true,31,6,false,0.01,0.0004,5321,2012,4,10,Friday,false,false,false,false,false,false,false
36665492,How to combine two lists in R,"I have two lists:
l1 = list(2, 3)
l2 = list(4)
I want a third list:
list(2, 3, 4).
How can I do it in simple way.
Although I can do it in for loop, but I am expecting a one liner answer, or maybe an in-built method.
Actually, I have a list:
list(list(2, 3), list(2, 4), list(3, 5), list(3, 7), list(5, 6), list(5, 7), list(6, 7)).
After computing on list(2, 3) and list(2, 4), I want list(2, 3, 4).
",https://stackoverflow.com/questions/36665492/how-to-combine-two-lists-in-r,185,282375.0,5.0,,,2016-04-16 14:37:05,2024-02-29 18:24:01,2016-04-16 14:48:24,,,r;list,Rohit Singh,2331,3609735,registered,true,36666613,,CC BY-SA 3.0,2024-04-17 06:40:08,542,406,6,0,0,2,true,false,false,true,true,true,29,7,false,0.018,0.0007,3871,2016,4,14,Saturday,true,false,false,false,false,false,false
18222286,Dynamically select data frame columns using $ and a character value,"I have a vector of different column names and I want to be able to loop over each of them to extract that column from a data.frame. For example, consider the data set mtcars and some variable names stored in a character vector cols. When I try to select a variable from mtcars using a dynamic subset of cols, nether of these work
cols <- c(""mpg"", ""cyl"", ""am"")
col <- cols[1]
col
# [1] ""mpg""
mtcars$col
# NULL
mtcars$cols[1]
# NULL
how can I get these to return the same values as
mtcars$mpg
Furthermore how can I loop over all the columns in cols to get the values in some sort of loop.
for(x in seq_along(cols)) {
value <- mtcars[ order(mtcars$cols[x]), ]
}
",https://stackoverflow.com/questions/18222286/dynamically-select-data-frame-columns-using-and-a-character-value,185,194531.0,10.0,,,2013-08-14 02:27:57,2023-02-07 21:37:36,2023-02-07 21:37:36,,,r;dataframe;r-faq;dollar-sign,Samuel Song,2195,2415342,registered,true,18228613,,CC BY-SA 4.0,,838,680,8,0,0,4,true,false,false,true,true,true,67,11,false,0.051,0.001,4847,2013,8,2,Wednesday,false,false,false,false,false,false,false
2076370,Most underused data visualization,"Histograms and scatterplots are great methods of visualizing data and the relationship between variables, but recently I have been wondering about what visualization techniques I am missing. What do you think is the most underused type of plot?
Answers should:
- Not be very commonly used in
practice.
- Be understandable without a great deal
of background discussion.
- Be applicable in many common situations.
- Include reproducible code to create
an example (preferably in R). A linked image would be
nice.
",https://stackoverflow.com/questions/2076370/most-underused-data-visualization,183,27388.0,15.0,,,2010-01-16 06:03:53,2020-03-23 19:59:48,,2011-12-21 14:20:29,not constructive,graphics;r;visualization;plot;ggplot2,Ian Fellows,17398,160314,registered,true,2078411,,,,565,506,0,0,0,5,true,true,false,true,true,false,33,4,false,0.548,0.0067,6153,2010,1,6,Saturday,true,false,false,false,false,false,false
3492379,data.frame rows to a list,"I have a data.frame which I would like to convert to a list by rows, meaning each row would correspond to its own list elements. In other words, I would like a list that is as long as the data.frame has rows.
So far, I've tackled this problem in the following manner, but I was wondering if there's a better way to approach this.
xy.df <- data.frame(x = runif(10), y = runif(10))
# pre-allocate a list and fill it with a loop
xy.list <- vector(""list"", nrow(xy.df))
for (i in 1:nrow(xy.df)) {
xy.list[[i]] <- xy.df[i,]
}
",https://stackoverflow.com/questions/3492379/data-frame-rows-to-a-list,183,266338.0,16.0,,,2010-08-16 10:37:57,2025-01-29 18:49:06,,,,list;r;dataframe,Roman Luštrik,70973,322912,registered,true,14370455,,CC BY-SA 2.5,,576,538,1,0,0,3,true,false,false,true,true,false,25,5,false,0.06,0.0007,5941,2010,8,10,Monday,false,false,false,false,false,false,false
1828742,Rotating axis labels in R,"How do I make a (bar) plot's y axis labels parallel to the X axis instead of parallel to the Y axis?
",https://stackoverflow.com/questions/1828742/rotating-axis-labels-in-r,182,396930.0,5.0,,,2009-12-01 20:35:33,2021-10-18 08:30:54,2021-10-18 08:30:54,,,r;label;axis;plot,Phoebe,2834,147537,registered,true,1828862,,CC BY-SA 4.0,,108,101,0,0,0,4,true,false,false,true,true,true,25,5,false,0.013,0.0005,6199,2009,12,20,Tuesday,false,false,false,false,false,false,false
1608130,Equivalent of "throw" in R,"How does one ""throw"" an error in R? I have a function that takes a data frame and some column names and does stuff with them. If the columns don't exist, I want the function to stop and to stop all functions depending on it.
I have looked at recover and browse and traceback but, well, they seemed to be close but not what I am looking for.
",https://stackoverflow.com/questions/1608130/equivalent-of-throw-in-r,182,110500.0,4.0,,,2009-10-22 15:44:16,2017-12-16 12:15:15,2016-01-04 08:48:21,,,r;error-handling,forkandwait,5237,2554948,registered,true,1608170,,CC BY-SA 3.0,2017-05-05 00:13:35,398,345,3,0,0,2,true,false,false,true,true,true,36,5,false,0.036,0.0016,6239,2009,10,15,Thursday,false,false,false,false,false,false,false
23050928,"Error in plot.new() : figure margins too large, Scatter plot","I've looked in different questions for a solution and I've tried what was suggested but I have not found a solution to make it work.
Everytime I want to run this code it always says:
Error in plot.new() : figure margins too large
and I don't know how to fix it. Here is my code:
par(mfcol=c(5,3))
hist(RtBio, main="Histograma de Bio Pappel")
boxplot(RtBio, main="Diagrama de Caja de Bio Pappel")
stem(RtBio)
plot(RtBio, main="Gráfica de Dispersión")
hist(RtAlsea, main="Histograma de Alsea")
boxplot(Alsea, main="Diagrama de caja de Alsea")
stem(RtAlsea)
plot(RtTelev, main="Gráfica de distribución de Alsea")
hist(RtTelev, main="Histograma de Televisa")
boxplot(telev, main="Diagrama de Caja de Televisa")
stem(Telev)
plot(Telev, main="Gráfica de dispersión de Televisa")
hist(RtWalmex, main="Histograma de Walmex")
boxplot(RtWalmex, main="Diagrama de caja de Walmex")
stem(RtWalmex)
plot(RtWalmex, main="Gráfica de dispersión de Walmex")
hist(RtIca, main="Histograma de Ica")
boxplot(RtIca, main="Gráfica de caja de Ica")
stem(RtIca)
plot(RtIca, main="Gráfica de dispersión de Ica")
What can I do?
",https://stackoverflow.com/questions/23050928/error-in-plot-new-figure-margins-too-large-scatter-plot,181,758790.0,8.0,,,2014-04-14 02:14:45,2025-04-05 01:01:25,2025-04-05 01:01:10,,,r;plot;figure;margins,user3530361,1821,3530361,registered,true,,,CC BY-SA 4.0,2016-09-16 11:34:36,1332,1256,2,0,0,4,false,false,false,true,true,true,60,10,false,0.011,0.0002,4604,2014,4,2,Monday,false,false,false,false,false,false,false
20457290,Installing R with Homebrew,"I'm trying to install R using Homebrew. I ran these commands which are recommended elsewhere on SO:
brew tap homebrew/science
brew install R
For brew tap homebrew/science, I'm receiving this error:
Error: Already tapped!
For the second command, I receive this:
Error: No available formula for r
Any suggestions?
",https://stackoverflow.com/questions/20457290/installing-r-with-homebrew,181,151907.0,14.0,,,2013-12-08 18:35:36,2024-11-27 12:45:25,,,,r;homebrew,duber,2889,1123664,registered,true,79230336,,CC BY-SA 3.0,,435,322,4,0,0,2,true,false,false,true,true,false,26,4,false,0.092,0.0012,4731,2013,12,18,Sunday,true,false,false,false,false,false,false
8637993,Better explanation of when to use Imports/Depends,"The "Writing R Extensions" manual provides the following guidance on when to use Imports or Depends:
The general rules are
- Packages whose namespace only is needed to load the package using library(pkgname) must be listed in the ‘Imports’ field and not in the
‘Depends’ field.
- Packages that need to be attached to successfully load the package using library(pkgname) must be listed in the ‘Depends’ field, only.
Can someone provide a bit more clarity on this? How do I know when my package only needs namespaces loaded versus when I need a package to be attached? What are examples of both? I think the typical package is just a collection of functions that sometimes call functions in other packages (where some bit of work has already been coded-up). Is this scenario 1 or 2 above?
",https://stackoverflow.com/questions/8637993/better-explanation-of-when-to-use-imports-depends,181,38548.0,5.0,,,2011-12-26 17:58:24,2025-09-30 15:56:55,2025-09-23 14:29:53,,,r,Suraj,36954,356790,registered,true,8638902,,CC BY-SA 4.0,,985,801,0,1,0,1,true,false,false,true,true,true,49,7,false,0.13,0.0047,5444,2011,12,17,Monday,false,false,false,false,false,false,false
22945651,Remove space between plotted data and the axes,"I have the following dataframe:
uniq <- structure(list(year = c(1986L, 1987L, 1991L, 1992L, 1993L, 1994L, 1995L, 1996L, 1997L, 1998L, 1999L, 2000L, 2001L, 2002L, 2003L, 2004L, 2005L, 2006L, 2007L, 2008L, 2009L, 2010L, 2011L, 2012L, 2013L, 2014L, 1986L, 1987L, 1991L, 1992L, 1993L, 1994L, 1995L, 1996L, 1997L, 1998L, 1999L, 2000L, 2001L, 2002L, 2003L, 2004L, 2005L, 2006L, 2007L, 2008L, 2009L, 2010L, 2011L, 2012L, 2013L, 2014L, 1986L, 1987L, 1991L, 1992L, 1993L, 1994L, 1995L, 1996L, 1997L, 1998L, 1999L, 2000L, 2001L, 2002L, 2003L, 2004L, 2005L, 2006L, 2007L, 2008L, 2009L, 2010L, 2011L, 2012L, 2013L, 2014L), uniq.loc = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), .Label = c(""u.1"", ""u.2"", ""u.3""), class = ""factor""), uniq.n = c(1, 1, 1, 2, 5, 4, 2, 16, 16, 10, 15, 14, 8, 12, 20, 11, 17, 30, 17, 21, 22, 19, 34, 44, 56, 11, 0, 0, 3, 3, 7, 17, 12, 21, 18, 10, 12, 9, 7, 11, 25, 14, 11, 17, 12, 24, 59, 17, 36, 50, 59, 12, 0, 0, 0, 1, 4, 6, 3, 3, 9, 3, 4, 2, 5, 2, 12, 6, 8, 8, 3, 2, 9, 5, 20, 7, 10, 8), uniq.p = c(100, 100, 25, 33.3, 31.2, 14.8, 11.8, 40, 37.2, 43.5, 48.4, 56, 40, 48, 35.1, 35.5, 47.2, 54.5, 53.1, 44.7, 24.4, 46.3, 37.8, 43.6, 44.8, 35.5, 0, 0, 75, 50, 43.8, 63, 70.6, 52.5, 41.9, 43.5, 38.7, 36, 35, 44, 43.9, 45.2, 30.6, 30.9, 37.5, 51.1, 65.6, 41.5, 40, 49.5, 47.2, 38.7, 0, 0, 0, 16.7, 25, 22.2, 17.6, 7.5, 20.9, 13, 12.9, 8, 25, 8, 21.1, 19.4, 22.2, 14.5, 9.4, 4.3, 10, 12.2, 22.2, 6.9, 8, 25.8)), .Names = c(""year"", ""uniq.loc"", ""uniq.n"", ""uniq.p""), class = ""data.frame"", row.names = c(NA, -78L))
When I make an area-plot with:
ggplot(data = uniq) +
geom_area(aes(x = year, y = uniq.p, fill = uniq.loc), stat = ""identity"", position = ""stack"") +
scale_x_continuous(limits=c(1986,2014)) +
scale_y_continuous(limits=c(0,101)) +
theme_bw()
I get this result:
![]()
However, I want to remove the space between the axis and the actual plot. When I add theme(panel.grid = element_blank(), panel.margin = unit(-0.8, ""lines"")) I get the following error message:
Error in theme(panel.grid = element_blank(), panel.margin = unit(-0.8, :
could not find function ""unit""
Any suggestions on how to solve this problem?
",https://stackoverflow.com/questions/22945651/remove-space-between-plotted-data-and-the-axes,180,192697.0,3.0,,,2014-04-08 18:44:39,2021-08-03 16:59:39,2021-08-03 16:59:39,,,r;plot;ggplot2,Jaap,83841,2204410,registered,true,22945857,,CC BY-SA 4.0,,2663,2433,4,0,1,3,true,false,false,true,true,true,46,8,false,0.016,0.0009,4610,2014,4,18,Tuesday,false,false,false,false,false,false,false
1154242,Remove plot axis values,"I was just wondering if there is a way to get rid of axis values, either the x-axis or y-axis respectively, in an r-plot graph.
I know that axes = false will get rid of the entire axis, but I would only like to get rid of the numbering.
",https://stackoverflow.com/questions/1154242/remove-plot-axis-values,180,486878.0,5.0,,,2009-07-20 15:25:31,2019-04-18 04:11:14,2017-12-22 11:08:40,,,r;plot;axis-labels,user130633,2313,130633,registered,true,,,CC BY-SA 3.0,2017-12-22 11:08:52,266,239,1,0,0,3,false,false,false,true,true,true,23,4,false,0.01,0.0004,6333,2009,7,15,Monday,false,false,false,false,false,false,false
11254524,Omit rows containing specific column of NA,"I want to know how to omit NA values in a data frame, but only in some columns I am interested in.
For example,
DF <- data.frame(x = c(1, 2, 3), y = c(0, 10, NA), z=c(NA, 33, 22))
but I only want to omit the data where y is NA, therefore the result should be
x y z
1 1 0 NA
2 2 10 33
na.omit seems delete all rows contain any NA.
Can somebody help me out of this simple question?
But if now I change the question like:
DF <- data.frame(x = c(1, 2, 3,NA), y = c(1,0, 10, NA), z=c(43,NA, 33, NA))
If I want to omit only x=na or z=na, where can I put the | in function?
",https://stackoverflow.com/questions/11254524/omit-rows-containing-specific-column-of-na,179,340968.0,10.0,,,2012-06-29 00:02:02,2022-08-27 13:37:30,2014-08-20 02:27:45,,,r;dataframe;na,user1489975,1941,1489975,registered,true,11258247,,CC BY-SA 3.0,,815,590,11,0,0,3,true,false,false,true,true,true,42,7,false,0.029,0.0005,5258,2012,6,0,Friday,false,false,false,false,false,false,false
6827299,R apply function with multiple parameters,"I have a function f(var1, var2) in R. Suppose we set var2 = 1 and now I want to apply the function f() to the list L. Basically I want to get a new list L* with the outputs
[f(L[1],1),f(L[2],1),...,f(L[n],1)]
How do I do this with either apply, mapply or lapply?
",https://stackoverflow.com/questions/6827299/r-apply-function-with-multiple-parameters,179,319284.0,3.0,,,2011-07-26 08:33:21,2022-01-24 03:45:23,2016-05-17 13:18:06,,,r,Michael,7467,851530,registered,true,6827519,,CC BY-SA 3.0,,397,268,8,0,0,1,true,false,false,true,true,true,41,6,false,0.009,0.0006,5597,2011,7,8,Tuesday,false,false,false,false,false,false,false
5391124,Select rows of a matrix that meet a condition,"In R with a matrix:
one two three four
[1,] 1 6 11 16
[2,] 2 7 12 17
[3,] 3 8 11 18
[4,] 4 9 11 19
[5,] 5 10 15 20
I want to extract the submatrix whose rows have column three = 11. That is:
one two three four
[1,] 1 6 11 16
[3,] 3 8 11 18
[4,] 4 9 11 19
I want to do this without looping. I am new to R so this is probably very obvious but the
documentation is often somewhat terse.
",https://stackoverflow.com/questions/5391124/select-rows-of-a-matrix-that-meet-a-condition,178,538175.0,6.0,,,2011-03-22 12:21:48,2023-08-09 04:36:13,2018-05-28 10:10:50,,,r;select;matrix;submatrix,peter2108,6260,205063,registered,true,5391697,,CC BY-SA 4.0,,549,480,2,0,0,4,true,false,false,true,true,true,45,9,false,0.011,0.0003,5723,2011,3,12,Tuesday,false,false,false,false,false,false,false
6329962,Split code over multiple lines in an R script,"I want to split a line in an R script over multiple lines (because it is too long). How do I do that?
Specifically, I have a line such as
setwd('~/a/very/long/path/here/that/goes/beyond/80/characters/and/then/some/more')
Is it possible to split the long path over multiple lines? I tried
setwd('~/a/very/long/path/here/that/goes/beyond/80/characters/and/
then/some/more')
with return key at the end of the first line; but that does not work.
Thanks.
",https://stackoverflow.com/questions/6329962/split-code-over-multiple-lines-in-an-r-script,177,386404.0,9.0,,,2011-06-13 11:44:52,2022-10-02 13:15:50,2014-03-29 12:54:29,,,r;multiline,Curious2learn,33976,316357,registered,true,6330066,,CC BY-SA 3.0,2019-05-15 21:13:29,554,458,3,0,0,2,true,false,false,true,true,true,45,9,false,0.023,0.0005,5640,2011,6,11,Monday,false,false,false,false,false,false,false
1401904,Painless way to install a new version of R?,"Andrew Gelman recently lamented the lack of an easy upgrade process for R (probably more relevant on Windows than Linux). Does anyone have a good trick for doing the upgrade, from installing the software to copying all the settings/packages over?
This suggestion was contained in the comments and is what I've been using recently. First you install the new version, then run this in the old verion:
#--run in the old version of R
setwd(""C:/Temp/"")
packages <- installed.packages()[,""Package""]
save(packages, file=""Rpackages"")
Followed by this in the new version:
#--run in the new version
setwd(""C:/Temp/"")
load(""Rpackages"")
for (p in setdiff(packages, installed.packages()[,""Package""]))
install.packages(p)
",https://stackoverflow.com/questions/1401904/painless-way-to-install-a-new-version-of-r,177,71776.0,12.0,,,2009-09-09 20:29:11,2024-05-14 13:36:02,2017-05-23 20:04:33,,,r;upgrade;package,Shane,100646,163053,registered,true,3977156,,CC BY-SA 3.0,,900,719,2,1,0,3,true,false,false,true,true,true,43,9,true,0.167,0.0025,6282,2009,9,20,Wednesday,false,false,false,false,false,false,false
10790204,How to delete a row by reference in data.table?,"My question is related to assignment by reference versus copying in data.table. I want to know if one can delete rows by reference, similar to
DT[ , someCol := NULL]
I want to know about
DT[someRow := NULL, ]
I guess there's a good reason for why this function doesn't exist, so maybe you could just point out a good alternative to the usual copying approach, as below. In particular, going with my favourite from example(data.table),
DT = data.table(x = rep(c(""a"", ""b"", ""c""), each = 3), y = c(1, 3, 6), v = 1:9)
# x y v
# [1,] a 1 1
# [2,] a 3 2
# [3,] a 6 3
# [4,] b 1 4
# [5,] b 3 5
# [6,] b 6 6
# [7,] c 1 7
# [8,] c 3 8
# [9,] c 6 9
Say I want to delete the first row from this data.table. I know I can do this:
DT <- DT[-1, ]
but often we may want to avoid that, because we are copying the object (and that requires about 3*N memory, if N object.size(DT), as pointed out here.
Now I found set(DT, i, j, value). I know how to set specific values (like here: set all values in rows 1 and 2 and columns 2 and 3 to zero)
set(DT, 1:2, 2:3, 0)
DT
# x y v
# [1,] a 0 0
# [2,] a 0 0
# [3,] a 6 3
# [4,] b 1 4
# [5,] b 3 5
# [6,] b 6 6
# [7,] c 1 7
# [8,] c 3 8
# [9,] c 6 9
But how can I erase the first two rows, say? Doing
set(DT, 1:2, 1:3, NULL)
sets the entire DT to NULL.
My SQL knowledge is very limited, so you guys tell me: given data.table uses SQL technology, is there an equivalent to the SQL command
DELETE FROM table_name
WHERE some_column=some_value
in data.table?
",https://stackoverflow.com/questions/10790204/how-to-delete-a-row-by-reference-in-data-table,177,61902.0,9.0,,,2012-05-28 20:41:07,2026-08-29 15:51:23,2017-05-23 12:10:34,,,r;data.table,Florian Oswald,5218,1168848,registered,true,,,CC BY-SA 3.0,,1890,1515,10,1,0,2,false,false,false,true,true,true,47,9,true,0.145,0.0029,5290,2012,5,20,Monday,false,false,false,false,false,false,false
3872070,How to force R to use a specified factor level as reference in a regression?,"How can I tell R to use a certain level as reference if I use binary explanatory variables in a regression?
It's just using some level by default.
lm(x ~ y + as.factor(b))
with b {0, 1, 2, 3, 4}. Let's say I want to use 3 instead of the zero that is used by R.
",https://stackoverflow.com/questions/3872070/how-to-force-r-to-use-a-specified-factor-level-as-reference-in-a-regression,175,383599.0,6.0,,,2010-10-06 11:46:59,2019-10-28 12:51:13,2017-08-11 11:28:21,,,r;regression;linear-regression;categorical-data;dummy-variable,Matt Bannert,28424,366256,registered,true,3872213,,CC BY-SA 3.0,2016-10-07 19:54:50,326,268,2,0,0,5,true,false,false,true,true,true,76,15,true,0.016,0.0005,5890,2010,10,11,Wednesday,false,false,false,false,false,false,false
5555408,Convert the values in a column into row names in an existing data frame,"I would like to convert the values in a column of an existing data frame into row names. Is is possible to do this without exporting the data frame and then reimporting it with a row.names = call?
For example I would like to convert:
> samp
names Var.1 Var.2 Var.3
1 A 1 5 0
2 B 2 4 1
3 C 3 3 2
4 D 4 2 3
5 E 5 1 4
Into:
> samp.with.rownames
Var.1 Var.2 Var.3
A 1 5 0
B 2 4 1
C 3 3 2
D 4 2 3
E 5 1 4
",https://stackoverflow.com/questions/5555408/convert-the-values-in-a-column-into-row-names-in-an-existing-data-frame,175,408410.0,5.0,,,2011-04-05 16:47:16,2022-04-18 12:01:53,2020-09-09 19:23:54,,,r,DQdlM,10354,686481,registered,true,5555455,,CC BY-SA 4.0,2017-08-13 14:11:29,649,567,3,0,0,1,true,false,false,true,true,true,71,14,false,0.012,0.0004,5709,2011,4,16,Tuesday,false,false,false,false,false,false,false
15678261,ggplot does not work if it is inside a for loop although it works outside of it,"I'm using a simple ggplot function which works fine outside a loop but not inside even if the iterative value does not interfere with the ggplot function. Why is it so ?
Here is my code
x=1:7
y=1:7
df = data.frame(x=x,y=y)
ggplot(df,aes(x,y))+geom_point()
It works ! But if the ggplot is inside a for loop ...
for (i in 1:5) {
ggplot(df,aes(x,y))+geom_point()
}
it doesn't work anymore, what am I missing ?
",https://stackoverflow.com/questions/15678261/ggplot-does-not-work-if-it-is-inside-a-for-loop-although-it-works-outside-of-it,175,144241.0,1.0,,,2013-03-28 09:29:44,2019-08-08 08:00:57,2019-08-08 08:00:57,2013-03-28 10:46:19,exact duplicate,r;for-loop;ggplot2,Remi.b,18399,2051137,registered,true,15678596,,,,493,417,2,0,0,3,true,true,false,true,true,true,79,17,false,0.007,0.0012,4986,2013,3,9,Thursday,false,false,false,false,false,false,false
7854433,"Finding ALL duplicate rows, including "elements with smaller subscripts"","R's duplicated returns a vector showing whether each element of a vector or data frame is a duplicate of an element with a smaller subscript. So if rows 3, 4, and 5 of a 5-row data frame are the same, duplicated will give me the vector
FALSE, FALSE, FALSE, TRUE, TRUE
But in this case I actually want to get
FALSE, FALSE, TRUE, TRUE, TRUE
that is, I want to know whether a row is duplicated by a row with a larger subscript too.
",https://stackoverflow.com/questions/7854433/finding-all-duplicate-rows-including-elements-with-smaller-subscripts,175,77446.0,10.0,,,2011-10-21 19:37:45,2025-09-15 06:27:57,2018-08-17 00:29:29,,,r;duplicates;r-faq,Lauren Samuels,2589,65246,registered,true,7854620,,CC BY-SA 4.0,,549,437,4,0,0,3,true,false,false,true,true,true,82,9,false,0.129,0.0023,5510,2011,10,19,Friday,false,false,false,false,false,false,false
11680579,"Assign multiple columns using := in data.table, by group","What is the best way to assign to multiple columns using data.table? For example:
f <- function(x) {c(""hi"", ""hello"")}
x <- data.table(id = 1:10)
I would like to do something like this (of course this syntax is incorrect):
x[ , (col1, col2) := f(), by = ""id""]
And to extend that, I may have many columns with names stored in a variable (say col_names) and I would like to do:
x[ , col_names := another_f(), by = ""id"", with = FALSE]
What is the correct way to do something like this?
",https://stackoverflow.com/questions/11680579/assign-multiple-columns-using-in-data-table-by-group,175,127589.0,2.0,,,2012-07-27 02:13:49,2019-09-27 07:35:06,2018-11-13 13:19:11,,,r;dataframe;data.table;variable-assignment;colon-equals,Alex,20011,714319,registered,true,12758229,,CC BY-SA 4.0,,625,499,5,0,0,5,true,false,false,true,true,true,56,9,false,0.016,0.0014,5230,2012,7,2,Friday,false,false,false,false,false,false,false
17059099,Saving grid.arrange() plot to file,"I am trying to plot multiple plots using ggplot2, arranging them using grid.arrange().
Since I managed to find someone describing the exact problem I have, I have quoted from the problem description from link:
When I use ggsave() after grid.arrange(), i.e.
grid.arrange(sgcir1,sgcir2,sgcir3,ncol=2,nrow=2)
ggsave(""sgcirNIR.jpg"")
I do not save the grid plot but the last individual ggplot. Is there any
way of actually saving the plot as displayed by grid.arrange() using
ggsave() or something similar?
Other than using the older way
jpeg(""sgcirNIR.jpg"")
grid.arrange(sgcir1,sgcir2,sgcir3,ncol=2,nrow=2)
dev.off()
The same link gives the solution below:
require(grid)
require(gridExtra)
p <- arrangeGrob(qplot(1,1), textGrob(""test""))
grid.draw(p) # interactive device
ggsave(""saving.pdf"", p) # need to specify what to save explicitly
However, I can't figure out how to use ggsave() to save the output of the grid.arrange() call in the following code, which is taken from link:
library(ggplot2)
library(gridExtra)
dsamp <- diamonds[sample(nrow(diamonds), 1000), ]
p1 <- qplot(carat, price, data=dsamp, colour=clarity)
p2 <- qplot(carat, price, data=dsamp, colour=clarity, geom=""path"")
g_legend<-function(a.gplot){
tmp <- ggplot_gtable(ggplot_build(a.gplot))
leg <- which(sapply(tmp$grobs, function(x) x$name) == ""guide-box"")
legend <- tmp$grobs[[leg]]
return(legend)}
legend <- g_legend(p1)
lwidth <- sum(legend$width)
## using grid.arrange for convenience
## could also manually push viewports
grid.arrange(arrangeGrob(p1 + theme(legend.position=""none""),
p2 + theme(legend.position=""none""),
main =""this is a title"",
left = ""This is my global Y-axis title""), legend,
widths=unit.c(unit(1, ""npc"") - lwidth, lwidth), nrow=1)
# What code to put here to save output of grid.arrange()?
",https://stackoverflow.com/questions/17059099/saving-grid-arrange-plot-to-file,174,148302.0,7.0,,,2013-06-12 06:38:34,2020-10-01 14:28:55,2013-12-02 21:29:59,,,r;ggplot2;gridextra,I Like to Code,7421,856624,registered,true,17075381,,CC BY-SA 3.0,,2438,1973,12,2,0,3,true,false,false,true,true,true,34,5,false,0.047,0.0012,4910,2013,6,6,Wednesday,false,false,false,false,false,false,false
6451152,How to catch integer(0)?,"Let's say we have a statement that produces integer(0), e.g.
a <- which(1:3 == 5)
What is the safest way of catching this?
",https://stackoverflow.com/questions/6451152/how-to-catch-integer0,174,158424.0,8.0,,,2011-06-23 08:18:22,2021-01-18 09:30:55,2011-06-23 10:49:49,,,r;error-handling;integer;try-catch,Roman Luštrik,70973,322912,registered,true,6451295,,CC BY-SA 3.0,,181,130,2,0,0,4,true,false,false,true,true,true,24,4,true,0.05,0.0011,5630,2011,6,8,Thursday,false,false,false,false,false,false,false
14543627,Extracting numbers from vectors of strings,"I have string like this:
years<-c(""20 years old"", ""1 years old"")
I would like to grep only the numeric number from this vector. Expected output is a vector:
c(20, 1)
How do I go about doing this?
",https://stackoverflow.com/questions/14543627/extracting-numbers-from-vectors-of-strings,173,301873.0,13.0,,,2013-01-27 01:47:43,2023-07-24 16:52:13,2016-08-02 07:19:38,,,regex;r,user1471980,10748,1471980,registered,true,14543645,,CC BY-SA 3.0,2022-07-28 09:00:09,274,205,2,0,0,2,true,false,false,true,true,true,42,6,false,0.043,0.0006,5046,2013,1,1,Sunday,true,false,false,false,false,false,false
8169323,R - Concatenate two dataframes?,"Given two dataframes a and b:
> a
a b c
1 -0.2246894 -1.48167912 -1.65099363
2 0.5559320 -0.87898575 -0.15634590
3 1.8469466 -0.01487524 -0.53098215
4 -0.6875051 0.23880967 0.01824621
5 -0.6735163 0.75485292 0.44154092
> b
a c
1 0.4287284 -0.3295925
2 0.5201492 0.3341251
3 -2.6355570 1.7916780
4 -1.3645337 1.3642276
5 -0.4954542 -0.6660001
Is there a simple way to concatenate these so as to return a new data frame of the form below?
> new
a b c
1 -0.2246894 -1.48167912106676 -1.65099363
2 0.5559320 -0.878985746842256 -0.15634590
3 1.8469466 -0.0148752354840942 -0.53098215
4 -0.6875051 0.238809666690982 0.01824621
5 -0.6735163 0.754852923524198 0.44154092
6 0.4287284 NA -0.32959248
7 0.5201492 NA 0.33412510
8 -2.6355570 NA 1.79167801
9 -1.3645337 NA 1.36422764
10 -0.4954542 NA -0.66600006
I want to merge the dataframes, match the headers and insert NA in for positions in dataframe b where the header is missing.
",https://stackoverflow.com/questions/8169323/r-concatenate-two-dataframes,173,450591.0,7.0,,,2011-11-17 15:02:26,2024-11-17 15:10:17,2018-06-17 22:13:59,,,r;dataframe;concatenation,Darren J. Fitzpatrick,7469,233816,registered,true,,,CC BY-SA 4.0,,1273,1152,6,0,0,3,false,false,false,true,true,true,31,5,true,0.016,0.0004,5483,2011,11,15,Thursday,false,false,false,false,false,false,false
13575180,How to change language settings in R,"My error messages are displayed in French. How can I change my system language setting so the error messages will be displayed in English?
",https://stackoverflow.com/questions/13575180/how-to-change-language-settings-in-r,173,249950.0,22.0,,,2012-11-26 23:49:01,2024-05-22 10:44:54,2014-11-28 18:02:08,,,r,agstudy,122012,1838509,registered,true,13575413,,CC BY-SA 3.0,,146,139,0,0,0,1,true,false,false,true,true,true,36,7,false,0.088,0.0007,5108,2012,11,23,Monday,false,false,false,false,false,false,false
8345759,How to save a data frame in R?,"I made a data frame in R that is not very big, but it takes quite some time to build. I would like to save it as a file, which I can then again open in R. How do I achieve this?
",https://stackoverflow.com/questions/8345759/how-to-save-a-data-frame-in-r,173,340082.0,3.0,,,2011-12-01 17:37:54,2025-02-17 19:17:14,2025-02-17 19:17:14,,,r;dataframe,Borut Flis,16525,847773,registered,true,8345810,,CC BY-SA 4.0,,185,178,0,0,0,2,true,false,false,true,true,true,30,8,true,0.009,0.0005,5469,2011,12,17,Thursday,false,false,false,false,false,false,false
10294284,Remove all special characters from a string in R?,"How to remove all special characters from string in R and replace them with spaces ?
Some special characters to remove are : ~!@#$%^&*(){}_+:"<>?,./;'[]-=
I've tried regex with [:punct:] pattern but it removes only punctuation marks.
Question 2 : And how to remove characters from foreign languages like : â í ü Â á ą ę ś ć ?
Answer : Use [^[:alnum:]] to remove~!@#$%^&*(){}_+:"<>?,./;'[]-= and use [^a-zA-Z0-9] to remove also â í ü Â á ą ę ś ć in regex or regexpr functions.
Solution in base R :
x <- "a1~!@#$%^&*(){}_+:\"<>?,./;'[]-="
gsub("[[:punct:]]", "", x) # no libraries needed
",https://stackoverflow.com/questions/10294284/remove-all-special-characters-from-a-string-in-r,172,358724.0,3.0,,,2012-04-24 08:24:48,2021-02-17 08:23:46,2021-02-17 08:23:46,,,regex;string;r;character,Qbik,6205,783421,registered,true,10294818,,CC BY-SA 4.0,2018-04-26 13:24:31,880,667,11,0,0,4,true,false,false,true,true,true,49,9,true,0.008,0.0005,5324,2012,4,8,Tuesday,false,false,false,false,false,false,false
1266279,How to organize large R programs?,"When I undertake an R project of any complexity, my scripts quickly get long and confusing.
What are some practices I can adopt so that my code will always be a pleasure to work with? I'm thinking about things like
- Placement of functions in source files
- When to break something out to another source file
- What should be in the master file
- Using functions as organizational units (whether this is worthwhile given that R makes it hard to access global state)
- Indentation / line break practices.
- Treat ( like {?
- Put things like )} on 1 or 2 lines?
Basically, what are your rules of thumb for organizing large R scripts?
",https://stackoverflow.com/questions/1266279/how-to-organize-large-r-programs,171,37305.0,10.0,,,2009-08-12 13:50:45,2021-02-06 09:45:50,2014-11-23 03:03:44,,,r;package;conventions;code-organization;project-organization,Dan Goldstein,25069,23929,registered,true,1266400,,CC BY-SA 3.0,,731,629,0,0,0,5,true,false,false,true,true,true,33,6,true,0.268,0.0046,6310,2009,8,13,Wednesday,false,false,false,false,false,false,false
8545035,Scatterplot with marginal histograms in ggplot2,"Is there a way of creating scatterplots with marginal histograms just like in the sample below in ggplot2? In Matlab it is the scatterhist() function and there exist equivalents for R as well. However, I haven't seen it for ggplot2.
![]()
I started an attempt by creating the single graphs but don't know how to arrange them properly.
require(ggplot2)
x<-rnorm(300)
y<-rt(300,df=2)
xy<-data.frame(x,y)
xhist <- qplot(x, geom=""histogram"") + scale_x_continuous(limits=c(min(x),max(x))) + opts(axis.text.x = theme_blank(), axis.title.x=theme_blank(), axis.ticks = theme_blank(), aspect.ratio = 5/16, axis.text.y = theme_blank(), axis.title.y=theme_blank(), background.colour=""white"")
yhist <- qplot(y, geom=""histogram"") + coord_flip() + opts(background.fill = ""white"", background.color =""black"")
yhist <- yhist + scale_x_continuous(limits=c(min(x),max(x))) + opts(axis.text.x = theme_blank(), axis.title.x=theme_blank(), axis.ticks = theme_blank(), aspect.ratio = 16/5, axis.text.y = theme_blank(), axis.title.y=theme_blank() )
scatter <- qplot(x,y, data=xy) + scale_x_continuous(limits=c(min(x),max(x))) + scale_y_continuous(limits=c(min(y),max(y)))
none <- qplot(x,y, data=xy) + geom_blank()
and arranging them with the function posted here. But to make long story short: Is there a way of creating these graphs?
",https://stackoverflow.com/questions/8545035/scatterplot-with-marginal-histograms-in-ggplot2,170,99174.0,14.0,,,2011-12-17 13:23:23,2020-01-03 15:30:52,,,,r;ggplot2;histogram;scatter-plot,Seb,5557,1063530,registered,true,8545849,,CC BY-SA 3.0,,1635,1365,3,1,1,4,true,false,false,true,true,false,47,6,false,0.141,0.0017,5453,2011,12,13,Saturday,true,false,false,false,false,false,false
18046051,Setting individual axis limits with facet_wrap and scales = "free" in ggplot2,"I'm creating a facetted plot to view predicted vs. actual values side by side with a plot of predicted value vs. residuals. I'll be using shiny to help explore the results of modeling efforts using different training parameters. I train the model with 85% of the data, test on the remaining 15%, and repeat this 5 times, collecting actual/predicted values each time. After calculating the residuals, my data.frame looks like this:
head(results)
act pred resid
2 52.81000 52.86750 -0.05750133
3 44.46000 42.76825 1.69175252
4 54.58667 49.00482 5.58184181
5 36.23333 35.52386 0.70947731
6 53.22667 48.79429 4.43237981
7 41.72333 41.57504 0.14829173
What I want:
- Side by side plot of
pred vs. act and pred vs. resid
- The x/y range/limits for
pred vs. act to be the same, ideally from min(min(results$act), min(results$pred)) to max(max(results$act), max(results$pred))
- The x/y range/limits for
pred vs. resid not to be affected by what I do to the actual vs. predicted plot. Plotting for x over only the predicted values and y over only the residual range is fine.
In order to view both plots side by side, I melt the data:
library(reshape2)
plot <- melt(results, id.vars = "pred")
Now plot:
library(ggplot2)
p <- ggplot(plot, aes(x = pred, y = value)) + geom_point(size = 2.5) + theme_bw()
p <- p + facet_wrap(~variable, scales = "free")
print(p)
That's pretty close to what I want:
![]()
What I'd like is for the x and y ranges for actual vs. predicted to be the same, but I'm not sure how to specify that, and I don't need that done for the predicted vs. residual plot since the ranges are completely different.
I tried adding something like this for both scale_x_continous and scale_y_continuous:
min_xy <- min(min(plot$pred), min(plot$value))
max_xy <- max(max(plot$pred), max(plot$value))
p <- ggplot(plot, aes(x = pred, y = value)) + geom_point(size = 2.5) + theme_bw()
p <- p + facet_wrap(~variable, scales = "free")
p <- p + scale_x_continuous(limits = c(min_xy, max_xy))
p <- p + scale_y_continuous(limits = c(min_xy, max_xy))
print(p)
But that picks up the min() of the residual values.
![]()
One last idea I had is to store the value of the minimum act and pred variables before melting, and then add them to the melted data frame in order to dictate in which facet they appear:
head(results)
act pred resid
2 52.81000 52.86750 -0.05750133
3 44.46000 42.76825 1.69175252
4 54.58667 49.00482 5.58184181
5 36.23333 35.52386 0.70947731
min_xy <- min(min(results$act), min(results$pred))
max_xy <- max(max(results$act), max(results$pred))
plot <- melt(results, id.vars = "pred")
plot <- rbind(plot, data.frame(pred = c(min_xy, max_xy),
variable = c("act", "act"), value = c(max_xy, min_xy)))
p <- ggplot(plot, aes(x = pred, y = value)) + geom_point(size = 2.5) + theme_bw()
p <- p + facet_wrap(~variable, scales = "free")
print(p)
That does what I want, with the exception that the points show up, too:
![]()
Any suggestions for doing something like this?
I saw this idea to add geom_blank(), but I'm not sure how to specify the aes() bit and have it work properly, or what the geom_point() equivalent is to the histogram use of aes(y = max(..count..)).
Here's data to play with (my actual, predicted, and residual values prior to melting):
results <- read.table(header = TRUE, text = "
act pred resid
52.81 52.8675013282404 -0.0575013282403773
44.46 42.7682474758679 1.69175252413213
54.5866666666667 49.0048248585123 5.58184180815435
36.2333333333333 35.5238560262515 0.709477307081826
53.2266666666667 48.7942868566949 4.43237980997177
41.7233333333333 41.5750416040131 0.148291729320228
35.2966666666667 33.9548164913007 1.34185017536599
30.6833333333333 29.9787449128663 0.704588420467079
39.25 37.6443975781139 1.60560242188613
35.8866666666667 36.7196211666685 -0.832954500001826
25.1 27.6043278172077 -2.50432781720766
29.0466666666667 27.0615724310721 1.98509423559461
23.2766666666667 31.2073056885252 -7.93063902185855
56.3866666666667 55.0886903524179 1.29797631424874
42.92 43.0895814712768 -0.169581471276786
41.57 43.0895814712768 -1.51958147127679
27.92 32.3549865881578 -4.43498658815778
23.16 26.2428426737583 -3.08284267375831
38.0166666666667 36.6926037128343 1.32406295383237
61.8966666666667 56.7987490221996 5.09791764446704
37.41 45.0370788180147 -7.62707881801468
41.6333333333333 41.8231642271826 -0.189830893849219
35.9466666666667 38.3297859332601 -2.38311926659339
48.9933333333333 49.5343916620086 -0.541058328675241
30.5666666666667 30.8535641206809 -0.286897454014273
32.08 29.0117492750411 3.06825072495888
40.3633333333333 36.9767968381391 3.38653649519422
53.2266666666667 49.0826677983065 4.14399886836018
64.6066666666667 54.4678549541069 10.1388117125598
38.5366666666667 35.5059204731218 3.03074619354486
41.7233333333333 41.5333417555995 0.189991577733821
25.78 27.6069075391361 -1.82690753913609
33.4066666666667 31.2404889715121 2.16617769515461
27.8033333333333 27.8920960978598 -0.088762764526507
39.3266666666667 37.8505531149324 1.47611355173427
48.9933333333333 49.2616631533957 -0.268329820062384
25.2433333333333 30.366837650159 -5.12350431682565
32.67 31.1623492639066 1.5076507360934
55.17 55.0456078770405 0.124392122959534
42.92 42.772538591063 0.147461408936991
54.5866666666667 49.2419293590535 5.34473730761318
23.16 26.1963523976241 -3.03635239762411
64.6066666666667 54.4080781796616 10.1985884870051
40.7966666666667 44.9796700541254 -4.18300338745873
39.0166666666667 34.6996927469131 4.31697391975358
41.6333333333333 41.6227713664027 0.0105619669306023
35.8866666666667 36.8449646519306 -0.958297985263961
25.1 27.5318686661673 -2.43186866616734
23.2766666666667 31.6641793552795 -8.38751268861282
44.46 42.8198894266632 1.64011057333683
34.2166666666667 40.5769177148146 -6.36025104814794
40.8033333333333 40.5769177148146 0.226415618518729
24.5766666666667 29.3807781312816 -4.80411146461488
35.73 36.8579132935989 -1.1279132935989
61.8966666666667 55.5617033901752 6.33496327649151
62.1833333333333 55.8097119335638 6.37362139976954
74.6466666666667 55.1041728261666 19.5424938405001
39.4366666666667 43.6094641699075 -4.17279750324084
36.6 37.0674887276681 -0.467488727668119
27.1333333333333 27.3876960746536 -0.254362741320246
")
",https://stackoverflow.com/questions/18046051/setting-individual-axis-limits-with-facet-wrap-and-scales-free-in-ggplot2,170,340933.0,4.0,,,2013-08-04 18:17:56,2024-02-23 11:54:52,2023-05-02 10:39:08,,,r;ggplot2;facet,Hendy,10801,495990,registered,true,21585521,,CC BY-SA 4.0,,7620,6617,29,1,3,3,true,false,false,true,true,true,87,12,false,0.012,0.0005,4857,2013,8,18,Sunday,true,false,false,false,false,false,false
1395229,Increasing (or decreasing) the memory available to R processes,"I would like to increase (or decrease) the amount of memory available to R. What are the methods for achieving this?
",https://stackoverflow.com/questions/1395229/increasing-or-decreasing-the-memory-available-to-r-processes,170,348660.0,7.0,,,2009-09-08 17:28:42,2020-12-04 01:59:07,2018-07-14 19:29:46,,,r;memory-management;memory-leaks,medriscoll,27595,2002705,registered,true,1395256,,CC BY-SA 4.0,2014-11-27 03:02:04,125,118,0,0,0,3,true,false,false,true,true,true,62,9,false,0.02,0.0005,6283,2009,9,17,Tuesday,false,false,false,false,false,false,false
2275896,Is R's apply family more than syntactic sugar?,"...regarding execution time and / or memory.
If this is not true, prove it with a code snippet. Note that speedup by vectorization does not count. The speedup must come from apply (tapply, sapply, ...) itself.
",https://stackoverflow.com/questions/2275896/is-rs-apply-family-more-than-syntactic-sugar,169,24439.0,5.0,,,2010-02-16 20:00:04,2023-03-05 15:18:28,2012-08-03 00:46:20,,,r;apply,steffen,2182,274686,registered,true,2276001,,CC BY-SA 3.0,,264,211,3,0,0,2,true,false,false,true,true,true,50,8,true,0.205,0.0069,6122,2010,2,20,Tuesday,false,false,false,false,false,false,false
7455046,How to make graphics with transparent background in R using ggplot2?,"I need to output ggplot2 graphics from R to PNG files with transparent background. Everything is ok with basic R graphics, but no transparency with ggplot2:
d <- rnorm(100) #generating random data
#this returns transparent png
png('tr_tst1.png',width=300,height=300,units=""px"",bg = ""transparent"")
boxplot(d)
dev.off()
df <- data.frame(y=d,x=1)
p <- ggplot(df) + stat_boxplot(aes(x = x,y=y))
p <- p + opts(
panel.background = theme_rect(fill = ""transparent"",colour = NA), # or theme_blank()
panel.grid.minor = theme_blank(),
panel.grid.major = theme_blank()
)
#returns white background
png('tr_tst2.png',width=300,height=300,units=""px"",bg = ""transparent"")
p
dev.off()
Is there any way to get transparent background with ggplot2?
",https://stackoverflow.com/questions/7455046/how-to-make-graphics-with-transparent-background-in-r-using-ggplot2,169,169473.0,6.0,,,2011-09-17 13:17:10,2023-05-29 18:02:37,,,,r;graphics;transparency;ggplot2,Yuriy Petrovskiy,8258,614735,registered,true,41878833,,CC BY-SA 3.0,,814,759,1,0,0,4,true,false,false,true,true,false,68,11,true,0.035,0.001,5544,2011,9,13,Saturday,true,false,false,false,false,false,false
32712301,Create empty data frame with column names by assigning a string vector?,"
- Create an empty data frame:
y <- data.frame()
- Assign x, a string vector, to y as its column names:
x <- c("name", "age", "gender")
colnames(y) <- x
Result:
Error in colnames<-(*tmp*, value = c("name", "age", "gender")) :
'names' attribute [3] must be the same length as the vector [0]
Actually, the x length is dynamic, so
y <- data.frame(name=character(), age=numeric(), gender=logical())
is not an efficient way to name the column. How can I solve the problem?
",https://stackoverflow.com/questions/32712301/create-empty-data-frame-with-column-names-by-assigning-a-string-vector,168,483285.0,1.0,,,2015-09-22 08:40:55,2021-01-01 02:01:47,2020-11-24 09:55:29,2015-09-28 06:10:00,Duplicate,r;dataframe,Eric Chang,2773,5102896,registered,true,32712555,,,,752,555,5,0,0,2,true,true,false,true,true,true,71,12,true,0.002,0.0003,4078,2015,9,8,Tuesday,false,false,false,false,false,false,false
11610377,How do I change the formatting of numbers on an axis with ggplot?,"I'm using R and ggplot to draw a scatterplot of some data, all is fine except that the numbers on the y-axis are coming out with computer style exponent formatting, i.e. 4e+05, 5e+05, etc. This is unacceptable to me, so I want to get it to display them as 500,000, 400,000, and so on. Getting a proper exponent notation would also be acceptable.
The code for the plot is as follows:
p <- ggplot(valids, aes(x=Test, y=Values)) +
geom_point(position="jitter") +
facet_grid(. ~ Facet) +
scale_y_continuous(name="Fluorescent intensity/arbitrary units") +
scale_x_discrete(name="Test repeat") +
stat_summary(fun.ymin=median, fun.ymax=median, fun.y=median, geom="crossbar")
Any help much appreciated.
",https://stackoverflow.com/questions/11610377/how-do-i-change-the-formatting-of-numbers-on-an-axis-with-ggplot,168,224480.0,5.0,,,2012-07-23 09:33:09,2021-02-24 11:46:11,2021-02-24 11:46:11,2022-07-05 05:55:57,Duplicate,r;ggplot2,anon,,,does_not_exist,true,24241954,,,,794,749,1,0,0,2,true,true,false,true,false,true,65,13,true,0.022,0.0007,5234,2012,7,9,Monday,false,false,false,false,false,false,false
14771546,Remove legend title in ggplot,"I'm trying to remove the title of a legend in ggplot2:
df <- data.frame(
g = rep(letters[1:2], 5),
x = rnorm(10),
y = rnorm(10)
)
library(ggplot2)
ggplot(df, aes(x, y, colour=g)) +
geom_line(stat=""identity"") +
theme(legend.position=""bottom"")
![]()
I've seen this question and none of the solutions there seem to work for me. Most give an error about how opts is deprecated and to use theme instead. I've also tried various versions of theme(legend.title=NULL), theme(legend.title=""""), theme(legend.title=element_blank), etc. Typical error messages are:
'opts' is deprecated. Use 'theme' instead. (Deprecated; last used in version 0.9.1)
'theme_blank' is deprecated. Use 'element_blank' instead. (Deprecated; last used in version 0.9.1)
I'm using ggplot2 for the first time since version 0.9.3 was released and I'm finding it difficult to navigate some of the changes...
",https://stackoverflow.com/questions/14771546/remove-legend-title-in-ggplot,168,230430.0,5.0,,,2013-02-08 11:28:32,2023-02-17 14:57:46,2023-02-17 14:57:46,2023-04-29 07:39:18,Duplicate,r;ggplot2,smillig,5359,1088647,registered,true,14771584,,,,1192,889,9,1,1,2,true,true,false,true,true,true,29,5,false,0.022,0.0007,5034,2013,2,11,Friday,false,false,false,false,false,false,false
5788117,Only read selected columns,"Can anyone please tell me how to read only the first 6 months (7 columns) for each year of the data below, for example by using read.table()?
Year Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
2009 -41 -27 -25 -31 -31 -39 -25 -15 -30 -27 -21 -25
2010 -41 -27 -25 -31 -31 -39 -25 -15 -30 -27 -21 -25
2011 -21 -27 -2 -6 -10 -32 -13 -12 -27 -30 -38 -29
",https://stackoverflow.com/questions/5788117/only-read-selected-columns,168,240297.0,5.0,,,2011-04-26 08:58:47,2021-02-24 04:33:46,2019-04-10 23:29:28,,,r;import;r-faq,StarCub,4331,109027,registered,true,5788200,,CC BY-SA 4.0,2016-12-07 19:52:02,456,412,2,0,0,3,true,false,false,true,true,true,26,4,false,0.021,0.0007,5688,2011,4,8,Tuesday,false,false,false,false,false,false,false
9965747,Linking R and Julia?,"Julia looks very promising for fast and syntax-sane computation (e.g. here), but I suspect it will not be anywhere near R in terms of overall statistics workflow for some time yet. So I'd like to use it where C++ is mainly used in R programs: to optimize slow portions of code. Before I invest the time in learning Julia, though, I am curious what facilities there are for embedding Julia snippets in R code.
So:
- What facilities are out there for linking R and Julia?
- How robust and well-thought-out are they, on a scale of zero to Rcpp?
I want to call Julia from R, just as Rcpp allows calling C++ from within R right now. I do not want to call R from Julia. (So RCall.jl would not work)
",https://stackoverflow.com/questions/9965747/linking-r-and-julia,168,19872.0,8.0,,,2012-04-01 15:43:20,2021-04-26 06:54:25,2017-06-24 04:08:01,,,r;julia,Ari B. Friedman,73197,636656,registered,true,31971399,,CC BY-SA 3.0,,844,697,0,1,0,2,true,false,false,true,true,true,20,4,true,0.403,0.0085,5347,2012,4,15,Sunday,true,false,false,false,false,false,false
27433798,How can I change the Y-axis figures into percentages in a barplot?,"How can we change y axis to percent like the figure? I can change y axis range but I can't make it to percent.
![]()
",https://stackoverflow.com/questions/27433798/how-can-i-change-the-y-axis-figures-into-percentages-in-a-barplot,167,270146.0,4.0,,,2014-12-11 21:47:57,2019-05-08 20:34:53,2019-04-25 14:03:34,,,r;ggplot2;bar-chart,STAT,,,does_not_exist,true,,,,,197,112,0,0,1,3,false,false,false,true,false,true,66,12,true,0.015,0.0006,4363,2014,12,21,Thursday,false,false,false,false,false,false,false
24237399,How to select the rows with maximum values in each group with dplyr?,"I would like to select a row with maximum value in each group with dplyr.
Firstly I generate some random data to show my question
set.seed(1)
df <- expand.grid(list(A = 1:5, B = 1:5, C = 1:5))
df$value <- runif(nrow(df))
In plyr, I could use a custom function to select this row.
library(plyr)
ddply(df, .(A, B), function(x) x[which.max(x$value),])
In dplyr, I am using this code to get the maximum value, but not the rows with maximum value (Column C in this case).
library(dplyr)
df %>% group_by(A, B) %>%
summarise(max = max(value))
How could I achieve this? Thanks for any suggestion.
sessionInfo()
R version 3.1.0 (2014-04-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
locale:
[1] LC_COLLATE=English_Australia.1252 LC_CTYPE=English_Australia.1252
[3] LC_MONETARY=English_Australia.1252 LC_NUMERIC=C
[5] LC_TIME=English_Australia.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] dplyr_0.2 plyr_1.8.1
loaded via a namespace (and not attached):
[1] assertthat_0.1.0.99 parallel_3.1.0 Rcpp_0.11.1
[4] tools_3.1.0
",https://stackoverflow.com/questions/24237399/how-to-select-the-rows-with-maximum-values-in-each-group-with-dplyr,167,260421.0,6.0,,,2014-06-16 06:00:23,2020-06-22 21:49:54,2017-04-13 19:54:47,2019-04-15 08:24:34,Duplicate,r;dplyr;plyr;greatest-n-per-group,Bangyou,9886,2060292,registered,true,24237538,,,,1312,1181,4,0,0,4,true,true,false,true,true,true,68,13,true,0.023,0.0006,4541,2014,6,6,Monday,false,false,false,false,false,false,false
8991709,Why were pandas merges in python faster than data.table merges in R in 2012?,"I recently came across the pandas library for python, which according to this benchmark performs very fast in-memory merges. It's even faster than the data.table package in R (my language of choice for analysis).
Why is pandas so much faster than data.table? Is it because of an inherent speed advantage python has over R, or is there some tradeoff I'm not aware of? Is there a way to perform inner and outer joins in data.table without resorting to merge(X, Y, all=FALSE) and merge(X, Y, all=TRUE)?
![]()
Here's the R code and the Python code used to benchmark the various packages.
",https://stackoverflow.com/questions/8991709/why-were-pandas-merges-in-python-faster-than-data-table-merges-in-r-in-2012,167,22449.0,4.0,,,2012-01-24 17:59:53,2019-11-15 04:13:22,2018-07-15 07:17:10,,,python;r;join;data.table;pandas,Zach,30561,345660,registered,true,8997908,,CC BY-SA 4.0,,1199,585,5,5,1,5,true,false,false,true,true,true,76,14,true,0.178,0.0074,5415,2012,1,17,Tuesday,false,true,false,false,false,false,false
5158790,Should I use a data.frame or a matrix?,"When should one use a data.frame, and when is it better to use a matrix?
Both keep data in a rectangular format, so sometimes it's unclear.
Are there any general rules of thumb for when to use which data type?
",https://stackoverflow.com/questions/5158790/should-i-use-a-data-frame-or-a-matrix,167,101247.0,7.0,,,2011-03-01 18:36:16,2023-07-03 17:03:47,2016-03-23 14:21:54,,,r;matrix;dataframe;r-faq,microbe,2179,639884,registered,true,5159049,,CC BY-SA 3.0,,259,212,2,0,0,4,true,false,false,true,true,true,38,8,true,0.069,0.0016,5744,2011,3,18,Tuesday,false,false,false,false,false,false,false
14577412,How to convert variable (object) name into String,"I have the following data frame with variable name ""foo"";
> foo <-c(3,4);
What I want to do is to convert ""foo"" into a string. So that in a function
I don't have to recreate another extra variables:
output <- myfunc(foo)
myfunc <- function(v1) {
# do something with v1
# so that it prints ""FOO"" when
# this function is called
#
# instead of the values (3,4)
return ()
}
",https://stackoverflow.com/questions/14577412/how-to-convert-variable-object-name-into-string,167,163448.0,1.0,,,2013-01-29 07:05:01,2014-01-25 07:31:36,2014-01-25 07:31:36,2016-07-10 21:22:45,Duplicate,string;r;object,neversaint,64786,67405,registered,true,14577878,,,,517,429,4,0,0,3,true,true,false,true,true,true,49,8,false,0.006,0.001,5044,2013,1,7,Tuesday,false,false,false,false,false,false,false
3290330,facet label font size,"Is there a way to change the font size of facet labels in ggplot? I googled and found that the issue was yet on Hadley's to-do list. I wonder if there is a workaround or any news on this issue?
",https://stackoverflow.com/questions/3290330/facet-label-font-size,167,191546.0,1.0,,,2010-07-20 13:20:44,2020-01-23 15:52:32,2020-01-23 15:52:32,2019-03-11 22:37:40,Duplicate,r;ggplot2,Matt Bannert,28424,366256,registered,true,3290463,,,,214,194,1,0,0,2,true,true,false,true,true,true,21,4,false,0.005,0.0009,5968,2010,7,13,Tuesday,false,false,false,false,false,false,false
26611717,Can dplyr join on multiple columns or composite key?,"I realize that dplyr v3.0 allows you to join on different variables:
left_join(x, y, by = c(""a"" = ""b"") will match x.a to y.b
However, is it possible to join on a combination of variables or do I have to add a composite key beforehand?
Something like this:
left_join(x, y, by = c(""a c"" = ""b d"") to match the concatenation of [x.a and x.c] to [y.b and y.d]
",https://stackoverflow.com/questions/26611717/can-dplyr-join-on-multiple-columns-or-composite-key,166,278514.0,2.0,,,2014-10-28 15:07:15,2023-08-24 11:50:27,2018-07-18 15:16:28,,,r;dplyr,JasonAizkalns,20631,2572423,registered,true,26611970,,CC BY-SA 4.0,,511,359,9,0,0,2,true,false,false,true,true,true,52,9,true,0.007,0.0006,4407,2014,10,15,Tuesday,false,false,false,false,false,false,false
5251507,How to succinctly write a formula with many variables from a data frame?,"Suppose I have a response variable and a data containing three covariates (as a toy example):
y = c(1,4,6)
d = data.frame(x1 = c(4,-1,3), x2 = c(3,9,8), x3 = c(4,-4,-2))
I want to fit a linear regression to the data:
fit = lm(y ~ d$x1 + d$x2 + d$y2)
Is there a way to write the formula, so that I don't have to write out each individual covariate? For example, something like
fit = lm(y ~ d)
(I want each variable in the data frame to be a covariate.) I'm asking because I actually have 50 variables in my data frame, so I want to avoid writing out x1 + x2 + x3 + etc.
",https://stackoverflow.com/questions/5251507/how-to-succinctly-write-a-formula-with-many-variables-from-a-data-frame,165,189650.0,6.0,,,2011-03-09 20:05:23,2019-09-18 14:52:36,2017-12-06 11:41:17,,,r;dataframe;glm;lm,grautur,30575,231588,registered,true,5251676,,CC BY-SA 3.0,2017-12-06 11:40:15,691,578,4,0,0,4,true,false,false,true,true,true,72,13,true,0.032,0.0009,5736,2011,3,20,Wednesday,false,false,false,false,false,false,false
34522732,Changing fonts in ggplot2,"Once upon a time, I changed my ggplot2 font using windowsFonts(Times=windowsFont("TT Times New Roman")). Now, I can't get it off of this.
In trying to set family="" in ggplot2 theme(), I can't seem to generate a change in fonts as I compile the MWE below with different font families.
library(ggplot2)
library(extrafont)
loadfonts(device = "win")
a <- ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() +
ggtitle("Fuel Efficiency of 32 Cars") +
xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
theme(text=element_text(size=16,
# family="Comic Sans MS"))
# family="CM Roman"))
# family="TT Times New Roman"))
# family="Sans"))
family="Serif"))
print(a)
print("Graph should have refreshed")
R is returning a warning font family not found in Windows font database, but there was a tutorial I was following (if I can find it again I will update the link here) that said this was normal and not a problem. Also, somehow this worked at one point because my graph once used some arial or helvitica type font. I think this has always been a present warning even during the initial times migration.
UPDATE
when I run windowsFonts() my output is
$serif [1] "TT Times New Roman"
$sans [1] "TT Arial"
$mono [1] "TT Courier New"
But, this is after I ran font_import() so I can only conclude that my fonts are not being saved in the right place. The code that ran the font_import() request actually loads the libraries with:
LocalLibraryLocation <- paste0("C:\\Users\\",Sys.getenv("USERNAME"),"\\Documents","\\R\\win-library\\3.2");
.libPaths(c(LocalLibraryLocation, .libPaths()))
",https://stackoverflow.com/questions/34522732/changing-fonts-in-ggplot2,165,394903.0,8.0,,,2015-12-30 04:02:42,2025-07-12 12:52:01,2022-01-05 21:41:57,,,r;ggplot2;fonts;extrafont;showtext,EngBIRD,2055,4383447,registered,true,34528522,,CC BY-SA 4.0,,2090,1837,11,0,0,5,true,false,false,true,true,true,25,4,false,0.02,0.0004,3979,2015,12,4,Wednesday,false,false,false,false,false,false,false
24558328,Select the row with the maximum value in each group,"In a dataset with multiple observations for each subject. For each subject I want to select the row which have the maximum value of 'pt'. For example, with a following dataset:
ID <- c(1,1,1,2,2,2,2,3,3)
Value <- c(2,3,5,2,5,8,17,3,5)
Event <- c(1,1,2,1,2,1,2,2,2)
group <- data.frame(Subject=ID, pt=Value, Event=Event)
# Subject pt Event
# 1 1 2 1
# 2 1 3 1
# 3 1 5 2 # max 'pt' for Subject 1
# 4 2 2 1
# 5 2 5 2
# 6 2 8 1
# 7 2 17 2 # max 'pt' for Subject 2
# 8 3 3 2
# 9 3 5 2 # max 'pt' for Subject 3
Subject 1, 2, and 3 have the biggest pt value of 5, 17, and 5 respectively.
How could I first find the biggest pt value for each subject, and then, put this observation in another data frame? The resulting data frame should only have the biggest pt values for each subject.
",https://stackoverflow.com/questions/24558328/select-the-row-with-the-maximum-value-in-each-group,164,207241.0,18.0,,,2014-07-03 15:54:11,2023-04-24 07:34:30,2021-03-12 22:05:35,,,r;dataframe;r-faq,Xinting WANG,1995,2215913,registered,true,24558696,,CC BY-SA 4.0,2019-05-08 09:15:36,941,896,1,0,0,3,true,false,false,true,true,true,51,10,false,0.087,0.0008,4524,2014,7,15,Thursday,false,false,false,false,false,false,false
15347282,Split delimited strings in a column and insert as new rows,"I have a data frame as follow:
+-----+-------+
| V1 | V2 |
+-----+-------+
| 1 | a,b,c |
| 2 | a,c |
| 3 | b,d |
| 4 | e,f |
| . | . |
+-----+-------+
Each of the alphabet is a character separated by comma. I would like to split V2 on each comma and insert the split strings as new rows. For instance, the desired output will be:
+----+----+
| V1 | V2 |
+----+----+
| 1 | a |
| 1 | b |
| 1 | c |
| 2 | a |
| 2 | c |
| 3 | b |
| 3 | d |
| 4 | e |
| 4 | f |
+----+----+
I am trying to use strsplit() to spit V2 first, then cast the list into a data frame. It didn't work. Any help will be appreciated.
",https://stackoverflow.com/questions/15347282/split-delimited-strings-in-a-column-and-insert-as-new-rows,164,133179.0,6.0,,,2013-03-11 19:47:55,2018-03-26 10:06:14,2016-10-17 14:17:31,2016-07-19 10:43:55,Duplicate,r;dataframe;reshape;data-manipulation;strsplit,Boxuan,5205,2158269,registered,true,15347463,,,,730,648,3,0,0,5,true,true,false,true,true,true,58,11,false,0.045,0.0012,5003,2013,3,19,Monday,false,false,false,false,false,false,false
5293715,How to use Greek symbols in ggplot2?,"My categories need to be named with Greek letters. I am using ggplot2, and it works beautifully with the data. Unfortunately I cannot figure out how to put those greek symbols on the x axis (at the tick marks) and also make them appear in the legend. Is there any way to do it?
UPDATE:
I had a look at the link, however, there is no good method described to accomplish what I want to do.
",https://stackoverflow.com/questions/5293715/how-to-use-greek-symbols-in-ggplot2,164,204670.0,4.0,,,2011-03-14 01:02:48,2021-02-25 22:44:30,2012-04-30 13:17:51,,,r;graphics;unicode;utf-8;ggplot2,Sam,8212,402681,registered,true,5294214,,CC BY-SA 3.0,,490,394,1,1,0,5,true,false,false,true,true,true,36,7,true,0.02,0.0008,5731,2011,3,1,Monday,false,false,false,false,false,false,false
23413331,How to remove last n characters from every element in the R vector,"I am very new to R, and I could not find a simple example online of how to remove the last n characters from every element of a vector (array?)
I come from a Java background, so what I would like to do is to iterate over every element of a$data and remove the last 3 characters from every element.
How would you go about it?
",https://stackoverflow.com/questions/23413331/how-to-remove-last-n-characters-from-every-element-in-the-r-vector,164,299020.0,6.0,,,2014-05-01 17:45:33,2022-10-13 23:24:00,2018-01-22 00:35:42,,,r;string,LucasSeveryn,6472,1087852,registered,true,23413408,,CC BY-SA 3.0,,362,328,1,0,0,2,true,false,false,true,true,true,66,13,false,0.02,0.0005,4587,2014,5,17,Thursday,false,false,false,false,false,false,false
14484728,Convert a row of a data frame to vector,"I want to create a vector out of a row of a data frame. But I don't want to have to row and column names. I tried several things... but had no luck.
This is my data frame:
> df <- data.frame(a=c(1,2,4,2),b=c(2,6,2,1),c=c(2.6,8.2,7.5,3))
> df
a b c
1 1 2 2.6
2 2 6 8.2
3 4 2 7.5
4 2 1 3.0
I tried:
> newV <- as.vector(df[1,])
> newV
a b c
1 1 2 2.6
But I really want something looking like this:
> newV <- c( 1,2,2.6)
> newV
[1] 1.0 2.0 2.6
",https://stackoverflow.com/questions/14484728/convert-a-row-of-a-data-frame-to-vector,164,230050.0,7.0,,,2013-01-23 16:39:29,2024-05-17 08:03:04,2019-10-30 16:15:29,,,r;vector;dataframe,Joko,2609,2004651,registered,true,14484812,,CC BY-SA 4.0,,584,484,3,0,0,3,true,false,false,true,true,true,39,9,false,0.03,0.0007,5050,2013,1,16,Wednesday,false,false,false,false,false,false,false
4236368,Apply a function to every row of a matrix or a data frame,"Suppose I have a n by 2 matrix and a function that takes a 2-vector as one of its arguments. I would like to apply the function to each row of the matrix and get a n-vector. How to do this in R?
For example, I would like to compute the density of a 2D standard Normal distribution on three points:
bivariate.density(x = c(0, 0), mu = c(0, 0), sigma = c(1, 1), rho = 0){
exp(-1/(2*(1-rho^2))*(x[1]^2/sigma[1]^2+x[2]^2/sigma[2]^2-2*rho*x[1]*x[2]/(sigma[1]*sigma[2]))) * 1/(2*pi*sigma[1]*sigma[2]*sqrt(1-rho^2))
}
out <- rbind(c(1, 2), c(3, 4), c(5, 6))
How to apply the function to each row of out?
How to pass values for the other arguments besides the points to the function in the way you specify?
",https://stackoverflow.com/questions/4236368/apply-a-function-to-every-row-of-a-matrix-or-a-data-frame,164,328285.0,7.0,,,2010-11-21 03:59:59,2022-03-29 23:28:49,2017-11-23 20:11:02,,,r;function;matrix;apply;sapply,Tim,101336,156458,registered,true,4236383,,CC BY-SA 3.0,2017-11-23 20:11:39,778,713,2,0,0,5,true,false,false,true,true,true,57,13,false,0.021,0.0005,5844,2010,11,3,Sunday,true,false,false,false,false,false,false
13043928,Selecting data frame rows based on partial string match in a column,"I want to select rows from a data frame based on partial match of a string in a column, e.g. column 'x' contains the string "hsa". Using sqldf - if it had a like syntax - I would do something like:
select * from <> where x like 'hsa'.
Unfortunately, sqldf does not support that syntax.
Or similarly:
selectedRows <- df[ , df$x %like% "hsa-"]
Which of course doesn't work.
Can somebody please help me with this?
",https://stackoverflow.com/questions/13043928/selecting-data-frame-rows-based-on-partial-string-match-in-a-column,163,496865.0,4.0,,,2012-10-24 06:25:55,2020-10-03 18:27:44,2020-07-31 09:25:37,,,r;regex;string;match;subset,Asda,1655,1738792,registered,true,,,CC BY-SA 4.0,2024-01-09 16:34:43,568,441,5,0,0,5,false,false,false,true,true,true,67,12,false,0.008,0.0003,5141,2012,10,6,Wednesday,false,false,false,false,false,false,false
14262497,Fixing the order of facets in ggplot,"Data:
df <- data.frame(
type = c("T", "F", "P", "T", "F", "P", "T", "F", "P", "T", "F", "P"),
size = c("50%", "50%", "50%", "100%", "100%", "100%", "150%", "150%", "150%", "200%", "200%", "200%"),
amount = c(48.4, 48.1, 46.8, 25.9, 26, 24.9, 21.1, 21.4, 20.1, 20.8, 21.5, 16.5)
)
I need to plot a bargraph of the above data using ggplot (x-axis -> type, y-axis -> amount, group by size). When I used the following code, I am not getting the variable type and as well as size in the order shown in the data. Please see the figure. I have used the following code for that.
ggplot(df, aes(type, amount , fill=type, group=type, shape=type, facets=size)) +
geom_col(width=0.5, position = position_dodge(width=0.6)) +
facet_grid(.~size) +
theme_bw() +
scale_fill_manual(values = c("darkblue","steelblue1","steelblue4"),
labels = c("T", "F", "P"))
.
For fixing the order issue, I have used a factor method for the variable "type" using the following. Please see the figure also.
temp$new = factor(temp$type, levels=c("T","F","P"), labels=c("T","F","P"))
![]()
However, now I don't know how to fix the order for the variable size. It should be 50%, 100%. 150%, and 200%.
",https://stackoverflow.com/questions/14262497/fixing-the-order-of-facets-in-ggplot,163,230918.0,7.0,,,2013-01-10 16:23:14,2023-08-23 13:39:17,2021-02-25 15:52:42,,,r;ggplot2;sequence;facet,samarasa,2155,785225,registered,true,14264107,,CC BY-SA 4.0,,1945,1593,9,0,2,4,true,false,false,true,true,true,36,7,false,0.03,0.0007,5063,2013,1,16,Thursday,false,false,false,false,false,false,false
5237557,Extract every nth element of a vector,"I would like to create a vector in which each element is the i+6th element of another vector.
For example, in a vector of length 120 I want to create another vector of length 20 in which each element is value i, i+6, i+12, i+18... of the initial vector, i.e. I want to extract every 6th element of the original.
",https://stackoverflow.com/questions/5237557/extract-every-nth-element-of-a-vector,163,160709.0,7.0,,,2011-03-08 19:56:45,2025-01-17 21:58:05,2017-11-29 10:45:22,,,r;vector,ThallyHo,2833,638196,registered,true,5237650,,CC BY-SA 3.0,2017-11-29 10:44:43,353,313,2,0,0,2,true,false,false,true,true,true,37,7,false,0.044,0.001,5737,2011,3,19,Tuesday,false,false,false,false,false,false,false
25685185,Limit ggplot2 axes without removing data (outside limits): zoom,"If you specify axis limits in ggplot the outlying points are removed. This is fine for points, but you might want to plot lines that intersect with the specified range, but ggplot's range or xlim/ylim methods removes these. Is there another way to specify the plot axis range without removing outlying data?
e.g.
require(ggplot2)
d = data.frame(x=c(1,4,7,2,9,7), y=c(2,5,4,10,5,3), grp=c('a','a','b','b','c','c'))
ggplot(d, aes(x, y, group=grp)) + geom_line()
ggplot(d, aes(x, y, group=grp)) + geom_line() + scale_y_continuous(limits=c(0,7))
ggplot(d, aes(x, y, group=grp)) + geom_line() + ylim(0,7)
",https://stackoverflow.com/questions/25685185/limit-ggplot2-axes-without-removing-data-outside-limits-zoom,163,105541.0,3.0,,,2014-09-05 11:45:24,2024-04-25 12:38:58,2014-09-05 13:04:53,,,r;ggplot2;zooming;limits,geotheory,24232,1156245,registered,true,25685952,,CC BY-SA 3.0,,669,605,3,0,0,4,true,false,false,true,true,true,63,9,false,0.028,0.0015,4460,2014,9,11,Friday,false,false,false,false,false,false,false
5210535,Passing data between view controllers,"I'm new to iOS and Objective-C and the whole MVC paradigm and I'm stuck with the following:
I have a view that acts as a data entry form and I want to give the user the option to select multiple products. The products are listed on another view with a UITableViewController and I have enabled multiple selections.
How do I transfer the data from one view to another? I will be holding the selections on the UITableView in an array, but how do I then pass that back to the previous data entry form view so it can be saved along with the other data to Core Data on submission of the form?
I have surfed around and seen some people declare an array in the app delegate. I read something about singletons, but I don't understand what these are and I read something about creating a data model.
What would be the correct way of performing this and how would I go about it?
",https://stackoverflow.com/questions/5210535/passing-data-between-view-controllers,1503,535829.0,44.0,,,2011-03-06 12:43:57,2024-11-08 15:16:32,2021-02-11 17:35:52,,,ios;objective-c;swift;model-view-controller;uiviewcontroller,Matt Price,34599,634273,registered,true,9736559,,CC BY-SA 4.0,2014-03-08 22:52:05,1107,868,2,2,0,5,true,false,false,true,true,true,37,5,false,0.082,0.0028,5739,2011,3,12,Sunday,true,false,false,false,false,false,false
24002369,How do I call Objective-C code from Swift?,"In Swift, how does one call Objective-C code?
Apple mentioned that they could co-exist in one application, but does this mean that one could technically re-use old classes made in Objective-C whilst building new classes in Swift?
",https://stackoverflow.com/questions/24002369/how-do-i-call-objective-c-code-from-swift,1143,391055.0,17.0,,,2014-06-02 20:05:42,2024-04-14 15:29:24,2024-04-14 15:29:24,,,swift;objective-c,David Mulder,27102,1266242,registered,true,24005242,,CC BY-SA 4.0,2017-09-24 11:41:28,245,231,0,0,0,2,true,false,false,true,true,true,42,8,true,0.043,0.0029,4555,2014,6,20,Monday,false,false,false,false,false,false,false
17678881,How to change Status Bar text color in iOS,"My application has a dark background, but in iOS 7 the status bar became transparent. So I can't see anything there, only the green battery indicator in the corner. How can I change the status bar text color to white like it is on the home screen?
",https://stackoverflow.com/questions/17678881/how-to-change-status-bar-text-color-in-ios,1097,679561.0,61.0,,,2013-07-16 14:11:22,2024-05-29 20:57:28,2020-02-21 17:39:35,,,ios;swift;ios7;statusbar;uistatusbar,Oleksandr Veremchuk,11095,1142999,registered,true,17768797,,CC BY-SA 4.0,2014-12-18 22:13:35,255,248,0,0,0,5,true,false,false,true,true,true,42,9,false,0.09,0.0016,4876,2013,7,14,Tuesday,false,false,false,false,false,false,false
24017316,#pragma mark in Swift?,"In Objective C, I can use #pragma mark to mark sections of my code in the symbol navigator. Since this is a C preprocessor command, it's not available in Swift. Is there a stand-in for this in Swift, or do I have to use ugly comments?
",https://stackoverflow.com/questions/24017316/pragma-mark-in-swift,1022,258806.0,20.0,,,2014-06-03 14:05:56,2023-01-23 09:46:47,2019-12-20 14:03:57,,,swift;documentation,Arbitur,39103,1296280,registered,true,24037870,,CC BY-SA 4.0,2016-10-01 12:31:46,255,235,1,0,0,2,true,false,false,true,true,true,22,4,true,0.077,0.0039,4554,2014,6,14,Tuesday,false,false,false,false,false,false,false
24101718,Swift Beta performance: sorting arrays,"I was implementing an algorithm in Swift Beta and noticed that the performance was very poor. After digging deeper I realized that one of the bottlenecks was something as simple as sorting arrays. The relevant part is here:
let n = 1000000
var x = [Int](repeating: 0, count: n)
for i in 0..<n {
x[i] = random()
}
// start clock here
let y = sort(x)
// stop clock here
In C++, a similar operation takes 0.06s on my computer.
In Python, it takes 0.6s (no tricks, just y = sorted(x) for a list of integers).
In Swift it takes 6s if I compile it with the following command:
xcrun swift -O3 -sdk `xcrun --show-sdk-path --sdk macosx`
And it takes as much as 88s if I compile it with the following command:
xcrun swift -O0 -sdk `xcrun --show-sdk-path --sdk macosx`
Timings in Xcode with ""Release"" vs. ""Debug"" builds are similar.
What is wrong here? I could understand some performance loss in comparison with C++, but not a 10-fold slowdown in comparison with pure Python.
Edit: weather noticed that changing -O3 to -Ofast makes this code run almost as fast as the C++ version! However, -Ofast changes the semantics of the language a lot — in my testing, it disabled the checks for integer overflows and array indexing overflows. For example, with -Ofast the following Swift code runs silently without crashing (and prints out some garbage):
let n = 10000000
print(n*n*n*n*n)
let x = [Int](repeating: 10, count: n)
print(x[n])
So -Ofast is not what we want; the whole point of Swift is that we have the safety nets in place. Of course, the safety nets have some impact on the performance, but they should not make the programs 100 times slower. Remember that Java already checks for array bounds, and in typical cases, the slowdown is by a factor much less than 2. And in Clang and GCC we have got -ftrapv for checking (signed) integer overflows, and it is not that slow, either.
Hence the question: how can we get reasonable performance in Swift without losing the safety nets?
Edit 2: I did some more benchmarking, with very simple loops along the lines of
for i in 0..<n {
x[i] = x[i] ^ 12345678
}
(Here the xor operation is there just so that I can more easily find the relevant loop in the assembly code. I tried to pick an operation that is easy to spot but also ""harmless"" in the sense that it should not require any checks related to integer overflows.)
Again, there was a huge difference in the performance between -O3 and -Ofast. So I had a look at the assembly code:
With -Ofast I get pretty much what I would expect. The relevant part is a loop with 5 machine language instructions.
With -O3 I get something that was beyond my wildest imagination. The inner loop spans 88 lines of assembly code. I did not try to understand all of it, but the most suspicious parts are 13 invocations of ""callq _swift_retain"" and another 13 invocations of ""callq _swift_release"". That is, 26 subroutine calls in the inner loop!
Edit 3: In comments, Ferruccio asked for benchmarks that are fair in the sense that they do not rely on built-in functions (e.g. sort). I think the following program is a fairly good example:
let n = 10000
var x = [Int](repeating: 1, count: n)
for i in 0..<n {
for j in 0..<n {
x[i] = x[j]
}
}
There is no arithmetic, so we do not need to worry about integer overflows. The only thing that we do is just lots of array references. And the results are here—Swift -O3 loses by a factor almost 500 in comparison with -Ofast:
- C++ -O3: 0.05 s
- C++ -O0: 0.4 s
- Java: 0.2 s
- Python with PyPy: 0.5 s
- Python: 12 s
- Swift -Ofast: 0.05 s
- Swift -O3: 23 s
- Swift -O0: 443 s
(If you are concerned that the compiler might optimize out the pointless loops entirely, you can change it to e.g. x[i] ^= x[j], and add a print statement that outputs x[0]. This does not change anything; the timings will be very similar.)
And yes, here the Python implementation was a stupid pure Python implementation with a list of ints and nested for loops. It should be much slower than unoptimized Swift. Something seems to be seriously broken with Swift and array indexing.
Edit 4: These issues (as well as some other performance issues) seems to have been fixed in Xcode 6 beta 5.
For sorting, I now have the following timings:
- clang++ -O3: 0.06 s
- swiftc -Ofast: 0.1 s
- swiftc -O: 0.1 s
- swiftc: 4 s
For nested loops:
- clang++ -O3: 0.06 s
- swiftc -Ofast: 0.3 s
- swiftc -O: 0.4 s
- swiftc: 540 s
It seems that there is no reason anymore to use the unsafe -Ofast (a.k.a. -Ounchecked); plain -O produces equally good code.
",https://stackoverflow.com/questions/24101718/swift-beta-performance-sorting-arrays,990,120414.0,9.0,,,2014-06-07 23:53:45,2020-04-19 16:54:39,2019-02-08 12:29:16,,,swift;performance;sorting;xcode6;compiler-optimization,Jukka Suomela,12467,383299,registered,true,24102237,,CC BY-SA 4.0,2014-06-12 12:23:05,5551,4582,21,0,0,5,true,false,false,true,true,true,38,5,false,0.075,0.0082,4550,2014,6,23,Saturday,true,false,false,false,false,false,false
24028421,How to iterate a loop with index and element in Swift,"Is there a function that I can use to iterate over an array and have both index and element, like Python's enumerate?
for index, element in enumerate(list):
...
",https://stackoverflow.com/questions/24028421/how-to-iterate-a-loop-with-index-and-element-in-swift,979,704889.0,21.0,,,2014-06-04 03:19:21,2025-11-12 12:36:58,2020-09-16 11:23:24,,,arrays;swift;enumeration,thinker3,13441,1890537,registered,true,24028458,,CC BY-SA 4.0,2020-01-06 16:06:59,210,166,2,0,0,3,true,false,false,true,true,true,53,11,false,0.03,0.0014,4553,2014,6,3,Wednesday,false,false,false,false,false,false,false
24003291,#ifdef replacement in the Swift language,"In C/C++/Objective C you can define a macro using compiler preprocessors.
Moreover, you can include/exclude some parts of code using compiler preprocessors.
#ifdef DEBUG
// Debug-only code
#endif
Is there a similar solution in Swift?
",https://stackoverflow.com/questions/24003291/ifdef-replacement-in-the-swift-language,887,362208.0,19.0,,,2014-06-02 21:06:37,2026-04-06 19:16:33,2021-08-13 12:25:57,,,swift;xcode;preprocessor;preprocessor-directive,mxg,21264,193718,registered,true,,,CC BY-SA 4.0,2019-07-29 16:31:35,315,239,1,0,0,4,false,false,false,true,true,true,40,6,false,0.052,0.0024,4555,2014,6,21,Monday,false,false,false,false,false,false,false
24037711,Get the length of a String,"How do you get the length of a String? For example, I have a variable defined like:
var test1: String = ""Scott""
However, I can't seem to find a length method on the string.
",https://stackoverflow.com/questions/24037711/get-the-length-of-a-string,845,549984.0,41.0,,,2014-06-04 12:40:01,2025-11-12 12:43:49,2023-10-13 01:07:39,,,swift;string,Scott Walter,9502,1561363,registered,true,24037756,,CC BY-SA 4.0,2018-12-20 04:41:42,227,176,2,0,0,2,true,false,false,true,true,true,26,6,false,0.075,0.0015,4553,2014,6,12,Wednesday,false,false,false,false,false,false,false
25678373,Split a String into an array in Swift?,"Say I have a string here:
var fullName: String = "First Last"
I want to split the string based on whitespace and assign the values to their respective variables
var fullNameArr = // something like: fullName.explode(" ")
var firstName: String = fullNameArr[0]
var lastName: String? = fullnameArr[1]
Also, sometimes users might not have a last name.
",https://stackoverflow.com/questions/25678373/split-a-string-into-an-array-in-swift,844,832264.0,41.0,,,2014-09-05 03:51:01,2024-04-15 17:47:58,2024-03-14 12:00:24,,,arrays;swift;string;split,blee908,12655,1022768,registered,true,26270721,,CC BY-SA 4.0,2018-10-19 11:52:22,441,372,2,0,0,4,true,false,false,true,true,true,38,8,true,0.049,0.001,4460,2014,9,3,Friday,false,false,false,false,false,false,false
30790188,How do I see which version of Swift I'm using?,"I just created a new Swift project within Xcode. I am wondering which version of Swift it's using.
How can I see, in Xcode or the terminal, what version of Swift I am using inside my project?
",https://stackoverflow.com/questions/30790188/how-do-i-see-which-version-of-swift-im-using,762,326179.0,19.0,,,2015-06-11 19:52:21,2024-06-25 21:39:06,2018-04-07 22:32:42,,,swift;xcode;terminal,David Snabel,10139,1854064,registered,true,46080904,,CC BY-SA 3.0,,208,194,0,0,0,3,true,false,false,true,true,true,50,10,true,0.058,0.0023,4181,2015,6,19,Thursday,false,false,false,false,false,false,false
24007650,@selector() in Swift?,"I'm trying to create an NSTimer in Swift but I'm having some trouble.
NSTimer(timeInterval: 1, target: self, selector: test(), userInfo: nil, repeats: true)
test() is a function in the same class.
I get an error in the editor:
Could not find an overload for 'init' that accepts the supplied
arguments
When I change selector: test() to selector: nil the error disappears.
I've tried:
selector: test()
selector: test
selector: Selector(test())
But nothing works and I can't find a solution in the references.
",https://stackoverflow.com/questions/24007650/selector-in-swift,697,358731.0,24.0,,,2014-06-03 05:21:43,2022-02-08 11:25:23,2016-05-11 09:06:56,,,swift;selector;nstimer,Arbitur,39103,1296280,registered,true,24007718,,CC BY-SA 3.0,2015-03-01 21:02:42,778,527,9,0,0,3,true,false,false,true,true,true,21,3,true,0.067,0.0019,4554,2014,6,5,Tuesday,false,false,false,false,false,false,false
25770119,iOS 8 UITableView separator inset 0 not working,"I have an app where the UITableView's separator inset is set to custom values - Right 0, Left 0. This works perfectly in iOS 7.x, however in iOS 8.0 I see that the separator inset is set to the default of 15 on the right. Even though in the xib files it set to 0, it still shows up incorrectly.
How do I remove the UITableViewCell separator margins?
",https://stackoverflow.com/questions/25770119/ios-8-uitableview-separator-inset-0-not-working,688,188652.0,43.0,,,2014-09-10 16:05:38,2020-04-29 16:49:43,2017-05-25 18:12:02,,,ios;objective-c;swift;uitableview;ios8,user3570727,10233,3570727,registered,true,25877725,,CC BY-SA 3.0,,469,351,8,0,0,5,true,false,false,true,true,true,47,8,false,0.228,0.0036,4455,2014,9,16,Wednesday,false,false,false,false,false,false,false
24161336,Convert Int to String in Swift,"I'm trying to work out how to cast an Int into a String in Swift.
I figure out a workaround, using NSNumber but I'd love to figure out how to do it all in Swift.
let x : Int = 45
let xNSNumber = x as NSNumber
let xString : String = xNSNumber.stringValue
",https://stackoverflow.com/questions/24161336/convert-int-to-string-in-swift,687,780404.0,23.0,,,2014-06-11 11:05:26,2022-02-07 08:33:32,2015-07-18 10:40:56,,,string;casting;int;converters;swift,Steve Marshall,8179,3729694,registered,true,24161392,,CC BY-SA 3.0,2016-09-12 09:11:22,334,257,4,0,0,5,true,false,false,true,true,true,30,6,false,0.029,0.0009,4546,2014,6,11,Wednesday,false,false,false,false,false,false,false
24333981,"iOS app with framework crashed on device, dyld: Library not loaded, Xcode 6 Beta","This crash has been a blocking issue I used the following steps to reproduce the issue:
- Create a Cocoa Touch Framework project
- Add a swift file and a class Dog
- Build a framework for device
- Create a Single View application in Swift
- Import framework into app project
- Instantiate swift class from the framework in ViewController
- Build and run an app on the device
The app immediate crashed upon launching, here is console log:
dyld: Library not loaded: @rpath/FrameworkTest03.framework/FrameworkTest03
Referenced from: /var/mobile/Applications/FA6BAAC8-1AAD-49B4-8326-F30F66458CB6/FrameworkTest03App.app/FrameworkTest03App
Reason: image not found
I have tried to build on iOS 7.1 and 8.0 devices, they both have the same crash. However, I can build an app and run on the simulator fine. Also, I am aware that I can change the framework to form Required to Optional in Link Binary With Libraries, but it did not completely resolve the problem, the app crashed when I create an instance of Dog. The behavior is different on the device and simulator, I suspect that we can't distribute a framework for the device using a beta version of Xcode. Can anyone shed light on this?
",https://stackoverflow.com/questions/24333981/ios-app-with-framework-crashed-on-device-dyld-library-not-loaded-xcode-6-beta,676,380023.0,34.0,,,2014-06-20 19:00:40,2023-11-12 18:54:29,2022-09-27 11:37:03,,,ios;swift;frameworks;dyld;dynamic-library,vladof81,26569,2920335,registered,true,24345546,,CC BY-SA 4.0,2015-04-16 15:47:42,1342,1180,1,0,0,5,true,false,false,true,true,true,80,14,false,0.089,0.0018,4537,2014,6,19,Friday,false,false,false,false,false,false,false
24034043,How do I check if a string contains another string in Swift?,"In Objective-C the code to check for a substring in an NSString is:
NSString *string = @""hello Swift"";
NSRange textRange =[string rangeOfString:@""Swift""];
if(textRange.location != NSNotFound)
{
NSLog(@""exists"");
}
But how do I do this in Swift?
",https://stackoverflow.com/questions/24034043/how-do-i-check-if-a-string-contains-another-string-in-swift,665,623088.0,29.0,,,2014-06-04 09:43:33,2025-02-22 12:46:40,2019-05-19 14:42:28,,,swift;string;nsstring;substring,Rajneesh071,31127,1369972,registered,true,24161872,,CC BY-SA 4.0,2020-04-25 10:36:06,317,253,3,0,0,4,true,false,false,true,true,true,60,12,true,0.047,0.0011,4553,2014,6,9,Wednesday,false,false,false,false,false,false,false
24130026,How to sort an array of custom objects by property value?,"Let's say we have a custom class named ImageFile and this class contains two properties:
class ImageFile {
var fileName = String()
var fileID = Int()
}
Lots of them are stored in an Array:
var images : Array = []
var aImage = ImageFile()
aImage.fileName = "image1.png"
aImage.fileID = 101
images.append(aImage)
aImage = ImageFile()
aImage.fileName = "image1.png"
aImage.fileID = 202
images.append(aImage)
How can I sort the images array by 'fileID' in ascending or descending order?
",https://stackoverflow.com/questions/24130026/how-to-sort-an-array-of-custom-objects-by-property-value,664,516916.0,20.0,,,2014-06-09 22:27:01,2024-04-29 16:51:08,2024-04-29 16:51:08,,,arrays;sorting;swift,modusCell,13449,544075,registered,true,24130092,,CC BY-SA 4.0,,597,515,3,0,0,3,true,false,false,true,true,true,57,11,true,0.039,0.0013,4548,2014,6,22,Monday,false,false,false,false,false,false,false
7010547,UITextField text change event,"How can I detect any text changes in a textField? The delegate method shouldChangeCharactersInRange works for something, but it did not fulfill my need exactly. Since until it returns YES, the textField texts are not available to other observer methods.
e.g. in my code calculateAndUpdateTextFields did not get the updated text, the user has typed.
Is their any way to get something like textChanged Java event handler.
- (BOOL)textField:(UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string
{
if (textField.tag == kTextFieldTagSubtotal
|| textField.tag == kTextFieldTagSubtotalDecimal
|| textField.tag == kTextFieldTagShipping
|| textField.tag == kTextFieldTagShippingDecimal)
{
[self calculateAndUpdateTextFields];
}
return YES;
}
",https://stackoverflow.com/questions/7010547/uitextfield-text-change-event,646,424972.0,22.0,,,2011-08-10 12:09:41,2024-04-25 14:32:11,2016-09-07 05:26:06,,,ios;objective-c;swift;event-handling;uitextfielddelegate,karim,15599,312627,registered,true,7010676,,CC BY-SA 3.0,,956,872,4,0,0,5,true,false,false,true,true,true,29,4,false,0.052,0.0015,5582,2011,8,12,Wednesday,false,false,false,false,false,false,false
19036228,UIScrollView Scrollable Content Size Ambiguity,"Fellow devs,
I am having trouble with AutoLayout in Interface Builder (Xcode 5 / iOS 7).
It's very basic and important so I think everyone should know how this properly works. If this is a bug in Xcode, it is a critical one!
So, whenever I have a view hierarchy such as this I run into trouble:
>UIViewController
>> UIView
>>>UIScrollView
>>>>UILabel (or any other comparable UIKit Element)
The UIScrollView has solid constraints, e.g., 50 px from every side (no problem).
Then I add a Top Space constraint to the UILabel (no problem) (and I can even pin height / width of the label, changes nothing, but should be unneccessary due to the Label's intrinsic size)
The trouble starts when I add a trailing constraint to the UILabel:
E.g., Trailing Space to: Superview Equals: 25
Now two warnings occur - and I don't understand why:
A) Scrollable Content Size Ambiguity (Scroll View has ambiguous scrollable content height/width)
B) Misplaced Views (Label Expected: x= -67 Actual: x= 207
I did this minimal example in a freshly new project which you can download and I attached a screenshot. As you can see, Interface Builder expects the Label to sit outside of the UIScrollView's boundary (the orange dashed rectangle). Updating the Label's frame with the Resolve Issues Tool moves it right there.
Please note: If you replace the UIScrollView with a UIView, the behaviour is as expected (the Label's frame is correct and according to the constraint). So there seems to either be an issue with UIScrollView or I am missing out on something important.
When I run the App without updating the Label's frame as suggested by IB it is positioned just fine, exactly where it's supposed to be and the UIScrollView is scrollable.
If I DO update the frame the Label is out of sight and the UIScrollView does not scroll.
Help me Obi-Wan Kenobi! Why the ambiguous layout? Why the misplaced view?
You can download the sample project here and try if you can figure out what's going on:
https://github.com/Wirsing84/AutoLayoutProblem
![]()
",https://stackoverflow.com/questions/19036228/uiscrollview-scrollable-content-size-ambiguity,628,374997.0,35.0,,,2013-09-26 18:45:38,2024-03-07 21:15:41,2018-03-28 16:17:53,,,ios;swift;uiscrollview;autolayout;interface-builder,Wirsing,6803,1165401,registered,true,27227174,,CC BY-SA 3.0,,2429,2063,1,1,1,5,true,false,false,true,true,true,46,5,false,0.093,0.0017,4804,2013,9,18,Thursday,false,false,false,false,false,false,false
24001778,Do Swift-based applications work on OS X 10.9/iOS 7 and lower?,"Will Swift-based applications work on OS X 10.9 (Mavericks)/iOS 7 and lower?
For example, I have a machine running OS X 10.8 (Mountain Lion), and I am wondering if an application I write in Swift will run on it.
Or what should I have to create a Swift application using Mac OS?
",https://stackoverflow.com/questions/24001778/do-swift-based-applications-work-on-os-x-10-9-ios-7-and-lower,627,111701.0,19.0,,,2014-06-02 19:25:57,2024-03-21 08:29:30,2020-11-02 08:48:39,,,swift;xcode;macos,MeIr,7336,635610,registered,true,24002461,,CC BY-SA 4.0,2014-09-07 22:54:40,453,278,0,2,0,3,true,false,false,true,true,true,62,11,true,0.17,0.0056,4555,2014,6,19,Monday,false,false,false,false,false,false,false
24007461,How to enumerate an enum with String type?,"enum Suit: String {
case spades = ""♠""
case hearts = ""♥""
case diamonds = ""♦""
case clubs = ""♣""
}
For example, how can I do something like:
for suit in Suit {
// do something with suit
print(suit.rawValue)
}
Resulting example:
♠
♥
♦
♣
",https://stackoverflow.com/questions/24007461/how-to-enumerate-an-enum-with-string-type,615,335359.0,42.0,,,2014-06-03 05:03:13,2020-08-20 09:02:52,2017-12-07 15:57:37,,,swift;string;enums;enumerate,Lucien,8413,438063,registered,true,49588446,,CC BY-SA 3.0,2018-06-19 05:17:24,349,263,3,0,0,4,true,false,false,true,true,true,42,8,true,0.125,0.0018,4554,2014,6,5,Tuesday,false,false,false,false,false,false,false
24066304,How can I make a weak protocol reference in 'pure' Swift (without @objc),"weak references don't seem to work in Swift unless a protocol is declared as @objc, which I don't want in a pure Swift app.
This code gives a compile error (weak cannot be applied to non-class type MyClassDelegate):
class MyClass {
weak var delegate: MyClassDelegate?
}
protocol MyClassDelegate {
}
I need to prefix the protocol with @objc, then it works.
Question: What is the 'pure' Swift way to accomplish a weak delegate?
",https://stackoverflow.com/questions/24066304/how-can-i-make-a-weak-protocol-reference-in-pure-swift-without-objc,604,141765.0,8.0,,,2014-06-05 17:16:54,2025-03-12 12:22:14,2018-01-02 02:17:16,,,swift;delegates;swift-protocols,hnh,14985,2203005,registered,true,24104371,,CC BY-SA 3.0,,590,434,9,0,0,3,true,false,false,true,true,true,80,13,false,0.056,0.0043,4552,2014,6,17,Thursday,false,false,false,false,false,false,false
24200888,Swift - How to replace characters in a String?,"I am looking for a way to replace characters in a Swift String.
In this example String: "This is my string"
I would like to replace the spaces, " ", with "+" to end up with "This+is+my+string".
How can I achieve this?
",https://stackoverflow.com/questions/24200888/swift-how-to-replace-characters-in-a-string,601,546858.0,24.0,,,2014-06-13 08:28:39,2025-12-29 16:37:56,2024-11-12 21:38:02,,,swift;string;replace,user3332801,6113,3332801,registered,true,24201206,,CC BY-SA 4.0,,351,258,5,0,0,3,true,false,false,true,true,true,46,9,true,0.044,0.0011,4544,2014,6,8,Friday,false,false,false,false,false,false,false
24024549,Using a dispatch_once singleton model in Swift,"I'm trying to work out an appropriate singleton model for usage in Swift. So far, I've been able to get a non-thread safe model working as:
class var sharedInstance: TPScopeManager {
get {
struct Static {
static var instance: TPScopeManager? = nil
}
if !Static.instance {
Static.instance = TPScopeManager()
}
return Static.instance!
}
}
Wrapping the singleton instance in the Static struct should allow a single instance that doesn't collide with singleton instances without complex naming schemings, and it should make things fairly private. Obviously though, this model isn't thread-safe. So I tried to add dispatch_once to the whole thing:
class var sharedInstance: TPScopeManager {
get {
struct Static {
static var instance: TPScopeManager? = nil
static var token: dispatch_once_t = 0
}
dispatch_once(Static.token) { Static.instance = TPScopeManager() }
return Static.instance!
}
}
But I get a compiler error on the dispatch_once line:
Cannot convert the expression's type 'Void' to type '()'
I've tried several different variants of the syntax, but they all seem to have the same results:
dispatch_once(Static.token, { Static.instance = TPScopeManager() })
What is the proper usage of dispatch_once using Swift? I initially thought the problem was with the block due to the () in the error message, but the more I look at it, the more I think it may be a matter of getting the dispatch_once_t correctly defined.
",https://stackoverflow.com/questions/24024549/using-a-dispatch-once-singleton-model-in-swift,598,140820.0,30.0,,,2014-06-03 20:41:12,2020-08-03 10:34:09,2019-11-27 19:44:18,,,swift;singleton;dispatch,David Berry,41347,3203487,registered,true,24147830,,CC BY-SA 4.0,2014-07-21 22:01:52,1776,1572,8,0,0,3,true,false,false,true,true,true,46,7,false,0.213,0.0042,4554,2014,6,20,Tuesday,false,false,false,false,false,false,false
24102024,How to check if an element is in an array,"In Swift, how can I check if an element exists in an array? Xcode does not have any suggestions for contain, include, or has, and a quick search through the book turned up nothing. Any idea how to check for this? I know that there is a method find that returns the index number, but is there a method that returns a boolean like ruby's #include??
Example of what I need:
var elements = [1,2,3,4,5]
if elements.contains(5) {
//do something
}
",https://stackoverflow.com/questions/24102024/how-to-check-if-an-element-is-in-an-array,588,600704.0,18.0,,,2014-06-08 00:52:11,2022-05-27 14:45:02,2016-10-20 11:46:24,,,arrays;swift,jaredsmith,7613,1956721,registered,true,25391725,,CC BY-SA 3.0,2018-06-11 00:42:22,549,446,6,0,0,2,true,false,false,true,true,true,41,10,false,0.03,0.001,4549,2014,6,0,Sunday,true,false,false,false,false,false,false
25965239,How do I get the App version and build number using Swift?,"I have an IOS app with an Azure back-end, and would like to log certain events, like logins and which versions of the app users are running.
How can I return the version and build number using Swift?
",https://stackoverflow.com/questions/25965239/how-do-i-get-the-app-version-and-build-number-using-swift,585,317477.0,34.0,,,2014-09-22 00:29:49,2025-03-07 16:36:45,,,,ios;swift,Øyvind Vik,6317,3412502,registered,true,26011822,,CC BY-SA 3.0,2016-08-27 04:09:10,215,201,0,0,0,2,true,false,false,true,true,false,58,12,true,0.107,0.0018,4443,2014,9,0,Monday,false,false,false,false,false,false,false
24034544,dispatch_after - GCD in Swift?,"I've gone through the iBook from Apple, and couldn't find any definition of it:
Can someone explain the structure of dispatch_after?
dispatch_after(<#when: dispatch_time_t#>, <#queue: dispatch_queue_t?#>, <#block: dispatch_block_t?#>)
",https://stackoverflow.com/questions/24034544/dispatch-after-gcd-in-swift,584,297662.0,26.0,,,2014-06-04 10:05:19,2021-05-07 22:39:10,2020-02-19 22:43:57,,,objective-c;swift;grand-central-dispatch,Kumar KL,15325,1127619,registered,true,24034838,,CC BY-SA 4.0,2015-02-09 13:07:55,503,256,2,1,0,3,true,false,false,true,true,true,30,5,true,0.087,0.002,4553,2014,6,10,Wednesday,false,false,false,false,false,false,false
43618487,Why are emoji characters like 👩👩👧👦 treated so strangely in Swift strings?,"The character 👩👩👧👦 (family with two women, one girl, and one boy) is encoded as such:
U+1F469 WOMAN,
U+200D ZWJ,
U+1F469 WOMAN,
U+200D ZWJ,
U+1F467 GIRL,
U+200D ZWJ,
U+1F466 BOY
So it's very interestingly-encoded; the perfect target for a unit test. However, Swift doesn't seem to know how to treat it. Here's what I mean:
"👩👩👧👦".contains("👩👩👧👦") // true
"👩👩👧👦".contains("👩") // false
"👩👩👧👦".contains("\u{200D}") // false
"👩👩👧👦".contains("👧") // false
"👩👩👧👦".contains("👦") // true
So, Swift says it contains itself (good) and a boy (good!). But it then says it does not contain a woman, girl, or zero-width joiner. What's happening here? Why does Swift know it contains a boy but not a woman or girl? I could understand if it treated it as a single character and only recognized it containing itself, but the fact that it got one subcomponent and no others baffles me.
This does not change if I use something like "👩".characters.first!.
Even more confounding is this:
let manual = "\u{1F469}\u{200D}\u{1F469}\u{200D}\u{1F467}\u{200D}\u{1F466}"
Array(manual.characters) // ["👩", "👩", "👧", "👦"]
Even though I placed the ZWJs in there, they aren't reflected in the character array. What followed was a little telling:
manual.contains("👩") // false
manual.contains("👧") // false
manual.contains("👦") // true
So I get the same behavior with the character array... which is supremely annoying, since I know what the array looks like.
This also does not change if I use something like "👩".characters.first!.
",https://stackoverflow.com/questions/43618487/why-are-emoji-characters-like-treated-so-strangely-in-swift-strings,583,39587.0,6.0,,,2017-04-25 18:36:28,2026-06-24 07:40:11,2026-06-24 07:40:11,,,swift;string;unicode;emoji,Ky -,32517,453435,registered,true,43619065,,CC BY-SA 4.0,2026-06-24 17:40:45,2501,1731,19,4,0,4,true,false,false,true,true,true,108,12,true,0.152,0.0147,3497,2017,4,18,Tuesday,false,false,false,false,false,false,false
25951195,Swift: print() vs println() vs NSLog(),"What's the difference between print, NSLog and println and when should I use each?
For example, in Python if I wanted to print a dictionary, I'd just print myDict, but now I have 2 other options. How and when should I use each?
",https://stackoverflow.com/questions/25951195/swift-print-vs-println-vs-nslog,582,442230.0,6.0,,,2014-09-20 16:59:14,2024-02-03 03:49:25,2022-01-06 15:07:31,,,swift;debugging;logging;console;oslog,User,24959,2199852,registered,true,25951564,,CC BY-SA 4.0,2015-11-04 15:44:19,295,229,4,0,0,5,true,false,false,true,true,true,38,6,false,0.014,0.0013,4445,2014,9,16,Saturday,true,false,false,false,false,false,false
29500227,"Getting error "No such module" using Xcode, but the framework is there","I'm currently coding in Swift, and I've got an error:
No such module Social
But I don't understand, because the module is in my project, declared in ""Linked frameworks and Libraries"" and in ""Embedded Binaries"".
The frameworks is in Objective-C, so I wrote a Bridge Header for it.
Please, how can I make Xcode recognize the framework?
![]()
![]()
![]()
![]()
",https://stackoverflow.com/questions/29500227/getting-error-no-such-module-using-xcode-but-the-framework-is-there,579,859130.0,92.0,,,2015-04-07 19:59:32,2025-05-24 19:53:08,2024-03-23 02:06:06,,,ios;swift;flutter;xcode,alexandresecanove,6275,4714492,registered,true,31077255,,CC BY-SA 4.0,2018-05-08 23:02:08,698,350,0,0,4,4,true,false,false,true,true,true,80,12,false,0.107,0.0007,4246,2015,4,19,Tuesday,false,false,false,false,false,false,false
26180822,How to add constraints programmatically using Swift,"I'm trying to figure this out since last week without going any step further. Ok, so I need to apply some constraints programmatically in Swift to a UIView using this code:
var new_view:UIView! = UIView(frame: CGRectMake(0, 0, 100, 100));
new_view.backgroundColor = UIColor.redColor();
view.addSubview(new_view);
var constX:NSLayoutConstraint = NSLayoutConstraint(item: new_view, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0);
self.view.addConstraint(constX);
var constY:NSLayoutConstraint = NSLayoutConstraint(item: new_view, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0);
self.view.addConstraint(constY);
var constW:NSLayoutConstraint = NSLayoutConstraint(item: new_view, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: new_view, attribute: NSLayoutAttribute.Width, multiplier: 1, constant: 0);
self.view.addConstraint(constW);
var constH:NSLayoutConstraint = NSLayoutConstraint(item: new_view, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: new_view, attribute: NSLayoutAttribute.Height, multiplier: 1, constant: 0);
self.view.addConstraint(constH);
But Xcode returns this weird output:
2014-10-03 09:48:12.657 Test[35088:2454916] Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
(
""<NSLayoutConstraint:0x7fa4ea446830 UIView:0x7fa4ea429290.centerX == UIView:0x7fa4ea4470f0.centerX>"",
""<NSAutoresizingMaskLayoutConstraint:0x7fa4ea4516c0 h=--& v=--& UIView:0x7fa4ea429290.midX == + 50>"",
""<NSLayoutConstraint:0x7fa4ea452830 'UIView-Encapsulated-Layout-Width' H:[UIView:0x7fa4ea4470f0(375)]>"",
""<NSAutoresizingMaskLayoutConstraint:0x7fa4ea446db0 h=-&- v=-&- 'UIView-Encapsulated-Layout-Left' H:|-(0)-[UIView:0x7fa4ea4470f0] (Names: '|':UIWindow:0x7fa4ea444b20 )>""
)
Will attempt to recover by breaking constraint <NSLayoutConstraint:0x7fa4ea446830 UIView:0x7fa4ea429290.centerX == UIView:0x7fa4ea4470f0.centerX>
Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger. The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in
<UIKit/UIView.h> may also be helpful.
2014-10-03 09:48:12.658 Test[35088:2454916] Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
(
""<NSLayoutConstraint:0x7fa4ea44d160 UIView:0x7fa4ea429290.centerY == UIView:0x7fa4ea4470f0.centerY>"",
""<NSAutoresizingMaskLayoutConstraint:0x7fa4ea451b30 h=--& v=--& UIView:0x7fa4ea429290.midY == + 50>"",
""<NSLayoutConstraint:0x7fa4ea44cf00 'UIView-Encapsulated-Layout-Height' V:[UIView:0x7fa4ea4470f0(667)]>"",
""<NSAutoresizingMaskLayoutConstraint:0x7fa4ea452700 h=-&- v=-&- 'UIView-Encapsulated-Layout-Top' V:|-(0)-[UIView:0x7fa4ea4470f0] (Names: '|':UIWindow:0x7fa4ea444b20 )>""
)
Will attempt to recover by breaking constraint <NSLayoutConstraint:0x7fa4ea44d160 UIView:0x7fa4ea429290.centerY == UIView:0x7fa4ea4470f0.centerY>
Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger. The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
Can you help me?
Thanks a lot
",https://stackoverflow.com/questions/26180822/how-to-add-constraints-programmatically-using-swift,573,706550.0,19.0,,,2014-10-03 14:25:22,2025-03-07 10:16:01,2018-08-08 19:18:49,,,ios;swift;uiview;autolayout;nslayoutconstraint,Sara Canducci,6301,3588489,registered,true,,,CC BY-SA 4.0,,4413,4271,3,0,0,5,false,false,false,true,true,true,51,7,false,0.027,0.0008,4432,2014,10,14,Friday,false,false,false,false,false,false,false
26028918,How to determine the current iPhone/device model?,"Is there a way to get the device model name (iPhone 4S, iPhone 5, iPhone 5S, etc) in Swift?
I know there is a property named UIDevice.currentDevice().model but it only returns device type (iPod touch, iPhone, iPad, iPhone Simulator, etc).
I also know it can be done easily in Objective-C with this method:
#import <sys/utsname.h>
struct utsname systemInfo;
uname(&systemInfo);
NSString* deviceModel = [NSString stringWithCString:systemInfo.machine
encoding:NSUTF8StringEncoding];
But I'm developing my iPhone app in Swift. What is the equivalent way to solve this in Swift?
",https://stackoverflow.com/questions/26028918/how-to-determine-the-current-iphone-device-model,569,445144.0,33.0,,,2014-09-25 01:08:01,2026-09-15 14:42:55,2025-12-29 00:49:45,,,ios;swift;iphone,The Mach System,7033,2640210,registered,true,26962452,,CC BY-SA 4.0,2018-07-13 23:17:47,678,613,2,0,0,3,true,false,false,true,true,true,49,7,true,0.074,0.0013,4440,2014,9,1,Thursday,false,false,false,false,false,false,false
24232799,Why Choose Struct Over Class?,"Playing around with Swift, coming from a Java background, why would you want to choose a Struct instead of a Class? Seems like they are the same thing, with a Struct offering less functionality. Why choose it then?
",https://stackoverflow.com/questions/24232799/why-choose-struct-over-class,569,197359.0,17.0,,,2014-06-15 18:33:02,2026-05-11 06:33:07,2023-06-06 14:02:58,,,swift;class;struct;value-type;design-principles,bluedevil2k,9501,414408,registered,true,24232845,,CC BY-SA 4.0,2020-07-10 11:49:58,224,217,0,0,0,5,true,false,false,true,true,true,29,5,true,0.086,0.0029,4542,2014,6,18,Sunday,true,false,false,false,false,false,false
24022479,How would I create a UIAlertView in Swift?,"I have been working to create a UIAlertView in Swift, but for some reason I can't get the statement right because I'm getting this error:
Could not find an overload for 'init' that accepts the supplied
arguments
Here is how I have it written:
let button2Alert: UIAlertView = UIAlertView(title: ""Title"", message: ""message"",
delegate: self, cancelButtonTitle: ""OK"", otherButtonTitles: nil)
Then to call it I'm using:
button2Alert.show()
As of right now it is crashing and I just can't seem to get the syntax right.
",https://stackoverflow.com/questions/24022479/how-would-i-create-a-uialertview-in-swift,566,767319.0,36.0,,,2014-06-03 18:35:19,2024-07-25 09:27:02,2018-03-26 02:50:42,,,ios;swift;cocoa-touch;uialertview;uialertcontroller,BlueBear,7639,1704317,registered,true,24022696,,CC BY-SA 3.0,2018-04-18 05:00:07,658,550,2,0,0,5,true,false,false,true,true,true,42,8,true,0.047,0.0007,4554,2014,6,18,Tuesday,false,false,false,false,false,false,false
27338573,Rounding a double value to x number of decimal places in swift,"Can anyone tell me how to round a double value to x number of decimal places in Swift?
I have:
var totalWorkTimeInHours = (totalWorkTime/60/60)
With totalWorkTime being an NSTimeInterval (double) in second.
totalWorkTimeInHours will give me the hours, but it gives me the amount of time in such a long precise number e.g. 1.543240952039......
How do I round this down to, say, 1.543 when I print totalWorkTimeInHours?
",https://stackoverflow.com/questions/27338573/rounding-a-double-value-to-x-number-of-decimal-places-in-swift,557,627088.0,36.0,,,2014-12-07 01:27:21,2025-12-20 15:46:53,2020-06-10 21:18:39,,,swift;double;nstimeinterval,Leighton,6709,4250683,registered,true,27341001,,CC BY-SA 4.0,2019-07-26 04:59:25,523,425,4,0,0,3,true,false,false,true,true,true,62,12,false,0.057,0.0009,4367,2014,12,1,Sunday,true,false,false,false,false,false,false
24007129,How to generate a random number in Swift?,"I realize the Swift book provided an implementation of a random number generator. Is the best practice to copy and paste this implementation? Or is there a library that does this that we can use now?
",https://stackoverflow.com/questions/24007129/how-to-generate-a-random-number-in-swift,557,459251.0,26.0,,,2014-06-03 04:27:24,2025-05-29 11:20:56,2022-11-08 10:52:51,,,swift;random,door_number_three,6091,1484490,registered,true,24007169,,CC BY-SA 4.0,,208,201,0,0,0,2,true,false,false,true,true,true,41,8,true,0.057,0.0012,4554,2014,6,4,Tuesday,false,false,false,false,false,false,false
24018327,What does an exclamation mark mean in the Swift language?,"The Swift Programming Language guide has the following example:
class Person {
let name: String
init(name: String) { self.name = name }
var apartment: Apartment?
deinit { println(""\(name) is being deinitialized"") }
}
class Apartment {
let number: Int
init(number: Int) { self.number = number }
var tenant: Person?
deinit { println(""Apartment #\(number) is being deinitialized"") }
}
var john: Person?
var number73: Apartment?
john = Person(name: ""John Appleseed"")
number73 = Apartment(number: 73)
//From Apple's “The Swift Programming Language” guide (https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html)
Then when assigning the apartment to the person, they use an exclamation point to ""unwrap the instance"":
john!.apartment = number73
What does it mean to ""unwrap the instance""? Why is it necessary? How is it different from just doing the following:
john.apartment = number73
I'm very new to the Swift language. Just trying to get the basics down.
UPDATE:
The big piece of the puzzle that I was missing (not directly stated in the answers - at least not at the time of writing this) is that when you do the following:
var john: Person?
that does NOT mean that ""john is of type Person and it might be nil"", as I originally thought. I was simply misunderstanding that Person and Person? are completely separate types. Once I grasped that, all of the other ?, ! madness, and the great answers below, made a lot more sense.
",https://stackoverflow.com/questions/24018327/what-does-an-exclamation-mark-mean-in-the-swift-language,549,169227.0,23.0,,,2014-06-03 14:52:26,2023-06-13 16:43:15,2017-06-28 13:03:48,,,swift;option-type;forced-unwrapping,Troy,22042,1354350,registered,true,24020951,,CC BY-SA 3.0,2016-04-13 14:51:10,1972,1557,10,1,0,3,true,false,false,true,true,true,57,10,true,0.136,0.0032,4554,2014,6,14,Tuesday,false,false,false,false,false,false,false
19226965,How to hide UINavigationBar 1px bottom line,"I have an app that sometimes needs its navigation bar to blend in with the content.
Does anyone know how to get rid of or to change color of this annoying little bar?
On the image below situation i have - i'm talking about this 1px height line below ""Root View Controller""
![]()
",https://stackoverflow.com/questions/19226965/how-to-hide-uinavigationbar-1px-bottom-line,539,237512.0,50.0,,,2013-10-07 14:04:47,2024-01-29 01:31:45,2017-10-26 09:31:02,,,ios;objective-c;swift;ipad;uinavigationbar,Szymon Kuczur,5831,696449,registered,true,19227158,,CC BY-SA 3.0,,385,279,0,0,1,5,true,false,false,true,true,true,43,7,false,0.211,0.0023,4793,2013,10,14,Monday,false,false,false,false,false,false,false
24028860,How to find index of list item in Swift?,"I am trying to find an item index by searching a list. Does anybody know how to do that?
I see there is list.StartIndex and list.EndIndex but I want something like python's list.index(""text"").
",https://stackoverflow.com/questions/24028860/how-to-find-index-of-list-item-in-swift,539,707283.0,23.0,,,2014-06-04 04:10:41,2023-11-06 06:08:07,2019-09-13 12:08:14,,,arrays;swift,Chéyo,9487,3705470,registered,true,24069331,,CC BY-SA 4.0,,274,195,5,0,0,2,true,false,false,true,true,true,40,9,true,0.033,0.0008,4553,2014,6,4,Wednesday,false,false,false,false,false,false,false
24231680,Loading/Downloading image from URL on Swift,"I'd like to load an image from a URL in my application, so I first tried with Objective-C and it worked, however, with Swift, I've a compilation error:
'imageWithData' is unavailable: use object construction 'UIImage(data:)'
My function:
@IBOutlet var imageView : UIImageView
override func viewDidLoad() {
super.viewDidLoad()
var url:NSURL = NSURL.URLWithString("http://myURL/ios8.png")
var data:NSData = NSData.dataWithContentsOfURL(url, options: nil, error: nil)
imageView.image = UIImage.imageWithData(data)// Error here
}
In Objective-C:
- (void)viewDidLoad {
[super viewDidLoad];
NSURL *url = [NSURL URLWithString:(@"http://myURL/ios8.png")];
NSData *data = [NSData dataWithContentsOfURL:url];
_imageView.image = [UIImage imageWithData: data];
_labelURL.text = @"http://www.urltest.fr/assets/img/iOS%20icon's%20Style/ios8.png";
}
Can someone please explain me why the imageWithData: doesn't work with Swift, and how can I solve the problem.
",https://stackoverflow.com/questions/24231680/loading-downloading-image-from-url-on-swift,526,778747.0,39.0,,,2014-06-15 16:27:05,2023-11-08 13:42:11,2023-11-08 13:42:11,,,ios;swift;uiimage;nsurl,QuentR,5347,3742601,registered,true,27712427,,CC BY-SA 4.0,2015-10-09 09:15:48,1147,1026,3,0,0,4,true,false,false,true,true,true,43,6,false,0.05,0.0007,4542,2014,6,16,Sunday,true,false,false,false,false,false,false
24092884,Get nth character of a string in Swift,"How can I get the nth character of a string? I tried bracket([]) accessor with no luck.
var string = ""Hello, world!""
var firstChar = string[0] // Throws error
ERROR: 'subscript' is unavailable: cannot subscript String with an Int, see the documentation comment for discussion
",https://stackoverflow.com/questions/24092884/get-nth-character-of-a-string-in-swift,519,460325.0,48.0,,,2014-06-07 01:50:31,2024-10-24 13:31:30,2022-11-08 10:54:14,,,swift;string;collections;character;subscript,Mohsen,66143,650722,registered,true,24144365,,CC BY-SA 4.0,2016-09-17 04:42:54,361,285,2,0,0,5,true,false,false,true,true,true,38,8,false,0.104,0.0011,4550,2014,6,1,Saturday,true,false,false,false,false,false,false
24006975,"Why create "Implicitly Unwrapped Optionals", since that implies you know there's a value?","Why would you create a ""Implicitly Unwrapped Optional"" vs creating just a regular variable or constant?
If you know that it can be successfully unwrapped then why create an optional in the first place?
For example, why is this:
let someString: String! = ""this is the string""
going to be more useful than:
let someString: String = ""this is the string""
If ”optionals indicate that a constant or variable is allowed to have 'no value'”, but “sometimes it is clear from a program’s structure that an optional will always have a value after that value is first set”, what is the point of making it an optional in the first place?
If you know an optional is always going to have a value, doesn't that make it not optional?
",https://stackoverflow.com/questions/24006975/why-create-implicitly-unwrapped-optionals-since-that-implies-you-know-theres,517,68627.0,10.0,,,2014-06-03 04:09:33,2021-04-04 12:30:51,2018-10-31 19:22:54,,,swift;design-patterns;option-type,Johnston,21114,974407,registered,true,24007032,,CC BY-SA 4.0,,794,725,2,0,0,3,true,false,false,true,true,true,103,13,true,0.146,0.0075,4554,2014,6,4,Tuesday,false,false,false,false,false,false,false
24320347,Shall we always use [unowned self] inside closure in Swift,"In WWDC 2014 session 403 Intermediate Swift and transcript, there was the following slide
![]()
The speaker said in that case, if we don't use [unowned self] there, it will be a memory leak. Does it mean we should always use [unowned self] inside closure?
On line 64 of ViewController.swift of the Swift Weather app, I don't use [unowned self]. But I update the UI by using some @IBOutlets like self.temperature and self.loadingIndicator. It may be OK because all @IBOutlets I defined are weak. But for safety, should we always use [unowned self]?
class TempNotifier {
var onChange: (Int) -> Void = {_ in }
var currentTemp = 72
init() {
onChange = { [unowned self] temp in
self.currentTemp = temp
}
}
}
",https://stackoverflow.com/questions/24320347/shall-we-always-use-unowned-self-inside-closure-in-swift,512,179674.0,12.0,,,2014-06-20 05:11:50,2024-03-03 02:57:04,2020-02-19 20:58:16,,,swift;automatic-ref-counting,Jake Lin,11544,749786,registered,true,24320474,,CC BY-SA 4.0,,1281,729,10,3,1,2,true,false,false,true,true,true,58,10,false,0.067,0.0028,4537,2014,6,5,Friday,false,false,false,false,false,false,false
32170456,What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?,"My Swift program is crashing with EXC_BAD_INSTRUCTION and one of the following similar errors. What does this error mean, and how do I fix it?
Fatal error: Unexpectedly found nil while unwrapping an Optional value
or
Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
This post is intended to collect answers to ""unexpectedly found nil"" issues, so that they are not scattered and hard to find. Feel free to add your own answer or edit the existing wiki answer.
",https://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu,512,673116.0,21.0,,,2015-08-23 19:10:23,2024-07-22 16:00:39,2019-12-08 21:39:51,,,swift;exception;error-handling,jtbandes,119609,23649,registered,true,32170457,,CC BY-SA 4.0,2016-07-30 19:56:02,692,510,1,1,0,3,true,false,false,true,true,true,98,13,true,0.031,0.0008,4108,2015,8,19,Sunday,true,false,false,false,false,false,false
24126678,Close iOS Keyboard by touching anywhere using Swift,"I have been looking all over for this but I can't seem to find it. I know how to dismiss the keyboard using Objective-C but I have no idea how to do that using Swift? Does anyone know?
",https://stackoverflow.com/questions/24126678/close-ios-keyboard-by-touching-anywhere-using-swift,511,525041.0,45.0,,,2014-06-09 18:38:10,2025-10-14 23:31:54,2016-09-04 16:41:25,,,ios;swift;uikeyboard,lagoon,6557,3491855,registered,true,27079103,,CC BY-SA 3.0,,219,186,2,0,0,3,true,false,false,true,true,true,51,8,false,0.086,0.001,4548,2014,6,18,Monday,false,false,false,false,false,false,false
39677330,How does String substring work in Swift,"I've been updating some of my old code and answers with Swift 3 but when I got to Swift Strings and Indexing with substrings things got confusing.
Specifically I was trying the following:
let str = ""Hello, playground""
let prefixRange = str.startIndex..<str.startIndex.advancedBy(5)
let prefix = str.substringWithRange(prefixRange)
where the second line was giving me the following error
Value of type 'String' has no member 'substringWithRange'
I see that String does have the following methods now:
str.substring(to: String.Index)
str.substring(from: String.Index)
str.substring(with: Range<String.Index>)
These were really confusing me at first so I started playing around index and range. This is a followup question and answer for substring. I am adding an answer below to show how they are used.
",https://stackoverflow.com/questions/39677330/how-does-string-substring-work-in-swift,511,565477.0,25.0,,,2016-09-24 14:17:09,2024-12-09 02:13:57,2017-11-15 02:16:00,,,swift;string;range;substring,Suragch,517239,3681880,registered,true,39677331,,CC BY-SA 3.0,2024-09-01 20:26:44,1049,824,3,1,0,4,true,false,false,true,true,true,39,7,false,0.044,0.0009,3710,2016,9,14,Saturday,true,false,false,false,false,false,false
25146382,How do I concatenate or merge arrays in Swift?,"If there are two arrays created in swift like this:
var a:[CGFloat] = [1, 2, 3]
var b:[CGFloat] = [4, 5, 6]
How can they be merged to [1, 2, 3, 4, 5, 6]?
",https://stackoverflow.com/questions/25146382/how-do-i-concatenate-or-merge-arrays-in-swift,510,365965.0,15.0,,,2014-08-05 19:02:26,2022-11-13 13:45:51,2020-06-10 10:56:54,,,arrays;swift;merge,Hristo,6570,1646862,registered,true,25146530,,CC BY-SA 4.0,,208,157,2,0,0,3,true,false,false,true,true,true,46,9,true,0.041,0.0014,4491,2014,8,19,Tuesday,false,false,false,false,false,false,false
44379348,The use of Swift 3 @objc inference in Swift 4 mode is deprecated?,"Briefly, while using Xcode 9 Beta, I have run into the following warning:
The use of Swift 3 @objc inference in Swift 4 mode is deprecated. Please address deprecated @objc inference warnings, test your code with “Use of deprecated Swift 3 @objc inference” logging enabled, and disable Swift 3 @objc inference.**
After some research, I still have no idea how to fix the issue.
I would greatly appreciate any tips on how to fix this issue as well as an explanation of what is going on.
My goal is to grasp a better understanding of what is happening with my code.
",https://stackoverflow.com/questions/44379348/the-use-of-swift-3-objc-inference-in-swift-4-mode-is-deprecated,496,105150.0,12.0,,,2017-06-05 23:49:05,2019-04-23 10:46:49,2017-06-29 09:22:23,,,swift;swift4;xcode9-beta,DaleK,5019,8116757,registered,true,,,CC BY-SA 3.0,2019-07-29 16:24:23,625,572,0,0,0,3,false,false,false,true,true,true,65,13,true,0.114,0.0047,3456,2017,6,23,Monday,false,false,false,false,false,false,false
29636633,Static vs class functions/variables in Swift classes?,"The following code compiles in Swift 1.2:
class myClass {
static func myMethod1() {
}
class func myMethod2() {
}
static var myVar1 = """"
}
func doSomething() {
myClass.myMethod1()
myClass.myMethod2()
myClass.myVar1 = ""abc""
}
What is the difference between a static function and a class function? Which one should I use, and when?
If I try to define another variable class var myVar2 = """", it says:
Class stored properties not yet supported in classes; did you mean 'static'?
When this feature is supported, what will the difference be between a static variable and a class variable (i.e. when both are defined in a class)? Which one should I use, and when?
(Xcode 6.3)
",https://stackoverflow.com/questions/29636633/static-vs-class-functions-variables-in-swift-classes,491,202415.0,9.0,,,2015-04-14 20:17:26,2025-05-20 12:53:51,,,,function;class;swift;variables;static,Senseful,93038,35690,registered,true,29636742,,CC BY-SA 3.0,,884,712,2,0,0,5,true,false,false,true,true,false,53,7,true,0.044,0.0024,4239,2015,4,20,Tuesday,false,false,false,false,false,false,false
37801436,"How do I write dispatch_after GCD in Swift 3, 4, and 5?","In Swift 2, I was able to use dispatch_after to delay an action using grand central dispatch:
var dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC)))
dispatch_after(dispatchTime, dispatch_get_main_queue(), {
// your function here
})
But this no longer seems to compile since Swift 3. What is the preferred way to write this in modern Swift?
",https://stackoverflow.com/questions/37801436/how-do-i-write-dispatch-after-gcd-in-swift-3-4-and-5,482,250315.0,9.0,,,2016-06-14 01:07:06,2023-03-05 01:02:24,2021-11-08 08:25:33,,,ios;swift;swift4;grand-central-dispatch;swift5,brandonscript,74010,1214800,registered,true,37801602,,CC BY-SA 4.0,2022-06-28 20:57:23,450,399,2,0,0,5,true,false,false,true,true,true,55,12,true,0.036,0.0019,3812,2016,6,1,Tuesday,false,false,false,false,false,false,false
24046164,How do I get a reference to the AppDelegate in Swift?,"How do I get a reference to AppDelegate in Swift?
Ultimately, I want to use the reference to access the managed object context.
",https://stackoverflow.com/questions/24046164/how-do-i-get-a-reference-to-the-appdelegate-in-swift,482,279723.0,18.0,,,2014-06-04 19:42:25,2026-01-04 18:54:53,2022-11-16 06:47:01,,,swift;appdelegate,AperioOculus,6811,3083382,registered,true,24046979,,CC BY-SA 4.0,,142,128,0,0,0,2,true,false,false,true,true,true,53,11,true,0.064,0.0017,4553,2014,6,19,Wednesday,false,false,false,false,false,false,false
24049020,NSNotificationCenter addObserver in Swift,"How do you add an observer in Swift to the default notification center? I'm trying to port this line of code that sends a notification when the battery level changes.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryLevelChanged:) name:UIDeviceBatteryLevelDidChangeNotification object:nil];
",https://stackoverflow.com/questions/24049020/nsnotificationcenter-addobserver-in-swift,469,440570.0,17.0,,,2014-06-04 23:02:04,2023-06-26 21:36:49,2017-04-09 16:23:30,,,ios;swift;nsnotificationcenter,Berry Blue,17156,284714,registered,true,24049111,,CC BY-SA 3.0,,357,326,1,0,0,3,true,false,false,true,true,true,41,4,false,0.039,0.0011,4553,2014,6,23,Wednesday,false,false,false,false,false,false,false
19274789,How can I change image tintColor in iOS and WatchKit,"I have an UIImageView called ""theImageView"", with UIImage in a single color (transparent background) just like the left black heart below. How can I change the tint color of this image programmatically in iOS 7 or above, as per the tint method used in the iOS 7+ Navigation Bar icons?
Can this method also work in WatchKit for an Apple Watch app?
![]()
",https://stackoverflow.com/questions/19274789/how-can-i-change-image-tintcolor-in-ios-and-watchkit,468,321127.0,25.0,,,2013-10-09 14:25:32,2022-08-03 11:19:53,2015-01-13 21:02:35,,,ios;swift;uiimage;uicolor;watchkit,chewy,8277,168273,registered,true,26443287,,CC BY-SA 3.0,,449,350,0,0,1,5,true,false,false,true,true,true,52,10,false,0.078,0.0015,4791,2013,10,14,Wednesday,false,false,false,false,false,false,false
26024100,dyld: Library not loaded: @rpath/libswiftCore.dylib,"I am trying to run a Swift app on my iPhone 4s. It works fine on the simulator, and my friend can successfully run it on his iPhone 4s. I have iOS 8 and the official release of Xcode 6.
I have tried
- Restarting Xcode, iPhone, computer
- Cleaning & rebuilding
- Revoking and creating new certificate/provision profile
- Runpath Search Paths is
$(inherited) @executable_path/Frameworks
- Embedded Content Contains Swift Code is 'Yes'
- Code Signing Identity is developer
Below is the error in entirety
dyld: Library not loaded: @rpath/libswiftCore.dylib
Referenced from: /private/var/mobile/Containers/Bundle/Application/LONGSERIALNUMBER/AppName.app/AppName
Reason: no suitable image found. Did find:
/private/var/mobile/Containers/Bundle/Application/LONGSERIALNUMBER/AppName.app/Frameworks/libswiftCore.dylib: mmap() error 1 at
address=0x008A1000, size=0x001A4000 segment=__TEXT in Segment::map() mapping
/private/var/mobile/Containers/Bundle/Application/LONGSERIALNUMBER/APPLICATION_NAME/Frameworks/libswiftCore.dylib
",https://stackoverflow.com/questions/26024100/dyld-library-not-loaded-rpath-libswiftcore-dylib,468,277906.0,59.0,,,2014-09-24 18:40:24,2023-08-15 20:28:28,2019-03-30 11:33:02,,,ios;swift;xcode;dyld,user3751185,4735,3751185,registered,true,,,CC BY-SA 4.0,2016-04-25 06:04:34,1159,1038,2,0,0,4,false,false,false,true,true,true,51,5,false,0.212,0.0017,4441,2014,9,18,Wednesday,false,false,false,false,false,false,false
24016142,How to make HTTP request in Swift?,"I read The Programming Language Swift by Apple in iBooks, but cannot figure out how to make an HTTP request (something like cURL) in Swift. Do I need to import Obj-C classes or do I just need to import default libraries? Or is it not possible to make an HTTP request based on native Swift code?
",https://stackoverflow.com/questions/24016142/how-to-make-http-request-in-swift,462,559842.0,21.0,,,2014-06-03 13:12:32,2024-02-24 06:33:59,2023-03-07 02:33:27,,,ios;swift;http;nsurlsession,Dicky Tsang,6383,2932812,registered,true,24016254,,CC BY-SA 4.0,2016-01-17 16:21:43,368,295,0,1,0,4,true,false,false,true,true,true,34,7,true,0.038,0.0008,4554,2014,6,13,Tuesday,false,false,false,false,false,false,false
24051314,Precision string format specifier in Swift,"Below is how I would have previously truncated a float to two decimal places
NSLog(@" %.02f %.02f %.02f", r, g, b);
I checked the docs and the eBook but haven't been able to figure it out.
",https://stackoverflow.com/questions/24051314/precision-string-format-specifier-in-swift,459,438588.0,32.0,,,2014-06-05 03:47:18,2026-09-29 00:21:36,2025-04-07 09:54:08,,,swift,user3524868,4603,3524868,registered,true,24055762,,CC BY-SA 4.0,,238,200,1,0,0,1,true,false,false,true,true,true,42,6,false,0.073,0.001,4552,2014,6,3,Thursday,false,false,false,false,false,false,false
24263007,How to use hex color values,"I am trying to use hex color values in Swift, instead of the few standard ones that UIColor allows you to use, but I have no idea how to do it.
Example: how would I use #ffffff as a color?
",https://stackoverflow.com/questions/24263007/how-to-use-hex-color-values,456,489497.0,42.0,,,2014-06-17 11:48:56,2025-07-19 19:31:40,2018-12-07 09:34:52,,,ios;swift;uicolor,Stephen Fox,14500,2875074,registered,true,24263296,,CC BY-SA 4.0,2016-10-19 12:25:33,231,191,2,0,0,3,true,false,false,true,true,true,27,6,false,0.086,0.0009,4540,2014,6,11,Tuesday,false,false,false,false,false,false,false
56433665,What is the "some" keyword in Swift(UI)?,"The new SwiftUI tutorial has the following code:
struct ContentView: View {
var body: some View {
Text(""Hello World"")
}
}
The second line the word some, and on their site is highlighted as if it were a keyword.
Swift 5.1 does not appear to have some as a keyword, and I don't see what else the word some could be doing there, since it goes where the type usually goes. Is there a new, unannounced version of Swift? Is it a function that's being used on a type in a way I didn't know about?
What does the keyword some do?
",https://stackoverflow.com/questions/56433665/what-is-the-some-keyword-in-swiftui,453,96433.0,13.0,,,2019-06-03 19:47:01,2025-11-30 15:15:13,2023-08-02 15:09:09,,,swift;swiftui;swift5;keyword,Half,5628,7282573,registered,true,56433885,,CC BY-SA 4.0,2025-11-30 16:52:21,792,542,5,1,0,4,true,false,false,true,true,true,50,7,true,0.135,0.0047,2728,2019,6,19,Monday,false,false,false,false,false,false,false
25156377,What is the difference between static func and class func in Swift?,"I can see these definitions in the Swift library:
extension Bool : BooleanLiteralConvertible {
static func convertFromBooleanLiteral(value: Bool) -> Bool
}
protocol BooleanLiteralConvertible {
typealias BooleanLiteralType
class func convertFromBooleanLiteral(value: BooleanLiteralType) -> Self
}
What's the difference between a member function defined as static func and another one defined as class func? Is it simply that static is for static functions of structs and enums, and class for classes and protocols? Are there any other differences that one should know about? What is the rationale for having this distinction in the syntax itself?
",https://stackoverflow.com/questions/25156377/what-is-the-difference-between-static-func-and-class-func-in-swift,452,148111.0,9.0,,,2014-08-06 09:11:22,2023-10-02 10:12:45,2015-02-03 08:11:21,,,class;static;swift,Jean-Philippe Pellet,60196,390581,registered,true,25157453,,CC BY-SA 3.0,,758,668,5,0,0,3,true,false,false,true,true,true,67,12,true,0.061,0.0031,4490,2014,8,9,Wednesday,false,false,false,false,false,false,false
25827033,How do I convert a Swift Array to a String?,"I know how to programmatically do it, but I'm sure there's a built-in way...
Every language I've used has some sort of default textual representation for a collection of objects that it will spit out when you try to concatenate the Array with a string, or pass it to a print() function, etc. Does Apple's Swift language have a built-in way of easily turning an Array into a String, or do we always have to be explicit when stringifying an array?
",https://stackoverflow.com/questions/25827033/how-do-i-convert-a-swift-array-to-a-string,450,393904.0,25.0,,,2014-09-13 19:48:08,2024-02-28 09:18:16,2017-05-10 10:22:37,,,ios;arrays;swift,Troy,22042,1354350,registered,true,25827087,,CC BY-SA 3.0,,463,449,0,0,0,3,true,false,false,true,true,true,43,10,true,0.063,0.0011,4452,2014,9,19,Saturday,true,false,false,false,false,false,false
24494784,Get class name of object as string in Swift,"Getting the classname of an object as String using:
object_getClassName(myViewController)
returns something like this:
_TtC5AppName22CalendarViewController
I am looking for the pure version: ""CalendarViewController"". How do I get a cleaned up string of the class name instead?
I found some attempts of questions about this but not an actual answer. Is it not possible at all?
",https://stackoverflow.com/questions/24494784/get-class-name-of-object-as-string-in-swift,445,338037.0,32.0,,,2014-06-30 16:29:37,2023-04-14 13:59:11,2020-06-08 19:47:00,,,swift;reflection;typeof,Bernd,11563,417096,registered,true,,,CC BY-SA 4.0,,504,384,4,0,0,3,false,false,false,true,true,true,43,9,false,0.095,0.0013,4527,2014,6,16,Monday,false,false,false,false,false,false,false
24032754,How does one declare optional methods in a Swift protocol?,"Is it possible in Swift? If not then is there a workaround to do it?
",https://stackoverflow.com/questions/24032754/how-does-one-declare-optional-methods-in-a-swift-protocol,439,248385.0,19.0,,,2014-06-04 08:41:51,2023-01-31 22:32:32,2023-01-31 22:32:32,,,ios;swift;optional-parameters;swift-protocols;swift-extensions,Selvin,12533,569497,registered,true,24032961,,CC BY-SA 4.0,,76,69,0,0,0,5,true,false,false,true,true,true,58,10,true,0.076,0.0018,4553,2014,6,8,Wednesday,false,false,false,false,false,false,false
26797739,Does Swift have a trim method on String?,"Does Swift have a trim() method on String? For example:
let result = " abc ".trim()
// result == "abc"
",https://stackoverflow.com/questions/26797739/does-swift-have-a-trim-method-on-string,437,232825.0,16.0,,,2014-11-07 09:12:33,2024-09-04 18:36:00,2024-07-26 10:14:04,,,string;swift;trim,tounaobun,14913,3115587,registered,true,26797958,,CC BY-SA 4.0,,181,124,3,0,0,3,true,false,false,true,true,true,40,8,true,0.069,0.0019,4397,2014,11,9,Friday,false,false,false,false,false,false,false
24002733,Add an element to an array in Swift,"Suppose I have an array, for example:
var myArray = [""Steve"", ""Bill"", ""Linus"", ""Bret""]
And later I want to push/append an element to the end of said array, to get:
[""Steve"", ""Bill"", ""Linus"", ""Bret"", ""Tim""]
What method should I use?
And what about the case where I want to add an element to the front of the array? Is there a constant time unshift?
",https://stackoverflow.com/questions/24002733/add-an-element-to-an-array-in-swift,435,564050.0,15.0,,,2014-06-02 20:29:51,2026-02-06 03:27:55,2023-09-05 17:46:45,,,arrays;swift,Fela,27630,1494793,registered,true,24002784,,CC BY-SA 4.0,2019-12-14 12:36:38,443,354,2,0,0,2,true,false,false,true,true,true,35,8,false,0.027,0.0008,4555,2014,6,20,Monday,false,false,false,false,false,false,false
25471114,How to validate an e-mail address in Swift?,"Does anyone know how to validate an e-mail address in Swift? I found this code:
- (BOOL) validEmail:(NSString*) emailString {
if([emailString length]==0){
return NO;
}
NSString *regExPattern = @""[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"";
NSRegularExpression *regEx = [[NSRegularExpression alloc] initWithPattern:regExPattern options:NSRegularExpressionCaseInsensitive error:nil];
NSUInteger regExMatches = [regEx numberOfMatchesInString:emailString options:0 range:NSMakeRange(0, [emailString length])];
NSLog(@""%i"", regExMatches);
if (regExMatches == 0) {
return NO;
} else {
return YES;
}
}
but I can't translate it to Swift.
",https://stackoverflow.com/questions/25471114/how-to-validate-an-e-mail-address-in-swift,426,300946.0,39.0,,,2014-08-24 11:15:58,2024-09-27 20:38:42,2024-04-27 20:01:48,,,swift;validation;email;nsregularexpression,giorgionocera,6546,3842100,registered,true,25471164,,CC BY-SA 4.0,2017-01-27 11:06:19,741,703,1,0,0,4,true,false,false,true,true,true,43,8,true,0.13,0.0014,4472,2014,8,11,Sunday,true,false,false,false,false,false,false
24056205,How to use background thread in swift?,"How to use threading in swift?
dispatchOnMainThread:^{
NSLog(@""Block Executed On %s"", dispatch_queue_get_label(dispatch_get_current_queue()));
}];
",https://stackoverflow.com/questions/24056205/how-to-use-background-thread-in-swift,424,409041.0,18.0,,,2014-06-05 09:16:44,2024-07-29 11:41:33,2021-11-07 10:23:00,2024-04-11 14:01:04,Needs details or clarity,ios;swift;multithreading;cocoa-touch;dispatch-queue,Anshul,4558,3376425,registered,true,,,,,186,155,1,0,0,5,false,true,false,true,true,true,38,7,true,0.044,0.001,4552,2014,6,9,Thursday,false,false,false,false,false,false,false
38031137,How to program a delay in Swift 3,"In earlier versions of Swift, one could create a delay with the following code:
let time = dispatch_time(dispatch_time_t(DISPATCH_TIME_NOW), 4 * Int64(NSEC_PER_SEC))
dispatch_after(time, dispatch_get_main_queue()) {
//put your code which should be executed with a delay here
}
But now, in Swift 3, Xcode automatically changes 6 different things but then the following error appears: ""Cannot convert DispatchTime.now to expected value dispatch_time_t aka UInt64.""
How can one create a delay before running a sequence of code in Swift 3?
",https://stackoverflow.com/questions/38031137/how-to-program-a-delay-in-swift-3,416,388054.0,8.0,,,2016-06-25 17:30:44,2023-08-17 18:03:16,2023-08-17 18:03:16,,,swift;swift3;dispatch-after,owlswipe,19529,5700898,registered,true,38031138,,CC BY-SA 4.0,,628,544,4,0,0,3,true,false,false,true,true,true,33,8,false,0.021,0.0011,3801,2016,6,17,Saturday,true,false,false,false,false,false,false
25566581,Leading zeros for Int in Swift,"I'd like to convert an Int in Swift to a String with leading zeros. For example consider this code:
for myInt in 1 ... 3 {
print(""\(myInt)"")
}
Currently the result of it is:
1
2
3
But I want it to be:
01
02
03
Is there a clean way of doing this within the Swift standard libraries?
",https://stackoverflow.com/questions/25566581/leading-zeros-for-int-in-swift,416,185191.0,12.0,,,2014-08-29 10:36:35,2023-08-01 12:53:07,2019-05-02 14:56:58,,,string;swift;int;type-conversion,Cihat Gündüz,21761,3451975,registered,true,25566860,,CC BY-SA 4.0,,421,295,5,0,0,4,true,false,false,true,true,true,30,6,false,0.065,0.0022,4467,2014,8,10,Friday,false,false,false,false,false,false,false
27517632,How to create a delay in Swift?,"I want to pause my app at a certain in point. In other words, I want my app to execute the code, but then at a certain point, pause for 4 seconds, and then continue on with the rest of the code. How can I do this?
I am using Swift.
",https://stackoverflow.com/questions/27517632/how-to-create-a-delay-in-swift,415,581106.0,19.0,,,2014-12-17 02:58:29,2025-04-24 19:46:37,2021-11-07 10:43:40,,,ios;swift;xcode;delay,Schuey999,5044,4268022,registered,true,27517642,,CC BY-SA 4.0,,247,233,0,0,0,4,true,false,false,true,true,true,31,7,true,0.033,0.0007,4357,2014,12,2,Wednesday,false,false,false,false,false,false,false
27652227,Add placeholder text inside UITextView in Swift?,"How can I add a placeholder in a UITextView, similar to the one you can set for UITextField, in Swift?
",https://stackoverflow.com/questions/27652227/add-placeholder-text-inside-uitextview-in-swift,414,392105.0,47.0,,,2014-12-26 02:12:05,2024-03-06 09:36:18,2020-09-25 15:37:11,,,ios;swift;uitextview;placeholder,StevenZ,7123,4392705,registered,true,27652289,,CC BY-SA 4.0,,149,103,3,0,0,4,true,false,false,true,true,true,48,7,true,0.12,0.0011,4348,2014,12,2,Friday,false,false,false,false,false,false,false
24115141,Converting String to Int with Swift,"The application basically calculates acceleration by inputting Initial and final velocity and time and then use a formula to calculate acceleration. However, since the values in the text boxes are string, I am unable to convert them to integers.
@IBOutlet var txtBox1 : UITextField
@IBOutlet var txtBox2 : UITextField
@IBOutlet var txtBox3 : UITextField
@IBOutlet var lblAnswer : UILabel
@IBAction func btn1(sender : AnyObject) {
let answer1 = ""The acceleration is""
var answer2 = txtBox1
var answer3 = txtBox2
var answer4 = txtBox3
",https://stackoverflow.com/questions/24115141/converting-string-to-int-with-swift,408,642194.0,32.0,,,2014-06-09 06:57:11,2025-04-02 00:29:15,2023-10-13 20:42:33,,,swift;string;integer,Marwan Qasem,4091,3721378,registered,true,24183839,,CC BY-SA 4.0,2021-12-29 09:37:40,584,553,1,0,0,3,true,false,false,true,true,true,35,6,false,0.05,0.0006,4548,2014,6,6,Monday,false,false,false,false,false,false,false
56443535,SwiftUI text-alignment,"Among the many properties of the Text view, I couldn't find any related to text alignment. I've seen in a demo that it automatically handles RTL, and when placing stuff using View's body, it always centers it automatically.
Is there some concept that I'm missing about layout system in SwiftUI and if not, how can I set the text alignment properties to the Text?
",https://stackoverflow.com/questions/56443535/swiftui-text-alignment,404,423982.0,14.0,,,2019-06-04 12:04:58,2024-08-20 14:38:07,2019-06-05 10:49:16,,,ios;swift;swiftui,inokey,6408,5479510,registered,true,56649668,,CC BY-SA 4.0,,430,364,4,0,0,3,true,false,false,true,true,true,22,2,false,0.033,0.001,2727,2019,6,12,Tuesday,false,false,false,false,false,false,false
38947101,What is the 'open' keyword in Swift?,"The ObjectiveC.swift file from the standard library contains the following few lines of code around line 228:
extension NSObject : Equatable, Hashable {
/// ...
open var hashValue: Int {
return hash
}
}
What does open var mean in this context, or what is the open keyword in general?
",https://stackoverflow.com/questions/38947101/what-is-the-open-keyword-in-swift,399,152574.0,5.0,,,2016-08-14 22:17:37,2020-10-08 11:52:51,2017-08-24 19:48:50,,,swift;swift3;syntax;declaration;modifier,Clashsoft,11893,4138801,registered,true,38950955,,CC BY-SA 3.0,,499,297,4,1,0,5,true,false,false,true,true,true,44,7,true,0.033,0.0026,3751,2016,8,22,Sunday,true,false,false,false,false,false,false
24551816,Swift - encode URL,"If I encode a string like this:
var escapedString = originalString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
it doesn't escape the slashes /.
I've searched and found this Objective C code:
NSString *encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)unencodedString,
NULL,
(CFStringRef)@""!*'();:@&=+$,/?%#[]"",
kCFStringEncodingUTF8 );
Is there an easier way to encode an URL and if not, how do I write this in Swift?
",https://stackoverflow.com/questions/24551816/swift-encode-url,398,378604.0,21.0,,,2014-07-03 10:56:02,2023-12-12 10:00:07,2014-07-03 10:57:12,,,ios;swift;urlencode,MegaCookie,5355,3801276,registered,true,24552028,,CC BY-SA 3.0,2019-02-26 14:05:35,699,610,3,0,0,3,true,false,false,true,true,true,18,4,false,0.055,0.0011,4524,2014,7,10,Thursday,false,false,false,false,false,false,false
3889634,Fast and Lean PDF Viewer for iPhone / iPad / iOS - tips and hints?,"There has been many Questions recently about drawing PDF's.
Yes, you can render PDF's very easily with a UIWebView but this cant give the performance and functionality that you would expect from a good PDF viewer.
You can draw a PDF page to a CALayer or to a UIImage. Apple even have sample code to show how draw a large PDF in a Zoomable UIScrollview
But the same issues keep cropping up.
UIImage Method:
- PDF's in a
UIImage don't optically
scale as well as a Layer approach.
- The CPU and memory hit on generating
the
UIImages from a PDFcontext
limits/prevents using it to create a
real-time render of new zoom-levels.
CATiledLayer Method:
- Theres a significant Overhead (time)
drawing a full PDF page to a
CALayer: individual tiles can be seen rendering (even with a tileSize tweak)
CALayers cant be prepared ahead of
time (rendered off-screen).
Generally PDF viewers are pretty heavy on memory too. Even monitor the memory usage of apple's zoomable PDF example.
In my current project, I'm developing a PDF viewer and am rendering a UIImage of a page in a separate thread (issues here too!) and presenting it while the scale is x1. CATiledLayer rendering kicks in once the scale is >1. iBooks takes a similar double take approach as if you scroll the pages you can see a lower res version of the page for just less than a second before a crisp version appears.
Im rendering 2 pages each side of the page in focus so that the PDF image is ready to mask the layer before it starts drawing.Pages are destroyed again when they are +2 pages away from the focused page.
Does anyone have any insights, no matter how small or obvious to improve the performance/ memory handling of Drawing PDF's? or any other issues discussed here?
EDIT: Some Tips (Credit- Luke Mcneice,VdesmedT,Matt Gallagher,Johann):
Save any media to disk when you can.
Use larger tileSizes if rendering on TiledLayers
init frequently used arrays with placeholder objects, alternitively another design approach is this one
Note that images will render faster than a CGPDFPageRef
Use NSOperations or GCD & Blocks to prepare pages ahead
of time.
call CGContextSetInterpolationQuality(ctx, kCGInterpolationHigh); CGContextSetRenderingIntent(ctx, kCGRenderingIntentDefault); before CGContextDrawPDFPage to reduce memory usage while drawing
init'ing your NSOperations with a docRef is a bad idea (memory), wrap the docRef into a singleton.
Cancel needless NSOperations When you can, especially if they will be using memory, beware of leaving contexts open though!
Recycle page objects and destroy unused views
Close any open Contexts as soon as you don't need them
on receiving memory warnings release and reload the DocRef and any page Caches
Other PDF Features:
Getting Links inside a PDF (and here and here)
Getting the target of the link (Getting the page number from the /Dest array)
Getting Raw Text (and here and Here and here (positioning focused))
Searching(and here) (doesn't work with all PDFs (some just show weird characters, I guess it's an encoding issue but I'm not sure) -Credit BrainFeeder)
CALayer and Off-Screen Rendering - render the next page for fast/smooth display
Documentation
- Quartz PDFObjects (Used for meta info, annotations, thumbs)
- Abobe PDF Spec
Example projects
- Apple/ ZoomingPDF - zooming,
UIScrollView, CATiledLayer
- vfr/ reader - zooming, paging,
UIScrollView, CATiledView
- brow/ leaves - paging with nice transitions
- / skim - everything it seems (PDF reader/editor for OSX)
",https://stackoverflow.com/questions/3889634/fast-and-lean-pdf-viewer-for-iphone-ipad-ios-tips-and-hints,379,104438.0,3.0,,,2010-10-08 10:23:10,2020-08-10 13:19:28,2020-08-10 13:19:28,,,ios;swift;pdf;calayer;apple-pdfkit,Luke Mcneice,2730,293008,registered,true,3890161,,CC BY-SA 4.0,2013-06-22 17:00:56,7340,3652,19,27,0,5,true,false,false,true,true,true,66,15,true,0.029,0.0036,5888,2010,10,10,Friday,false,false,false,false,false,false,false
24666515,How do I make an attributed string using Swift?,"I am trying to make a coffee calculator. I need to display the amount of coffee in grams. The "g" symbol for grams needs to be attached to my UILabel that I am using to display the amount.
The numbers in the UILabel are changing dynamically with user input just fine, but I need to add a lower case "g" on the end of the string that is formatted differently from the updating numbers. The "g" needs to be attached to the numbers so that as the number size and position changes, the "g" "moves" with the numbers.
What would be helpful is a clear example of creating a custom font with custom attributes using an attributed string in Swift. My plan is to create the attributed string and add it to the end of my coffeeAmount string:
var coffeeAmount: String = calculatedCoffee + attributedText
Where calculatedCoffee is an Int converted to a string and attributedText is the lowercase "g" with customized font that I am trying to create.
",https://stackoverflow.com/questions/24666515/how-do-i-make-an-attributed-string-using-swift,378,447751.0,33.0,,,2014-07-10 02:21:04,2026-02-22 09:55:09,2025-06-12 09:51:24,,,fonts;uilabel;swift;nsattributedstring,dcbenji,4668,3822654,registered,true,,,CC BY-SA 4.0,2018-04-18 04:58:41,1076,998,3,0,0,4,false,false,false,true,true,true,47,9,true,0.074,0.0008,4517,2014,7,2,Thursday,false,false,false,false,false,false,false
24097826,Read and write a String from text file,"I need to read and write data to/from a text file, but I haven't been able to figure out how.
I found this sample code in the Swift's iBook, but I still don't know how to write or read data.
import Cocoa
class DataImporter {
/*
DataImporter is a class to import data from an external file.
The class is assumed to take a non-trivial amount of time to initialize.
*/
var fileName = "data.txt"
// the DataImporter class would provide data importing functionality here
}
class DataManager {
@lazy var importer = DataImporter()
var data = String[]()
// the DataManager class would provide data management functionality here
}
let manager = DataManager()
manager.data += "Some data"
manager.data += "Some more data"
// the DataImporter instance for the importer property has not yet been created”
println(manager.importer.fileName)
// the DataImporter instance for the importer property has now been created
// prints "data.txt”
var str = "Hello World in Swift Language."
",https://stackoverflow.com/questions/24097826/read-and-write-a-string-from-text-file,378,572953.0,22.0,,,2014-06-07 13:42:17,2024-03-14 14:12:03,2022-07-12 16:34:28,,,swift;string;file-io,Jorge Vega Sánchez,7568,565200,registered,true,24098149,,CC BY-SA 4.0,2019-08-13 02:36:41,1096,1058,1,0,0,3,true,false,false,true,true,true,38,8,false,0.038,0.0007,4550,2014,6,13,Saturday,true,false,false,false,false,false,false
57134259,How to resolve: 'keyWindow' was deprecated in iOS 13.0,"I'm using Core Data with Cloud Kit, and have therefore to check the iCloud user status during application startup. In case of problems I want to issue a dialog to the user, and I do it using UIApplication.shared.keyWindow?.rootViewController?.present(...) up to now.
In Xcode 11 beta 4, there is now a new deprecation message, telling me:
'keyWindow' was deprecated in iOS 13.0: Should not be used for applications that support multiple scenes as it returns a key window across all connected scenes
How shall I present the dialog instead?
",https://stackoverflow.com/questions/57134259/how-to-resolve-keywindow-was-deprecated-in-ios-13-0,377,215629.0,32.0,,,2019-07-21 14:48:27,2024-04-16 12:24:49,2024-02-09 06:11:32,,,swift;ios13;uiwindow;uiscene,Hardy,4866,1982755,registered,true,57169802,,CC BY-SA 4.0,2021-11-09 10:19:40,739,542,1,1,1,4,true,false,false,true,true,true,62,9,false,0.148,0.0017,2680,2019,7,14,Sunday,true,false,false,false,false,false,false
25738817,Removing duplicate elements from an array in Swift,"I might have an array that looks like the following:
[1, 4, 2, 2, 6, 24, 15, 2, 60, 15, 6]
Or, really, any sequence of like-typed portions of data. What I want to do is ensure that there is only one of each identical element. For example, the above array would become:
[1, 4, 2, 6, 24, 15, 60]
Notice that the duplicates of 2, 6, and 15 were removed to ensure that there was only one of each identical element. Does Swift provide a way to do this easily, or will I have to do it myself?
",https://stackoverflow.com/questions/25738817/removing-duplicate-elements-from-an-array-in-swift,376,333689.0,51.0,,,2014-09-09 07:21:58,2024-05-19 04:28:48,2020-09-24 17:08:10,,,arrays;swift;standard-library,Altair357,3771,4021808,registered,true,25739498,,CC BY-SA 4.0,2017-05-03 11:16:29,619,487,2,0,0,3,true,false,false,true,true,true,50,8,false,0.153,0.0011,4456,2014,9,7,Tuesday,false,false,false,false,false,false,false
26252233,Global constants file in Swift,"In my Objective-C projects I often use a global constants file to store things like notification names and keys for NSUserDefaults. It looks something like this:
@interface GlobalConstants : NSObject
extern NSString *someNotification;
@end
@implementation GlobalConstants
NSString *someNotification = @""aaaaNotification"";
@end
How do I do exactly the same thing in Swift?
",https://stackoverflow.com/questions/26252233/global-constants-file-in-swift,375,193593.0,15.0,,,2014-10-08 08:20:15,2021-02-15 11:57:53,2019-01-03 08:00:32,,,ios;objective-c;swift,user1028028,6453,1028028,registered,true,26252377,,CC BY-SA 4.0,,431,380,2,0,0,3,true,false,false,true,true,true,30,5,false,0.077,0.0019,4427,2014,10,8,Wednesday,false,false,false,false,false,false,false
24002092,What is the difference between `let` and `var` in Swift?,"What is the difference between let and var in Apple's Swift language?
In my understanding, it is a compiled language but it does not check the type at compile time. It makes me confused. How does the compiler know about the type error? If the compiler doesn't check the type, isn't it a problem with production environment?
This error is given when I try to assign a value to a let:
Cannot assign to property: 'variableName' is a 'let' constant
Change 'let' to 'var' to make it mutable
",https://stackoverflow.com/questions/24002092/what-is-the-difference-between-let-and-var-in-swift,375,235286.0,32.0,,,2014-06-02 19:46:11,2025-12-03 16:47:21,2024-04-14 15:34:20,,,swift,Edward,4995,2440343,registered,true,24002209,,CC BY-SA 4.0,2017-12-12 07:14:57,586,488,3,0,0,1,true,false,false,true,true,true,56,10,true,0.136,0.0016,4555,2014,6,19,Monday,false,false,false,false,false,false,false
25329186,"Safe (bounds-checked) array lookup in Swift, through optional bindings?","If I have an array in Swift, and try to access an index that is out of bounds, there is an unsurprising runtime error:
var str = [""Apple"", ""Banana"", ""Coconut""]
str[0] // ""Apple""
str[3] // EXC_BAD_INSTRUCTION
However, I would have thought with all the optional chaining and safety that Swift brings, it would be trivial to do something like:
let theIndex = 3
if let nonexistent = str[theIndex] { // Bounds check + Lookup
print(nonexistent)
...do other things with nonexistent...
}
Instead of:
let theIndex = 3
if (theIndex < str.count) { // Bounds check
let nonexistent = str[theIndex] // Lookup
print(nonexistent)
...do other things with nonexistent...
}
But this is not the case - I have to use the ol' if statement to check and ensure the index is less than str.count.
I tried adding my own subscript() implementation, but I'm not sure how to pass the call to the original implementation, or to access the items (index-based) without using subscript notation:
extension Array {
subscript(var index: Int) -> AnyObject? {
if index >= self.count {
NSLog(""Womp!"")
return nil
}
return ... // What?
}
}
",https://stackoverflow.com/questions/25329186/safe-bounds-checked-array-lookup-in-swift-through-optional-bindings,371,167874.0,23.0,,,2014-08-15 15:20:53,2026-02-09 22:02:55,2014-10-03 11:43:44,,,xcode;swift,Craig Otis,32410,88111,registered,true,30593673,,CC BY-SA 3.0,2019-08-25 01:39:04,1388,1209,7,0,0,2,true,false,false,true,true,true,71,9,true,0.137,0.0022,4481,2014,8,15,Friday,false,false,false,false,false,false,false
45562662,How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator,"I have the following simple code written in Swift 3:
let str = ""Hello, playground""
let index = str.index(of: "","")!
let newStr = str.substring(to: index)
From Xcode 9 beta 5, I get the following warning:
'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator.
How can this slicing subscript with partial range from be used in Swift 4?
",https://stackoverflow.com/questions/45562662/how-can-i-use-string-substring-in-swift-4-substringto-is-deprecated-pleas,371,211757.0,21.0,,,2017-08-08 08:04:27,2022-11-25 13:52:24,2020-06-23 00:56:28,,,swift;swift4,Adrian,20258,340554,registered,true,45562735,,CC BY-SA 4.0,,513,393,3,0,0,2,true,false,false,true,true,true,163,23,false,0.099,0.0018,3392,2017,8,8,Tuesday,false,false,false,false,false,false,false
5067785,How do I add 1 day to an NSDate?,"I'm wondering how I could add 1 day to an NSDate.
So if it were:
21st February 2011
It would become:
22nd February 2011
Or if it were:
31st December 2011
It would become:
1st January 2012.
",https://stackoverflow.com/questions/5067785/how-do-i-add-1-day-to-an-nsdate,369,253064.0,30.0,,,2011-02-21 15:28:01,2026-09-08 07:57:51,2026-09-08 07:57:51,,,objective-c;swift;date;cocoa-touch;nsdate,Andrew,16021,561395,registered,true,,,CC BY-SA 4.0,2020-05-25 11:39:44,337,193,5,0,0,5,false,false,false,true,true,true,32,9,true,0.119,0.0015,5752,2011,2,15,Monday,false,false,false,false,false,false,false
28394933,How do I check when a UITextField changes?,"I am trying to check when a text field changes, equivalent too the function used for textView - textViewDidChange so far I have done this:
func textFieldDidBeginEditing(textField: UITextField) {
if self.status.text == """" && self.username.text == """" {
self.topRightButton.enabled = false
} else {
self.topRightButton.enabled = true
}
}
Which kind of works, but the topRightButton is enabled as soon as the text field is pressed on, I want it to be enabled only when text is actually typed in?
",https://stackoverflow.com/questions/28394933/how-do-i-check-when-a-uitextfield-changes,369,370149.0,21.0,,,2015-02-08 14:16:24,2023-05-10 06:29:26,2016-09-27 10:16:38,,,ios;swift;uitextfield,user4184036,,,does_not_exist,true,28395000,,CC BY-SA 3.0,,625,561,3,0,0,3,true,false,false,true,false,true,42,8,true,0.057,0.001,4304,2015,2,14,Sunday,true,false,false,false,false,false,false
24006165,How do I print the type or class of a variable in Swift?,"Is there a way to print the runtime type of a variable in swift? For example:
var now = NSDate()
var soon = now.dateByAddingTimeInterval(5.0)
println(""\(now.dynamicType)"")
// Prints ""(Metatype)""
println(""\(now.dynamicType.description()"")
// Prints ""__NSDate"" since objective-c Class objects have a ""description"" selector
println(""\(soon.dynamicType.description()"")
// Compile-time error since ImplicitlyUnwrappedOptional<NSDate> has no ""description"" method
In the example above, I'm looking for a way to show that the variable ""soon"" is of type ImplicitlyUnwrappedOptional<NSDate>, or at least NSDate!.
",https://stackoverflow.com/questions/24006165/how-do-i-print-the-type-or-class-of-a-variable-in-swift,368,272317.0,34.0,,,2014-06-03 02:24:42,2019-04-09 17:32:43,2016-10-20 11:49:17,,,swift;types,Matt Bridges,49765,125871,registered,true,25345480,,CC BY-SA 3.0,,686,622,3,0,0,2,true,false,false,true,true,true,56,13,true,0.125,0.0014,4554,2014,6,2,Tuesday,false,false,false,false,false,false,false
24869481,How to detect if app is being built for device or simulator in Swift,"Note, extremely old historic QA.
(Is now just #if targetEnvironment(simulator).)
In Objective-C we can know if an app is being built for device or simulator using macros:
#if TARGET_IPHONE_SIMULATOR
// Simulator
#else
// Device
#endif
These are compile time macros and not available at runtime.
How can I achieve the same in Swift?
",https://stackoverflow.com/questions/24869481/how-to-detect-if-app-is-being-built-for-device-or-simulator-in-swift,364,153682.0,21.0,,,2014-07-21 15:59:51,2024-03-06 16:28:22,2024-03-06 16:28:22,,,ios;swift,Rafał Sroka,40105,348796,registered,true,24869607,,CC BY-SA 4.0,,464,342,2,0,0,2,true,false,false,true,true,true,68,14,false,0.137,0.0024,4506,2014,7,15,Monday,false,false,false,false,false,false,false
28129401,Determining if Swift dictionary contains key and obtaining any of its values,"I am currently using the following (clumsy) pieces of code for determining if a (non-empty) Swift dictionary contains a given key and for obtaining one (any) value from the same dictionary.
How can one put this more elegantly in Swift?
// excerpt from method that determines if dict contains key
if let _ = dict[key] {
return true
}
else {
return false
}
// excerpt from method that obtains first value from dict
for (_, value) in dict {
return value
}
",https://stackoverflow.com/questions/28129401/determining-if-swift-dictionary-contains-key-and-obtaining-any-of-its-values,356,336037.0,8.0,,,2015-01-24 19:30:52,2022-05-30 14:01:18,2015-01-24 19:39:32,,,swift;dictionary,Drux,12798,1789384,registered,true,28129484,,CC BY-SA 3.0,,507,469,1,0,0,2,true,false,false,true,true,true,76,12,false,0.024,0.0011,4319,2015,1,19,Saturday,true,false,false,false,false,false,false
58657087,"After upgrading to Xcode 11.2 from Xcode 11.1, app crashes due to _UITextLayoutView","After upgrading to Xcode 11.2 from Xcode 11.1 my app crashes:
*** Terminating app due to uncaught exception 'NSInvalidUnarchiveOperationException', reason: 'Could not instantiate class named _UITextLayoutView because no class named _UITextLayoutView was found; the class needs to be defined in source code or linked in from a library (ensure the class is part of the correct target)'
Why is this happening? How can I prevent this crash?
",https://stackoverflow.com/questions/58657087/after-upgrading-to-xcode-11-2-from-xcode-11-1-app-crashes-due-to-uitextlayoutv,355,58913.0,15.0,,,2019-11-01 09:47:39,2020-01-09 10:55:49,2019-11-05 23:53:41,,,ios;swift;xcode;uitextview;xcode11,Sudhakar Tharigoppula,2867,3000061,registered,true,58699326,,CC BY-SA 4.0,2019-11-02 15:40:11,489,443,0,0,0,5,true,false,false,true,true,true,83,13,false,0.255,0.006,2577,2019,11,9,Friday,false,false,false,false,false,false,false
24035984,Instantiate and Present a viewController in Swift,"Issue
I started taking a look on the Swift Programming Language, and somehow I am not able to correctly type the initialization of a UIViewController from a specific UIStoryboard.
In Objective-C I simply write:
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"StoryboardName" bundle:nil];
UIViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:@"ViewControllerID"];
[self presentViewController:viewController animated:YES completion:nil];
Can anyone help me on how to achieve this on Swift?
",https://stackoverflow.com/questions/24035984/instantiate-and-present-a-viewcontroller-in-swift,353,393777.0,19.0,,,2014-06-04 11:16:57,2024-10-15 18:13:20,2021-08-22 18:31:44,,,ios;objective-c;swift;uiviewcontroller,Riddie,14800,2664437,registered,true,24036067,,CC BY-SA 4.0,,663,557,5,0,0,4,true,false,false,true,true,true,49,7,false,0.048,0.0009,4553,2014,6,11,Wednesday,false,false,false,false,false,false,false
26070242,Move view with keyboard using Swift,"I have an app that has a text field on the lower half of the view.
This means that when I go to type in the text field the keyboard covers the textfield.
How would I go about moving the view upwards while typing so I can see what i'm typing and then moving it back down to its original place when the keyboard disappears?
I've looked everywhere but all the solutions appear to be in Obj-C which I can't quite convert just yet.
Any help would be greatly appreciated.
",https://stackoverflow.com/questions/26070242/move-view-with-keyboard-using-swift,352,303197.0,44.0,,,2014-09-27 00:53:44,2024-02-07 06:07:00,2015-10-02 16:36:12,,,ios;swift;uikit;nsnotificationcenter;uikeyboard,Alex Catchpole,7346,3195915,registered,true,31124676,,CC BY-SA 3.0,,497,469,0,0,0,5,true,false,false,true,true,true,35,6,false,0.145,0.0012,4438,2014,9,0,Saturday,true,false,false,false,false,false,false
8082719,Convert an NSURL to an NSString,"I have an app where the user can choose an image either from the built-in app images or from the iphone photo library. I use an object Occasion that has an NSString property to save the imagePath.
Now in the case of the built-in app images I do get the file name as an NSString an save in the [occasion imagePath]. But in the 2nd case where the user picks an image form the photo library I get an NSURL which I want to convert to an NSString to be able to save it in [occasion imagePath].
Is it possible to convert the NSURL to an NSString?
",https://stackoverflow.com/questions/8082719/convert-an-nsurl-to-an-nsstring,349,234949.0,7.0,,,2011-11-10 16:20:51,2019-03-27 10:07:34,2016-03-15 09:40:01,,,ios;objective-c;swift;nsstring;nsurl,Ali,4245,850350,registered,true,8082747,,CC BY-SA 3.0,,682,544,9,0,0,5,true,false,false,true,true,true,31,6,false,0.03,0.0015,5490,2011,11,16,Thursday,false,false,false,false,false,false,false
24428250,Generate a UUID on iOS from Swift,"In my iOS Swift app I want to generate random UUID (GUID) strings for use as a table key, and this snippet appears to work:
let uuid = CFUUIDCreateString(nil, CFUUIDCreate(nil))
Is this safe?
Or is there perhaps a better (recommended) approach?
",https://stackoverflow.com/questions/24428250/generate-a-uuid-on-ios-from-swift,342,209073.0,8.0,,,2014-06-26 10:35:18,2022-08-05 22:41:36,2016-04-25 19:40:56,,,ios;swift;cocoa-touch;guid;core-foundation,zacjordaan,3840,1256917,registered,true,24428458,,CC BY-SA 3.0,,313,250,1,0,0,5,true,false,false,true,true,true,33,7,false,0.038,0.0016,4531,2014,6,10,Thursday,false,false,false,false,false,false,false
24070450,How to get the current time as datetime,"Just started with the playground. I'm trying to create a simple app.
I've created a date object like this:
var date = NSDate()
How can I get the current hour? In other languages I can do something like this:
var hour = date.hour
But I can't find any properties/methods like that. I've found a method, dateWithCalendarFormat. Should I use that? If so, HOW?
",https://stackoverflow.com/questions/24070450/how-to-get-the-current-time-as-datetime,341,679112.0,28.0,,,2014-06-05 21:27:50,2023-08-07 08:56:44,2016-10-03 10:17:26,,,datetime;swift,JOSEFtw,10111,1141089,registered,true,24070837,,CC BY-SA 3.0,,452,363,3,0,0,2,true,false,false,true,true,true,39,8,false,0.041,0.0005,4552,2014,6,21,Thursday,false,false,false,false,false,false,false
56437036,How do I change the background color of a SwiftUI View?,"Is there a straightforward way to change the background of a View using SwiftUI?
",https://stackoverflow.com/questions/56437036/how-do-i-change-the-background-color-of-a-swiftui-view,340,462106.0,22.0,,,2019-06-04 03:38:54,2025-08-05 15:41:56,2025-08-05 15:41:56,,,swift;swiftui;view;background,jeremyabannister,4466,2977972,registered,true,,,CC BY-SA 4.0,,101,81,1,0,0,4,false,false,false,true,true,true,55,11,true,0.048,0.0007,2727,2019,6,3,Tuesday,false,false,false,false,false,false,false
39176196,How to provide a localized description with an Error type in Swift?,"I am defining a custom error type with Swift 3 syntax and I want to provide a user-friendly description of the error which is returned by the localizedDescription property of the Error object. How can I do it?
public enum MyError: Error {
case customError
var localizedDescription: String {
switch self {
case .customError:
return NSLocalizedString(""A user-friendly description of the error."", comment: ""My error"")
}
}
}
let error: Error = MyError.customError
error.localizedDescription
// ""The operation couldn’t be completed. (MyError error 0.)""
Is there a way for the localizedDescription to return my custom error description (""A user-friendly description of the error."")? Note that the error object here is of type Error and not MyError. I can, of course, cast the object to MyError
(error as? MyError)?.localizedDescription
but is there a way to make it work without casting to my error type?
",https://stackoverflow.com/questions/39176196/how-to-provide-a-localized-description-with-an-error-type-in-swift,338,125290.0,7.0,,,2016-08-27 00:06:03,2023-01-14 18:11:26,2018-12-28 18:39:25,,,swift;swift3;error-handling;nslocalizedstring,Evgenii,37549,297131,registered,true,39176551,,CC BY-SA 4.0,,1066,932,7,0,0,4,true,false,false,true,true,true,67,12,true,0.056,0.0027,3738,2016,8,0,Saturday,true,false,false,false,false,false,false
24002819,Difference between == and ===,"In swift there seem to be two equality operators: the double equals (==) and the triple equals (===), what is the difference between the two?
",https://stackoverflow.com/questions/24002819/difference-between-and,337,129558.0,10.0,,,2014-06-02 20:35:12,2023-03-29 10:31:24,2014-06-05 03:59:24,,,swift,Fela,27630,1494793,registered,true,50645846,,CC BY-SA 3.0,,209,142,2,0,0,1,true,false,false,true,true,true,29,5,false,0.077,0.0026,4555,2014,6,20,Monday,false,false,false,false,false,false,false
24102104,How can I import Swift code to Objective-C?,"I have written a library in Swift and I wasn't able to import it to my current project, written in Objective-C.
Are there any ways to import it?
#import ""SCLAlertView.swift"" - 'SCLAlertView.swift' file not found
",https://stackoverflow.com/questions/24102104/how-can-i-import-swift-code-to-objective-c,334,269403.0,16.0,,,2014-06-08 01:08:00,2023-12-31 13:27:36,2018-04-12 13:31:26,,,objective-c;import;swift,Dark Matter,3698,1738900,registered,true,24102880,,CC BY-SA 3.0,2015-12-21 09:55:05,254,216,1,0,0,3,true,false,false,true,true,true,43,8,true,0.059,0.0012,4549,2014,6,1,Sunday,true,false,false,false,false,false,false
29209453,How to hide a navigation bar from first ViewController in Swift?,"How can I hide a navigation bar from first ViewController or a particular ViewController in swift?
I used the following code in viewDidLoad():
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.isNavigationBarHidden = true
}
and also on viewWillAppear:
override func viewWillAppear(animated: Bool) {
self.navigationController?.isNavigationBarHidden = true
}
Both methods hide the navigation controller from all ViewControllers.
",https://stackoverflow.com/questions/29209453/how-to-hide-a-navigation-bar-from-first-viewcontroller-in-swift,334,332476.0,14.0,,,2015-03-23 11:48:09,2022-08-26 01:31:12,2018-06-09 13:55:39,,,ios;swift;uinavigationcontroller;uinavigationbar,Vettiyanakan,8660,2082723,registered,true,29209623,,CC BY-SA 4.0,2018-11-17 22:16:42,576,474,4,0,0,4,true,false,false,true,true,true,64,11,true,0.042,0.001,4261,2015,3,11,Monday,false,false,false,false,false,false,false
24059327,Detect current device with UI_USER_INTERFACE_IDIOM() in Swift,"What is the equivalent of UI_USER_INTERFACE_IDIOM() in Swift to detect between iPhone and iPad?
I get an Use of unresolved identifier error when compiling in Swift.
",https://stackoverflow.com/questions/24059327/detect-current-device-with-ui-user-interface-idiom-in-swift,332,212012.0,18.0,,,2014-06-05 11:43:52,2022-02-12 02:47:50,2014-07-19 05:06:35,,,ios;iphone;objective-c;ipad;swift,Berry Blue,17156,284714,registered,true,24059373,,CC BY-SA 3.0,,206,166,2,0,0,5,true,false,false,true,true,true,61,7,false,0.085,0.0016,4552,2014,6,11,Thursday,false,false,false,false,false,false,false
24091882,Checking if an object is a given type in Swift,"I have an array that is made up of AnyObject. I want to iterate over it, and find all elements that are array instances.
How can I check if an object is of a given type in Swift?
",https://stackoverflow.com/questions/24091882/checking-if-an-object-is-a-given-type-in-swift,330,312434.0,20.0,,,2014-06-06 23:04:37,2025-09-22 04:47:24,2018-12-18 15:35:32,,,swift;type-inference;typechecking,Encore PTL,8284,843244,registered,true,24091892,,CC BY-SA 4.0,,207,180,1,0,0,3,true,false,false,true,true,true,46,10,false,0.064,0.0011,4551,2014,6,23,Friday,false,false,false,false,false,false,false
24026510,How do I shuffle an array in Swift?,".shuffle() and .shuffled() are part of Swift
Original historic question:
How do I randomize or shuffle the elements within an array in Swift? For example, if my array consists of 52 playing cards, I want to shuffle the array in order to shuffle the deck.
",https://stackoverflow.com/questions/24026510/how-do-i-shuffle-an-array-in-swift,329,104720.0,25.0,,,2014-06-03 23:15:08,2022-11-17 14:14:18,2022-11-17 14:14:18,,,arrays;swift;shuffle,M-P,4959,577237,registered,true,24029847,,CC BY-SA 4.0,,317,256,0,0,0,3,true,false,false,true,true,true,35,8,true,0.239,0.0031,4554,2014,6,23,Tuesday,false,false,false,false,false,false,false
24051633,How to remove an element from an array in Swift,"How can I unset/remove an element from an array in Apple's new language Swift?
Here's some code:
let animals = [""cats"", ""dogs"", ""chimps"", ""moose""]
How could the element animals[2] be removed from the array?
",https://stackoverflow.com/questions/24051633/how-to-remove-an-element-from-an-array-in-swift,328,504659.0,19.0,,,2014-06-05 04:26:36,2025-02-22 16:45:46,2016-06-09 12:55:30,,,arrays;swift,Leopold Joy,4670,2590203,registered,true,24051661,,CC BY-SA 3.0,,269,211,2,0,0,2,true,false,false,true,true,true,47,10,false,0.038,0.0006,4552,2014,6,4,Thursday,false,false,false,false,false,false,false
24475792,How to use pull-to-refresh in Swift?,"I am building an RSS reader using Swift and need to implement pull-to-reload functionality.
Here is how I am trying to do it.
class FirstViewController: UIViewController,
UITableViewDelegate, UITableViewDataSource {
@IBOutlet var refresh: UIScreenEdgePanGestureRecognizer
@IBOutlet var newsCollect: UITableView
var activityIndicator:UIActivityIndicatorView? = nil
override func viewDidLoad() {
super.viewDidLoad()
self.newsCollect.scrollEnabled = true
// Do any additional setup after loading the view, typically from a nib.
if nCollect.news.count <= 2{
self.collectNews()
}
else{
self.removeActivityIndicator()
}
view.addGestureRecognizer(refresh)
}
@IBAction func reload(sender: UIScreenEdgePanGestureRecognizer) {
nCollect.news = News[]()
return newsCollect.reloadData()
}
I am getting :
Property 'self.refresh' not initialized at super.init call
Please help me to understand the behavior of Gesture recognizers. A working sample code will be a great help.
Thanks.
",https://stackoverflow.com/questions/24475792/how-to-use-pull-to-refresh-in-swift,324,277132.0,19.0,,,2014-06-29 11:47:42,2023-10-04 09:41:04,2023-09-22 21:42:45,,,ios;swift;xcode;uirefreshcontrol,xrage,4821,1523811,registered,true,24476087,,CC BY-SA 4.0,2016-06-14 18:24:00,1175,1084,1,0,0,4,true,false,false,true,true,true,36,6,true,0.069,0.0012,4528,2014,6,11,Sunday,true,false,false,false,false,false,false
56973959,SwiftUI: How to implement a custom init with @Binding variables,"I am working on a money input screen and I need to implement a custom init to set a state variable based on the initialized amount.
I thought the following would work:
struct AmountView : View {
@Binding var amount: Double
@State var includeDecimal = false
init(amount: Binding<Double>) {
self.amount = amount
self.includeDecimal = round(amount)-amount > 0
}
}
However, this gives me a compiler error as follows:
Cannot assign value of type 'Binding' to type 'Double'
How do I implement a custom init method which takes in a Binding struct?
",https://stackoverflow.com/questions/56973959/swiftui-how-to-implement-a-custom-init-with-binding-variables,323,144915.0,7.0,,,2019-07-10 15:23:37,2022-12-22 07:06:14,2022-12-22 07:06:14,,,swift;swiftui,keegan3d,11343,239380,registered,true,56975728,,CC BY-SA 4.0,,753,590,4,0,0,2,true,false,false,true,true,true,63,10,false,0.048,0.0022,2691,2019,7,15,Wednesday,false,false,false,false,false,false,false
26386093,Array from dictionary keys in swift,"Trying to fill an array with strings from the keys in a dictionary in swift.
var componentArray: [String]
let dict = NSDictionary(contentsOfFile: NSBundle.mainBundle().pathForResource(""Components"", ofType: ""plist"")!)
componentArray = dict.allKeys
This returns an error of: 'AnyObject' not identical to string
Also tried
componentArray = dict.allKeys as String
but get: 'String' is not convertible to [String]
",https://stackoverflow.com/questions/26386093/array-from-dictionary-keys-in-swift,322,243355.0,12.0,,,2014-10-15 15:16:23,2020-06-14 07:53:38,,,,ios;arrays;xcode;dictionary;swift,Kyle Goslan,10940,1081325,registered,true,28658885,,CC BY-SA 3.0,,494,418,2,0,0,5,true,false,false,true,true,false,35,6,false,0.049,0.0013,4420,2014,10,15,Wednesday,false,false,false,false,false,false,false
24006234,What is the purpose of willSet and didSet in Swift?,"Swift has a property declaration syntax very similar to C#'s:
var foo: Int {
get { return getFoo() }
set { setFoo(newValue) }
}
However, it also has willSet and didSet actions. These are called before and after the setter is called, respectively. What is their purpose, considering that you could just have the same code inside the setter?
",https://stackoverflow.com/questions/24006234/what-is-the-purpose-of-willset-and-didset-in-swift,322,272762.0,11.0,,,2014-06-03 02:32:38,2022-12-23 22:56:34,2019-07-16 21:22:00,,,swift;callback;didset;property-observer,zneak,139335,251153,registered,true,24006282,,CC BY-SA 4.0,2018-05-23 04:42:13,415,351,3,0,0,4,true,false,false,true,true,true,51,10,true,0.04,0.0012,4554,2014,6,2,Tuesday,false,false,false,false,false,false,false
30743408,Check for internet connection with Swift,"When I try to check for an internet connection on my iPhone I get a bunch of errors. Can anyone help me to fix this?
The code:
import Foundation
import SystemConfiguration
public class Reachability {
class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}
var flags: SCNetworkReachabilityFlags = 0
if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == 0 {
return false
}
let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
return (isReachable && !needsConnection) ? true : false
}
}
The errors with the code:
![]()
If it is unreadable, error 1 says:
'Int' is not convertible to 'SCNetworkReachabilityFlags'
Error 2 & 3:
Could not find an overload for 'init' that accepts the supplied arguments
",https://stackoverflow.com/questions/30743408/check-for-internet-connection-with-swift,319,363813.0,32.0,,,2015-06-09 21:45:11,2025-11-10 13:50:09,2025-11-10 13:50:09,,,ios;swift;reachability;network-framework,b3rge,5019,2514271,registered,true,30743763,,CC BY-SA 4.0,2015-09-30 22:24:37,1351,1165,1,0,1,4,true,false,false,true,true,true,40,6,false,0.088,0.0009,4183,2015,6,21,Tuesday,false,false,false,false,false,false,false
28302019,Getting a "This application is modifying the autolayout engine from a background thread" error?,"Been encountering this error a lot in my OS X using swift:
""This application is modifying the autolayout engine from a background thread, which can lead to engine corruption and weird crashes. This will cause an exception in a future release.""
I have a my NSWindow and I'm swapping in views to the contentView of the window. I get the error when I try and do a NSApp.beginSheet on the window, or when I add a subview to the window. Tried disabling autoresize stuff, and I don't have anything using auto layout. Any thoughts?
Sometimes it's fine and nothing happens, other times it totally breaks my UI and nothing loads
",https://stackoverflow.com/questions/28302019/getting-a-this-application-is-modifying-the-autolayout-engine-from-a-background,319,163336.0,21.0,,,2015-02-03 15:01:18,2020-06-05 06:05:06,2018-05-30 15:16:51,,,swift;macos;autolayout;background-thread,Mark,12572,4396258,registered,true,28321213,,CC BY-SA 4.0,2018-05-30 06:55:52,768,629,4,0,0,4,true,false,false,true,true,true,105,14,true,0.129,0.002,4309,2015,2,15,Tuesday,false,false,false,false,false,false,false
24687238,Changing navigation bar color in Swift,"I am using a Picker View to allow the user to choose the colour theme for the entire app.
I am planning on changing the colour of the navigation bar, background and possibly the tab bar (if that is possible).
I've been researching how to do this but can't find any Swift examples. Could anyone please give me an example of the code I would need to use to change the navigation bar colour and navigation bar text colour?
The Picker View is set up, I'm just looking for the code to change the UI colours.
",https://stackoverflow.com/questions/24687238/changing-navigation-bar-color-in-swift,316,451922.0,37.0,,,2014-07-10 22:18:45,2026-02-28 07:22:05,2020-01-07 00:48:04,,,ios;swift;uinavigationbar,user3746428,11174,3746428,registered,true,24687554,,CC BY-SA 4.0,,534,506,0,0,0,3,true,false,false,true,true,true,38,6,false,0.082,0.0007,4517,2014,7,22,Thursday,false,false,false,false,false,false,false
5494498,How to control the line spacing in UILabel,"Is it possible to reduce the gap between text, when put in multiple lines in a UILabel? We can set the frame, font size and number of lines. I want to reduce the gap between the two lines in that label.
",https://stackoverflow.com/questions/5494498/how-to-control-the-line-spacing-in-uilabel,316,286135.0,21.0,,,2011-03-31 01:50:12,2021-02-11 10:53:36,2020-04-28 22:00:30,,,objective-c;swift;xcode;uilabel;line-spacing,Abhinav,38200,418029,registered,true,5513730,,CC BY-SA 4.0,,223,203,1,0,0,5,true,false,false,true,true,true,42,8,false,0.073,0.0011,5714,2011,3,1,Thursday,false,false,false,false,false,false,false
35700281,How do I convert a date/time string into a different date string?,"How will I convert this datetime from the date?
From this: 2016-02-29 12:24:26
to: Feb 29, 2016
So far, this is my code and it returns a nil value:
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = ""MM-dd-yyyy""
dateFormatter.timeZone = NSTimeZone(name: ""UTC"")
let date: NSDate? = dateFormatter.dateFromString(""2016-02-29 12:24:26"")
print(date)
",https://stackoverflow.com/questions/35700281/how-do-i-convert-a-date-time-string-into-a-different-date-string,314,571193.0,25.0,,,2016-02-29 13:02:20,2025-01-16 22:07:37,2023-04-04 19:01:34,,,ios;swift;nsdate;nsdateformatter,Sydney Loteria,10471,4335771,registered,true,35700409,,CC BY-SA 4.0,2020-10-20 23:14:21,461,370,1,0,0,4,true,false,false,true,true,true,65,12,true,0.044,0.0005,3918,2016,2,13,Monday,false,false,false,false,false,false,false
24410881,Reading in a JSON File Using Swift,"I'm really struggling with trying to read a JSON file into Swift so I can play around with it. I've spent the best part of 2 days re-searching and trying different methods but no luck as of yet so I have signed up to StackOverFlow to see if anyone can point me in the right direction.....
My JSON file is called test.json and contains the following:
{
""person"":[
{
""name"": ""Bob"",
""age"": ""16"",
""employed"": ""No""
},
{
""name"": ""Vinny"",
""age"": ""56"",
""employed"": ""Yes""
}
]
}
The file is stored in the documents directly and I access it using the following code:
let file = ""test.json""
let dirs : String[] = NSSearchPathForDirectoriesInDomains(
NSSearchpathDirectory.DocumentDirectory,
NSSearchPathDomainMask.AllDomainMask,
true) as String[]
if (dirs != nil) {
let directories: String[] = dirs
let dir = directories[0]
let path = dir.stringByAppendingPathComponent(file)
}
var jsonData = NSData(contentsOfFile:path, options: nil, error: nil)
println(""jsonData \(jsonData)"" // This prints what looks to be JSON encoded data.
var jsonDict = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: nil) as? NSDictionary
println(""jsonDict \(jsonDict)"") - This prints nil.....
If anyone can just give me a push in the right direction on how I can de-serialize the JSON file and put it in an accessible Swift object I will be eternally grateful!
Kind Regards,
Krivvenz.
",https://stackoverflow.com/questions/24410881/reading-in-a-json-file-using-swift,313,392060.0,35.0,,,2014-06-25 14:04:26,2022-11-01 20:53:16,2020-02-18 11:01:53,,,json;xcode;swift;ios8;nsjsonserialization,Krivvenz,4059,3775328,registered,true,36827996,,CC BY-SA 4.0,2022-02-28 15:33:17,1732,1642,2,0,0,5,true,false,false,true,true,true,34,7,false,0.089,0.0008,4532,2014,6,14,Wednesday,false,false,false,false,false,false,false
24795130,Finding sum of elements in Swift array,"What is the easiest (best) way to find the sum of an array of integers in swift?
I have an array called multiples and I would like to know the sum of the multiples.
",https://stackoverflow.com/questions/24795130/finding-sum-of-elements-in-swift-array,310,207486.0,16.0,,,2014-07-17 04:53:30,2024-03-13 16:58:35,2017-12-25 15:07:50,,,arrays;swift,ejLev,3231,3738678,registered,true,24795181,,CC BY-SA 3.0,2022-05-27 06:33:20,172,165,0,0,0,2,true,false,false,true,true,true,38,7,false,0.077,0.0015,4510,2014,7,4,Thursday,false,false,false,false,false,false,false
24031621,Swift - How to convert String to Double,"I'm trying to write a BMI program in swift language.
And I got this problem: how to convert a String to a Double?
In Objective-C, I can do like this:
double myDouble = [myString doubleValue];
But how can I achieve this in Swift language?
",https://stackoverflow.com/questions/24031621/swift-how-to-convert-string-to-double,308,424362.0,31.0,,,2014-06-04 07:36:42,2023-09-20 22:48:51,2019-01-03 08:08:23,,,swift,ohyes,3338,3081804,registered,true,32850058,,CC BY-SA 4.0,2021-08-21 11:00:30,282,241,1,0,0,1,true,false,false,true,true,true,39,8,false,0.073,0.0007,4553,2014,6,7,Wednesday,false,false,false,false,false,false,false
25644054,UIActivityViewController crashing on iOS 8 iPads,"I am currently testing my app with Xcode 6 (Beta 6). UIActivityViewController works fine with iPhone devices and simulators but crashes with iPad simulators and devices (iOS 8) with following logs
Terminating app due to uncaught exception 'NSGenericException',
reason: 'UIPopoverPresentationController
(<_UIAlertControllerActionSheetRegularPresentationController: 0x7fc7a874bd90>)
should have a non-nil sourceView or barButtonItem set before the presentation occurs.
I am using following code for iPhone and iPad for both iOS 7 as well as iOS 8
NSData *myData = [NSData dataWithContentsOfFile:_filename];
NSArray *activityItems = [NSArray arrayWithObjects:myData, nil];
UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:nil applicationActivities:nil];
activityViewController.excludedActivityTypes = @[UIActivityTypeCopyToPasteboard];
[self presentViewController:activityViewController animated:YES completion:nil];
I am getting a similar crash in of one my other app as well. Can you please guide me ? has anything changed with UIActivityViewController in iOS 8? I checked but i did not find anything on this
",https://stackoverflow.com/questions/25644054/uiactivityviewcontroller-crashing-on-ios-8-ipads,308,102916.0,21.0,,,2014-09-03 12:15:10,2022-06-16 23:29:47,2020-08-26 11:52:51,,,ios;objective-c;swift;uiactivityviewcontroller,Bhumit Mehta,16318,2321467,registered,true,25644145,,CC BY-SA 4.0,,1250,1181,2,0,0,4,true,false,false,true,true,true,48,6,false,0.204,0.003,4462,2014,9,12,Wednesday,false,false,false,false,false,false,false
24101450,How do you find out the type of an object (in Swift)?,"When trying to understand a program, or in some corner-cases, it's useful to find out what type something is. I know the debugger can show you some type information, and you can usually rely on type inference to get away with not specifying the type in those situations, but still, I'd really like to have something like Python's type()
dynamicType (see this question)
Update: this has been changed in a recent version of Swift, obj.dynamicType now gives you a reference to the type and not the instance of the dynamic type.
This one seems the most promising, but I haven't been able to find out the actual type so far.
class MyClass {
var count = 0
}
let mc = MyClass()
# update: this now evaluates as true
mc.dynamicType === MyClass.self
I also tried using a class reference to instantiate a new object, which does work, but oddly gave me an error saying I must add a required initializer:
works:
class MyClass {
var count = 0
required init() {
}
}
let myClass2 = MyClass.self
let mc2 = MyClass2()
Still only a small step toward actually discovering the type of any given object though
edit: I've removed a substantial number of now irrelevant details - look at the edit history if you're interested :)
",https://stackoverflow.com/questions/24101450/how-do-you-find-out-the-type-of-an-object-in-swift,306,285238.0,14.0,,,2014-06-07 20:46:23,2021-06-20 11:00:43,2021-06-20 11:00:43,,,ios;swift;typechecking,Jiaaro,77586,2908,registered,true,40132792,,CC BY-SA 4.0,,1524,1226,5,1,0,3,true,false,false,true,true,true,53,12,true,0.049,0.0011,4550,2014,6,20,Saturday,true,false,false,false,false,false,false
25649926,Animating a constraint in Swift,"I have a UITextField that I want to enlarge its width when tapped on. I set up the constraints and made sure the constraint on the left has the lower priority then the one that I am trying to animate on the right side.
Here is the code that I am trying to use.
// move the input box
UIView.animateWithDuration(10.5, animations: {
self.nameInputConstraint.constant = 8
}, completion: {
(value: Bool) in
println(">>> move const")
})
This works, but it seems to just happen instantly and there doesn't seem to be any movement. I tried to set it 10 seconds to make sure I wasn't missing anything, but I got the same results.
nameInputConstraint is the name of the constraint that I control dragged to connect into my class from IB.
",https://stackoverflow.com/questions/25649926/animating-a-constraint-in-swift,305,163199.0,7.0,,,2014-09-03 17:03:11,2023-05-17 16:21:37,2023-05-17 16:21:37,,,xcode;swift;constraints;xcode6,icekomo,9526,2875080,registered,true,25650669,,CC BY-SA 4.0,,890,772,3,0,0,4,true,false,false,true,true,true,31,5,false,0.043,0.0019,4462,2014,9,17,Wednesday,false,false,false,false,false,false,false
24122288,Remove last character from string. Swift language,"How can I remove last character from String variable using Swift? Can't find it in documentation.
Here is full example:
var expression = ""45+22""
expression = expression.substringToIndex(countElements(expression) - 1)
",https://stackoverflow.com/questions/24122288/remove-last-character-from-string-swift-language,305,222542.0,23.0,,,2014-06-09 14:21:09,2022-08-12 19:55:45,2014-06-09 14:34:45,,,string;character;swift,Konstantin Cherkasov,3353,2527793,registered,true,24122445,,CC BY-SA 3.0,,258,220,1,0,0,3,true,false,false,true,true,true,49,7,false,0.103,0.0014,4548,2014,6,14,Monday,false,false,false,false,false,false,false
24091233,How to write a multiline string in Swift?,"How could I split a string over multiple lines such as below?
var text:String = ""This is some text
over multiple lines""
",https://stackoverflow.com/questions/24091233/how-to-write-a-multiline-string-in-swift,305,177891.0,18.0,,,2014-06-06 21:56:55,2024-11-26 12:09:42,2023-10-16 20:08:30,,,string;swift,Andrew Deniszczyc,3438,1376619,registered,true,24091332,,CC BY-SA 4.0,,172,141,1,0,0,2,true,false,false,true,true,true,41,8,true,0.101,0.0017,4551,2014,6,21,Friday,false,false,false,false,false,false,false
24356888,How do I change the font size of a UILabel in Swift?,"label.font.pointSize is read-only, so I'm not sure how to change it.
",https://stackoverflow.com/questions/24356888/how-do-i-change-the-font-size-of-a-uilabel-in-swift,302,360778.0,21.0,,,2014-06-23 00:04:37,2022-11-10 08:11:44,2021-11-08 08:35:09,,,ios;swift;xcode;cocoa-touch;uilabel,Jay,9650,336892,registered,true,24356906,,CC BY-SA 4.0,,89,69,1,0,0,5,true,false,false,true,true,true,52,12,true,0.058,0.0008,4534,2014,6,0,Monday,false,false,false,false,false,false,false
458304,How can I programmatically determine if my app is running in the iphone simulator?,"As the question states, I would mainly like to know whether or not my code is running in the simulator, but would also be interested in knowing the specific iphone version that is running or being simulated.
EDIT: I added the word 'programmatically' to the question name. The point of my question is to be able to dynamically include / exclude code depending on which version / simulator is running, so I'd really be looking for something like a pre-processor directive that can provide me this info.
",https://stackoverflow.com/questions/458304/how-can-i-programmatically-determine-if-my-app-is-running-in-the-iphone-simulato,298,131703.0,21.0,,,2009-01-19 16:55:32,2022-10-21 10:06:45,2018-08-08 13:10:23,,,ios;objective-c;swift;xcode;ios-simulator,Jeffrey Meyer,5470,2323,registered,true,458388,,CC BY-SA 4.0,,516,502,0,0,0,5,true,false,false,true,true,true,82,14,true,0.159,0.0023,6515,2009,1,16,Monday,false,false,false,false,false,false,false
25138339,NSRange to Range<String.Index>,"How can I convert NSRange to Range<String.Index> in Swift?
I want to use the following UITextFieldDelegate method:
func textField(textField: UITextField!,
shouldChangeCharactersInRange range: NSRange,
replacementString string: String!) -> Bool {
textField.text.stringByReplacingCharactersInRange(???, withString: string)
![]()
",https://stackoverflow.com/questions/25138339/nsrange-to-rangestring-index,298,147695.0,16.0,,,2014-08-05 12:01:21,2021-11-14 16:59:08,2014-11-05 09:12:04,,,nsstring;swift;ios8;nsrange,János,35580,239219,registered,true,26517690,,CC BY-SA 3.0,2019-07-29 10:27:22,519,357,4,0,1,4,true,false,false,true,true,true,36,3,false,0.108,0.002,4491,2014,8,12,Tuesday,false,false,false,false,false,false,false
56760335,How can I round specific corners of a View?,"I know you can use .cornerRadius() to round all the corners of a SwiftUI view, but is there a way to round only specific corners, such as the top?
",https://stackoverflow.com/questions/56760335/how-can-i-round-specific-corners-of-a-view,297,158892.0,12.0,,,2019-06-25 18:50:08,2025-08-04 14:34:03,2025-08-04 14:32:25,,,swift;swiftui;cornerradius,Richard Witherspoon,5169,10830089,registered,true,58606176,,CC BY-SA 4.0,,167,147,1,0,0,3,true,false,false,true,true,true,43,9,true,0.076,0.0019,2706,2019,6,18,Tuesday,false,false,false,false,false,false,false
26076054,Changing Placeholder Text Color with Swift,"I have a design that implements a dark blue UITextField, as the placeholder text is by default a dark grey colour I can barely make out what the place holder text says.
I've googled the problem of course but I have yet to come up with a solution while using the Swift language and not Obj-c.
Is there a way to change the placeholder text colour in a UITextField using Swift?
",https://stackoverflow.com/questions/26076054/changing-placeholder-text-color-with-swift,297,275825.0,32.0,,,2014-09-27 15:10:34,2023-07-20 10:18:05,2018-08-03 09:36:22,,,ios;swift;uikit,Alex Catchpole,7346,3195915,registered,true,26076202,,CC BY-SA 4.0,,424,377,2,0,0,3,true,false,false,true,true,true,42,6,false,0.116,0.0011,4438,2014,9,15,Saturday,true,false,false,false,false,false,false
56505692,How to resize Image with SwiftUI?,"I have a large image in Assets.xcassets. How to resize this image with SwiftUI to make it small?
I tried to set frame but it doesn't work:
Image(room.thumbnailImage)
.frame(width: 32.0, height: 32.0)
",https://stackoverflow.com/questions/56505692/how-to-resize-image-with-swiftui,296,314621.0,26.0,,,2019-06-08 10:55:56,2025-09-24 19:17:22,,,,ios;swift;swiftui,Daniil Subbotin,6743,4106171,registered,true,56505725,,CC BY-SA 4.0,2023-08-10 20:46:29,245,207,1,0,0,3,true,false,false,true,true,false,33,6,true,0.083,0.0009,2723,2019,6,10,Saturday,true,false,false,false,false,false,false
24924809,"The file "MyApp.app" couldn't be opened because you don't have permission to view it" when running app in Xcode 6 Beta 4,"Whenever I try to run my app in Xcode 6 Beta 4 I am getting the error:
The file ""MyApp.app"" couldn't be opened because you don't have permission to view it.
This error appears no matter what simulator or device I target.
I have tried:
- Deleting all Derived Data from Organizer in Xcode
- Repairing permissions on my drive
- Manually elevating the permissions of the built MyApp.app
- Restarting my computer
Has anyone else run into this problem and found a solution?
![]()
",https://stackoverflow.com/questions/24924809/the-file-myapp-app-couldnt-be-opened-because-you-dont-have-permission-to-vi,295,197082.0,60.0,,,2014-07-24 03:48:27,2022-02-21 00:24:22,2015-03-27 13:06:07,,,swift;xcode5;xcode6,drewag,95163,661853,registered,true,24925131,,CC BY-SA 3.0,2015-09-12 14:38:35,634,470,1,0,1,3,true,false,false,true,true,true,149,22,false,0.304,0.0015,4503,2014,7,3,Thursday,false,false,false,false,false,false,false
24111627,Iterating Through a Dictionary in Swift,"I am a little confused on the answer that Xcode is giving me to this experiment in the Swift Programming Language Guide:
// Use a for-in to iterate through a dictionary (experiment)
let interestingNumbers = [
""Prime"": [2, 3, 5, 7, 11, 13],
""Fibonacci"": [1, 1, 2, 3, 5, 8],
""Square"": [1, 4, 9, 16, 25]
]
var largest = 0
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
}
}
}
largest
I understand that as the dictionary is being transversed, the largest number is being set to the variable, largest. However, I am confused as to why Xcode is saying that largest is being set 5 times, or 1 time, or 3 times, depending on each test.
When looking through the code, I see that it should be set 6 times in ""Prime"" alone (2, 3, 5, 7, 11, 13). Then it should skip over any numbers in ""Fibonacci"" since those are all less than the largest, which is currently set to 13 from ""Prime"". Then, it should be set to 16, and finally 25 in ""Square"", yielding a total of 8 times.
Am I missing something entirely obvious?
",https://stackoverflow.com/questions/24111627/iterating-through-a-dictionary-in-swift,295,303532.0,6.0,,,2014-06-08 22:42:54,2021-12-21 21:17:02,2016-10-12 20:10:22,,,dictionary;swift,Nick Kohrn,6119,3720634,registered,true,24111700,,CC BY-SA 3.0,,1197,1119,3,0,0,2,true,false,false,true,true,true,39,6,false,0.02,0.001,4549,2014,6,22,Sunday,true,false,false,false,false,false,false
24007518,How can I use Timer (formerly NSTimer) in Swift?,"I tried
var timer = NSTimer()
timer(timeInterval: 0.01, target: self, selector: update, userInfo: nil, repeats: false)
But, I got an error saying
'(timeInterval: $T1, target: ViewController, selector: () -> (), userInfo: NilType, repeats: Bool) -> $T6' is not identical to 'NSTimer'
",https://stackoverflow.com/questions/24007518/how-can-i-use-timer-formerly-nstimer-in-swift,294,417413.0,17.0,,,2014-06-03 05:09:02,2023-03-03 00:15:50,2019-08-11 16:32:51,,,ios;nstimer;nstimeinterval;swift,user3225917,3021,3225917,registered,true,24007862,,CC BY-SA 4.0,,356,294,2,0,0,4,true,false,false,true,true,true,48,9,true,0.041,0.0007,4554,2014,6,5,Tuesday,false,false,false,false,false,false,false
56496638,How to add an activity indicator in SwiftUI,"I'm trying to add a full screen activity indicator in SwiftUI.
I can use .overlay(overlay: ) function in a View Protocol.
With this, I can make any view overlay, but I can't find the iOS default style UIActivityIndicatorView equivalent in SwiftUI.
How can I make a default style spinner with SwiftUI?
NOTE: This is not about adding an activity indicator in UIKit framework.
",https://stackoverflow.com/questions/56496638/how-to-add-an-activity-indicator-in-swiftui,294,231619.0,18.0,,,2019-06-07 14:51:55,2025-09-08 23:54:32,2025-08-05 14:27:03,,,swift;swiftui,Johnykutty,12998,899573,registered,true,56496896,,CC BY-SA 4.0,2025-08-05 14:29:59,452,374,2,0,0,2,true,false,false,true,true,true,43,8,false,0.078,0.0013,2724,2019,6,14,Friday,false,false,false,false,false,false,false
24003918,Does Swift have access modifiers?,"In Objective-C instance data can be public, protected or private. For example:
@interface Foo : NSObject
{
@public
int x;
@protected:
int y;
@private:
int z;
}
-(int) apple;
-(int) pear;
-(int) banana;
@end
I haven't found any mention of access modifiers in the Swift reference. Is it possible to limit the visibility of data in Swift?
",https://stackoverflow.com/questions/24003918/does-swift-have-access-modifiers,294,111873.0,16.0,,,2014-06-02 21:52:47,2023-02-01 04:11:34,2017-12-11 15:15:30,,,access-modifiers;swift,Gergo Erdosi,42341,775443,registered,true,24012515,,CC BY-SA 3.0,,436,359,4,0,0,2,true,false,false,true,true,true,33,5,true,0.143,0.0026,4555,2014,6,21,Monday,false,false,false,false,false,false,false
24096708,What is the Swift equivalent of isEqualToString in Objective-C?,"I am trying to run the code below:
import UIKit
class LoginViewController: UIViewController {
@IBOutlet var username : UITextField = UITextField()
@IBOutlet var password : UITextField = UITextField()
@IBAction func loginButton(sender : AnyObject) {
if username .isEqual("") || password.isEqual(""))
{
println("Sign in failed. Empty character")
}
}
My previous code was in Objective-C, which was working fine:
if([[self.username text] isEqualToString: @""] ||
[[self.password text] isEqualToString: @""] ) {
I assume I cannot use isEqualToString in Swift.
",https://stackoverflow.com/questions/24096708/what-is-the-swift-equivalent-of-isequaltostring-in-objective-c,293,275993.0,8.0,,,2014-06-07 11:33:02,2023-02-17 09:16:08,2023-02-17 09:16:08,,,string;swift,Gokhan Dilek,4422,2873875,registered,true,24096764,,CC BY-SA 4.0,,758,636,3,0,0,2,true,false,false,true,true,true,63,9,true,0.029,0.0011,4550,2014,6,11,Saturday,true,false,false,false,false,false,false
25002017,How to change font of UIButton with Swift,"I am trying to change the font of a UIButton using Swift...
myButton.font = UIFont(name: ""..."", 10)
However .font is deprecated and I'm not sure how to change the font otherwise.
Any suggestions?
",https://stackoverflow.com/questions/25002017/how-to-change-font-of-uibutton-with-swift,292,316817.0,20.0,,,2014-07-28 18:39:20,2024-09-06 17:07:28,2014-07-28 18:42:01,,,ios;uibutton;swift;uifont,Stephen Fox,14500,2875074,registered,true,25002063,,CC BY-SA 3.0,,258,200,2,0,0,4,true,false,false,true,true,true,41,8,false,0.063,0.0009,4499,2014,7,18,Monday,false,false,false,false,false,false,false
25724527,Swift: Test class type in switch statement,"In Swift you can check the class type of an object using 'is'. How can I incorporate this into a 'switch' block?
I think it's not possible, so I'm wondering what is the best way around this.
",https://stackoverflow.com/questions/25724527/swift-test-class-type-in-switch-statement,292,130145.0,5.0,,,2014-09-08 12:41:51,2024-08-28 09:06:45,2019-08-07 09:19:40,,,class;swift;switch-statement,kingrolo,3027,1626099,registered,true,25724652,,CC BY-SA 4.0,,207,193,0,0,0,3,true,false,false,true,true,true,42,7,false,0.038,0.0022,4457,2014,9,12,Monday,false,false,false,false,false,false,false
27313242,How to append elements into a dictionary in Swift?,"I have a simple Dictionary which is defined like:
var dict : NSDictionary = [ 1 : ""abc"", 2 : ""cde""]
Now I want to add an element into this dictionary: 3 : ""efg""
How can I append 3 : ""efg"" into this existing dictionary?
",https://stackoverflow.com/questions/27313242/how-to-append-elements-into-a-dictionary-in-swift,292,451134.0,20.0,,,2014-12-05 09:59:44,2021-08-25 11:57:27,2019-07-08 15:16:54,,,swift;nsdictionary,Dharmesh Kheni,71954,4085910,registered,true,27313755,,CC BY-SA 4.0,,294,223,3,0,0,2,true,false,false,true,true,true,50,9,true,0.044,0.0006,4369,2014,12,9,Friday,false,false,false,false,false,false,false
26306326,Swift apply .uppercaseString to only the first letter of a string,"I am trying to make an autocorrect system, and when a user types a word with a capital letter, the autocorrect doesn't work. In order to fix this, I made a copy of the string typed, applied .lowercaseString, and then compared them. If the string is indeed mistyped, it should correct the word. However then the word that replaces the typed word is all lowercase. So I need to apply .uppercaseString to only the first letter. I originally thought I could use
nameOfString[0]
but this apparently does not work. How can I get the first letter of the string to uppercase, and then be able to print the full string with the first letter capitalized?
Thanks for any help!
",https://stackoverflow.com/questions/26306326/swift-apply-uppercasestring-to-only-the-first-letter-of-a-string,291,205283.0,31.0,,,2014-10-10 19:03:39,2023-01-16 14:33:33,2019-02-19 02:45:55,,,ios;swift;string;ios8-extension,SomeGuy,3875,1672545,registered,true,26306372,,CC BY-SA 4.0,2021-09-16 12:17:48,716,671,1,0,0,4,true,false,false,true,true,true,65,11,false,0.151,0.0014,4425,2014,10,19,Friday,false,false,false,false,false,false,false
10167221,iOS detect if user is on an iPad,"I have an app that runs on the iPhone and iPod Touch, it can run on the Retina iPad and everything but there needs to be one adjustment. I need to detect if the current device is an iPad. What code can I use to detect if the user is using an iPad in my UIViewController and then change something accordingly?
",https://stackoverflow.com/questions/10167221/ios-detect-if-user-is-on-an-ipad,291,173389.0,17.0,,,2012-04-15 23:53:06,2024-01-16 15:27:30,2023-06-08 17:25:47,,,ios;swift;objective-c;ipad,Albert Renshaw,18000,2057171,registered,true,10167255,,CC BY-SA 4.0,,329,309,1,0,0,4,true,false,false,true,true,true,32,8,false,0.098,0.0017,5333,2012,4,23,Sunday,true,false,false,false,false,false,false
26845307,Generate random alphanumeric string in Swift,"How can I generate a random alphanumeric string in Swift?
",https://stackoverflow.com/questions/26845307/generate-random-alphanumeric-string-in-swift,291,151846.0,26.0,,,2014-11-10 13:46:47,2025-02-19 18:32:55,2020-05-13 21:36:55,,,string;swift,vishnu,2981,1068205,registered,true,26845710,,CC BY-SA 4.0,,65,58,0,0,0,2,true,false,false,true,true,true,44,6,false,0.171,0.0019,4394,2014,11,13,Monday,false,false,false,false,false,false,false
46829840,Get safe area inset top and bottom heights,"What would be the most proper way to get both top and bottom height for the unsafe areas?
",https://stackoverflow.com/questions/46829840/get-safe-area-inset-top-and-bottom-heights,290,344564.0,27.0,,,2017-10-19 12:25:59,2024-12-18 19:59:20,2022-10-28 12:56:01,,,ios;swift;objective-c;safearealayoutguide,Tulleb,9323,2854405,registered,true,46831519,,CC BY-SA 4.0,,248,91,0,1,1,4,true,false,false,true,true,true,42,8,false,0.078,0.0008,3320,2017,10,12,Thursday,false,false,false,false,false,false,false
56487323,Make a VStack fill the width of the screen in SwiftUI,"Given this code:
import SwiftUI
struct ContentView: View {
var body: some View {
VStack(alignment: .leading) {
Text("Title")
.font(.title)
Text("Content")
.lineLimit(nil)
.font(.body)
Spacer()
}
.background(Color.red)
}
}
#if DEBUG
struct ContentView_Previews : PreviewProvider {
static var previews: some View {
ContentView()
}
}
#endif
It results in this interface:
How can I make the VStack fill the width of the screen even if the labels/text components don't need the full width?
A trick I've found is to insert an empty HStack in the structure like so:
VStack(alignment: .leading) {
HStack {
Spacer()
}
Text("Title")
.font(.title)
Text("Content")
.lineLimit(nil)
.font(.body)
Spacer()
}
Which yields the desired design:
Is there a better way?
",https://stackoverflow.com/questions/56487323/make-a-vstack-fill-the-width-of-the-screen-in-swiftui,290,290168.0,19.0,,,2019-06-07 02:38:02,2025-07-07 16:27:11,2021-04-18 07:39:49,,,ios;swift;xcode;swiftui,ielyamani,18671,2907715,registered,true,56487605,,CC BY-SA 4.0,,1375,893,4,2,2,4,true,false,false,true,true,true,53,11,false,0.065,0.001,2724,2019,6,2,Friday,false,false,false,false,false,false,false
24503001,Check OS version in Swift?,"I'm trying to check system information in Swift. I figured out, that it could be achieved by code:
var sysData:CMutablePointer<utsname> = nil
let retVal:CInt = uname(sysData)
I have two problems with this code:
- What should be sysData's initial value? This example gives -1 in retVal probably because sysData is nil.
- How can I read information from sysData?
",https://stackoverflow.com/questions/24503001/check-os-version-in-swift,288,252250.0,19.0,,,2014-07-01 05:26:31,2025-01-01 07:16:16,2016-10-27 16:15:17,,,ios;macos;swift,Gergely,3145,1347918,registered,true,24505884,,CC BY-SA 3.0,,434,369,1,0,0,3,true,false,false,true,true,true,26,5,true,0.075,0.0011,4526,2014,7,5,Tuesday,false,false,false,false,false,false,false
24003642,What is an optional value in Swift?,"From Apple's documentation:
You can use if and let together to work with values that might be missing. These values are represented as optionals. An optional value either contains a value or contains nil to indicate that the value is missing. Write a question mark (?) after the type of a value to mark the value as optional.
Why would you want to use an optional value?
",https://stackoverflow.com/questions/24003642/what-is-an-optional-value-in-swift,287,165493.0,15.0,,,2014-06-02 21:32:29,2023-11-02 09:19:02,2017-03-06 10:13:54,,,swift;option-type,Tim Vermeulen,12573,1223781,registered,true,24026093,,CC BY-SA 3.0,2018-09-20 21:59:13,649,377,4,1,0,2,true,false,false,true,true,true,35,7,true,0.091,0.0017,4555,2014,6,21,Monday,false,false,false,false,false,false,false
24110762,Swift: Determine iOS Screen size,"I would like to use Swift code to properly position items in my app for no matter what the screen size is. For example, if I want a button to be 75% of the screen wide, I could do something like (screenWidth * .75) to be the width of the button. I have found that this could be determined in Objective-C by doing
CGFloat screenWidth = screenSize.width;
CGFloat screenHeight = screenSize.height;
Unfortunately, I am unsure of how to convert this to Swift. Does anyone have an idea?
Thanks!
",https://stackoverflow.com/questions/24110762/swift-determine-ios-screen-size,284,364050.0,1.0,,,2014-06-08 20:58:57,2023-02-14 03:49:50,2014-06-08 21:05:20,2014-06-08 21:09:45,Duplicate,ios;swift,Z-Tech,4470,3530188,registered,true,24110816,,,,551,493,2,0,0,2,true,true,false,true,true,true,32,5,false,0.003,0.0008,4549,2014,6,20,Sunday,true,false,false,false,false,false,false
26326296,Changing text of UIButton programmatically swift,"Simple question here. I have a UIButton, currencySelector, and I want to programmatically change the text. Here's what I have:
currencySelector.text = ""foobar""
Xcode gives me the error ""Expected Declaration"". What am I doing wrong, and how can I make the button's text change?
",https://stackoverflow.com/questions/26326296/changing-text-of-uibutton-programmatically-swift,283,350669.0,13.0,,,2014-10-12 14:42:01,2023-09-29 03:01:52,2017-03-23 15:34:47,,,ios;xcode;swift;uibutton,rocket101,7547,3892545,registered,true,26326362,,CC BY-SA 3.0,,318,280,1,0,0,4,true,false,false,true,true,true,48,6,false,0.037,0.0008,4423,2014,10,14,Sunday,true,false,false,false,false,false,false
24206732,Can't use Swift classes inside Objective-C,"I try to integrate Swift code in my app.My app is written in Objective-C and I added a Swift class. I've done everything described here. But my problem is that Xcode haven't created the -Swift.h file, only the bridging headers. So I created it, but it's actually empty.
I can use all my ObjC classes in Swift, but I can't do it vice versa. I marked my swift class with @objc but it didn't help. What can I do now?
EDIT: Apple says:"" When you import Swift code into Objective-C, you rely on an Xcode-generated header file to expose those files to Objective-C. [...] The name of this header is your product module name followed by adding “-Swift.h”. ""
Now when I want to import that File, it gives an error:
//MainMenu.m
#import ""myProjectModule-Swift.h"" //Error: 'myProjectModule-Swift.h' file not found
@implementation MainMenu
Here is my FBManager.swift file:
@objc class FBManager: NSObject {
var descr = ""FBManager class""
init() {
super.init()
}
func desc(){
println(descr)
}
func getSharedGameState() -> GameState{
return GameState.sharedGameState() //OK! GameState is written in Objective-C and no error here
}
}
",https://stackoverflow.com/questions/24206732/cant-use-swift-classes-inside-objective-c,282,182197.0,28.0,,,2014-06-13 13:39:14,2024-12-18 07:20:09,2022-09-23 11:39:55,,,ios;swift;objective-c;static-libraries,dnnagy,3523,1708155,registered,true,,,CC BY-SA 4.0,2014-07-09 16:32:58,1556,1198,9,1,0,4,false,false,false,true,true,true,46,6,false,0.154,0.0015,4544,2014,6,13,Friday,false,false,false,false,false,false,false
29923881,Could not insert new outlet connection: Could not find any information for the class named,"I got an error on Xcode saying that there was no information about the view controller.
Could not insert new outlet connection: Could not find any information for the class named
Why is this happening?
",https://stackoverflow.com/questions/29923881/could-not-insert-new-outlet-connection-could-not-find-any-information-for-the-c,281,194490.0,19.0,,,2015-04-28 15:42:19,2019-03-02 16:47:03,2016-09-21 10:55:09,,,ios;swift;xcode;interface-builder;iboutlet,Ege Kaan Gürkan,2913,4770282,registered,true,34082979,,CC BY-SA 3.0,2016-08-20 12:10:26,388,210,0,1,1,5,true,false,false,true,true,true,90,15,false,0.098,0.0014,4225,2015,4,15,Tuesday,false,false,false,false,false,false,false
24030348,How to create a button programmatically?,"How do I programmatically create graphical elements (like a UIButton) in Swift? I tried to create and add button into a view, but wasn't able to.
",https://stackoverflow.com/questions/24030348/how-to-create-a-button-programmatically,280,416646.0,24.0,,,2014-06-04 06:18:37,2020-08-10 12:10:10,2018-11-22 08:56:17,,,ios;swift;uibutton,val_lek,3150,3051809,registered,true,,,CC BY-SA 4.0,,166,146,1,0,0,3,false,false,false,true,true,true,40,6,true,0.058,0.0007,4553,2014,6,6,Wednesday,false,false,false,false,false,false,false
25230780,Is it possible to allow didSet to be called during initialization in Swift?," Question
Apple's docs specify that:
willSet and didSet observers are not called when a property is first initialized. They are only called when the property’s value is set outside of an initialization context.
Is it possible to force these to be called during initialization?
Why?
Let's say I have this class
class SomeClass {
var someProperty: AnyObject {
didSet {
doStuff()
}
}
init(someProperty: AnyObject) {
self.someProperty = someProperty
doStuff()
}
func doStuff() {
// do stuff now that someProperty is set
}
}
I created the method doStuff, to make the processing calls more concise, but I'd rather just process the property within the didSet function. Is there a way to force this to call during initialization?
Update
I decided to just remove the convenience intializer for my class and force you to set the property after initialization. This allows me to know didSet will always be called. I haven't decided if this is better overall, but it suits my situation well.
",https://stackoverflow.com/questions/25230780/is-it-possible-to-allow-didset-to-be-called-during-initialization-in-swift,278,70369.0,9.0,,,2014-08-10 16:38:56,2020-07-06 19:01:20,2016-06-27 05:26:36,,,ios;swift;didset,Logan,53168,2611971,registered,true,25231068,,CC BY-SA 3.0,,1436,1079,4,1,0,3,true,false,false,true,true,true,75,13,true,0.128,0.004,4486,2014,8,16,Sunday,true,false,false,false,false,false,false
28527797,How to return first 5 objects of Array in Swift?,"In Swift, is there a clever way of using the higher order methods on Array to return the 5 first objects?
The obj-c way of doing it was saving an index, and for-loop through the array incrementing index until it was 5 and returning the new array. Is there a way to do this with filter, map or reduce?
",https://stackoverflow.com/questions/28527797/how-to-return-first-5-objects-of-array-in-swift,276,182961.0,13.0,,,2015-02-15 15:39:50,2025-11-06 23:23:00,,,,arrays;swift,bogen,10632,1071332,registered,true,32490675,,CC BY-SA 3.0,,348,302,3,0,0,2,true,false,false,true,true,false,48,10,true,0.071,0.0015,4297,2015,2,15,Sunday,true,false,false,false,false,false,false
24670290,How to copy text to clipboard/pasteboard with Swift,"I'm looking for a clean example of how to copy text to iOS clipboard that can then be used/pasted in other apps.
The benefit of this function is that the text can be copied quickly, without the standard text highlighting functions of the traditional text copying.
I am assuming that the key classes are in UIPasteboard, but can't find the relevant areas in the code example they supply.
",https://stackoverflow.com/questions/24670290/how-to-copy-text-to-clipboard-pasteboard-with-swift,276,157412.0,6.0,,,2014-07-10 06:58:24,2023-02-06 13:00:58,2018-10-22 16:20:10,,,ios;swift;cocoa-touch;copy;uipasteboard,Garry Law,3106,1425177,registered,true,24670971,,CC BY-SA 4.0,,515,389,1,1,0,5,true,false,false,true,true,true,51,8,false,0.038,0.0018,4517,2014,7,6,Thursday,false,false,false,false,false,false,false
24044851,"How do you use String.substringWithRange? (or, how do Ranges work in Swift?)","I have not yet been able to figure out how to get a substring of a String in Swift:
var str = “Hello, playground”
func test(str: String) -> String {
return str.substringWithRange( /* What goes here? */ )
}
test (str)
I'm not able to create a Range in Swift. Autocomplete in the Playground isn’t super helpful - this is what it suggests:
return str.substringWithRange(aRange: Range<String.Index>)
I haven't found anything in the Swift Standard Reference Library that helps. Here was another wild guess:
return str.substringWithRange(Range(0, 1))
And this:
let r:Range<String.Index> = Range<String.Index>(start: 0, end: 2)
return str.substringWithRange(r)
I've seen other answers (Finding index of character in Swift String) that seem to suggest that since String is a bridge type for NSString, the ""old"" methods should work, but it's not clear how - e.g., this doesn't work either (doesn't appear to be valid syntax):
let x = str.substringWithRange(NSMakeRange(0, 3))
Thoughts?
",https://stackoverflow.com/questions/24044851/how-do-you-use-string-substringwithrange-or-how-do-ranges-work-in-swift,276,254191.0,33.0,,,2014-06-04 18:25:20,2021-02-23 18:52:14,2017-05-23 12:34:53,,,swift,Rob,26503,18505,registered,true,24045156,,CC BY-SA 3.0,,1317,1014,8,1,0,1,true,false,false,true,true,true,76,12,false,0.13,0.0011,4553,2014,6,18,Wednesday,false,false,false,false,false,false,false
26961274,How can I make a button have a rounded border in Swift?,"I'm building an app using swift in the latest version of Xcode 6, and would like to know how I can modify my button so that it can have a rounded border that I could adjust myself if needed. Once that's done, how can I change the color of the border itself without adding a background to it? In other words I want a slightly rounded button with no background, only a 1pt border of a certain color.
",https://stackoverflow.com/questions/26961274/how-can-i-make-a-button-have-a-rounded-border-in-swift,275,405261.0,16.0,,,2014-11-16 17:07:49,2021-08-03 15:19:20,2017-07-03 15:33:42,,,swift;uibutton,GuiGui23,4075,4192321,registered,true,26962509,,,2016-01-29 21:53:34,405,398,0,0,0,2,true,false,false,true,true,true,55,12,true,0.039,0.0007,4388,2014,11,17,Sunday,true,false,false,false,false,false,false
11251340,Convert between UIImage and Base64 string,"Does anyone know how to convert a UIImage to a Base64 string, and then reverse it?
I have the below code; the original image before encoding is good, but I only get a blank image after I encode and decode it.
NSData *imageData = UIImagePNGRepresentation(viewImage);
NSString *b64EncStr = [self encode: imageData];
NSString *base64String = [self encodeBase64:imageData];
",https://stackoverflow.com/questions/11251340/convert-between-uiimage-and-base64-string,274,321253.0,24.0,,,2012-06-28 19:11:10,2022-09-02 12:16:43,2018-10-05 13:06:30,,,ios;swift;uiimage;base64;nsdata,changey,19766,1105036,registered,true,11251478,,CC BY-SA 4.0,,426,375,2,0,0,5,true,false,false,true,true,true,41,6,false,0.075,0.0009,5259,2012,6,19,Thursday,false,false,false,false,false,false,false
31443645,Simplest way to throw an error/exception with a custom message in Swift?,"I want to do something in Swift that I'm used to doing in multiple other languages: throw a runtime exception with a custom message. For example (in Java):
throw new RuntimeException("A custom message here")
I understand that I can throw enum types that conform to the ErrorType protocol, but I don't want to have to define enums for every type of error I throw. Ideally, I'd like to be able mimic the example above as closely as possible. I looked into creating a custom class that implements the ErrorType protocol, but I can't even figure out that what that protocol requires. Ideas?
",https://stackoverflow.com/questions/31443645/simplest-way-to-throw-an-error-exception-with-a-custom-message-in-swift,273,228589.0,16.0,,,2015-07-16 00:50:03,2026-06-12 16:53:30,2021-06-23 00:00:50,,,ios;swift,markdb314,6295,585287,registered,true,31443717,,CC BY-SA 4.0,,789,603,1,1,0,2,true,false,false,true,true,true,72,12,true,0.07,0.0012,4146,2015,7,0,Thursday,false,false,false,false,false,false,false
24045895,What is the Swift equivalent to Objective-C's "@synchronized"?,"I've searched the Swift book, but can't find the Swift version of @synchronized. How do I do mutual exclusion in Swift?
",https://stackoverflow.com/questions/24045895/what-is-the-swift-equivalent-to-objective-cs-synchronized,272,141676.0,24.0,,,2014-06-04 19:26:00,2022-08-11 23:21:14,,,,concurrency;mutex;swift,Bill,46073,126855,registered,true,73314198,,CC BY-SA 3.0,,127,120,0,0,0,3,true,false,false,true,true,false,76,8,true,0.169,0.0019,4553,2014,6,19,Wednesday,false,false,false,false,false,false,false
24011575,What is the difference between a weak reference and an unowned reference?,"Swift has:
- Strong References
- Weak References
- Unowned References
How is an unowned reference different from a weak reference?
When is it safe to use an unowned reference?
Are unowned references a security risk like dangling pointers in C/C++?
",https://stackoverflow.com/questions/24011575/what-is-the-difference-between-a-weak-reference-and-an-unowned-reference,272,92198.0,7.0,,,2014-06-03 09:27:39,2024-03-25 09:02:57,2015-05-08 21:27:34,,,swift;memory-management;automatic-ref-counting;weak-references;dangling-pointer,Ian Ringrose,52313,57159,registered,true,26025176,,CC BY-SA 3.0,,372,248,0,1,0,5,true,false,false,true,true,true,73,12,true,0.076,0.003,4554,2014,6,9,Tuesday,false,false,false,false,false,false,false
19556336,How do you add an in-app purchase to an iOS application?,"How do you add an in-app purchase to an iOS app? What are all the details and is there any sample code?
This is meant to be a catch-all of sorts for how to add in-app purchases to iOS apps
",https://stackoverflow.com/questions/19556336/how-do-you-add-an-in-app-purchase-to-an-ios-application,271,121131.0,5.0,,,2013-10-24 03:24:07,2022-12-22 10:41:58,2019-07-21 06:53:36,,,ios;objective-c;swift;cocoa-touch;in-app-purchase,Jojodmo,23596,2767207,registered,true,19556337,,CC BY-SA 4.0,2014-04-15 00:01:18,233,191,0,0,0,5,true,false,false,true,true,true,56,11,true,0.041,0.0022,4776,2013,10,3,Thursday,false,false,false,false,false,false,false
10428629,Programmatically set the initial view controller using Storyboards,"How do I programmatically set the InitialViewController for a Storyboard? I want to open my storyboard to a different view depending on some condition which may vary from launch to launch.
",https://stackoverflow.com/questions/10428629/programmatically-set-the-initial-view-controller-using-storyboards,268,169623.0,25.0,,,2012-05-03 09:29:51,2023-03-27 13:56:00,2017-03-23 15:18:09,,,ios;objective-c;swift;uiviewcontroller;uistoryboard,Jagdev Sendhav,2881,1273281,registered,true,14926009,,CC BY-SA 3.0,,209,189,1,0,0,5,true,false,false,true,true,true,66,8,false,0.147,0.0016,5315,2012,5,9,Thursday,false,false,false,false,false,false,false
27713747,Execute action when back bar button of UINavigationController is pressed,"I need to execute an action (emptying an array), when the back button of a UINavigationController is pressed, while the button still causes the previous ViewController on the stack to appear. How could I accomplish this using swift? ![]()
",https://stackoverflow.com/questions/27713747/execute-action-when-back-bar-button-of-uinavigationcontroller-is-pressed,267,281753.0,33.0,,,2014-12-30 22:53:55,2024-06-07 12:29:38,,,,ios;xcode;swift;uinavigationcontroller,StevenZ,7123,4392705,registered,true,27713813,,CC BY-SA 3.0,2017-11-06 15:42:28,346,235,2,0,1,4,true,false,false,true,true,false,72,10,false,0.117,0.0009,4344,2014,12,22,Tuesday,false,false,false,false,false,false,false
576265,Convert NSDate to NSString,"How do I convert, NSDate to NSString so that only the year in @""yyyy"" format is output to the string?
",https://stackoverflow.com/questions/576265/convert-nsdate-to-nsstring,265,330032.0,19.0,,,2009-02-23 01:18:24,2021-11-28 17:31:01,2018-11-07 13:57:29,,,objective-c;swift;nsstring;nsdate,4thSpace,44492,40106,registered,true,930786,,CC BY-SA 4.0,,152,102,2,0,0,4,true,false,false,true,true,true,26,4,false,0.058,0.0008,6480,2009,2,1,Monday,false,false,false,false,false,false,false
28760541,Programmatically go back to previous ViewController in Swift,"I send the user over to a page on a button click. This page is a UITableViewController.
Now if the user taps on a cell, I would like to push him back to the previous page.
I thought about something like self.performSegue(""back"").... but this seems to be a bad idea.
What is the correct way to do it?
",https://stackoverflow.com/questions/28760541/programmatically-go-back-to-previous-viewcontroller-in-swift,265,308998.0,16.0,,,2015-02-27 08:29:59,2023-07-12 08:35:56,2017-01-21 08:39:01,,,ios;swift;segue,Christian Kellner,7427,867432,registered,true,28761084,,CC BY-SA 3.0,,364,306,1,0,0,3,true,false,false,true,true,true,60,8,false,0.052,0.0009,4285,2015,2,8,Friday,false,false,false,false,false,false,false
28733936,Change color of Back button in navigation bar,"I am trying to change the color of the Settings button to white, but can't get it to change.
I've tried both of these:
navigationItem.leftBarButtonItem?.tintColor = UIColor.whiteColor()
navigationItem.backBarButtonItem?.tintColor = UIColor.whiteColor()
but no change, it still looks like this:
![]()
How do I make that button white?
",https://stackoverflow.com/questions/28733936/change-color-of-back-button-in-navigation-bar,264,245961.0,31.0,,,2015-02-26 03:27:19,2023-05-14 03:51:56,2016-04-13 11:39:16,,,ios;swift;uinavigationbar;uibarbuttonitem;backbarbuttonitem,Brandon Evans,2641,4608512,registered,true,,,CC BY-SA 3.0,2022-06-14 11:08:38,471,334,1,0,1,5,false,false,false,true,true,true,45,8,false,0.126,0.0011,4286,2015,2,3,Thursday,false,false,false,false,false,false,false
24180954,How to hide keyboard in swift on pressing return key?,"I am using UITextfied while clicking on textfied keyboard appear but when i pressed the return key, keyboard is not disappearing. I used the following code:
func textFieldShouldReturn(textField: UITextField!) -> Bool // called when 'return' key pressed. return NO to ignore.
{
return true;
}
the method resignfirstresponder is not getting in function.
",https://stackoverflow.com/questions/24180954/how-to-hide-keyboard-in-swift-on-pressing-return-key,264,281711.0,20.0,,,2014-06-12 09:30:00,2023-02-02 09:20:47,2019-01-17 14:40:00,,,ios;swift;uitextfield,Ashwinkumar Mangrulkar,2955,2713452,registered,true,,,CC BY-SA 4.0,,424,362,2,0,0,3,false,false,false,true,true,true,53,10,true,0.071,0.0009,4545,2014,6,9,Thursday,false,false,false,false,false,false,false
27182023,Getting the difference between two Dates (months/days/hours/minutes/seconds) in Swift,"I am trying to get the difference between the current date as NSDate() and a date from a PHP time(); call for example: NSDate(timeIntervalSinceReferenceDate: 1417147270). How do I go about getting the difference in time between the two dates. I'd like to have a function that compares the two dates and if(seconds > 60) then it returns minutes, if(minutes > 60) return hours and if(hours > 24) return days and so on.
How should I go about this?
EDIT: The current accepted answer has done exactly what I've wanted to do. I recommend it for easy usage for getting the time between two dates in the form that that PHP time() function uses. If you aren't particularly familiar with PHP, that's the time in seconds from January 1st, 1970. This is beneficial for a backend in PHP. If perhaps you're using a backend like NodeJS you might want to consider some of the other options you'll find below.
",https://stackoverflow.com/questions/27182023/getting-the-difference-between-two-dates-months-days-hours-minutes-seconds-in,264,163725.0,20.0,,,2014-11-28 04:43:09,2022-04-19 20:36:06,2020-09-26 03:26:17,,,ios;swift;macos;date;nsdate,uhfocuz,3180,4263409,registered,true,27184261,,CC BY-SA 4.0,,1017,905,7,0,0,5,true,false,false,true,true,true,85,9,false,0.122,0.0016,4376,2014,11,4,Friday,false,false,false,false,false,false,false
32036146,How to play a sound using Swift?,"I would like to play a sound using Swift.
My code worked in Swift 1.0 but now it doesn't work anymore in Swift 2 or newer.
override func viewDidLoad() {
super.viewDidLoad()
let url:NSURL = NSBundle.mainBundle().URLForResource(""soundName"", withExtension: ""mp3"")!
do {
player = try AVAudioPlayer(contentsOfURL: url, fileTypeHint: nil)
} catch _{
return
}
bgMusic.numberOfLoops = 1
bgMusic.prepareToPlay()
if (Data.backgroundMenuPlayed == 0){
player.play()
Data.backgroundMenuPlayed = 1
}
}
",https://stackoverflow.com/questions/32036146/how-to-play-a-sound-using-swift,264,331432.0,22.0,,,2015-08-16 14:25:37,2025-02-03 02:47:56,2019-09-07 14:43:47,,,ios;swift;avfoundation,Michel Kansou,2981,4724949,registered,true,32036291,,CC BY-SA 4.0,2019-09-07 14:34:49,569,531,1,0,0,3,true,false,false,true,true,true,32,7,true,0.066,0.0008,4115,2015,8,14,Sunday,true,false,false,false,false,false,false
37801370,"How do I dispatch_sync, dispatch_async, dispatch_after, etc in Swift 3, Swift 4, and beyond?","I have lots of code in Swift 2.x (or even 1.x) projects that looks like this:
// Move to a background thread to do some long running work
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
let image = self.loadOrGenerateAnImage()
// Bounce back to the main thread to update the UI
dispatch_async(dispatch_get_main_queue()) {
self.imageView.image = image
}
}
Or stuff like this to delay execution:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.5 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) {
print(""test"")
}
Or any of all kinds of other uses of the Grand Central Dispatch API...
Now that I've opened my project in Xcode 8 (beta) for Swift 3, I get all kinds of errors. Some of them offer to fix my code, but not all of the fixes produce working code. What do I do about this?
",https://stackoverflow.com/questions/37801370/how-do-i-dispatch-sync-dispatch-async-dispatch-after-etc-in-swift-3-swift-4,264,216771.0,6.0,,,2016-06-14 00:58:40,2020-02-05 06:20:43,2018-03-29 14:34:36,,,swift;grand-central-dispatch;dispatch-async;swift3;libdispatch,rickster,126367,957768,registered,true,37801371,,CC BY-SA 3.0,,934,858,2,0,0,5,true,false,false,true,true,true,92,14,true,0.028,0.0012,3812,2016,6,0,Tuesday,false,false,false,false,false,false,false
32542846,ReactiveCocoa vs RxSwift - pros and cons?,"So now with swift, the ReactiveCocoa people have rewritten it in version 3.0 for swift
Also, there's been another project spun up called RxSwift.
I wonder if people could add information about what the differences in design/api/philosophy of the two frameworks are (please, in the spirit of SO, stick to things which are true, rather than opinions about which is "best")
To get started, my initial impression from reading their ReadMe's is:
- As someone who is familiar with the "real" C# Rx from microsoft, RxSwift looks a lot more recognisable.
- ReactiveCococa seems to have gone off into its own space now, introducing new abstractions such as Signals vs SignalProducers and Lifting. On the one hand this seems to clarify some situations (what's a Hot vs Cold signal) but on the other hand this seems to increase the complexity of the framework a LOT
",https://stackoverflow.com/questions/32542846/reactivecocoa-vs-rxswift-pros-and-cons,263,31474.0,1.0,,,2015-09-12 19:29:41,2023-10-29 13:46:19,2023-10-29 13:46:19,,,swift;reactive-programming;rx-swift;reactive-cocoa-3,Orion Edwards,124990,234,registered,true,32581824,,CC BY-SA 4.0,,1092,873,0,2,0,4,true,false,false,true,true,true,41,7,true,0.032,0.0084,4088,2015,9,19,Saturday,true,false,false,false,false,false,false
29625133,Convert Dictionary to JSON in Swift,"I have create the next Dictionary:
var postJSON = [ids[0]:answersArray[0], ids[1]:answersArray[1], ids[2]:answersArray[2]] as Dictionary
and I get:
[2: B, 1: A, 3: C]
So, how can I convert it to JSON?
",https://stackoverflow.com/questions/29625133/convert-dictionary-to-json-in-swift,262,405790.0,16.0,,,2015-04-14 10:34:08,2023-06-30 22:56:58,2015-10-17 11:32:26,,,json;swift;serialization,Orkhan Alizade,7549,4754273,registered,true,,,CC BY-SA 3.0,,276,207,2,0,0,3,false,false,false,true,true,true,35,6,false,0.039,0.0006,4239,2015,4,10,Tuesday,false,false,false,false,false,false,false
3586871,Bold & Non-Bold Text In A Single UILabel?,"How would it be possible to include both bold and non-bold text in a uiLabel?
I'd rather not use a UIWebView.. I've also read this may be possible using NSAttributedString but I have no idea how to use that. Any ideas?
Apple achieves this in several of their apps;
Examples Screenshot:
Thanks!
- Dom
",https://stackoverflow.com/questions/3586871/bold-non-bold-text-in-a-single-uilabel,262,161600.0,15.0,,,2010-08-27 17:52:43,2022-02-09 08:53:22,2019-05-09 20:16:38,,,ios;objective-c;swift;uilabel;nsattributedstring,DomMaiocchi,2747,433213,unregistered,true,,,CC BY-SA 4.0,,392,305,0,0,1,5,false,false,false,true,true,true,45,8,true,0.093,0.0016,5930,2010,8,17,Friday,false,false,false,false,false,false,false
29046695,Swift Set to Array,"An NSSet can be converted to Array using set.allObjects() but there is no such method in the new Set (introduced with Swift 1.2). It can still be done by converting Swift Set to NSSet and use the allObjects() method but that is not optimal.
",https://stackoverflow.com/questions/29046695/swift-set-to-array,262,176459.0,6.0,,,2015-03-14 07:47:33,2018-02-13 18:34:00,2016-02-24 19:29:11,,,arrays;swift;set,Fried Rice,3813,945711,registered,true,29046827,,CC BY-SA 3.0,,313,241,5,0,0,3,true,false,false,true,true,true,18,4,false,0.034,0.0015,4270,2015,3,7,Saturday,true,false,false,false,false,false,false
24058906,Printing a variable memory address in swift,"Is there anyway to simulate the [NSString stringWithFormat:@""%p"", myVar], from Objective-C, in the new Swift language?
For example:
let str = ""A String""
println("" str value \(str) has address: ?"")
",https://stackoverflow.com/questions/24058906/printing-a-variable-memory-address-in-swift,261,180156.0,15.0,,,2014-06-05 11:22:32,2025-06-05 12:43:58,2020-01-01 17:59:42,,,swift;debugging;memory-address,apouche,10023,591482,registered,true,29741007,,CC BY-SA 4.0,,251,200,2,0,0,3,true,false,false,true,true,true,43,7,false,0.083,0.0014,4552,2014,6,11,Thursday,false,false,false,false,false,false,false
37967555,How can I mimic the bottom sheet from the Maps app?,"Can anyone tell me how I can mimic the bottom sheet in the new Apple Maps app in iOS 10?
In Android, you can use a BottomSheet which mimics this behaviour, but I could not find anything like that for iOS.
Is that a simple scroll view with a content inset, so that the search bar is at the bottom?
I am fairly new to iOS programming so if someone could help me creating this layout, that would be highly appreciated.
This is what I mean by "bottom sheet":
",https://stackoverflow.com/questions/37967555/how-can-i-mimic-the-bottom-sheet-from-the-maps-app,259,149122.0,10.0,,,2016-06-22 12:06:55,2021-12-13 14:07:20,2021-06-07 20:29:32,,,ios;swift;uiview;uiscrollview;mapkit,qwertz,6276,4730005,registered,true,38152508,,CC BY-SA 4.0,2018-08-06 12:12:11,849,467,1,2,2,5,true,false,false,true,true,true,51,11,true,0.067,0.0017,3804,2016,6,12,Wednesday,false,false,false,false,false,false,false
30480672,How to convert a JSON string to a dictionary?,"I want to make one function in my swift project that converts String to Dictionary json format but I got one error:
Cannot convert expression's type (@lvalue NSData,options:IntegerLitralConvertible ...
This is my code:
func convertStringToDictionary (text:String) -> Dictionary<String,String> {
var data :NSData = text.dataUsingEncoding(NSUTF8StringEncoding)!
var json :Dictionary = NSJSONSerialization.JSONObjectWithData(data, options:0, error: nil)
return json
}
I make this function in Objective-C :
- (NSDictionary*)convertStringToDictionary:(NSString*)string {
NSError* error;
//giving error as it takes dic, array,etc only. not custom object.
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
return json;
}
",https://stackoverflow.com/questions/30480672/how-to-convert-a-json-string-to-a-dictionary,258,373459.0,10.0,,,2015-05-27 11:05:33,2024-07-07 22:38:23,2017-03-22 15:03:59,,,json;swift;dictionary;nsjsonserialization,trousout,2591,4944356,registered,true,30480777,,CC BY-SA 3.0,,957,856,2,0,0,4,true,false,false,true,true,true,45,9,true,0.027,0.0007,4196,2015,5,11,Wednesday,false,false,false,false,false,false,false
24027116,How can I extend typed Arrays in Swift?,"How can I extend Swift's Array<T> or T[] type with custom functional utils?
Browsing around Swift's API docs shows that Array methods are an extension of the T[], e.g:
extension T[] : ArrayType {
//...
init()
var count: Int { get }
var capacity: Int { get }
var isEmpty: Bool { get }
func copy() -> T[]
}
When copying and pasting the same source and trying any variations like:
extension T[] : ArrayType {
func foo(){}
}
extension T[] {
func foo(){}
}
It fails to build with the error:
Nominal type T[] can't be extended
Using the full type definition fails with Use of undefined type 'T', i.e:
extension Array<T> {
func foo(){}
}
And it also fails with Array<T : Any> and Array<String>.
Curiously Swift lets me extend an untyped array with:
extension Array {
func each(fn: (Any) -> ()) {
for i in self {
fn(i)
}
}
}
Which it lets me call with:
[1,2,3].each(println)
But I can't create a proper generic type extension as the type seems to be lost when it flows through the method, e.g trying to replace Swift's built-in filter with:
extension Array {
func find<T>(fn: (T) -> Bool) -> T[] {
var to = T[]()
for x in self {
let t = x as T
if fn(t) {
to += t
}
}
return to
}
}
But the compiler treats it as untyped where it still allows calling the extension with:
[""A"",""B"",""C""].find { $0 > ""A"" }
And when stepped-thru with a debugger indicates the type is Swift.String but it's a build error to try access it like a String without casting it to String first, i.e:
[""A"",""B"",""C""].find { ($0 as String).compare(""A"") > 0 }
Does anyone know what's the proper way to create a typed extension method that acts like the built-in extensions?
",https://stackoverflow.com/questions/24027116/how-can-i-extend-typed-arrays-in-swift,258,125431.0,12.0,,,2014-06-04 00:26:14,2024-01-01 16:31:10,2017-05-23 12:10:26,,,arrays;swift,mythz,143598,85785,registered,true,33557647,,CC BY-SA 3.0,,2363,1881,17,1,0,2,true,false,false,true,true,true,39,8,true,0.096,0.0021,4553,2014,6,0,Wednesday,false,false,false,false,false,false,false
26667009,Get top most UIViewController,"I can't seem to get the top most UIViewController without access to a UINavigationController. Here is what I have so far:
UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(vc, animated: true, completion: nil)
However, it does not seem to do anything. The keyWindow and rootViewController seem to be non-nil values too, so the optional chaining shouldn't be an issue.
NOTE: It is a bad idea to do something like this. It breaks the MVC pattern.
",https://stackoverflow.com/questions/26667009/get-top-most-uiviewcontroller,256,271372.0,29.0,,,2014-10-31 03:14:00,2024-07-26 07:47:54,2018-12-18 22:43:39,,,swift;uiviewcontroller,Zoyt,4997,2016800,registered,true,26667122,,CC BY-SA 4.0,,608,485,5,0,0,2,true,false,false,true,true,true,29,4,false,0.107,0.0009,4404,2014,10,3,Friday,false,false,false,false,false,false,false
28016578,"How can I parse / create a date time stamp formatted with fractional seconds UTC timezone (ISO 8601, RFC 3339) in Swift?","How to generate a date time stamp, using the format standards for ISO 8601 and RFC 3339?
The goal is a string that looks like this:
"2015-01-01T00:00:00.000Z"
Format:
- year, month, day, as "XXXX-XX-XX"
- the letter "T" as a separator
- hour, minute, seconds, milliseconds, as "XX:XX:XX.XXX".
- the letter "Z" as a zone designator for zero offset, a.k.a. UTC, GMT, Zulu time.
Best case:
- Swift source code that is simple, short, and straightforward.
- No need to use any additional framework, subproject, cocoapod, C code, etc.
I've searched StackOverflow, Google, Apple, etc. and haven't found a Swift answer to this.
The classes that seem most promising are NSDate, NSDateFormatter, NSTimeZone.
Related Q&A: How do I get an ISO 8601 date on iOS?
Here's the best I've come up with so far:
var now = NSDate()
var formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
println(formatter.stringFromDate(now))
",https://stackoverflow.com/questions/28016578/how-can-i-parse-create-a-date-time-stamp-formatted-with-fractional-seconds-utc,255,183987.0,14.0,,,2015-01-19 00:58:31,2023-11-20 02:30:46,2021-10-07 05:46:31,,,date;swift;time;iso8601;rfc3339,joelparkerhenderson,35663,528726,registered,true,28016692,,CC BY-SA 4.0,,1941,1049,5,6,0,5,true,false,false,true,true,true,120,22,true,0.076,0.0014,4324,2015,1,0,Monday,false,false,false,false,false,false,false
24047991,Does Swift have documentation generation support?,"Many languages support documentation comments to allow a generator (like javadoc or doxygen) to generate code documentation by parsing that same code.
Does Swift have any type documentation comment feature like this?
",https://stackoverflow.com/questions/24047991/does-swift-have-documentation-generation-support,255,66891.0,13.0,,,2014-06-04 21:34:58,2025-06-04 19:16:50,2019-03-26 11:55:56,,,swift;documentation-generation,pconcepcion,5631,574353,registered,true,28633899,,CC BY-SA 4.0,,316,218,1,1,0,2,true,false,false,true,true,true,49,6,true,0.194,0.0038,4553,2014,6,21,Wednesday,false,false,false,false,false,false,false
26224693,"How can I make the memberwise initialiser public, by default, for structs in Swift?","I have a Swift framework that defines a struct:
public struct CollectionTO {
var index: Order
var title: String
var description: String
}
However, I can't seem to use the implicit memberwise initialiser from another project that imports the library. The error is:
'CollectionTO' cannot be initialised because it has no accessible initialisers
i.e. the default synthesized memberwise initialiser is not public.
var collection1 = CollectionTO(index: 1, title: "New Releases", description: "All the new releases")
I'm having to add my own init method like so:
public struct CollectionTO {
var index: Order
var title: String
var description: String
public init(index: Order, title: String, description: String) {
self.index = index;
self.title = title;
self.description = description;
}
}
... but is there a way to do this without explicitly defining a public init?
",https://stackoverflow.com/questions/26224693/how-can-i-make-the-memberwise-initialiser-public-by-default-for-structs-in-swi,254,50146.0,6.0,,,2014-10-06 20:53:11,2024-05-06 21:45:18,2022-01-07 14:52:44,,,swift;initialization,bandejapaisa,27062,300098,registered,true,26224873,,CC BY-SA 4.0,,1109,944,5,0,0,2,true,false,false,true,true,true,83,14,true,0.12,0.0051,4429,2014,10,20,Monday,false,false,false,false,false,false,false
24021093,Error in Swift class: Property not initialized at super.init call,"I have two classes, Shape and Square
class Shape {
var numberOfSides = 0
var name: String
init(name:String) {
self.name = name
}
func simpleDescription() -> String {
return ""A shape with \(numberOfSides) sides.""
}
}
class Square: Shape {
var sideLength: Double
init(sideLength:Double, name:String) {
super.init(name:name) // Error here
self.sideLength = sideLength
numberOfSides = 4
}
func area () -> Double {
return sideLength * sideLength
}
}
With the implementation above I get the error:
property 'self.sideLength' not initialized at super.init call
super.init(name:name)
Why do I have to set self.sideLength before calling super.init?
",https://stackoverflow.com/questions/24021093/error-in-swift-class-property-not-initialized-at-super-init-call,253,158780.0,12.0,,,2014-06-03 17:11:19,2023-07-12 20:32:19,2014-06-06 18:20:42,,,properties;compiler-errors;swift,JuJoDi,15185,1370927,registered,true,24021346,,CC BY-SA 3.0,2023-07-16 05:57:28,871,750,6,0,0,3,true,false,false,true,true,true,65,10,false,0.076,0.0016,4554,2014,6,17,Tuesday,false,false,false,false,false,false,false
24062618,Swift to Objective-C header not created in Xcode 6,"I have recently been working to add Swift to an existing project, to get to try it out in a real-world fashion.
Upon adding a Swift source file to the project, I have no problems about getting the ""Bridging Header"", that is, Objective-C to Swift.
But the *-Swift.h header file that is supposed to expose Swift classes either marked @objc or subclasses of ObjC classes, is nowhere to be found :-(
I don't see any specific instructions on how to accomplish the usage of my new subclass, written in Swift, in my main app code (which is still Objective-C).
The app that I am lead developer of has a fairly large codebase (70.000 lines), so transitioning it in one go is out of the question.
",https://stackoverflow.com/questions/24062618/swift-to-objective-c-header-not-created-in-xcode-6,252,99964.0,33.0,,,2014-06-05 14:17:16,2025-03-13 14:21:23,2018-12-21 11:19:32,,,objective-c;xcode;swift,David Kristensen,4340,2691708,registered,true,,,CC BY-SA 4.0,,759,691,2,0,0,3,false,false,false,true,true,true,50,9,false,0.33,0.0025,4552,2014,6,14,Thursday,false,false,false,false,false,false,false
25081757,What's NSLocalizedString equivalent in Swift?,"Is there an Swift equivalent of NSLocalizedString(...)?
In Objective-C, we usually use:
NSString *string = NSLocalizedString(@""key"", @""comment"");
How can I achieve the same in Swift? I found a function:
func NSLocalizedString(
key: String,
tableName: String? = default,
bundle: NSBundle = default,
value: String = default,
#comment: String) -> String
However, it is very long and not convenient at all.
",https://stackoverflow.com/questions/25081757/whats-nslocalizedstring-equivalent-in-swift,249,134058.0,19.0,,,2014-08-01 13:48:47,2024-02-04 17:31:28,2016-01-18 20:12:12,,,ios;swift;localization;nslocalizedstring,Rafał Sroka,40105,348796,registered,true,25081758,,CC BY-SA 3.0,,527,432,4,0,0,4,true,false,false,true,true,true,49,5,true,0.142,0.0019,4495,2014,8,13,Friday,false,false,false,false,false,false,false
24074479,How to create a String with format?,"I need to create a String with format which can convert Int, Int64, Double, etc types into String. Using Objective-C, I can do it by:
NSString *str = [NSString stringWithFormat:@"%d , %f, %ld, %@", INT_VALUE, FLOAT_VALUE, DOUBLE_VALUE, STRING_VALUE];
How to do same but in Swift?
",https://stackoverflow.com/questions/24074479/how-to-create-a-string-with-format,248,355320.0,14.0,,,2014-06-06 05:00:59,2022-12-03 00:56:30,2022-06-17 21:28:31,,,ios;swift;ios8;nsstring;string-formatting,Apurv,17176,1168908,registered,true,24097543,,CC BY-SA 4.0,,394,291,6,0,0,5,true,false,false,true,true,true,35,7,true,0.039,0.0007,4551,2014,6,5,Friday,false,false,false,false,false,false,false
24508592,How to iterate for loop in reverse order in swift?,"When I use the for loop in Playground, everything worked fine, until I changed the first parameter of for loop to be the highest value. (iterated in descending order)
Is this a bug? Did any one else have it?
for index in 510..509
{
var a = 10
}
The counter that displays the number of iterations that will be executions keeps ticking...
![]()
",https://stackoverflow.com/questions/24508592/how-to-iterate-for-loop-in-reverse-order-in-swift,246,180566.0,16.0,,,2014-07-01 10:59:32,2022-03-13 10:03:04,2016-07-20 23:00:54,,,ios;swift;swift-playground,RK-,12239,189006,registered,true,24510093,,CC BY-SA 3.0,,477,347,1,0,1,3,true,false,false,true,true,true,50,10,true,0.089,0.0014,4526,2014,7,10,Tuesday,false,false,false,false,false,false,false
24668818,How to dismiss ViewController in Swift?,"I am trying to dismiss a ViewController in swift by calling dismissViewController in an IBAction
@IBAction func cancel(sender: AnyObject) {
self.dismissViewControllerAnimated(false, completion: nil)
println(""cancel"")
}
@IBAction func done(sender: AnyObject) {
self.dismissViewControllerAnimated(false, completion: nil)
println(""done"")
}
![]()
I could see the println message in console output but ViewController never gets dismissed. What could be the problem?
",https://stackoverflow.com/questions/24668818/how-to-dismiss-viewcontroller-in-swift,245,413977.0,20.0,,,2014-07-10 05:02:41,2021-11-08 08:36:29,2021-11-08 08:36:29,,,ios;swift;xcode;storyboard;viewcontroller,rshankar,3085,1275287,registered,true,24669203,,CC BY-SA 4.0,,624,480,3,0,1,5,true,false,false,true,true,true,39,6,true,0.048,0.0006,4517,2014,7,5,Thursday,false,false,false,false,false,false,false
24019707,Using isKindOfClass with Swift,"I'm trying to pick up a bit of Swift lang and I'm wondering how to convert the following Objective-C into Swift:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesBegan:touches withEvent:event];
UITouch *touch = [touches anyObject];
if ([touch.view isKindOfClass: UIPickerView.class]) {
//your touch was in a uipickerview ... do whatever you have to do
}
}
More specifically I need to know how to use isKindOfClass in the new syntax.
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
???
if ??? {
// your touch was in a uipickerview ...
}
}
",https://stackoverflow.com/questions/24019707/using-iskindofclass-with-swift,245,141020.0,5.0,,,2014-06-03 15:59:19,2019-10-12 23:28:25,2019-10-12 23:28:25,,,ios;swift;reflection;introspection,lkemitchll,2751,2819263,registered,true,24220444,,CC BY-SA 4.0,,720,645,3,0,0,4,true,false,false,true,true,true,30,4,false,0.035,0.0017,4554,2014,6,15,Tuesday,false,false,false,false,false,false,false
24089999,How do you create a Swift Date object?,"How do you create a date object from a date in swift xcode.
eg in javascript you would do:
var day = new Date('2014-05-20');
",https://stackoverflow.com/questions/24089999/how-do-you-create-a-swift-date-object,245,315495.0,12.0,,,2014-06-06 20:18:00,2023-02-27 22:46:23,2020-02-23 12:13:12,,,ios;iphone;swift;nsdate,code_cookies,4080,2367491,registered,true,33344575,,CC BY-SA 4.0,,157,130,1,0,0,4,true,false,false,true,true,true,38,8,true,0.038,0.0008,4551,2014,6,20,Friday,false,false,false,false,false,false,false
18946490,How to stop unwanted UIButton animation on title change?,"In iOS 7 my UIButton titles are animating in and out at the wrong time - late. This problem does not appear on iOS 6. I'm just using:
[self setTitle:text forState:UIControlStateNormal];
I would prefer this happens instantly and without a blank frame. This blink is especially distracting and draws attention away from other animations.
",https://stackoverflow.com/questions/18946490/how-to-stop-unwanted-uibutton-animation-on-title-change,244,67395.0,24.0,,,2013-09-22 17:10:01,2020-05-22 10:03:40,2017-03-23 00:14:44,,,objective-c;swift;ios7;uibutton;uikit,exsulto,2525,327216,registered,true,19303693,,CC BY-SA 3.0,,377,339,1,0,0,5,true,false,false,true,true,true,56,9,true,0.356,0.0036,4808,2013,9,17,Sunday,true,false,false,false,false,false,false
57244713,Get index in ForEach in SwiftUI,"I have an array and I want to iterate through it initialize views based on array value, and want to perform action based on array item index
When I iterate through objects
ForEach(array, id: \.self) { item in
CustomView(item: item)
.tapAction {
self.doSomething(index) // Can't get index, so this won't work
}
}
So, I've tried another approach
ForEach((0..<array.count)) { index in
CustomView(item: array[index])
.tapAction {
self.doSomething(index)
}
}
But the issue with second approach is, that when I change array, for example, if doSomething does following
self.array = [1,2,3]
views in ForEach do not change, even if values are changed. I believe, that happens because array.count haven't changed.
Is there a solution for this?
",https://stackoverflow.com/questions/57244713/get-index-in-foreach-in-swiftui,244,216765.0,14.0,,,2019-07-28 20:26:42,2025-05-13 09:52:13,2022-12-17 04:56:44,,,swift;swiftui,Pavel,4480,978994,registered,true,57244880,,CC BY-SA 4.0,,1005,772,6,0,0,2,true,false,false,true,true,true,31,6,false,0.065,0.0011,2673,2019,7,20,Sunday,true,false,false,false,false,false,false
24006206,SourceKitService Terminated,"I am having a issue with Xcode where the error ""Source Kit Service Terminated"" is popping up and all syntax highlighting and code completion is gone in Swift. How can I fix this?
Here is an example image:
![]()
",https://stackoverflow.com/questions/24006206/sourcekitservice-terminated,242,42882.0,34.0,,,2014-06-03 02:29:34,2022-12-26 03:58:22,2018-11-21 13:00:50,,,ios;swift;xcode;sourcekitservice,Tony,4629,953628,registered,true,25839664,,CC BY-SA 4.0,2014-06-08 01:16:08,308,209,0,0,1,4,true,false,false,true,true,true,27,2,false,0.793,0.0056,4554,2014,6,2,Tuesday,false,false,false,false,false,false,false
44580719,How do I make an enum Decodable in Swift?,"enum PostType: Decodable {
init(from decoder: Decoder) throws {
// What do i put here?
}
case Image
enum CodingKeys: String, CodingKey {
case image
}
}
What do i put to complete this?
Also, lets say i changed the case to this:
case image(value: Int)
How do I make this conform to Decodable?
Here is my full code (which does not work)
let jsonData = """
{
"count": 4
}
""".data(using: .utf8)!
do {
let decoder = JSONDecoder()
let response = try decoder.decode(PostType.self, from: jsonData)
print(response)
} catch {
print(error)
}
}
}
enum PostType: Int, Codable {
case count = 4
}
Also, how will it handle an enum like this?
enum PostType: Decodable {
case count(number: Int)
}
",https://stackoverflow.com/questions/44580719/how-do-i-make-an-enum-decodable-in-swift,241,142803.0,10.0,,,2017-06-16 04:15:21,2025-07-22 06:13:41,2022-06-09 23:51:33,,,swift;enums,swift nub,2957,5458240,registered,true,44582674,,CC BY-SA 4.0,,1010,873,5,0,0,2,true,false,false,true,true,true,41,9,true,0.07,0.0017,3445,2017,6,4,Friday,false,false,false,false,false,false,false
25296691,Get User's Current Location / Coordinates,"How can I store the user's current location and also show the location on a map?
I am able to show pre-defined coordinates on a map, I just don't know how to receive information from the device.
Also I know I have to add some items into a Plist. How can I do that?
",https://stackoverflow.com/questions/25296691/get-users-current-location-coordinates,241,355626.0,16.0,,,2014-08-13 21:43:23,2025-02-19 18:09:46,2019-05-15 05:52:36,,,ios;swift;iphone;location;cllocationmanager,Awais Hussain,2470,3939170,registered,true,,,CC BY-SA 4.0,,288,267,0,0,0,5,false,false,false,true,true,true,45,6,false,0.045,0.0007,4483,2014,8,21,Wednesday,false,false,false,false,false,false,false
24127587,How do I declare an array of weak references in Swift?,"I'd like to store an array of weak references in Swift. The array itself should not be a weak reference - its elements should be. I think Cocoa NSPointerArray offers a non-typesafe version of this.
",https://stackoverflow.com/questions/24127587/how-do-i-declare-an-array-of-weak-references-in-swift,241,71683.0,19.0,,,2014-06-09 19:34:30,2024-04-14 14:40:46,2019-02-06 23:08:49,,,swift;automatic-ref-counting;weak-references;nspointerarray,Bill,46073,126855,registered,true,24128121,,CC BY-SA 4.0,2022-09-08 15:46:42,218,198,1,0,0,4,true,false,false,true,true,true,54,11,true,0.265,0.0034,4548,2014,6,19,Monday,false,false,false,false,false,false,false
3074483,Save string to the NSUserDefaults?,"How to save a string into the NSUserDefaults?
",https://stackoverflow.com/questions/3074483/save-string-to-the-nsuserdefaults,240,186036.0,16.0,,,2010-06-19 05:33:37,2022-04-18 15:36:35,2021-11-08 08:29:04,,,ios;swift;objective-c;cocoa-touch;nsuserdefaults,Shishir.bobby,10974,1497488,registered,true,3074489,,CC BY-SA 4.0,,66,46,1,0,0,5,true,false,false,true,true,true,34,5,true,0.086,0.0013,5999,2010,6,5,Saturday,true,false,false,false,false,false,false
26956728,Changing the Status Bar Color for specific ViewControllers using Swift in iOS8,"override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent;
}
Using the above code in any ViewController to set the statusBar color to White for a specific viewcontroller doesnt work in iOS8 for me. Any suggestions? Using the UIApplication.sharedApplication method, the color changes after required changes in the Info.plist for the whole app.
// Change the colour of status bar from black to white
UIApplication.sharedApplication().statusBarStyle = .LightContent
How can I just make changes to the status bar color for some required and specific ViewControllers?
",https://stackoverflow.com/questions/26956728/changing-the-status-bar-color-for-specific-viewcontrollers-using-swift-in-ios8,237,317916.0,37.0,,,2014-11-16 12:05:37,2023-08-24 11:41:35,2015-02-14 06:41:26,,,swift;uiviewcontroller;ios8;xcode6;statusbar,Anuj,7087,812950,registered,true,28513320,,CC BY-SA 3.0,,728,614,2,0,0,5,true,false,false,true,true,true,78,12,false,0.116,0.0007,4388,2014,11,12,Sunday,true,false,false,false,false,false,false
24380535,How to Apply Gradient to background view of iOS Swift App,"I'm trying to apply a gradient as the background color of a View (main view of a storyboard). The code runs, but nothing changes. I'm using xCode Beta 2 and Swift.
Here's the code:
class Colors {
let colorTop = UIColor(red: 192.0/255.0, green: 38.0/255.0, blue: 42.0/255.0, alpha: 1.0)
let colorBottom = UIColor(red: 35.0/255.0, green: 2.0/255.0, blue: 2.0/255.0, alpha: 1.0)
let gl: CAGradientLayer
init() {
gl = CAGradientLayer()
gl.colors = [ colorTop, colorBottom]
gl.locations = [ 0.0, 1.0]
}
}
then in the view controller:
let colors = Colors()
func refresh() {
view.backgroundColor = UIColor.clearColor()
var backgroundLayer = colors.gl
backgroundLayer.frame = view.frame
view.layer.insertSublayer(backgroundLayer, atIndex: 0)
}
}
}
",https://stackoverflow.com/questions/24380535/how-to-apply-gradient-to-background-view-of-ios-swift-app,237,354142.0,31.0,,,2014-06-24 07:13:36,2024-08-26 08:44:47,,,,ios;ios7;swift;cagradientlayer,justingordon,13029,1009332,registered,true,24380968,,CC BY-SA 3.0,,888,819,2,0,0,4,true,false,false,true,true,false,57,11,false,0.088,0.0007,4533,2014,6,7,Tuesday,false,false,false,false,false,false,false
26364914,HTTP Request in Swift with POST method,"I'm trying to run a HTTP Request in Swift, to POST 2 parameters to a URL.
Example:
Link: www.thisismylink.com/postName.php
Params:
id = 13
name = Jack
What is the simplest way to do that?
I don't even want to read the response. I just want to send that to perform changes on my database through a PHP file.
",https://stackoverflow.com/questions/26364914/http-request-in-swift-with-post-method,237,371667.0,7.0,,,2014-10-14 15:47:14,2022-05-14 19:14:58,2016-03-03 05:12:44,,,post;swift;parameters;http-post;httprequest,angeant,2815,2772908,registered,true,26365148,,CC BY-SA 3.0,2015-10-17 15:18:58,393,314,2,0,0,5,true,false,false,true,true,true,38,7,false,0.019,0.0006,4421,2014,10,15,Tuesday,false,false,false,false,false,false,false
37843049,Xcode 8 / Swift 3: "Expression of type UIViewController? is unused" warning,"I've got the following function which compiled cleanly previously but generates a warning with Xcode 8.
func exitViewController()
{
navigationController?.popViewController(animated: true)
}
""Expression of type ""UIViewController?"" is unused"".
Why is it saying this and is there a way to remove it?
The code executes as expected.
",https://stackoverflow.com/questions/37843049/xcode-8-swift-3-expression-of-type-uiviewcontroller-is-unused-warning,236,52374.0,7.0,,,2016-06-15 18:24:57,2021-10-30 10:03:46,,,,ios;swift,Piepants,37396,1082219,registered,true,37843720,,CC BY-SA 3.0,,418,341,1,0,0,2,true,false,false,true,true,false,85,12,false,0.134,0.0045,3811,2016,6,18,Wednesday,false,false,false,false,false,false,false
27880650,Swift extract regex matches,"I want to extract substrings from a string that match a regex pattern.
So I'm looking for something like this:
func matchesForRegexInText(regex: String!, text: String!) -> [String] {
???
}
So this is what I have:
func matchesForRegexInText(regex: String!, text: String!) -> [String] {
var regex = NSRegularExpression(pattern: regex,
options: nil, error: nil)
var results = regex.matchesInString(text,
options: nil, range: NSMakeRange(0, countElements(text)))
as Array<NSTextCheckingResult>
/// ???
return ...
}
The problem is, that matchesInString delivers me an array of NSTextCheckingResult, where NSTextCheckingResult.range is of type NSRange.
NSRange is incompatible with Range<String.Index>, so it prevents me of using text.substringWithRange(...)
Any idea how to achieve this simple thing in swift without too many lines of code?
",https://stackoverflow.com/questions/27880650/swift-extract-regex-matches,236,199219.0,16.0,,,2015-01-10 20:04:04,2023-05-29 17:32:28,,,,ios;regex;string;swift,mitchkman,6730,1867854,registered,true,27880748,,CC BY-SA 3.0,,1100,919,9,0,0,4,true,false,false,true,true,false,27,4,false,0.08,0.0012,4333,2015,1,20,Saturday,true,false,false,false,false,false,false
36861732,Convert string to date in Swift,"How can I convert this string ""2016-04-14T10:44:00+0000"" into an NSDate and keep only the year, month, day, hour?
The T in the middle of it really throws off what I am used to when working with dates.
",https://stackoverflow.com/questions/36861732/convert-string-to-date-in-swift,235,433567.0,18.0,,,2016-04-26 10:06:16,2023-02-14 19:09:18,2018-12-29 07:48:24,,,swift;nsdate;nsdateformatter,asheyla,3335,5367540,registered,true,36862162,,CC BY-SA 4.0,2019-08-06 03:42:39,255,202,3,0,0,3,true,false,false,true,true,true,31,6,false,0.042,0.0005,3861,2016,4,10,Tuesday,false,false,false,false,false,false,false
35963128,Swift: Understanding // MARK,"What is the purpose of writing comments in Swift as:
// MARK: This is a comment
When you can also do:
// This is a comment
What does the // MARK achieve?
",https://stackoverflow.com/questions/35963128/swift-understanding-mark,235,109629.0,3.0,,,2016-03-12 20:48:27,2025-06-29 09:21:56,2019-11-10 10:16:04,,,xcode;swift;comments,Marcus Leon,57129,47281,registered,true,35963262,,CC BY-SA 4.0,,314,160,3,0,0,3,true,false,false,true,true,true,28,4,false,0.027,0.0021,3906,2016,3,20,Saturday,true,false,false,false,false,false,false
28675209,How to call gesture tap on UIView programmatically in swift,"I have a UIView and and I have added tap gesture to it:
let tap = UITapGestureRecognizer(target: self, action: Selector(""handleTap:""))
tap.delegate = self
myView.addGesture(tap)
I am trying to call it programmatically in the testfile.
sendActionForEvent
I am using this function, but it is not working:
myView.sendActionForEvent(UIEvents.touchUpDown)
It shows unrecognised selector sent to instance.
How can I solve this problem?
",https://stackoverflow.com/questions/28675209/how-to-call-gesture-tap-on-uiview-programmatically-in-swift,234,426385.0,24.0,,,2015-02-23 13:46:09,2023-04-06 14:15:06,2019-06-18 17:11:43,,,ios;swift;iphone;ios8;uigesturerecognizer,George,3738,2481247,registered,true,,,CC BY-SA 4.0,,548,441,3,0,0,5,false,false,false,true,true,true,59,10,false,0.056,0.0005,4289,2015,2,13,Monday,false,false,false,false,false,false,false
39627106,Why do I need underscores in swift?,"Here it says, ""Note: the _ means “I don’t care about that value”"", but coming from JavaScript, I don't understand what that means.
The only way I can get these functions to print was by using the underscores before the parameters:
func divmod(_ a: Int, _ b:Int) -> (Int, Int) {
return (a / b, a % b)
}
print(divmod(7, 3))
print(divmod(5, 2))
print(divmod(12,4))
Without the underscores I have to write it like this to avoid any errors:
func divmod(a: Int, b:Int) -> (Int, Int) {
return (a / b, a % b)
}
print(divmod(a: 7, b: 3))
print(divmod(a: 5, b: 2))
print(divmod(a: 12,b: 4))
I don't understand this underscore usage. When, how and why do I use these underscores?
",https://stackoverflow.com/questions/39627106/why-do-i-need-underscores-in-swift,234,68287.0,4.0,,,2016-09-21 21:48:52,2021-06-19 16:54:48,2016-10-09 01:41:53,,,swift,Michael Rader,5985,1029365,registered,true,39627305,,CC BY-SA 3.0,,856,693,3,1,0,1,true,false,false,true,true,true,35,7,true,0.059,0.0034,3713,2016,9,21,Wednesday,false,false,false,false,false,false,false
25693130,Move textfield when keyboard appears swift,"I'm using Swift for programing with iOS and I'm using this code to move the UITextField, but it does not work. I call the function keyboardWillShow correctly, but the textfield doesn't move. I'm using autolayout.
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector(""keyboardWillShow:""), name:UIKeyboardWillShowNotification, object: nil);
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector(""keyboardWillHide:""), name:UIKeyboardWillHideNotification, object: nil);
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self);
}
func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
//let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0)
var frame = self.ChatField.frame
frame.origin.y = frame.origin.y - keyboardSize.height + 167
self.chatField.frame = frame
println(""asdasd"")
}
}
",https://stackoverflow.com/questions/25693130/move-textfield-when-keyboard-appears-swift,233,271359.0,38.0,,,2014-09-05 19:57:25,2024-05-14 09:07:43,2016-12-22 17:57:34,,,ios;swift;cocoa-touch;keyboard;uitextfield,Pedro Manfredi,3778,3426109,registered,true,27135992,,CC BY-SA 3.0,,1153,1096,3,0,0,5,true,false,false,true,true,true,42,6,false,0.14,0.0009,4460,2014,9,19,Friday,false,false,false,false,false,false,false
27880607,How to assign an action for UIImageView object in Swift,"I'm trying to assign an UIImageView to an action when the user taps it.
I know how to create an action for a UIButton, but how could I mimic the same behavior of a UIButton, but using a UIImageView?
",https://stackoverflow.com/questions/27880607/how-to-assign-an-action-for-uiimageview-object-in-swift,232,212170.0,12.0,,,2015-01-10 19:59:27,2022-02-10 16:10:14,2015-01-10 20:14:35,,,ios;swift;uiimageview,user3706773,3049,3706773,registered,true,27880669,,CC BY-SA 3.0,,266,200,4,0,0,3,true,false,false,true,true,true,55,10,false,0.057,0.0011,4333,2015,1,19,Saturday,true,false,false,false,false,false,false
24339807,How to test equality of Swift enums with associated values,"I want to test the equality of two Swift enum values. For example:
enum SimpleToken {
case Name(String)
case Number(Int)
}
let t1 = SimpleToken.Number(123)
let t2 = SimpleToken.Number(123)
XCTAssert(t1 == t2)
However, the compiler won't compile the equality expression:
error: could not find an overload for '==' that accepts the supplied arguments
XCTAssert(t1 == t2)
^~~~~~~~~~~~~~~~~~~
Do I have do define my own overload of the equality operator? I was hoping the Swift compiler would handle it automatically, much like Scala and Ocaml do.
",https://stackoverflow.com/questions/24339807/how-to-test-equality-of-swift-enums-with-associated-values,232,125920.0,15.0,,,2014-06-21 08:31:44,2024-03-27 10:43:12,,,,swift,Jay Lieske,4908,656176,registered,true,26703912,,CC BY-SA 3.0,,637,568,2,0,0,1,true,false,false,true,true,false,58,10,false,0.119,0.0018,4536,2014,6,8,Saturday,true,false,false,false,false,false,false
24113126,How to get the name of enumeration value in Swift?,"If I have an enumeration with raw Integer values:
enum City: Int {
case Melbourne = 1, Chelyabinsk, Bursa
}
let city = City.Melbourne
How can I convert a city value to a string Melbourne? Is this kind of a type name introspection available in the language?
Something like (this code will not work):
println(""Your city is \(city.magicFunction)"")
> Your city is Melbourne
",https://stackoverflow.com/questions/24113126/how-to-get-the-name-of-enumeration-value-in-swift,232,153527.0,12.0,,,2014-06-09 03:04:27,2021-08-10 20:40:37,2014-06-22 12:40:59,,,swift;enumeration,Evgenii,37549,297131,registered,true,31893968,,CC BY-SA 3.0,,490,382,5,0,0,2,true,false,false,true,true,true,50,10,true,0.078,0.0015,4548,2014,6,3,Monday,false,false,false,false,false,false,false
25167458,Changing navigation title programmatically,"I have a navigation bar with a title.
When I double click the text to rename it, it actually says it's a navigation item, so it might be that.
I'm trying to change the text using code, like:
declare navigation bar as navagationbar here
button stuff {
navigationbar.text = ""title""
}
That's not my code obviously, just showing how it would work.
So whenever I press the button, I want the title to change.
",https://stackoverflow.com/questions/25167458/changing-navigation-title-programmatically,231,289258.0,18.0,,,2014-08-06 18:23:24,2023-04-10 12:14:55,2015-06-18 00:24:59,,,swift;uinavigationbar;title,Rising,2555,3915586,registered,true,25167491,,CC BY-SA 3.0,,465,413,1,0,0,3,true,false,false,true,true,true,42,4,false,0.062,0.0008,4490,2014,8,18,Wednesday,false,false,false,false,false,false,false
24025340,Property getters and setters,"With this simple class I am getting the compiler warning
Attempting to modify/access x within its own setter/getter
and when I use it like this:
var p: point = Point()
p.x = 12
I get an EXC_BAD_ACCESS. How can I do this without explicit backing ivars?
class Point {
var x: Int {
set {
x = newValue * 2 //Error
}
get {
return x / 2 //Error
}
}
// ...
}
",https://stackoverflow.com/questions/24025340/property-getters-and-setters,231,348234.0,11.0,,,2014-06-03 21:35:37,2020-10-09 20:40:25,2018-06-05 19:45:21,,,swift;properties;compiler-warnings;getter-setter,Atomix,13922,3285649,registered,true,24025548,,CC BY-SA 4.0,,556,433,3,0,0,4,true,false,false,true,true,true,28,4,false,0.032,0.0007,4554,2014,6,21,Tuesday,false,false,false,false,false,false,false
25925481,How to get a unique device ID in Swift?,"How can I get a device's unique ID in Swift?
I need an ID to use in the database and as the API-key for my web service in my social app. Something to keep track of this devices daily use and limit its queries to the database.
",https://stackoverflow.com/questions/25925481/how-to-get-a-unique-device-id-in-swift,231,243161.0,11.0,,,2014-09-19 02:30:50,2023-11-15 09:18:08,2021-03-25 20:44:19,,,ios;swift;uuid;uniqueidentifier,User,24959,2199852,registered,true,25929324,,CC BY-SA 4.0,2018-07-17 22:16:06,240,226,0,0,0,4,true,false,false,true,true,true,39,9,true,0.045,0.0009,4446,2014,9,2,Friday,false,false,false,false,false,false,false
56691630,SwiftUI @State var initialization issue,"I would like to initialise the value of a @State var in SwiftUI through the init() method of a Struct, so it can take the proper text from a prepared dictionary for manipulation purposes in a TextField.
The source code looks like this:
struct StateFromOutside: View {
let list = [
"a": "Letter A",
"b": "Letter B",
// ...
]
@State var fullText: String = ""
init(letter: String) {
self.fullText = list[letter]!
}
var body: some View {
TextField($fullText)
}
}
Unfortunately the execution fails with the error
Thread 1: Fatal error: Accessing State outside View.body
How can I resolve the situation?
",https://stackoverflow.com/questions/56691630/swiftui-state-var-initialization-issue,229,102473.0,9.0,,,2019-06-20 18:07:24,2025-08-05 14:24:28,2025-08-05 14:24:28,,,swift;swiftui,Daniel Messner,2617,2420843,registered,true,56692335,,CC BY-SA 4.0,,837,721,4,0,0,2,true,false,false,true,true,true,39,5,false,0.088,0.0022,2711,2019,6,18,Thursday,false,false,false,false,false,false,false
24029917,Convert Float to Int in Swift,"I want to convert a Float to an Int in Swift. Basic casting like this does not work because these types are not primitives, unlike floats and ints in Objective-C
var float: Float = 2.2
var integer: Int = float as Float
But this produces the following error message:
'Float' is not convertible to 'Int'
Any idea how to property convert from Float to Int?
",https://stackoverflow.com/questions/24029917/convert-float-to-int-in-swift,229,244606.0,15.0,,,2014-06-04 05:46:52,2022-10-08 13:55:02,2016-05-18 19:35:24,,,swift;casting;type-conversion,kev,7860,2137369,registered,true,24030079,,CC BY-SA 3.0,2018-04-03 06:54:55,518,363,7,0,0,3,true,false,false,true,true,true,29,6,false,0.061,0.0009,4553,2014,6,5,Wednesday,false,false,false,false,false,false,false
28570973,How should I remove all the leading spaces from a string? - swift,"I need a way to remove the first character from a string which is a space. I am looking for a method or even an extension for the String type that I can use to cut out a character of a string.
",https://stackoverflow.com/questions/28570973/how-should-i-remove-all-the-leading-spaces-from-a-string-swift,228,249486.0,33.0,,,2015-02-17 20:58:38,2025-04-11 14:56:31,2018-11-22 05:56:35,,,string;swift,dhruvm,2822,3798602,registered,true,28571100,,CC BY-SA 4.0,2019-07-20 10:20:10,200,193,0,0,0,2,true,false,false,true,true,true,65,13,false,0.132,0.0009,4295,2015,2,20,Tuesday,false,false,false,false,false,false,false
24591167,How to get current language code with Swift?,"I want get the language code of the device (en, es...) in my app written with Swift. How can get this?
I'm trying this:
var preferredLanguages : NSLocale!
let pre = preferredLanguages.displayNameForKey(NSLocaleIdentifier, value: preferredLanguages)
But this returns nil.
",https://stackoverflow.com/questions/24591167/how-to-get-current-language-code-with-swift,227,230086.0,21.0,,,2014-07-05 22:45:03,2026-08-23 07:34:29,2020-02-06 12:44:56,,,swift;nslocale,user3739367,4507,3739367,registered,true,,,CC BY-SA 4.0,,320,275,1,0,0,2,false,false,false,true,true,true,44,8,true,0.091,0.001,4522,2014,7,22,Saturday,true,false,false,false,false,false,false
24312760,How to remove all subviews of a view in Swift?,"I'm looking for a simple method to remove at once all subviews from a superview instead of removing them one by one.
//I'm trying something like this, but is not working
let theSubviews : Array = container_view.subviews
for (view : NSView) in theSubviews {
view.removeFromSuperview(container_view)
}
What I am missing?
UPDATE
My app has a main container_view. I have to add different other views as subviews to container_view in order to provide a sort of navigation.
So, when clicking the button to ""open"" a particular page, I need to remove allsubviews and add the new one.
UPDATE 2 - A working solution (OS X)
I guess Apple fixed it.
Now it is more easy than ever, just call:
for view in containerView.subviews{
view.removeFromSuperview()
}
",https://stackoverflow.com/questions/24312760/how-to-remove-all-subviews-of-a-view-in-swift,227,208779.0,22.0,,,2014-06-19 17:26:22,2026-09-27 11:49:50,2016-01-27 06:40:23,,,macos;view;swift,Alberto,4262,1189841,registered,true,24666052,,CC BY-SA 3.0,,928,764,4,0,0,3,true,false,false,true,true,true,46,10,true,0.105,0.0011,4538,2014,6,17,Thursday,false,false,false,false,false,false,false
56514998,How to find all available images for Image(systemName:),"Where can I find all the system images that are available in the initializer Image(systemName:)?
I've only been using "chevron" and "star.fill" so far, as discovered in Apple's SwiftUI tutorial series. However, I haven't been able to find a full list of icons in any official documentation.
",https://stackoverflow.com/questions/56514998/how-to-find-all-available-images-for-imagesystemname,227,342380.0,9.0,,,2019-06-09 13:31:22,2026-02-14 20:30:04,2025-08-12 21:14:31,,,ios;swift;swiftui;sf-symbols,LinusG.,29442,3397217,registered,true,56515152,,CC BY-SA 4.0,,364,311,3,0,0,4,true,false,false,true,true,true,55,8,false,0.026,0.0007,2722,2019,6,13,Sunday,true,false,false,false,false,false,false
57517803,How to remove the default Navigation Bar space in SwiftUI NavigationView,"I am new to SwiftUI (like most people) and trying to figure out how to remove some whitespace above a List that I embedded in a NavigationView.
In this image, you can see that there is some white space above the List.
![]()
What I want to accomplish is this:
![]()
I've tried using:
.navigationBarHidden(true)
but this did not make any noticeable changes.
I'm currently setting up my navigiationView like this:
NavigationView {
FileBrowserView(jsonFromCall: URLRetrieve(URLtoFetch: applicationDelegate.apiURL))
.navigationBarHidden(true)
}
where FileBrowserView is a view with a List and FileCells defined like this:
List {
Section(header: Text("Root")) {
FileCell(name: "Test", fileType: "JPG",fileDesc: "Test number 1")
FileCell(name: "Test 2", fileType: "txt",fileDesc: "Test number 2")
FileCell(name: "test3", fileType: "fasta", fileDesc: "")
}
}
I do want to note that the ultimate goal here is that you will be able to click on these cells to navigate deeper into a file tree and thus should display a Back button on the bar on deeper navigation, but I do not want anything at the top as such during my initial view.
",https://stackoverflow.com/questions/57517803/how-to-remove-the-default-navigation-bar-space-in-swiftui-navigationview,226,164337.0,30.0,,,2019-08-16 01:01:19,2024-12-12 02:55:09,2021-09-15 20:58:21,,,ios;swift;swiftui;swiftui-list;swiftui-navigationview,Vapidant,2672,10099396,registered,true,57518324,,CC BY-SA 4.0,,1617,1256,9,0,2,5,true,false,false,true,true,true,72,11,false,0.183,0.0014,2654,2019,8,1,Friday,false,false,false,false,false,false,false
56471973,How do I create a multiline TextField in SwiftUI?,"I've been trying to create a multiline TextField in SwiftUI, but I can't figure out how.
This is the code I currently have:
struct EditorTextView : View {
@Binding var text: String
var body: some View {
TextField($text)
.lineLimit(4)
.multilineTextAlignment(.leading)
.frame(minWidth: 100, maxWidth: 200, minHeight: 100, maxHeight: .infinity, alignment: .topLeading)
}
}
#if DEBUG
let sampleText = """
Very long line 1
Very long line 2
Very long line 3
Very long line 4
"""
struct EditorTextView_Previews : PreviewProvider {
static var previews: some View {
EditorTextView(text: .constant(sampleText))
.previewLayout(.fixed(width: 200, height: 200))
}
}
#endif
But this is the output:
",https://stackoverflow.com/questions/56471973/how-do-i-create-a-multiline-textfield-in-swiftui,225,154052.0,18.0,,,2019-06-06 06:30:12,2025-08-12 20:21:05,2025-08-12 20:20:13,,,ios;swift;swiftui;textview;textfield,gabriellanata,4386,380404,registered,true,56549250,,CC BY-SA 4.0,2025-08-12 20:21:36,1025,808,2,1,1,5,true,false,false,true,true,true,49,9,true,0.117,0.0015,2725,2019,6,6,Thursday,false,false,false,false,false,false,false
27094878,How do I get the count of a Swift enum?,"How can I determine the number of cases in a Swift enum?
(I would like to avoid manually enumerating through all the values, or using the old ""enum_count trick"" if possible.)
",https://stackoverflow.com/questions/27094878/how-do-i-get-the-count-of-a-swift-enum,224,85417.0,26.0,,,2014-11-23 21:59:30,2022-03-10 16:04:42,2017-05-23 12:26:23,,,swift;enums;count,Robert Atkins,25008,17294,registered,true,50177561,,CC BY-SA 3.0,,304,176,0,2,0,3,true,false,false,true,true,true,39,10,true,0.304,0.0026,4381,2014,11,21,Sunday,true,false,false,false,false,false,false
25537614,Why is Swift compile time so slow?,"I'm using Xcode 6 Beta 6.
This is something that's been bugging me for some time now, but it's reaching a point where it's barely usable now.
My project is starting to have a decent size of 65 Swift files and a few bridged Objective-C files (which are really not the cause of the problem).
It seems like any slight modification to any Swift file (like adding a simple white space in a class that's barely used in the app) will cause the entire Swift files for the specified target to be recompiled.
After a deeper investigation, I've found that what is taking pretty much 100% of the compiler time is the CompileSwift phase where Xcode runs the swiftc command on all Swift files of your target.
I did some further investigation, and if I only keep the app delegate with a default controller the compilation is very fast, but as I was adding more and more of my project files, the compile time was starting to get really slow.
Now with only 65 source files, it takes about 8/10 seconds to compile each time. Not very swift at all.
I haven't seen any post talking about this issue except this one, but it was an old version of Xcode 6. So I'm wondering if I'm the only one in that case.
UPDATE
I've checked a few Swift projects on GitHub like Alamofire, Euler and CryptoSwift, but none of them had enough Swift files to actually compare. The only project I found that was starting a have decent size was SwiftHN, and even though it only had a dozen source files I was still able to verify the same thing, one simple space and the whole project needed recompilation which was starting to take a little time (2/3 seconds).
Compared to Objective-C code where both analyzer and compilation are blazing fast, this really feels like Swift will never be able to handle big projects, but please tell me I'm wrong.
UPDATE With Xcode 6 Beta 7
Still no improvement whatsoever. This is starting to get ridiculous. With the lack of #import in Swift, I really don't see how Apple will ever be able to optimize this.
UPDATE With Xcode 6.3 and Swift 1.2
Apple has added incremental builds (and many other compiler optimizations). You have to migrate your code to Swift 1.2 to see those benefits, but Apple added a tool in Xcode 6.3 to help you do so:
![]()
HOWEVER
Don't rejoice too quickly as I did. The graph solver that they use to make the build incremental is not very well optimised yet.
Indeed first, it doesn't look at function signature changes so if you add a space in the block of one method, all files depending on that class will be recompiled.
Second, it seems to create the tree based on the files that were recompiled even if a change doesn't affect them. For example, if you move these three classes into different files
class FileA: NSObject {
var foo:String?
}
class FileB: NSObject {
var bar:FileA?
}
class FileC: NSObject {
var baz:FileB?
}
Now if you modify FileA, the compiler will obviously mark FileA to be recompiled. It will also recompile FileB (that would be OK based on the changes to FileA), but also FileC because FileB is recompiled, and that is pretty bad because FileC never uses FileA here.
So I hope they improve that dependency tree solver... I've opened a radar with this sample code.
UPDATE With Xcode 7 beta 5 and Swift 2.0
Yesterday Apple released the beta 5 and inside the release notes we could see:
Swift Language & Compiler
• Incremental builds: changing just the body of a function should no longer cause dependent files to be rebuilt. (15352929)
I have given it a try and I must say it is working really (really !) well now. They greatly optimized the incremental builds in swift.
I highly recommend you create a swift2.0 branch and keep your code up to date using XCode 7 beta 5. You will be pleased by the enhancements of the compiler (however I'd say the global state of XCode 7 is still slow & buggy)
UPDATE With Xcode 8.2
It's been a while since my last update on this issue so here it is.
Our app is now about 20k lines of almost exclusively Swift code, which is decent but not outstanding. It underwent swift 2 and than swift 3 migration. It takes about 5/6m to compile on a mid 2014 Macbook pro (2.5 GHz Intel Core i7) which is okay on a clean build.
However the incremental build is still a joke despite Apple claiming that:
Xcode will not rebuild an entire target when only small changes have occurred. (28892475)
Obviously I think many of us just laughed after checking out this nonsense (adding one private (private!) property to any file of my project will recompile the whole thing...)
I would like to point you guys to this thread on Apple developer forums which has some more information about the issue (as well as appreciated Apple dev communication on the matter once in a while)
Basically people have come up with a few things to try to improve the incremental build:
- Add a
HEADER_MAP_USES_VFS project setting set to true
- Disable
Find implicit dependencies from your scheme
- Create a new project and move your files hierarchy to the new one.
I will try solution 3 but solution 1/2 didn't work for us.
What's ironically funny in this whole situation is that looking at the first post on this issue we were using Xcode 6 with I believe swift 1 or swift 1.1 code when we reached the first compilations slugginess and now about two years later despite actual improvements from Apple the situation is just as bad as it was with Xcode 6. How ironic.
I actually REALLY regret choosing Swift over Obj/C for our project because of the daily frustration it involves. (I even switch to AppCode but that's another story)
Anyways I see this SO post has 32k+ views and 143 ups as of this writing so I guess I'm not the only one. Hang in there guys despite being pessimistic over this situation there might be some light at the end of the tunnel.
If you have the time (and courage!) I guess Apple welcomes radar about this.
UPDATE With Xcode 9
Stumble upon this today. Xcode quietly introduced a new build system to improve on the current awful performance. You have to enable it through the workspace settings.
Have given a try yet but will update this post after it's done. Looks promising though.
",https://stackoverflow.com/questions/25537614/why-is-swift-compile-time-so-slow,224,55065.0,22.0,,,2014-08-27 21:57:05,2022-12-24 09:02:04,2022-12-24 09:02:04,,,swift;optimization;compilation;type-inference;compilation-time,apouche,10023,591482,registered,true,,,CC BY-SA 4.0,,7935,6157,16,11,2,5,false,false,false,true,true,true,34,7,true,0.4,0.0041,4469,2014,8,21,Wednesday,false,false,false,false,false,false,false
24045570,How do I get a plist as a Dictionary in Swift?,"I am playing around with Apple's new Swift programming language and have some problems...
Currently I'm trying to read a plist file, in Objective-C I would do the following to get the content as a NSDictionary:
NSString *filePath = [[NSBundle mainBundle] pathForResource:@""Config"" ofType:@""plist""];
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:filePath];
How do I get a plist as a Dictionary in Swift?
I assume I can get the path to the plist with:
let path = NSBundle.mainBundle().pathForResource(""Config"", ofType: ""plist"")
When this works (If it's correct?): How do I get the content as a Dictionary?
Also a more general question:
Is it OK to use the default NS* classes? I think so...or am I missing something? As far as I know the default framework NS* classes are still valid and alright to use?
",https://stackoverflow.com/questions/24045570/how-do-i-get-a-plist-as-a-dictionary-in-swift,222,220032.0,27.0,,,2014-06-04 19:05:17,2023-10-23 01:17:56,2018-01-08 09:34:19,,,ios;swift,Sebastian,3409,470964,registered,true,39453212,,CC BY-SA 3.0,,980,832,2,0,0,2,true,false,false,true,true,true,46,11,true,0.123,0.001,4553,2014,6,19,Wednesday,false,false,false,false,false,false,false
24029163,Finding index of character in Swift String,"It's time to admit defeat...
In Objective-C, I could use something like:
NSString* str = @""abcdefghi"";
[str rangeOfString:@""c""].location; // 2
In Swift, I see something similar:
var str = ""abcdefghi""
str.rangeOfString(""c"").startIndex
...but that just gives me a String.Index, which I can use to subscript back into the original string, but not extract a location from.
FWIW, that String.Index has a private ivar called _position that has the correct value in it. I just don't see how it's exposed.
I know I could easily add this to String myself. I'm more curious about what I'm missing in this new API.
",https://stackoverflow.com/questions/24029163/finding-index-of-character-in-swift-string,222,282884.0,33.0,,,2014-06-04 04:42:23,2022-05-18 06:26:12,2014-06-05 17:02:23,,,string;swift,Matt Wilding,20163,538308,registered,true,24056932,,CC BY-SA 3.0,,747,618,5,0,0,2,true,false,false,true,true,true,42,7,false,0.117,0.0008,4553,2014,6,4,Wednesday,false,false,false,false,false,false,false
28152526,How do I open phone settings when a button is clicked?,"I am trying to implement a feature in an App that shows an alert when the internet connection is not available.
The alert has two actions (OK and Settings), whenever a user clicks on settings, I want to take them to the phone settings programmatically.
I am using Swift and Xcode.
",https://stackoverflow.com/questions/28152526/how-do-i-open-phone-settings-when-a-button-is-clicked,221,205171.0,14.0,,,2015-01-26 14:52:29,2024-03-28 16:01:34,2018-04-25 10:43:01,,,ios;swift;settings,Solomon Ayoola,2699,4485982,registered,true,28152624,,CC BY-SA 3.0,,296,282,0,0,0,3,true,false,false,true,true,true,54,11,true,0.068,0.0011,4317,2015,1,14,Monday,false,false,false,false,false,false,false
27040924,NSRange from Swift Range?,"Problem: NSAttributedString takes an NSRange while I'm using a Swift String that uses Range
let text = ""Long paragraph saying something goes here!""
let textRange = text.startIndex..<text.endIndex
let attributedString = NSMutableAttributedString(string: text)
text.enumerateSubstringsInRange(textRange, options: NSStringEnumerationOptions.ByWords, { (substring, substringRange, enclosingRange, stop) -> () in
if (substring == ""saying"") {
attributedString.addAttribute(NSForegroundColorAttributeName, value: NSColor.redColor(), range: substringRange)
}
})
Produces the following error:
error: 'Range' is not convertible to 'NSRange'
attributedString.addAttribute(NSForegroundColorAttributeName, value: NSColor.redColor(), range: substringRange)
",https://stackoverflow.com/questions/27040924/nsrange-from-swift-range,221,176113.0,13.0,,,2014-11-20 13:33:16,2024-01-11 13:46:33,,,,ios;macos;swift;nsrange,Jay,4580,308020,registered,true,27041376,,CC BY-SA 3.0,,889,785,1,0,0,4,true,false,false,true,true,false,25,4,true,0.074,0.0013,4384,2014,11,13,Thursday,false,false,false,false,false,false,false
24081009,Is there a reason that Swift array assignment is inconsistent (neither a reference nor a deep copy)?,"I'm reading the documentation and I am constantly shaking my head at some of the design decisions of the language. But the thing that really got me puzzled is how arrays are handled.
I rushed to the playground and tried these out. You can try them too. So the first example:
var a = [1, 2, 3]
var b = a
a[1] = 42
a
b
Here a and b are both [1, 42, 3], which I can accept. Arrays are referenced - OK!
Now see this example:
var c = [1, 2, 3]
var d = c
c.append(42)
c
d
c is [1, 2, 3, 42] BUT d is [1, 2, 3]. That is, d saw the change in the last example but doesn't see it in this one. The documentation says that's because the length changed.
Now, how about this one:
var e = [1, 2, 3]
var f = e
e[0..2] = [4, 5]
e
f
e is [4, 5, 3], which is cool. It's nice to have a multi-index replacement, but f STILL doesn't see the change even though the length has not changed.
So to sum it up, common references to an array see changes if you change 1 element, but if you change multiple elements or append items, a copy is made.
This seems like a very poor design to me. Am I right in thinking this? Is there a reason I don't see why arrays should act like this?
EDIT: Arrays have changed and now have value semantics. Much more sane!
",https://stackoverflow.com/questions/24081009/is-there-a-reason-that-swift-array-assignment-is-inconsistent-neither-a-referen,221,22228.0,10.0,,,2014-06-06 11:41:14,2019-03-08 20:34:32,2014-07-07 21:49:20,,,arrays;swift,Cthutu,8967,268687,registered,true,24081412,,CC BY-SA 3.0,,1544,1250,14,0,0,2,true,false,false,true,true,true,100,17,true,0.45,0.0099,4551,2014,6,11,Friday,false,false,false,false,false,false,false
24465281,Flatten an Array of Arrays in Swift,"Is there a counterpart in Swift to flatten in Scala, Xtend, Groovy, Ruby and co?
var aofa = [[1,2,3],[4],[5,6,7,8,9]]
aofa.flatten() // shall deliver [1,2,3,4,5,6,7,8,9]
of course i could use reduce for that but that kinda sucks
var flattened = aofa.reduce(Int[]()){
a,i in var b : Int[] = a
b.extend(i)
return b
}
",https://stackoverflow.com/questions/24465281/flatten-an-array-of-arrays-in-swift,220,127465.0,15.0,,,2014-06-28 09:03:00,2024-09-15 19:15:02,2019-11-22 05:55:10,,,swift,Christian Dietrich,11878,935687,registered,true,26041954,,CC BY-SA 4.0,,408,333,3,0,0,1,true,false,false,true,true,true,35,7,false,0.118,0.0017,4529,2014,6,9,Saturday,true,false,false,false,false,false,false
26794703,Swift - Integer conversion to Hours/Minutes/Seconds,"I have a (somewhat?) basic question regarding time conversions in Swift.
I have an integer that I would like converted into Hours / Minutes / Seconds.
Example: Int = 27005 would give me:
7 Hours 30 Minutes 5 Seconds
I know how to do this in PHP, but alas, swift isn't PHP.
",https://stackoverflow.com/questions/26794703/swift-integer-conversion-to-hours-minutes-seconds,219,194978.0,25.0,,,2014-11-07 05:30:03,2023-04-08 05:25:20,2023-01-05 21:07:55,,,ios;swift,Joe,3990,4220994,registered,true,26794841,,CC BY-SA 4.0,,374,275,2,0,0,2,true,false,false,true,true,true,51,6,false,0.128,0.0011,4397,2014,11,5,Friday,false,false,false,false,false,false,false
24236912,How do I hide the status bar in a Swift iOS app?,"I'd like to remove the status bar at the top of the screen.
This does not work:
func application
(application: UIApplication,
didFinishLaunchingWithOptions launchOptions: NSDictionary?)
-> Bool
{
application.statusBarHidden = true
return true
}
I've also tried:
func application
(application: UIApplication,
didFinishLaunchingWithOptions launchOptions: NSDictionary?)
-> Bool
{
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
var controller = UIViewController()
application.statusBarHidden = true
controller.setNeedsStatusBarAppearanceUpdate()
var view = UIView(frame: CGRectMake(0, 0, 320, 568))
view.backgroundColor = UIColor.redColor()
controller.view = view
var label = UILabel(frame: CGRectMake(0, 0, 200, 21))
label.center = CGPointMake(160, 284)
label.textAlignment = NSTextAlignment.Center
label.text = ""Hello World""
controller.view.addSubview(label)
self.window!.rootViewController = controller
self.window!.makeKeyAndVisible()
return true
}
",https://stackoverflow.com/questions/24236912/how-do-i-hide-the-status-bar-in-a-swift-ios-app,218,179934.0,28.0,,,2014-06-16 05:04:05,2025-04-28 11:08:38,2015-04-24 09:38:41,,,ios;iphone;ios7;swift,Jay,9650,336892,registered,true,24236943,,CC BY-SA 3.0,,1124,1055,2,0,0,4,true,false,false,true,true,true,48,12,true,0.156,0.0012,4541,2014,6,5,Monday,false,false,false,false,false,false,false
25921204,Convert Swift string to array,"How can I convert a String "Hello" to an Array ["H","e","l","l","o"] in Swift?
In Objective-C I have used this:
NSMutableArray *characters = [[NSMutableArray alloc] initWithCapacity:[myString length]];
for (int i=0; i < [myString length]; i++) {
NSString *ichar = [NSString stringWithFormat:@"%c", [myString characterAtIndex:i]];
[characters addObject:ichar];
}
",https://stackoverflow.com/questions/25921204/convert-swift-string-to-array,218,289551.0,14.0,,,2014-09-18 19:50:19,2022-03-20 14:53:11,2021-02-08 22:48:37,,,ios;arrays;swift;string,Mr.KLD,2772,1526507,registered,true,25921323,,CC BY-SA 4.0,,509,445,3,0,0,4,true,false,false,true,true,true,29,5,false,0.048,0.0008,4447,2014,9,19,Thursday,false,false,false,false,false,false,false
24893110,Can I use the range operator with if statement in Swift?,"Is it possible to use the range operator ... and ..< with if statement. Maye something like this:
let statusCode = 204
if statusCode in 200 ..< 299 {
NSLog(""Success"")
}
",https://stackoverflow.com/questions/24893110/can-i-use-the-range-operator-with-if-statement-in-swift,218,84994.0,6.0,,,2014-07-22 16:42:10,2020-09-15 04:08:22,,,,if-statement;swift;range,Jimmy,10411,302707,registered,true,24893494,,CC BY-SA 3.0,,236,179,3,0,0,3,true,false,false,true,true,false,56,11,true,0.071,0.0026,4505,2014,7,16,Tuesday,false,false,false,false,false,false,false
24034174,How do I concatenate strings in Swift?,"How to concatenate string in Swift?
In Objective-C we do like
NSString *string = @""Swift"";
NSString *resultStr = [string stringByAppendingString:@"" is a new Programming Language""];
or
NSString *resultStr=[NSString stringWithFormat:@""%@ is a new Programming Language"",string];
But I want to do this in Swift-language.
",https://stackoverflow.com/questions/24034174/how-do-i-concatenate-strings-in-swift,218,372403.0,21.0,,,2014-06-04 09:49:15,2024-04-14 15:30:50,2024-04-14 15:30:50,,,swift;string;concatenation;string-concatenation,Rajneesh071,31127,1369972,registered,true,24034334,,CC BY-SA 4.0,,413,324,3,0,0,4,true,false,false,true,true,true,38,7,true,0.056,0.0006,4553,2014,6,9,Wednesday,false,false,false,false,false,false,false
32256834,Swift: guard let vs if let,"I have been reading about Optionals in Swift, and I have seen examples where if let is used to check if an Optional holds a value, and in case it does – do something with the unwrapped value.
However, I have seen that in Swift 2.0 the keyword guard let is used mostly. I wonder whether if let has been removed from Swift 2.0 or if it still possible to be used.
Should I change my programs that contain if let to guard let?
",https://stackoverflow.com/questions/32256834/swift-guard-let-vs-if-let,218,157389.0,11.0,,,2015-08-27 18:23:49,2024-10-18 14:08:17,2020-03-12 14:27:47,,,swift;swift2;option-type;conventions;control-flow,lmiguelvargasf,71913,3705840,registered,true,32256911,,CC BY-SA 4.0,,511,425,5,0,0,5,true,false,false,true,true,true,26,6,false,0.07,0.0014,4104,2015,8,18,Thursday,false,false,false,false,false,false,false
24002836,dyld: Library not loaded: @rpath/libswift_stdlib_core.dylib,"I get this error after adding a Swift class to an old Xcode project.
dyld: Library not loaded: @rpath/libswift_stdlib_core.dylib
How can I make the project run again?
",https://stackoverflow.com/questions/24002836/dyld-library-not-loaded-rpath-libswift-stdlib-core-dylib,217,80121.0,36.0,,,2014-06-02 20:36:18,2024-08-09 15:06:47,2019-03-30 09:44:51,,,swift;dyld,Anton,6073,1491531,registered,true,25772532,,CC BY-SA 4.0,2016-01-27 11:21:46,203,169,1,0,0,2,true,false,false,true,true,true,59,5,false,0.449,0.0027,4555,2014,6,20,Monday,false,false,false,false,false,false,false
29457720,Compiler error: Method with Objective-C selector conflicts with previous declaration with the same Objective-C selector,"I am starting to learn Swift, and have been following the very good Stanford University video lectures on YouTube. Here is a link if you are interested or it helps (although it isn't required to understand my problem):
Developing iOS 8 Apps with Swift - 2. More Xcode and Swift, MVC
While following the lectures I got to a point where (as far as I could tell) my code was identical to the code in the video but on my system I got a compiler error. After a lot of trial and error I have managed to reduce my code to two examples, one of which generates an error, the other or which doesn't, but I have no idea what is actually causing the error or how to resolve it.
The code which creates the error is:
import UIKit
class BugViewController: UIViewController
{
func perform(operation: (Double) -> Double) {
}
func perform(operation: (Double, Double) -> Double) {
}
}
This creates the following compiler error:
Method 'perform' with Objective-C selector 'perform: ' conflicts with previous declaration with the same Objective-C selector
By simply removing the sub-classing of UIViewController the code compiles:
import UIKit
class BugViewController
{
func perform(operation: (Double) -> Double) {
}
func perform(operation: (Double, Double) -> Double) {
}
}
Some other information which may or may not be relevant:
- I have recently upgraded to Yosemite.
- When I installed Xcode, I ended up with a Beta version (Version 6.3 (6D543q)) because (if I remember correctly) this was the version I needed to run on my version of OS X.
I am half hoping this is a bug in the compiler because otherwise this doesn't make any sense to me. Any help very gratefully received!
",https://stackoverflow.com/questions/29457720/compiler-error-method-with-objective-c-selector-conflicts-with-previous-declara,216,69142.0,6.0,,,2015-04-05 13:19:12,2017-05-05 22:15:24,2016-01-29 21:51:50,,,swift,Auspice,2326,655926,registered,true,29457777,,CC BY-SA 3.0,2015-12-16 02:54:19,1997,1724,2,1,0,1,true,false,false,true,true,true,119,15,false,0.087,0.0031,4248,2015,4,13,Sunday,true,false,false,false,false,false,false
32390611,"try, try! & try? what’s the difference, and when to use each?","In Swift 2.0, Apple introduced a new way to handle errors (do-try-catch).
And few days ago in Beta 6 an even newer keyword was introduced (try?).
Also, knew that I can use try!.
What's the difference between the 3 keywords, and when to use each?
",https://stackoverflow.com/questions/32390611/try-try-try-what-s-the-difference-and-when-to-use-each,216,71517.0,1.0,,,2015-09-04 05:20:21,2019-07-29 10:22:25,2017-04-09 00:20:10,,,swift;error-handling;swift3;swift2,Abdurrahman,6766,976419,registered,true,32390612,,CC BY-SA 3.0,,343,246,2,1,0,4,true,false,false,true,true,true,65,12,true,0.014,0.003,4096,2015,9,5,Friday,false,false,false,false,false,false,false
24167791,What is the Swift equivalent of respondsToSelector?,"I've googled but not been able to find out what the swift equivalent to respondsToSelector: is.
This is the only thing I could find (Swift alternative to respondsToSelector:) but isn't too relevant in my case as its checking the existence of the delegate, I don't have a delegate I just want to check if a new API exists or not when running on the device and if not fall back to a previous version of the api.
",https://stackoverflow.com/questions/24167791/what-is-the-swift-equivalent-of-respondstoselector,216,117415.0,17.0,,,2014-06-11 16:16:13,2020-07-24 09:56:43,2018-08-31 18:06:48,,,objective-c;swift;selector,Piepants,37396,1082219,registered,true,24168825,,CC BY-SA 4.0,,537,411,1,1,0,3,true,false,false,true,true,true,51,7,true,0.145,0.0018,4546,2014,6,16,Wednesday,false,false,false,false,false,false,false
24217586,structure vs class in Swift language,"From the Apple book:
One of the most important differences between structures and classes is that structures are always copied when they are passed around in your code, but classes are passed by reference.
Can anyone help me understand what that means? To me, classes and structs seem to be the same.
",https://stackoverflow.com/questions/24217586/structure-vs-class-in-swift-language,215,98198.0,13.0,,,2014-06-14 07:18:31,2026-06-30 08:56:56,2026-06-29 20:36:17,,,swift,Manish Agrawal,11067,2450704,registered,true,24217633,,CC BY-SA 4.0,,349,303,0,0,0,1,true,false,false,true,true,true,36,6,false,0.132,0.0022,4543,2014,6,7,Saturday,true,false,false,false,false,false,false
24033393,Swift: declare an empty dictionary,"I am beginning to learn swift by following the iBook-The Swift Programming Language on Swift provided by Apple. The book says to create an empty dictionary one should use [:] same as while declaring array as []:
I declared an empty array as follows :
let emptyArr = [] // or String[]()
But on declaring empty dictionary, I get syntax error:
let emptyDict = [:]
How do I declare an empty dictionary?
",https://stackoverflow.com/questions/24033393/swift-declare-an-empty-dictionary,215,264310.0,19.0,,,2014-06-04 09:12:42,2021-08-11 04:17:20,2016-03-30 15:31:39,,,ios;swift;dictionary,z22,10113,1390680,registered,true,24033461,,CC BY-SA 3.0,,534,406,6,0,0,3,true,false,false,true,true,true,34,5,false,0.072,0.0008,4553,2014,6,9,Wednesday,false,false,false,false,false,false,false
32551890,How to add leading padding to view added inside an UIStackView,"This is my setup: I have an UIScrollView with leading,top, trialing edge set to 0. Inside this I add an UIStackView with this constraints:
stackView.centerYAnchor.constraintEqualToAnchor(selectedContactsScrollView.centerYAnchor).active = true
stackView.leadingAnchor.constraintEqualToAnchor(selectedContactsScrollView.leadingAnchor).active = true
Inside the stack view I add some views.
My issue is that because of the constraints the first view added to stack view will also have leading edge = 0.
What are the ways that I could add some padding to the first view ? Without adjusting the scroll view constraints.
",https://stackoverflow.com/questions/32551890/how-to-add-leading-padding-to-view-added-inside-an-uistackview,214,167514.0,13.0,,,2015-09-13 16:29:29,2024-10-30 12:30:25,,,,ios;swift;uiscrollview;uistackview,Adrian,20258,340554,registered,true,32581345,,CC BY-SA 3.0,,696,621,3,0,0,4,true,false,false,true,true,false,62,11,false,0.078,0.0013,4087,2015,9,16,Sunday,true,false,false,false,false,false,false
24003191,Pick a random element from an array,"Suppose I have an array and I want to pick one element at random.
What would be the simplest way to do this?
The obvious way would be array[random index]. But perhaps there is something like ruby's array.sample? Or if not could such a method be created by using an extension?
",https://stackoverflow.com/questions/24003191/pick-a-random-element-from-an-array,214,131267.0,16.0,,,2014-06-02 20:59:22,2022-05-19 16:09:20,2018-04-25 22:37:39,,,arrays;swift;random,Fela,27630,1494793,registered,true,24052491,,CC BY-SA 3.0,,325,278,2,0,0,3,true,false,false,true,true,true,35,7,false,0.122,0.0016,4555,2014,6,20,Monday,false,false,false,false,false,false,false
27062454,Converting URL to String and back again,"So I have converted an NSURL to a String.
So if I println it looks like file:///Users/... etc.
Later I want this back as an NSURL so I try and convert it back as seen below, but I lose two of the forward slashes that appear in the string version above, that in turn breaks the code as the url is invalid.
Why is my conversion back to NSURL removing two forward slashes from the String I give it, and how can I convert back to the NSURL containing three forward slashes?
var urlstring: String = recordingsDictionaryArray[selectedRow][""path""] as String
println(""the url string = \(urlstring)"")
// looks like file:///Users/........etc
var url = NSURL.fileURLWithPath(urlstring)
println(""the url = \(url!)"")
// looks like file:/Users/......etc
",https://stackoverflow.com/questions/27062454/converting-url-to-string-and-back-again,214,324565.0,10.0,,,2014-11-21 13:23:52,2024-10-02 02:28:52,2016-01-18 01:17:07,,,swift;nsurl,Gary Simpson,2837,503314,registered,true,27062664,,CC BY-SA 3.0,,906,744,10,0,0,2,true,false,false,true,true,true,39,7,false,0.031,0.0007,4383,2014,11,13,Friday,false,false,false,false,false,false,false
24116271,What's the cleanest way of applying map() to a dictionary in Swift?,"I'd like to map a function on all keys in the dictionary. I was hoping something like the following would work, but filter cannot be applied to dictionary directly. What's the cleanest way of achieving this?
In this example, I'm trying to increment each value by 1. However this is incidental for the example - the main purpose is to figure out how to apply map() to a dictionary.
var d = [""foo"" : 1, ""bar"" : 2]
d.map() {
$0.1 += 1
}
",https://stackoverflow.com/questions/24116271/whats-the-cleanest-way-of-applying-map-to-a-dictionary-in-swift,214,166080.0,14.0,,,2014-06-09 08:19:51,2022-10-17 09:48:23,2017-06-18 13:35:50,,,swift;dictionary,Maria Zverina,11233,655183,registered,true,24219069,,CC BY-SA 3.0,,480,442,1,0,0,2,true,false,false,true,true,true,71,12,true,0.084,0.0013,4548,2014,6,8,Monday,false,false,false,false,false,false,false
24159627,Swift - Convert to absolute value,"is there any way to get absolute value from an integer?
for example
-8
to
8
I already tried to use UInt() assuming it will convert the Int to unsigned value but it didn't work.
",https://stackoverflow.com/questions/24159627/swift-convert-to-absolute-value,214,113905.0,4.0,,,2014-06-11 09:43:33,2019-07-06 09:26:57,2015-04-08 04:18:59,,,ios;iphone;swift,Niko Adrianus Yuwono,11122,1509106,registered,true,24159740,,CC BY-SA 3.0,,230,188,1,0,0,3,true,false,false,true,true,true,33,6,false,0.035,0.0019,4546,2014,6,9,Wednesday,false,false,false,false,false,false,false
24701075,Swift: Convert enum value to String?,"Given the following enum:
enum Audience {
case Public
case Friends
case Private
}
How do I get the string ""Public"" from the audience constant below?
let audience = Audience.Public
",https://stackoverflow.com/questions/24701075/swift-convert-enum-value-to-string,213,203137.0,19.0,,,2014-07-11 15:16:05,2024-01-25 01:25:05,,,,string;enums;swift,ma11hew28,128159,242933,registered,true,33706783,,CC BY-SA 3.0,,285,197,4,0,0,3,true,false,false,true,true,false,36,6,true,0.094,0.001,4516,2014,7,15,Friday,false,false,false,false,false,false,false
28012205,Map or reduce with index in Swift,"Is there a way to get the index of the array in map or reduce in Swift? I'm looking for something like each_with_index in Ruby.
func lunhCheck(number : String) -> Bool
{
var odd = true;
return reverse(number).map { String($0).toInt()! }.reduce(0) {
odd = !odd
return $0 + (odd ? ($1 == 9 ? 9 : ($1 * 2) % 9) : $1)
} % 10 == 0
}
lunhCheck(""49927398716"")
lunhCheck(""49927398717"")
I would like to get rid of the odd variable above.
",https://stackoverflow.com/questions/28012205/map-or-reduce-with-index-in-swift,213,110069.0,6.0,,,2015-01-18 16:46:50,2026-01-14 21:06:53,,,,swift;functional-programming,Jonas Elfström,31706,44620,registered,true,28012291,,CC BY-SA 3.0,,638,465,5,1,0,2,true,false,false,true,true,false,33,7,false,0.055,0.0019,4325,2015,1,16,Sunday,true,false,false,false,false,false,false
56491386,How to hide keyboard when using SwiftUI?,"How to hide keyboard using SwiftUI for below cases?
Case 1
I have TextField and I need to hide the keyboard when the user clicks the return button.
Case 2
I have TextField and I need to hide the keyboard when the user taps outside.
How I can do this using SwiftUI?
Note:
I have not asked a question regarding UITextField. I want to do it by using SwifUI.TextField.
",https://stackoverflow.com/questions/56491386/how-to-hide-keyboard-when-using-swiftui,212,155227.0,39.0,,,2019-06-07 09:13:16,2025-07-01 13:15:46,2020-10-31 08:41:53,,,ios;swift;keyboard;swiftui;textfield,Hitesh Surani,13669,5036586,registered,true,,,CC BY-SA 4.0,2022-09-30 08:43:22,602,365,10,0,0,5,false,false,false,true,true,true,40,7,true,0.251,0.0014,2724,2019,6,9,Friday,false,false,false,false,false,false,false
24985716,In Swift how to call method with parameters on GCD main thread?,"In my app I have a function that makes an NSRURLSession and sends out an NSURLRequest using
sesh.dataTaskWithRequest(req, completionHandler: {(data, response, error)
In the completion block for this task, I need to do some computation that adds a UIImage to the calling viewcontroller. I have a func called
func displayQRCode(receiveAddr, withAmountInBTC:amountBTC)
that does the UIImage-adding computation. If I try to run the view-adding code inside of the completion block, Xcode throws an error saying that I can't use the layout engine while in a background process. So I found some code on SO that tries to queue a method on the main thread:
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(0.0 * Double(NSEC_PER_MSEC)))
dispatch_after(time, dispatch_get_main_queue(), {
let returned = UIApplication.sharedApplication().sendAction(""displayQRCode:"", to: self.delegate, from: self, forEvent: nil)
})
However, I don't know how to add the parameters ""receiveAddr"" and ""amountBTC"" to this function call. How would I do this, or can someone suggest an optimal way for adding a method call to the application's main queue?
",https://stackoverflow.com/questions/24985716/in-swift-how-to-call-method-with-parameters-on-gcd-main-thread,212,197300.0,11.0,,,2014-07-27 21:12:47,2022-07-22 12:49:58,2021-11-08 08:35:23,,,ios;swift;cocoa-touch;parameters;grand-central-dispatch,almel,8068,1484555,registered,true,24985766,,CC BY-SA 4.0,,1237,1137,3,0,0,5,true,false,false,true,true,true,63,12,true,0.056,0.0011,4500,2014,7,21,Sunday,true,false,false,false,false,false,false
24103169,Swift compiler error: "non-modular header inside framework module","Now I would like to migrate my ObjC framework to Swift and I got the following error:
include of non-modular header inside framework module 'SOGraphDB'
The references is to a header file which just define a protocol and I use this header file in some classes to use this protocol.
Is seems related to the module feature but it is at the moment not quite clear how to fix, do you know a solution?
UPDATE:
This is a Swift compiler error.
UPDATE 2:
A quick fix (but not solving the root cause) is to set the following setting to yes:
CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES = YES
",https://stackoverflow.com/questions/24103169/swift-compiler-error-non-modular-header-inside-framework-module,212,107367.0,21.0,,,2014-06-08 05:04:23,2021-12-17 13:52:24,2015-07-17 06:46:21,,,objective-c;frameworks;swift,Stephan,4333,565336,registered,true,24317456,,CC BY-SA 3.0,,672,599,1,0,0,3,true,false,false,true,true,true,76,8,false,0.196,0.002,4549,2014,6,5,Sunday,true,false,false,false,false,false,false
52387452,Command CompileSwift failed with a nonzero exit code in Xcode 10,"After updating to the latest version of Xcode at the moment (version 10.0) the project is unable to build because it found some errors regarding some "Command CompileSwift failed with a nonzero exit code" error.
How do I solve this errors?
They appear in most of the Pods (I use CocoaPods) I use inside my project.
I have tried updating the pod version and the pods to the latest version available, but the problem is still there.
I have searched a lot through the web and there is very little information regarding this issue.
",https://stackoverflow.com/questions/52387452/command-compileswift-failed-with-a-nonzero-exit-code-in-xcode-10,212,386267.0,23.0,,,2018-09-18 13:13:43,2021-06-17 08:54:16,2021-06-17 08:54:16,2019-03-27 01:23:00,Duplicate,ios;swift;xcode;swift4;xcode10,Jordi Gámez,3563,4315956,registered,true,52419690,,,,583,538,0,0,0,5,true,true,false,true,true,true,64,11,false,0.06,0.0005,2986,2018,9,13,Tuesday,false,false,false,false,false,false,false
37003623,How can I capture multiple repeated groups?,"I need to capture multiple groups of the same pattern. Suppose, I have the following string:
HELLO,THERE,WORLD
And I've written the following pattern
^(?:([A-Z]+),?)+$
I want it to capture every single word, so that Group 1 is: "HELLO", Group 2 is "THERE" and Group 3 is "WORLD". My regex is actually capturing only the last one, which is "WORLD".
I'm testing my regular expression here, and I want to use it with Swift (maybe there's a way in Swift to get intermediate results somehow, so that I can use them?)
I don't want to use split. I just need to now how to capture all the groups that match the pattern, not only the last one.
",https://stackoverflow.com/questions/37003623/how-can-i-capture-multiple-repeated-groups,211,355109.0,13.0,,,2016-05-03 12:02:56,2025-05-28 18:32:46,2025-05-23 21:12:04,,,swift;regex,phbelov,2669,949303,registered,true,37004214,,CC BY-SA 4.0,,909,677,3,1,0,2,true,false,false,true,true,true,43,7,true,0.037,0.0006,3854,2016,5,12,Tuesday,false,false,false,false,false,false,false
26350977,How to round a Double to the nearest Int in swift?,"I'm trying to make a calculator of growth rate (Double) that will round the result to the nearest Integer and recalculate from there, as such:
let firstUsers = 10.0
let growth = 0.1
var users = firstUsers
var week = 0
while users < 14 {
println(""week \(week) has \(users) users"")
users += users * growth
week += 1
}
but I've been unable so far.
EDIT
I kinda did it like so:
var firstUsers = 10.0
let growth = 0.1
var users:Int = Int(firstUsers)
var week = 0
while users <= 14 {
println(""week \(week) has \(users) users"")
firstUsers += firstUsers * growth
users = Int(firstUsers)
week += 1
}
Although I don't mind that it is always rounding down, I don't like it because firstUsers had to become a variable and change throughout the program (in order to make the next calculation), which I don't want it to happen.
",https://stackoverflow.com/questions/26350977/how-to-round-a-double-to-the-nearest-int-in-swift,210,225126.0,9.0,,,2014-10-14 00:35:29,2022-04-21 15:22:37,2016-12-02 01:48:14,,,swift;int;double;rounding,duarte harris,2273,4111177,registered,true,26351144,,CC BY-SA 3.0,,970,859,4,0,0,4,true,false,false,true,true,true,50,11,true,0.04,0.0009,4421,2014,10,0,Tuesday,false,false,false,false,false,false,false
13279105,Access Container View Controller from Parent iOS,"in iOS6 I noticed the new Container View but am not quite sure how to access it's controller from the containing view.
Scenario:
![]()
I want to access the labels in Alert view controller from the view controller that houses the container view.
There's a segue between them, can I use that?
",https://stackoverflow.com/questions/13279105/access-container-view-controller-from-parent-ios,210,95620.0,11.0,,,2012-11-07 22:07:28,2019-11-19 00:53:34,2019-11-19 00:53:34,,,ios;objective-c;swift;uiviewcontroller;uicontainerview,Adam Waite,18380,1050447,registered,true,13279703,,CC BY-SA 4.0,,382,290,0,0,1,5,true,false,false,true,true,true,48,7,false,0.115,0.0022,5127,2012,11,22,Wednesday,false,false,false,false,false,false,false
26988167,Swift Dictionary: Get values as array,"I have a dictionary containing UIColor objects hashed by an enum value, ColorScheme:
var colorsForColorScheme: [ColorScheme : UIColor] = ...
I would like to be able to extract an array of all the colors (the values) contained by this dictionary. I thought I could use the values property, as is used when iterating over dictionary values (for value in dictionary.values {...}), but this returns an error:
let colors: [UIColor] = colorsForColorSchemes.values
~~~~~~~~~~~~~~~~~~~~~^~~~~~~
'LazyBidrectionalCollection<MapCollectionView<Dictionary<ColorScheme, UIColor>, UIColor>>' is not convertible to 'UIColor'
It seems that rather than returning an Array of values, the values method returns a more abstract collection type. Is there a way to get an Array containing the dictionary's values without extracting them in a for-in loop?
",https://stackoverflow.com/questions/26988167/swift-dictionary-get-values-as-array,210,144996.0,7.0,,,2014-11-18 06:41:46,2021-02-22 14:50:55,,,,arrays;dictionary;swift,Stuart,37113,429427,registered,true,26988168,,CC BY-SA 3.0,,1054,881,10,0,0,3,true,false,false,true,true,false,37,6,false,0.048,0.0014,4386,2014,11,6,Tuesday,false,false,false,false,false,false,false
31735228,How to make a simple collection view with Swift,"I'm trying to learn how to use UICollectionView. The documentation is a little hard to understand and the tutorials that I found were either in Objective C or long complicated projects.
When I was learning how to use UITableView, We ❤ Swift's How to make a simple tableview with iOS 8 and Swift had a very basic setup and explanation to get me going. Is there anything like this for UICollectionView?
The answer below is my attempt to learn to do this.
",https://stackoverflow.com/questions/31735228/how-to-make-a-simple-collection-view-with-swift,207,254607.0,5.0,,,2015-07-30 22:36:28,2021-03-01 02:53:25,,,,ios;swift;uicollectionview,Suragch,517239,3681880,registered,true,31735229,,CC BY-SA 3.0,2016-12-10 18:10:43,763,455,3,2,0,3,true,false,false,true,true,false,47,9,false,0.02,0.0008,4132,2015,7,22,Thursday,false,false,false,false,false,false,false
30430550,How to create an empty array in Swift?,"I'm really confused with regards to how we create an empty array in Swift. Could you please show me the different ways we have to create an empty array with some detail?
",https://stackoverflow.com/questions/30430550/how-to-create-an-empty-array-in-swift,207,368339.0,15.0,,,2015-05-25 02:43:22,2023-07-16 05:31:22,2023-01-11 16:58:19,,,ios;arrays;swift,Inuyasha,2376,4935333,registered,true,35420598,,CC BY-SA 4.0,2019-07-31 03:49:42,177,170,0,0,0,3,true,false,false,true,true,true,38,8,true,0.041,0.0006,4198,2015,5,2,Monday,false,false,false,false,false,false,false
35906568,Wait until swift for loop with asynchronous network requests finishes executing,"I would like a for in loop to send off a bunch of network requests to firebase, then pass the data to a new view controller once the the method finishes executing. Here is my code:
var datesArray = [String: AnyObject]()
for key in locationsArray {
let ref = Firebase(url: ""http://myfirebase.com/"" + ""\(key.0)"")
ref.observeSingleEventOfType(.Value, withBlock: { snapshot in
datesArray[""\(key.0)""] = snapshot.value
})
}
// Segue to new view controller here and pass datesArray once it is complete
I have a couple concerns. First, how do I wait until the for loop is finished and all the network requests are complete? I can't modify the observeSingleEventOfType function, it is part of the firebase SDK. Also, will I create some sort of race condition by trying to access the datesArray from different iterations of the for loop (hope that makes sense)? I've been reading about GCD and NSOperation but I'm a bit lost as this is the first app I've built.
Note: Locations array is an array containing the keys I need to access in firebase. Also, it's important that the network requests are fired off asynchronously. I just want to wait until ALL the asynchronous requests complete before I pass the datesArray to the next view controller.
",https://stackoverflow.com/questions/35906568/wait-until-swift-for-loop-with-asynchronous-network-requests-finishes-executing,206,127684.0,10.0,,,2016-03-10 02:37:03,2025-06-13 20:41:41,2019-05-09 08:26:19,,,swift;asynchronous;grand-central-dispatch;nsoperation,Josh,2587,5167919,registered,true,35906703,,CC BY-SA 4.0,,1316,1271,1,0,0,4,true,false,false,true,true,true,79,11,false,0.078,0.0016,3908,2016,3,2,Thursday,false,false,false,false,false,false,false
32351343,Instance member cannot be used on type,"I have the following class:
class ReportView: NSView {
var categoriesPerPage = [[Int]]()
var numPages: Int = { return categoriesPerPage.count }
}
Compilation fails with the message:
Instance member 'categoriesPerPage' cannot be used on type
'ReportView'
What does this mean?
",https://stackoverflow.com/questions/32351343/instance-member-cannot-be-used-on-type,206,235823.0,8.0,,,2015-09-02 10:59:47,2022-01-22 18:54:43,2018-12-17 16:58:34,,,swift;instantiation;getter-setter;computed-properties,Aderstedt,6548,453082,registered,true,32351727,,CC BY-SA 4.0,,374,297,1,0,0,4,true,false,false,true,true,true,38,7,false,0.034,0.0009,4098,2015,9,10,Wednesday,false,false,false,false,false,false,false
27604192,How to segue programmatically in iOS using Swift,"I'm creating an app that uses the Facebook SDK to authenticate users. I'm trying to consolidate the facebook logic in a separate class. Here is the code (stripped for simplicity):
import Foundation
class FBManager {
class func fbSessionStateChane(fbSession:FBSession!, fbSessionState:FBSessionState, error:NSError?){
//... handling all session states
FBRequestConnection.startForMeWithCompletionHandler { (conn: FBRequestConnection!, result: AnyObject!, error: NSError!) -> Void in
println("Logged in user: \n\(result)");
let storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
let loggedInView: UserViewController = storyboard.instantiateViewControllerWithIdentifier("loggedInView") as UserViewController
loggedInView.result = result;
//todo: segue to the next view???
}
}
}
I'm using the above class method to check session state changes, and it works fine.
Q: Once I have the user's data, how can I segue to the next view from within this custom class?
Just to be clear, I have a segue with identifier on the storyboard, and I'm trying to find a way to perform a segue from a class which is not the view controller
",https://stackoverflow.com/questions/27604192/how-to-segue-programmatically-in-ios-using-swift,206,270268.0,11.0,,,2014-12-22 14:00:39,2023-09-18 12:09:34,2021-12-21 06:56:38,,,ios;iphone;facebook;swift;segue,Shlomi Schwartz,8963,1115237,registered,true,,,CC BY-SA 4.0,2024-02-21 19:18:25,1369,1300,1,0,0,5,false,false,false,true,true,true,48,8,false,0.041,0.0008,4352,2014,12,14,Monday,false,false,false,false,false,false,false
26319660,What's the best practice for naming Swift files that add extensions to existing objects?,"It's possible to add extensions to existing Swift object types using extensions, as described in the language specification.
As a result, it's possible to create extensions such as:
extension String {
var utf8data:NSData {
return self.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
}
}
However, what's the best naming practice for Swift source files containing such extensions?
In the past, the convention was to use extendedtype+categoryname.m for the Objective-C
type as discussed in the Objective-C guide. But the Swift example doesn't have a category name, and calling it String.swift doesn't seem appropriate.
So the question is: given the above String extension, what should the swift source file be called?
",https://stackoverflow.com/questions/26319660/whats-the-best-practice-for-naming-swift-files-that-add-extensions-to-existing,206,62392.0,7.0,,,2014-10-11 21:54:41,2020-04-26 15:38:40,2018-04-25 15:25:31,2025-02-11 16:27:28,Opinion-based,ios;objective-c;swift;xcode,AlBlue,24225,130659,registered,true,26320397,,,,1202,761,4,2,0,4,true,true,false,true,true,true,92,14,true,0.112,0.0033,4424,2014,10,21,Saturday,true,false,false,false,false,false,false
24051904,How do you add a Dictionary of items into another Dictionary,"Arrays in Swift support the += operator to add the contents of one Array to another. Is there an easy way to do that for a dictionary?
eg:
var dict1 = [""a"" : ""foo""]
var dict2 = [""b"" : ""bar""]
var combinedDict = ... (some way of combining dict1 & dict2 without looping)
",https://stackoverflow.com/questions/24051904/how-do-you-add-a-dictionary-of-items-into-another-dictionary,205,143725.0,29.0,,,2014-06-05 04:55:51,2025-10-25 14:17:57,2014-06-05 05:12:10,,,dictionary;swift,rustyshelf,45131,6044,registered,true,24052094,,CC BY-SA 3.0,,314,276,1,0,0,2,true,false,false,true,true,true,60,11,false,0.202,0.0014,4552,2014,6,4,Thursday,false,false,false,false,false,false,false
25367502,Create space at the beginning of a UITextField,"I want to leave a bit of space at the beginning of a UITextField, just like here:
Add lefthand margin to UITextField
But I don't know how to do that with Swift.
",https://stackoverflow.com/questions/25367502/create-space-at-the-beginning-of-a-uitextfield,204,203182.0,23.0,,,2014-08-18 16:04:32,2023-09-18 19:39:09,2017-05-23 12:02:47,,,ios;swift;cocoa-touch;uitextfield,LinusG.,29442,3397217,registered,true,27066764,,CC BY-SA 3.0,,264,162,0,1,0,4,true,false,false,true,true,true,46,8,false,0.113,0.001,4478,2014,8,16,Monday,false,false,false,false,false,false,false
31656642,Lesser than or greater than in Swift switch statement,"I am familiar with switch statements in Swift, but wondering how to replace this piece of code with a switch:
if someVar < 0 {
// do something
} else if someVar == 0 {
// do something else
} else if someVar > 0 {
// etc
}
",https://stackoverflow.com/questions/31656642/lesser-than-or-greater-than-in-swift-switch-statement,204,97828.0,10.0,,,2015-07-27 15:04:38,2021-12-31 20:16:04,2015-07-27 16:50:57,,,swift;switch-statement,Pieter,2721,1411378,registered,true,31656822,,CC BY-SA 3.0,,299,242,3,0,0,2,true,false,false,true,true,true,53,9,false,0.102,0.0021,4135,2015,7,15,Monday,false,false,false,false,false,false,false
57334455,How can I pop to the Root view using SwiftUI?,"Finally now with Beta 5 we can programmatically pop to a parent View. However, there are several places in my app where a view has a "Save" button that concludes a several step process and returns to the beginning. In UIKit, I use popToRootViewController(), but I have been unable to figure out a way to do the same in SwiftUI.
Below is a simple example of the pattern I'm trying to achieve.
How can I do it?
import SwiftUI
struct DetailViewB: View {
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
var body: some View {
VStack {
Text("This is Detail View B.")
Button(action: { self.presentationMode.value.dismiss() } )
{ Text("Pop to Detail View A.") }
Button(action: { /* How to do equivalent to popToRootViewController() here?? */ } )
{ Text("Pop two levels to Master View.") }
}
}
}
struct DetailViewA: View {
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
var body: some View {
VStack {
Text("This is Detail View A.")
NavigationLink(destination: DetailViewB() )
{ Text("Push to Detail View B.") }
Button(action: { self.presentationMode.value.dismiss() } )
{ Text("Pop one level to Master.") }
}
}
}
struct MasterView: View {
var body: some View {
VStack {
Text("This is Master View.")
NavigationLink(destination: DetailViewA() )
{ Text("Push to Detail View A.") }
}
}
}
struct ContentView: View {
var body: some View {
NavigationView {
MasterView()
}
}
}
",https://stackoverflow.com/questions/57334455/how-can-i-pop-to-the-root-view-using-swiftui,203,116093.0,34.0,,,2019-08-02 23:37:12,2025-04-04 19:54:24,2022-06-08 14:18:51,,,swift;swiftui,Chuck H,8421,899918,registered,true,59662275,,CC BY-SA 4.0,,1858,1813,1,0,0,2,true,false,false,true,true,true,45,10,true,0.293,0.0017,2668,2019,8,23,Friday,false,false,false,false,false,false,false
38740648,How to set Status Bar Style in Swift 3,"I'm using Xcode 8.0 beta 4.
In previous version, UIViewController have method to set the status bar style
public func preferredStatusBarStyle() -> UIStatusBarStyle
However, I found it changed to a ""Get ONLY varaiable"" in Swift 3.
public var preferredStatusBarStyle: UIStatusBarStyle { get }
How can provide the style to use in my UIViewController?
",https://stackoverflow.com/questions/38740648/how-to-set-status-bar-style-in-swift-3,202,246292.0,33.0,,,2016-08-03 10:12:08,2020-11-04 08:23:31,2018-03-29 09:22:12,,,ios;swift;uiviewcontroller;uistatusbar;ios-statusbar,Willjay,6459,5571327,registered,true,40066798,,CC BY-SA 3.0,,436,360,2,0,0,5,true,false,false,true,true,true,38,9,false,0.134,0.0008,3762,2016,8,10,Wednesday,false,false,false,false,false,false,false
38446097,Xcode 8 Beta 3 Use Legacy Swift issue,"I have an Objective-C project in Xcode 8 Beta 3. Since updating, whenever I try to build I receive the following error:
“Use Legacy Swift Language Version” (SWIFT_VERSION) is required to be configured correctly for targets which use Swift. Use the [Edit > Convert > To Current Swift Syntax…] menu to choose a Swift version or use the Build Settings editor to configure the build setting directly.
Has anyone encountered this? Since it's an Objective-C project there's no build setting to configure Swift. I have also made sure none of the project dependencies or CocoaPods are using Swift. The only solution I have is to use Beta 2. Any ideas how I might fix this issue?
I should also mention I'm running OSX 10.12 Beta 2.
",https://stackoverflow.com/questions/38446097/xcode-8-beta-3-use-legacy-swift-issue,202,98903.0,20.0,,,2016-07-18 21:14:23,2022-08-18 09:59:32,2017-07-11 16:09:08,,,swift;xcode8;xcode8-beta3,Bryan,3219,4528837,registered,true,38597681,,CC BY-SA 3.0,,783,730,0,0,0,3,true,false,false,true,true,true,37,8,false,0.202,0.002,3778,2016,7,21,Monday,false,false,false,false,false,false,false
26442414,libc++abi.dylib: terminating with uncaught exception of type NSException (lldb),"I'm programming an app in swift and when I run the test app on the iPhone simulator everything works, but then I try to swipe right, which is a gesture that I added for it to go to the next Page(View Controller Two) it crashes and shows this error report in the console log.
2014-10-18 12:07:34.400 soundtest[17081:818922] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<soundtest.ViewControllerTwo 0x7f92f1f20090> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key sfdfa.'
*** First throw call stack:
(
0 CoreFoundation 0x00000001067813f5 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x00000001082afbb7 objc_exception_throw + 45
2 CoreFoundation 0x0000000106781039 -[NSException raise] + 9
3 Foundation 0x0000000106b984d3 -[NSObject(NSKeyValueCoding) setValue:forKey:] + 259
4 CoreFoundation 0x00000001066cb400 -[NSArray makeObjectsPerformSelector:] + 224
5 UIKit 0x00000001072ce97d -[UINib instantiateWithOwner:options:] + 1506
6 UIKit 0x000000010712f698 -[UIViewController _loadViewFromNibNamed:bundle:] + 242
7 UIKit 0x000000010712fc88 -[UIViewController loadView] + 109
8 UIKit 0x000000010712fef9 -[UIViewController loadViewIfRequired] + 75
9 UIKit 0x000000010713038e -[UIViewController view] + 27
10 UIKit 0x00000001076cd83f -[_UIFullscreenPresentationController _setPresentedViewController:] + 65
11 UIKit 0x000000010710bc49 -[UIPresentationController initWithPresentedViewController:presentingViewController:] + 105
12 UIKit 0x000000010713c121 -[UIViewController _presentViewController:withAnimationController:completion:] + 1746
13 UIKit 0x000000010713e461 __62-[UIViewController presentViewController:animated:completion:]_block_invoke + 132
14 UIKit 0x000000010713e385 -[UIViewController presentViewController:animated:completion:] + 229
15 UIKit 0x00000001073bb9d6 _UIGestureRecognizerSendActions + 262
16 UIKit 0x00000001073ba679 -[UIGestureRecognizer _updateGestureWithEvent:buttonEvent:] + 532
17 UIKit 0x00000001073bf296 ___UIGestureRecognizerUpdate_block_invoke662 + 51
18 UIKit 0x00000001073bf192 _UIGestureRecognizerRemoveObjectsFromArrayAndApplyBlocks + 254
19 UIKit 0x00000001073b520d _UIGestureRecognizerUpdate + 2796
20 UIKit 0x00000001070520a6 -[UIWindow _sendGesturesForEvent:] + 1041
21 UIKit 0x0000000107052cd3 -[UIWindow sendEvent:] + 667
22 UIKit 0x000000010701fae1 -[UIApplication sendEvent:] + 246
23 UIKit 0x000000010702cbad _UIApplicationHandleEventFromQueueEvent + 17370
24 UIKit 0x0000000107008233 _UIApplicationHandleEventQueue + 1961
25 CoreFoundation 0x00000001066b6ad1 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
26 CoreFoundation 0x00000001066ac99d __CFRunLoopDoSources0 + 269
27 CoreFoundation 0x00000001066abfd4 __CFRunLoopRun + 868
28 CoreFoundation 0x00000001066aba06 CFRunLoopRunSpecific + 470
29 GraphicsServices 0x000000010a1699f0 GSEventRunModal + 161
30 UIKit 0x000000010700b550 UIApplicationMain + 1282
31 soundtest 0x000000010624503e top_level_code + 78
32 soundtest 0x000000010624507a main + 42
33 libdyld.dylib 0x000000010ae4a145 start + 1
34 ??? 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
",https://stackoverflow.com/questions/26442414/libcabi-dylib-terminating-with-uncaught-exception-of-type-nsexception-lldb,200,429406.0,33.0,,,2014-10-18 17:11:36,2020-04-13 22:04:19,,,,ios;swift,Nick,2625,4143556,registered,true,27389647,,CC BY-SA 3.0,2016-06-28 00:18:41,4370,4339,1,0,0,2,true,false,false,true,true,false,79,9,false,0.077,0.0005,4417,2014,10,17,Saturday,true,false,false,false,false,false,false
30859334,Compare Protocol in Swift vs Interface in Java,"I'm going through the iOS tutorial from Apple developer page.
It seems to me that protocol and interface almost have the same functionality.
Are there any differences between the two?
the different usage in the project?
Updated
Yes, I did read the link above and I'm still not sure what the differences and usage between protocol and interface. When I ask a question like this, I would like to see a simple explanation about the topic. Sometime it could be tough to get everything from the documentation.
",https://stackoverflow.com/questions/30859334/compare-protocol-in-swift-vs-interface-in-java,200,47582.0,3.0,,,2015-06-16 05:17:00,2020-10-17 12:14:29,2019-11-13 19:02:49,,,java;swift,Bun,3125,2484238,registered,true,30859843,,CC BY-SA 4.0,,853,512,4,1,0,2,true,false,false,true,true,true,46,8,false,0.063,0.0042,4176,2015,6,5,Tuesday,false,false,false,true,false,false,false
28727845,Find an object in array?,"Does Swift have something like _.findWhere in Underscore.js?
I have an array of structs of type T and would like to check if array contains a struct object whose name property is equal to Foo.
Tried to use find() and filter() but they only work with primitive types, e.g. String or Int. Throws an error about not conforming to Equitable protocol or something like that.
",https://stackoverflow.com/questions/28727845/find-an-object-in-array,199,263669.0,16.0,,,2015-02-25 19:25:45,2020-01-30 07:27:32,2015-09-01 15:53:17,,,ios;swift,Sahat Yalkabov,33895,274117,registered,true,28733586,,CC BY-SA 3.0,,546,372,8,1,0,2,true,false,false,true,true,true,24,5,true,0.061,0.0008,4287,2015,2,19,Wednesday,false,false,false,false,false,false,false
56553672,How can I remove the line separators from a List in SwiftUI without using ForEach?,"I have this code to display a list of custom rows:
struct ContentView : View {
var body: some View {
VStack(alignment: .leading) {
List(1...10) {_ in
CustomRow()
}
}
}
}
However, I want to remove the line on each row. I tried not using List and instead using ForEach inside ScrollView, but it completely removes all the styling, including its padding and margins. I just want to remove the lines and nothing else.
How can I do it?
",https://stackoverflow.com/questions/56553672/how-can-i-remove-the-line-separators-from-a-list-in-swiftui-without-using-foreac,198,150535.0,24.0,,,2019-06-12 01:52:51,2025-07-26 21:38:18,2025-07-26 19:59:46,,,ios;swift;swiftui,ygee,3362,1970407,registered,true,58474518,,CC BY-SA 4.0,,580,496,4,0,0,3,true,false,false,true,true,true,82,15,true,0.159,0.0013,2719,2019,6,1,Wednesday,false,false,false,false,false,false,false
30720497,Swift do-try-catch syntax,"I give it a try to understand new error handling thing in swift 2. Here is what I did: I first declared an error enum:
enum SandwichError: Error {
case NotMe
case DoItYourself
}
And then I declared a method that throws an error (not an exception folks. It is an error.). Here is that method:
func makeMeSandwich(names: [String: String]) throws -> String {
guard let sandwich = names["sandwich"] else {
throw SandwichError.NotMe
}
return sandwich
}
The problem is from the calling side. Here is the code that calls this method:
let kitchen = ["sandwich": "ready", "breakfast": "not ready"]
do {
let sandwich = try makeMeSandwich(kitchen)
print("i eat it \(sandwich)")
} catch SandwichError.NotMe {
print("Not me error")
} catch SandwichError.DoItYourself {
print("do it error")
}
After the do line compiler says Errors thrown from here are not handled because the enclosing catch is not exhaustive. But in my opinion, it is exhaustive because there are only two cases in SandwichError enum.
For regular switch statements, swift can understand it is exhaustive when every case is handled.
",https://stackoverflow.com/questions/30720497/swift-do-try-catch-syntax,197,239182.0,8.0,,,2015-06-08 23:05:18,2025-03-10 03:19:21,2025-03-10 03:19:21,,,swift;error-handling;try-catch,mustafa,15514,3068061,registered,true,30720807,,CC BY-SA 4.0,,1369,1223,6,0,0,3,true,false,false,true,true,true,25,3,false,0.033,0.0008,4184,2015,6,23,Monday,false,false,false,false,false,false,false
24133157,Check empty string in Swift?,"In Objective C, one could do the following to check for strings:
if ([myString isEqualToString:@""""]) {
NSLog(@""myString IS empty!"");
} else {
NSLog(@""myString IS NOT empty, it is: %@"", myString);
}
How does one detect empty strings in Swift?
",https://stackoverflow.com/questions/24133157/check-empty-string-in-swift,195,222383.0,16.0,,,2014-06-10 04:59:33,2024-04-14 15:32:21,2024-04-14 15:32:21,,,swift,chrisl-921fb74d,23640,171217,registered,true,24133180,,CC BY-SA 4.0,,327,253,1,0,0,1,true,false,false,true,true,true,28,5,true,0.072,0.0009,4547,2014,6,4,Tuesday,false,false,false,false,false,false,false
24777496,How can I convert string date to NSDate?,"I want to convert the string "2014-07-15 06:55:14.198000+00:00" to an NSDate in Swift.
",https://stackoverflow.com/questions/24777496/how-can-i-convert-string-date-to-nsdate,195,206532.0,19.0,,,2014-07-16 09:44:53,2024-06-26 16:24:39,2023-10-13 20:44:37,,,swift;string;type-conversion;nsdate,Shardul,4264,1213871,registered,true,24777965,,CC BY-SA 4.0,,130,97,2,0,0,4,true,false,false,true,true,true,40,8,true,0.092,0.0009,4511,2014,7,9,Wednesday,false,false,false,false,false,false,false
30867325,Binary operator '|' cannot be applied to two UIViewAutoresizing operands,"Getting this error in Swift 2.0.
Binary operator '|' cannot be applied to two UIViewAutoresizing operands
Here is the code:
let view = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 568))
addSubview(view)
view.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
Any idea what can be the problem?
![]()
",https://stackoverflow.com/questions/30867325/binary-operator-cannot-be-applied-to-two-uiviewautoresizing-operands,195,48090.0,6.0,,,2015-06-16 12:15:42,2017-05-20 15:14:46,2015-06-16 12:34:39,,,ios;swift;cocoa-touch;swift2,Khawar,9261,1444321,registered,true,30867540,,CC BY-SA 3.0,,503,348,1,0,1,4,true,false,false,true,true,true,80,10,false,0.125,0.0041,4176,2015,6,12,Tuesday,false,false,false,false,false,false,false
24010569,Error-Handling in Swift-Language,"I haven't read too much into Swift but one thing I noticed is that there are no exceptions.
So how do they do error handling in Swift? Has anyone found anything related to error-handling?
",https://stackoverflow.com/questions/24010569/error-handling-in-swift-language,195,96688.0,13.0,,,2014-06-03 08:35:33,2022-02-03 06:15:00,2016-09-14 13:48:36,,,swift;error-handling,peko,11335,612304,registered,true,24030038,,CC BY-SA 3.0,,195,188,0,0,0,2,true,false,false,true,true,true,32,3,false,0.134,0.002,4554,2014,6,8,Tuesday,false,false,false,false,false,false,false
24755558,Measure elapsed time in Swift,"How can we measure the time elapsed for running a function in Swift? I am trying to display the elapsed time like this: "Elapsed time is .05 seconds". Saw that in Java, we can use System.nanoTime(), are there any equivalent methods available in Swift to accomplish this?
Please have a look at the sample program:
func isPrime(_ number: Int) -> Bool {
var i = 0;
for i=2; i<number; i++ {
if number % i == 0, i != 0 {
return false
}
}
return true
}
var number = 5915587277
if isPrime(number) {
print("Prime number")
} else {
print("NOT a prime number")
}
",https://stackoverflow.com/questions/24755558/measure-elapsed-time-in-swift,194,161061.0,20.0,,,2014-07-15 10:14:32,2025-04-06 08:38:49,2023-01-04 14:53:53,,,swift;time;nsdate;elapsedtime,jay,3687,878414,registered,true,24755958,,CC BY-SA 4.0,,779,644,1,1,0,4,true,false,false,true,true,true,29,5,false,0.124,0.0012,4512,2014,7,10,Tuesday,false,false,false,false,false,false,false
24183812,Swift: #warning equivalent,"Does Swift have a #warning equivalent?
It's simply used to show a warning in Xcode's own GUI
I'm also interested in whether there's a #error equivalent.
Apple has said #pragma mark is coming soon, it could possibly be the same with this.
![]()
",https://stackoverflow.com/questions/24183812/swift-warning-equivalent,194,50049.0,14.0,,,2014-06-12 11:58:27,2018-10-25 12:40:30,,,,swift,SomeGuy,9708,885029,registered,true,,,CC BY-SA 3.0,,348,242,0,0,1,1,false,false,false,true,true,false,26,3,false,0.28,0.0039,4545,2014,6,11,Thursday,false,false,false,false,false,false,false
30761996,Swift 2.0 - Binary Operator "|" cannot be applied to two UIUserNotificationType operands,"I am trying to register my application for local notifications this way:
UIApplication.sharedApplication().registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Alert | UIUserNotificationType.Badge, categories: nil))
In Xcode 7 and Swift 2.0 - I get error Binary Operator ""|"" cannot be applied to two UIUserNotificationType operands. Please help me.
",https://stackoverflow.com/questions/30761996/swift-2-0-binary-operator-cannot-be-applied-to-two-uiusernotificationtype,194,47371.0,4.0,,,2015-06-10 16:21:51,2017-04-19 15:53:49,2015-06-10 16:25:51,,,ios;swift;swift2,Nikita Zernov,5645,2938258,registered,true,30763344,,CC BY-SA 3.0,,443,392,2,0,0,3,true,false,false,true,true,true,98,13,false,0.084,0.0041,4182,2015,6,16,Wednesday,false,false,false,false,false,false,false
26542035,How to create a UIImage with solid color?,"I want to programmatically create a UIImage filled by a solid color. Does anyone have an idea of how to do this in Swift?
",https://stackoverflow.com/questions/26542035/how-to-create-a-uiimage-with-solid-color,193,136446.0,15.0,,,2014-10-24 05:31:55,2024-04-30 21:48:37,2024-04-30 21:48:37,,,swift;uikit;uiimage,Henry Pham,2527,2348932,registered,true,33675160,,CC BY-SA 4.0,,129,122,0,0,0,3,true,false,false,true,true,true,41,8,true,0.11,0.0014,4411,2014,10,5,Friday,false,false,false,false,false,false,false
38192751,Swift 3.0 Result of call is unused,"I am writing in swift 3.0
I have this code which gives me the warning result of the call is unused
public override init(){
super.init()
}
public init(annotations: [MKAnnotation]){
super.init()
addAnnotations(annotations: annotations)
}
public func setAnnotations(annotations:[MKAnnotation]){
tree = nil
addAnnotations(annotations: annotations)
}
public func addAnnotations(annotations:[MKAnnotation]){
if tree == nil {
tree = AKQuadTree()
}
lock.lock()
for annotation in annotations {
// The warning occurs at this line
tree!.insertAnnotation(annotation: annotation)
}
lock.unlock()
}
I have tried using this method in another class but it still gives me the error the code for insert Annotation is above
func insertAnnotation(annotation:MKAnnotation) -> Bool {
return insertAnnotation(annotation: annotation, toNode:rootNode!)
}
func insertAnnotation(annotation:MKAnnotation, toNode node:AKQuadTreeNode) -> Bool {
if !AKQuadTreeNode.AKBoundingBoxContainsCoordinate(box: node.boundingBox!, coordinate: annotation.coordinate) {
return false
}
if node.count < nodeCapacity {
node.annotations.append(annotation)
node.count += 1
return true
}
if node.isLeaf() {
node.subdivide()
}
if insertAnnotation(annotation: annotation, toNode:node.northEast!) {
return true
}
if insertAnnotation(annotation: annotation, toNode:node.northWest!) {
return true
}
if insertAnnotation(annotation: annotation, toNode:node.southEast!) {
return true
}
if insertAnnotation(annotation: annotation, toNode:node.southWest!) {
return true
}
return false
}
I have tried many methods but just doesn't work but in swift 2.2 it works fine any ideas why this is happening?
",https://stackoverflow.com/questions/38192751/swift-3-0-result-of-call-is-unused,193,113391.0,1.0,,,2016-07-04 22:04:36,2021-10-31 09:27:56,2021-10-31 09:27:56,2016-07-05 00:31:14,Duplicate,ios;swift;swift3,Aryan Kashyap,1983,6548861,registered,true,,,,,2174,2018,2,0,0,3,false,true,false,true,true,true,34,7,false,0.009,0.0017,3792,2016,7,22,Monday,false,false,false,false,false,false,false
26008536,"NavigationBar bar, tint, and title text color in iOS 8","The background text in the status bar is still black. How do I change the color to white?
// io8, swift, Xcode 6.0.1
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.barTintColor = UIColor.blackColor()
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.orangeColor()]
}
![]()
",https://stackoverflow.com/questions/26008536/navigationbar-bar-tint-and-title-text-color-in-ios-8,192,258174.0,18.0,,,2014-09-24 04:25:45,2021-11-08 07:54:30,2021-11-08 07:54:30,,,ios;swift;xcode;ios8;uinavigationbar,AG1,6794,761288,registered,true,27929937,,CC BY-SA 4.0,,499,383,1,0,1,5,true,false,false,true,true,true,54,10,false,0.07,0.0007,4441,2014,9,4,Wednesday,false,false,false,false,false,false,false
28628225,How to save local data in a Swift app?,"I'm currently working on a iOS app developed in Swift and I need to store some user-created content on the device but I can't seem to find a simple and quick way to store/receive the users content on the device.
Could someone explain how to store and access local storage?
The idea is to store the data when the user executes an action and receive it when the app starts.
",https://stackoverflow.com/questions/28628225/how-to-save-local-data-in-a-swift-app,192,229031.0,13.0,,,2015-02-20 11:46:23,2023-09-30 09:21:52,2017-02-15 09:57:26,,,ios;swift;nsuserdefaults,Nicklas Ridewing,2441,4571812,registered,true,28628776,,CC BY-SA 3.0,,413,375,0,0,0,3,true,false,false,true,true,true,38,9,true,0.057,0.0008,4292,2015,2,11,Friday,false,false,false,false,false,false,false
58654714,Module compiled with Swift 5.1 cannot be imported by the Swift 5.1.2 compiler,"I have a framework (in this instance it's RxSwift) which I've compiled using Xcode 11.0 into the traditional RxSwift.framework style package
This imported fine into Xcode 11.0 and also 11.1 never had any problems with it
Today, upon Apple's release of Xcode 11.2, I upgraded, and I am presented with the error:
Module compiled with Swift 5.1 cannot be imported by the Swift 5.1.2 compiler
I'm used to swift compiler mismatches, and I'm aware I can just recompile RxSwift using Xcode 11.2 and carry on, but the headline feature of Swift 5.1 was module stability.
I was under the impression that now that we have module stability, frameworks won't need to keep getting recompiled with every new Xcode release, yet this is clearly not the case.
If anyone can explain what is going on here I would much appreciate it. Is Xcode 11.2 exhibiting a bug? or did I somehow need to tell it I wanted module stability when I originally compiled with Xcode 11.0?
",https://stackoverflow.com/questions/58654714/module-compiled-with-swift-5-1-cannot-be-imported-by-the-swift-5-1-2-compiler,192,176892.0,12.0,,,2019-11-01 05:57:20,2022-09-30 14:58:05,,,,ios;swift;xcode;swift5,Orion Edwards,124990,234,registered,true,58656323,,CC BY-SA 4.0,,1051,955,1,0,0,4,true,false,false,true,true,false,77,13,false,0.068,0.0011,2577,2019,11,5,Friday,false,false,false,false,false,false,false
25976909,Swift Array - Check if an index exists,"In Swift, is there any way to check if an index exists in an array without a fatal error being thrown?
I was hoping I could do something like this:
let arr: [String] = [""foo"", ""bar""]
let str: String? = arr[1]
if let str2 = arr[2] as String? {
// this wouldn't run
println(str2)
} else {
// this would be run
}
But I get
fatal error: Array index out of range
",https://stackoverflow.com/questions/25976909/swift-array-check-if-an-index-exists,191,126495.0,12.0,,,2014-09-22 14:46:11,2025-03-14 13:23:07,2016-02-20 04:54:26,,,swift,chrishale,2546,1380185,registered,true,35512668,,CC BY-SA 3.0,,456,379,1,0,0,1,true,false,false,true,true,true,38,8,false,0.095,0.0015,4443,2014,9,14,Monday,false,false,false,false,false,false,false
25932570,How to play video with AVPlayerViewController (AVKit) in Swift,"How do you play a video with AV Kit Player View Controller in Swift?
override func viewDidLoad() {
super.viewDidLoad()
let videoURLWithPath = ""http://****/5.m3u8""
let videoURL = NSURL(string: videoURLWithPath)
playerViewController = AVPlayerViewController()
dispatch_async(dispatch_get_main_queue()) {
self.playerViewController?.player = AVPlayer.playerWithURL(videoURL) as AVPlayer
}
}
",https://stackoverflow.com/questions/25932570/how-to-play-video-with-avplayerviewcontroller-avkit-in-swift,191,283595.0,15.0,,,2014-09-19 11:10:12,2023-11-11 17:23:43,2016-04-07 23:37:47,,,ios;swift;avfoundation;avplayerviewcontroller;avkit,orazz,2198,3617760,registered,true,31277658,,CC BY-SA 3.0,,485,454,1,0,0,5,true,false,false,true,true,true,62,9,false,0.053,0.0007,4446,2014,9,11,Friday,false,false,false,false,false,false,false
44655562,How to exclude properties from Swift Codable?,"Swift's Encodable/Decodable protocols, released with Swift 4, make JSON (de)serialization quite pleasant. However, I have not yet found a way to have fine-grained control over which properties should be encoded and which should get decoded.
I have noticed that excluding the property from the accompanying CodingKeys enum excludes the property from the process altogether, but is there a way to have more fine-grained control?
",https://stackoverflow.com/questions/44655562/how-to-exclude-properties-from-swift-codable,191,76160.0,7.0,,,2017-06-20 14:16:08,2025-03-20 14:13:00,2021-06-23 22:02:04,,,json;swift;codable,RamwiseMatt,3007,6900003,registered,true,44663775,,CC BY-SA 4.0,,480,427,3,0,0,3,true,false,false,true,true,true,45,7,true,0.092,0.0025,3441,2017,6,14,Tuesday,false,false,false,false,false,false,false
29965397,Cannot load underlying module for XCTest,"I'm working in swift on Xcode and by default it creates a test file that references XCTest.
When I set the target membership to my main project it causes this error
Cannot load underlying module for XCTest
If this target membership is not set the tests runs properly and everything works fine.
",https://stackoverflow.com/questions/29965397/cannot-load-underlying-module-for-xctest,190,82812.0,15.0,,,2015-04-30 10:32:47,2025-01-16 23:00:40,2021-01-07 14:08:28,,,swift;xcode;xctest,brduca,3633,3488526,registered,true,29995445,,CC BY-SA 4.0,,349,296,0,0,0,3,true,false,false,true,true,true,40,6,false,0.181,0.0023,4223,2015,4,10,Thursday,false,false,false,false,false,false,false
838724,How can I scan barcodes on iOS?,"How can I simply scan barcodes on iPhone and/or iPad?
",https://stackoverflow.com/questions/838724/how-can-i-scan-barcodes-on-ios,190,148200.0,12.0,,,2009-05-08 08:05:48,2020-12-03 14:02:09,2019-06-06 10:21:53,2021-09-15 11:43:34,Not suitable for this site,ios;swift;iphone;cocoa-touch;barcode,Stefan,29045,76371,registered,true,862656,,,2011-03-14 17:03:36,61,54,0,0,0,5,true,true,false,true,true,true,31,7,true,0.081,0.0013,6406,2009,5,8,Friday,false,false,false,false,false,false,false
25248598,Importing CommonCrypto in a Swift framework,"How do you import CommonCrypto in a Swift framework for iOS?
I understand how to use CommonCrypto in a Swift app:
You add #import <CommonCrypto/CommonCrypto.h> to the bridging header.
However, Swift frameworks don't support bridging headers. The documentation says:
You can import external frameworks that have a pure Objective-C codebase, a pure Swift codebase, or a mixed-language codebase. The
process for importing an external framework is the same whether the
framework is written in a single language or contains files from both
languages. When you import an external framework, make sure the
Defines Module build setting for the framework you’re importing is set
to Yes.
You can import a framework into any Swift file within a different
target using the following syntax:
import FrameworkName
Unfortunately, import CommonCrypto doesn't work. Neither does adding #import <CommonCrypto/CommonCrypto.h> to the umbrella header.
",https://stackoverflow.com/questions/25248598/importing-commoncrypto-in-a-swift-framework,189,117248.0,16.0,,,2014-08-11 17:03:49,2019-08-25 23:25:39,2018-11-28 20:39:10,,,ios;swift;commoncrypto,hpique,120714,143378,registered,true,25250520,,CC BY-SA 4.0,,1267,970,6,1,0,3,true,false,false,true,true,true,43,6,false,0.136,0.0016,4485,2014,8,17,Monday,false,false,false,false,false,false,false
38990882,Closure use of non-escaping parameter may allow it to escape,"I have a protocol:
enum DataFetchResult {
case success(data: Data)
case failure
}
protocol DataServiceType {
func fetchData(location: String, completion: (DataFetchResult) -> (Void))
func cachedData(location: String) -> Data?
}
With an example implementation:
/// An implementation of DataServiceType protocol returning predefined results using arbitrary queue for asynchronyous mechanisms.
/// Dedicated to be used in various tests (Unit Tests).
class DataMockService: DataServiceType {
var result : DataFetchResult
var async : Bool = true
var queue : DispatchQueue = DispatchQueue.global(qos: .background)
var cachedData : Data? = nil
init(result : DataFetchResult) {
self.result = result
}
func cachedData(location: String) -> Data? {
switch self.result {
case .success(let data):
return data
default:
return nil
}
}
func fetchData(location: String, completion: (DataFetchResult) -> (Void)) {
// Returning result on arbitrary queue should be tested,
// so we can check if client can work with any (even worse) implementation:
if async == true {
queue.async { [weak self ] in
guard let weakSelf = self else { return }
// This line produces compiler error:
// ""Closure use of non-escaping parameter 'completion' may allow it to escape""
completion(weakSelf.result)
}
} else {
completion(self.result)
}
}
}
The code above compiled and worked in Swift3 (Xcode8-beta5) but does not work with beta 6 anymore. Can you point me to the underlying cause?
",https://stackoverflow.com/questions/38990882/closure-use-of-non-escaping-parameter-may-allow-it-to-escape,189,134215.0,3.0,,,2016-08-17 07:46:03,2023-03-16 18:42:44,2020-08-14 09:04:46,,,swift;xcode;swift3;closures,Lukasz,19936,229229,registered,true,38990967,,CC BY-SA 4.0,,1952,1883,2,0,0,4,true,false,false,true,true,true,60,10,false,0.022,0.0014,3748,2016,8,7,Wednesday,false,false,false,false,false,false,false
24024376,Passing an array to a function with variable number of args in Swift,"In The Swift Programming Language, it says:
Functions can also take a variable number of arguments, collecting them into an array.
func sumOf(numbers: Int...) -> Int {
...
}
When I call such a function with a comma-separated list of numbers (`sumOf(1, 2, 3, 4), they are made available as an array inside the function.
Question: what if I already have an array of numbers that I want to pass to this function?
let numbers = [1, 2, 3, 4]
sumOf(numbers)
This fails with a compiler error, “Could not find an overload for '__conversion' that accepts the supplied arguments”. Is there a way to turn an existing array into a list of elements that I can pass to a variadic function?
",https://stackoverflow.com/questions/24024376/passing-an-array-to-a-function-with-variable-number-of-args-in-swift,189,109979.0,8.0,,,2014-06-03 20:29:17,2024-04-29 21:37:27,2014-06-06 22:00:07,,,swift;variadic-functions,Ole Begemann,135576,116862,registered,true,24024724,,CC BY-SA 3.0,,989,701,2,1,0,2,true,false,false,true,true,true,68,13,false,0.073,0.0017,4554,2014,6,20,Tuesday,false,false,false,false,false,false,false
56614080,How to remove the left and right Padding of a List in SwiftUI?,"How to remove the left and right Padding of a List in SwiftUI?
Every List i create has borders to the leading and trailing of a cell.
What modifier should I add to remove this?
",https://stackoverflow.com/questions/56614080/how-to-remove-the-left-and-right-padding-of-a-list-in-swiftui,188,124012.0,13.0,,,2019-06-15 20:51:13,2025-07-20 14:55:12,2019-06-16 19:25:04,,,swift;swiftui,qubicswap.com,16980,433073,registered,true,58210994,,CC BY-SA 4.0,,192,178,0,0,0,2,true,false,false,true,true,true,62,13,true,0.105,0.0015,2716,2019,6,20,Saturday,true,false,false,false,false,false,false
25945324,Swift Open Link in Safari,"I am currently opening the link in my app in a WebView, but I'm looking for an option to open the link in Safari instead.
",https://stackoverflow.com/questions/25945324/swift-open-link-in-safari,187,158321.0,11.0,,,2014-09-20 04:44:09,2022-03-07 09:24:04,2018-05-21 08:57:37,,,webview;swift;safari,Fabian Boulegue,6588,997120,registered,true,25945530,,CC BY-SA 4.0,,159,122,1,0,0,3,true,false,false,true,true,true,25,5,false,0.069,0.0012,4445,2014,9,4,Saturday,true,false,false,false,false,false,false
34868344,How to change the background color of UIStackView?,"Note that in modern iOS you CAN SET THE BACKGROUND COLOR NORMALLY.
historic question:
I tried to change the UIStackView background from clear to white in Storyboard inspector, but when simulating, the background color of the stack view still has a clear color.
How can I change the background color of a UIStackView?
",https://stackoverflow.com/questions/34868344/how-to-change-the-background-color-of-uistackview,187,84088.0,23.0,,,2016-01-19 04:06:46,2024-07-31 20:54:07,2024-07-31 20:54:07,,,ios;swift;uistackview,LukasTong,1891,5742055,registered,true,34868367,,CC BY-SA 4.0,,396,318,2,0,0,3,true,false,false,true,true,true,50,8,true,0.274,0.0022,3959,2016,1,4,Tuesday,false,false,false,false,false,false,false
31937686,How to make HTTP Post request with JSON body in Swift?,"I'm trying to make an HTTP post request with a JSON body :
How to be able to add an NSdictionnary to the HTTP request body.
Here is my code, it doesn't seem to work properly.
var entry1 = Response(IdQuestion: 6510,IdProposition: 10,Time: 30)
var entry2 = Response(IdQuestion: 8284,IdProposition: 10,Time: 30)
Responses.append(entry1)
Responses.append(entry2)
let list = Responses.map { $0.asDictionary }
let json = ["List":list,"IdSurvey":"102","IdUser":"iOSclient","UserInformation":"iOSClient"]
let data: NSData = NSKeyedArchiver.archivedDataWithRootObject(json)
NSJSONSerialization.isValidJSONObject(json)
let myURL = NSURL(string: "http://www.myserver.com")!
let request = NSMutableURLRequest(URL: myURL)
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.HTTPBody = data
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
println(response)
// Your completion handler code here
}
task.resume()
",https://stackoverflow.com/questions/31937686/how-to-make-http-post-request-with-json-body-in-swift,187,303164.0,17.0,,,2015-08-11 09:13:16,2023-04-16 19:18:02,2022-06-02 00:19:28,,,json;swift;http;post,Stranger B.,9574,2841703,registered,true,,,CC BY-SA 4.0,,1280,1235,1,0,0,4,false,false,false,true,true,true,54,11,true,0.056,0.0006,4120,2015,8,9,Tuesday,false,false,false,false,false,false,false
25981422,How to open mail app from Swift,"Im working on a simple swift app where the user inputs an email address and presses a button which opens the mail app, with the entered address in the address bar. I know how to do this in Objective-C, but I'm having trouble getting it to work in Swift.
",https://stackoverflow.com/questions/25981422/how-to-open-mail-app-from-swift,186,173111.0,19.0,,,2014-09-22 19:07:18,2024-08-21 09:33:58,,,,ios;swift,Jesse.H,1893,4067851,registered,true,,,CC BY-SA 3.0,,261,254,0,0,0,2,false,false,false,true,true,false,31,7,false,0.11,0.0011,4443,2014,9,19,Monday,false,false,false,false,false,false,false
19088231,Base64 Decoding in iOS 7+,"I have Encoded text(NSString) using NSData Class new API which is Added in iOS7.
using this
- (NSData *)dataUsingEncoding:(NSStringEncoding)encoding;
here is my code
NSString *base64EncodedString = [[myText dataUsingEncoding:NSUTF8StringEncoding] base64EncodedStringWithOptions:0];
NSLog(@""%@"", base64EncodedString);
I am looking to decode it
",https://stackoverflow.com/questions/19088231/base64-decoding-in-ios-7,186,132526.0,3.0,,,2013-09-30 07:01:31,2023-11-03 14:26:13,2016-11-11 16:01:07,,,ios;objective-c;swift;ios7;ios8,Sandeep Khade,2823,1414994,registered,true,19088341,,CC BY-SA 3.0,,456,354,4,0,0,5,true,false,false,true,true,true,25,5,false,0.023,0.0014,4800,2013,9,7,Monday,false,false,false,false,false,false,false
27797351,Class has no initializers Swift,"I have a problem with Swift class. I have a swift file for UITableViewController class and UITableViewCell class. My problem is the UITableViewCell class, and outlets. This class has an error Class ""HomeCell"" has no initializers, and I don't understand this problem.
Thanks for your responses.
import Foundation
import UIKit
class HomeTable: UITableViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet var tableViex: UITableView!
var items: [(String, String, String)] = [
(""Test"", ""123"", ""1.jpeg""),
(""Test2"", ""236"", ""2.jpeg""),
(""Test3"", ""678"", ""3.jpeg"")
]
override func viewDidLoad() {
super.viewDidLoad()
var nib = UINib(nibName: ""HomeCell"", bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier: ""bookCell"")
}
// Number row
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items.count
}
// Style Cell
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier(""bookCell"") as UITableViewCell
// Style here
return cell
}
// Select row
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// Select
}
}
// PROBLEM HERE
class HomeCell : UITableViewCell {
@IBOutlet var imgBook: UIImageView
@IBOutlet var titleBook: UILabel
@IBOutlet var pageBook: UILabel
func loadItem(#title: String, page: String, image:String) {
titleBook.text = title
pageBook.text = page
imgBook.image = UIImage(named: image)
}
}
",https://stackoverflow.com/questions/27797351/class-has-no-initializers-swift,186,149435.0,8.0,,,2015-01-06 11:07:22,2024-02-29 16:13:24,,,,ios;uitableview;swift,Kevin Py,2468,2223952,registered,true,27797738,,CC BY-SA 3.0,,1828,1773,1,0,0,3,true,false,false,true,true,false,31,5,false,0.054,0.0012,4337,2015,1,11,Tuesday,false,false,false,false,false,false,false
25405133,How to manually deprecate members,"Unlike Objective-C, Swift has no preprocessor, so is there still a way to manually deprecate members of a class?
I am looking for something similar to this:
-(id)method __deprecated;
",https://stackoverflow.com/questions/25405133/how-to-manually-deprecate-members,186,48601.0,6.0,,,2014-08-20 12:47:07,2023-02-20 07:42:27,2016-07-16 14:45:07,,,ios;objective-c;swift;c-preprocessor;deprecated,Atomix,13922,3285649,registered,true,25406285,,CC BY-SA 3.0,,224,186,1,0,0,5,true,false,false,true,true,true,33,5,false,0.123,0.0038,4476,2014,8,12,Wednesday,false,false,false,false,false,false,false
44575293,"With JSONDecoder in Swift 4, can missing keys use a default value instead of having to be optional properties?","Swift 4 added the new Codable protocol. When I use JSONDecoder it seems to require all the non-optional properties of my Codable class to have keys in the JSON or it throws an error.
Making every property of my class optional seems like an unnecessary hassle since what I really want is to use the value in the json or a default value. (I don't want the property to be nil.)
Is there a way to do this?
class MyCodable: Codable {
var name: String = ""Default Appleseed""
}
func load(input: String) {
do {
if let data = input.data(using: .utf8) {
let result = try JSONDecoder().decode(MyCodable.self, from: data)
print(""name: \(result.name)"")
}
} catch {
print(""error: \(error)"")
// `Error message: ""Key not found when expecting non-optional type
// String for coding key \""name\""""`
}
}
let goodInput = ""{\""name\"": \""Jonny Appleseed\"" }""
let badInput = ""{}""
load(input: goodInput) // works, `name` is Jonny Applessed
load(input: badInput) // breaks, `name` required since property is non-optional
",https://stackoverflow.com/questions/44575293/with-jsondecoder-in-swift-4-can-missing-keys-use-a-default-value-instead-of-hav,186,79354.0,9.0,,,2017-06-15 19:18:15,2025-05-20 15:14:55,2019-09-03 10:30:35,,,json;swift;swift4;codable,zekel,9535,168594,registered,true,57260118,,CC BY-SA 4.0,,1164,1080,4,0,0,4,true,false,false,true,true,true,110,19,true,0.113,0.0023,3446,2017,6,19,Thursday,false,false,false,false,false,false,false
62635914,Initialize @StateObject with a parameter in SwiftUI,"I would like to know if there is currently (at the time of asking, the first Xcode 12.0 Beta) a way to initialize a @StateObject with a parameter coming from an initializer.
To be more specific, this snippet of code works fine:
struct MyView: View {
@StateObject var myObject = MyObject(id: 1)
}
But this does not:
struct MyView: View {
@StateObject var myObject: MyObject
init(id: Int) {
self.myObject = MyObject(id: id)
}
}
From what I understand the role of @StateObject is to make the view the owner of the object.
The current workaround I use is to pass the already initialized MyObject instance like this:
struct MyView: View {
@ObservedObject var myObject: MyObject
init(myObject: MyObject) {
self.myObject = myObject
}
}
But now, as far as I understand, the view that created the object owns it, while this view does not.
Thanks.
",https://stackoverflow.com/questions/62635914/initialize-stateobject-with-a-parameter-in-swiftui,186,65822.0,12.0,,,2020-06-29 10:14:19,2024-04-21 23:21:42,,,,swift;swiftui;xcode12,Emilio Schepis,2067,10026736,registered,true,62636048,,CC BY-SA 4.0,,1125,865,5,0,0,3,true,false,false,true,true,false,51,7,false,0.182,0.0028,2336,2020,6,10,Monday,false,false,false,false,false,false,false
24857986,Load a UIView from nib in Swift,"Here is my Objective-C code which I'm using to load a nib for my customised UIView:
-(id)init{
NSArray *subviewArray = [[NSBundle mainBundle] loadNibNamed:@""myXib"" owner:self options:nil];
return [subviewArray objectAtIndex:0];
}
What is the equivalent code in Swift?
",https://stackoverflow.com/questions/24857986/load-a-uiview-from-nib-in-swift,185,264458.0,30.0,,,2014-07-21 04:57:13,2022-07-06 18:19:36,2016-06-01 14:42:39,,,swift;uiview;xib,Bagusflyer,13022,118562,registered,true,26018312,,CC BY-SA 3.0,,332,281,2,0,0,3,true,false,false,true,true,true,31,7,false,0.113,0.0007,4506,2014,7,4,Monday,false,false,false,false,false,false,false
15864364,ViewDidAppear is not called when opening app from background,"I have a View Controller in which my value is 0 (label) and when I open that View Controller from another ViewController I have set viewDidAppear to set value 20 on label. It works fine but when I close my app and than again I open my app but the value doesn't change because viewDidLoad, viewDidAppear and viewWillAppear nothing get called. How can I call when I open my app. Do I have to do anything from applicationDidBecomeActive?
",https://stackoverflow.com/questions/15864364/viewdidappear-is-not-called-when-opening-app-from-background,185,118268.0,8.0,,,2013-04-07 15:52:36,2020-04-17 01:31:11,2017-02-12 19:03:15,,,ios;objective-c;iphone;xcode;swift,Zohaib,2875,1808761,registered,true,15864784,,CC BY-SA 3.0,,524,439,6,0,0,5,true,false,false,true,true,true,60,9,false,0.068,0.0016,4976,2013,4,15,Sunday,true,false,false,false,false,false,false
16336500,Kotlin Ternary Conditional Operator,"What is the equivalent of this expression in Kotlin?
a ? b : c
This is not valid code in Kotlin.
",https://stackoverflow.com/questions/16336500/kotlin-ternary-conditional-operator,897,534778.0,33.0,,,2013-05-02 11:07:57,2025-03-25 10:01:00,2023-04-24 00:12:53,,,kotlin;conditional-operator,Drew Noakes,314034,24874,registered,true,16336507,,CC BY-SA 4.0,2022-04-10 16:23:30,138,100,1,0,0,2,true,false,false,true,true,true,35,4,false,0.062,0.0017,4951,2013,5,11,Thursday,false,false,false,false,false,false,false
37618738,How to check if a "lateinit" variable has been initialized?,"I wonder if there is a way to check if a lateinit variable has been initialized. For example:
class Foo() {
private lateinit var myFile: File
fun bar(path: String?) {
path?.let { myFile = File(it) }
}
fun bar2() {
myFile.whateverMethod()
// May crash since I don't know whether myFile has been initialized
}
}
",https://stackoverflow.com/questions/37618738/how-to-check-if-a-lateinit-variable-has-been-initialized,886,411151.0,8.0,,,2016-06-03 15:53:56,2023-08-17 18:57:33,2019-11-27 12:03:33,,,kotlin,Mathew Hany,14240,4613968,registered,true,46584412,,CC BY-SA 4.0,,403,359,2,0,0,1,true,false,false,true,true,true,69,10,true,0.019,0.0022,3823,2016,6,15,Friday,false,false,false,false,false,false,false
48988778,Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6,"When trying to run the Example CorDapp (GitHub CorDapp) via IntelliJ, I receive the following error:
Cannot inline bytecode built with JVM target 1.8 into bytecode that is
being built with JVM target 1.6
How can I modify the IntelliJ settings so that all the bytecode is built with the same JVM target?
",https://stackoverflow.com/questions/48988778/cannot-inline-bytecode-built-with-jvm-target-1-8-into-bytecode-that-is-being-bui,791,290330.0,38.0,,,2018-02-26 12:41:42,2023-11-04 04:06:44,2020-07-23 15:37:01,,,android;intellij-idea;kotlin;jvm;corda,Joel,23240,4620025,registered,true,48988779,,CC BY-SA 4.0,,423,305,0,1,0,5,true,false,false,true,true,true,102,18,false,0.131,0.0027,3190,2018,2,12,Monday,false,false,false,false,false,false,false
3872063,How to launch an Activity from another Application in Android,"I want to launch an installed package from my Android application. I assume that it is possible using intents, but I didn't find a way of doing it. Is there a link, where to find the information?
",https://stackoverflow.com/questions/3872063/how-to-launch-an-activity-from-another-application-in-android,578,572795.0,19.0,,,2010-10-06 11:46:06,2024-06-05 11:16:51,2021-01-30 16:14:43,,,java;android;kotlin;android-intent,Bastian,9795,467895,unregistered,true,,,CC BY-SA 4.0,2016-10-21 05:29:46,203,196,0,0,0,4,false,false,false,true,true,true,61,10,false,0.033,0.001,5890,2010,10,11,Wednesday,false,false,false,true,false,false,false
34957430,How to convert a Kotlin source file to a Java source file,"I have a Kotlin source file, but I want to translate it to Java.
How can I convert Kotlin to Java source?
",https://stackoverflow.com/questions/34957430/how-to-convert-a-kotlin-source-file-to-a-java-source-file,550,442282.0,9.0,,,2016-01-22 23:07:14,2026-08-29 09:30:21,2020-04-23 05:36:29,,,java;kotlin;code-conversion,activedecay,11075,823282,registered,true,40762755,,CC BY-SA 4.0,2021-07-10 07:39:54,121,107,0,0,0,3,true,false,false,true,true,true,57,12,false,0.02,0.0012,3956,2016,1,23,Friday,false,false,false,true,false,false,false
36623177,Property initialization using "by lazy" vs. "lateinit","In Kotlin, if you don't want to initialize a class property inside the constructor or in the top of the class body, you have basically these two options (from the language reference):
lazy() is a function that takes a lambda and returns an instance of Lazy<T> which can serve as a delegate for implementing a lazy property: the first call to get() executes the lambda passed to lazy() and remembers the result, subsequent calls to get() simply return the remembered result.
Example
public class Hello {
val myLazyString: String by lazy { "Hello" }
}
So, the first call and the subsequential calls, wherever it is, to myLazyString will return Hello
Normally, properties declared as having a non-null type must be initialized in the constructor. However, fairly often this is not convenient. For example, properties can be initialized through dependency injection, or in the setup method of a unit test. In this case, you cannot supply a non-null initializer in the constructor, but you still want to avoid null checks when referencing the property inside the body of a class.
To handle this case, you can mark the property with the lateinit modifier:
public class MyTest {
lateinit var subject: TestSubject
@SetUp fun setup() { subject = TestSubject() }
@Test fun test() { subject.method() }
}
The modifier can only be used on var properties declared inside the body of a class (not in the primary constructor), and only when the property does not have a custom getter or setter. The type of the property must be non-null, and it must not be a primitive type.
So, how to choose correctly between these two options, since both of them can solve the same problem?
",https://stackoverflow.com/questions/36623177/property-initialization-using-by-lazy-vs-lateinit,517,259107.0,8.0,,,2016-04-14 12:30:00,2022-07-20 14:19:54,2021-10-03 10:44:06,,,properties;kotlin,regmoraes,5559,2327342,registered,true,36623703,,CC BY-SA 4.0,,2268,1747,9,2,0,2,true,false,false,true,true,true,74,7,false,0.031,0.002,3873,2016,4,12,Thursday,false,false,false,false,false,false,false
37595936,What is the difference between "const" and "val"?,"I have recently read about the const keyword, and I'm so confused! I can't find any difference between const and the val keyword, I mean we can use both of them to make an immutable variable, is there anything else that I'm missing?
",https://stackoverflow.com/questions/37595936/what-is-the-difference-between-const-and-val,493,130642.0,10.0,,,2016-06-02 15:20:32,2025-12-08 15:03:15,2019-10-16 04:38:29,,,constants;kotlin,Mathew Hany,14240,4613968,registered,true,37596023,,CC BY-SA 4.0,,279,233,3,0,0,2,true,false,false,true,true,true,69,8,true,0.077,0.0038,3824,2016,6,15,Thursday,false,false,false,false,false,false,false
45949584,How does the reified keyword in Kotlin work?,"I'm trying to understand the purpose of the reified keyword. Apparently, it's allowing us to do reflection on generics.
However, when I leave it out, it works just as fine. When does this make an actual difference?
",https://stackoverflow.com/questions/45949584/how-does-the-reified-keyword-in-kotlin-work,458,169653.0,4.0,,,2017-08-29 23:11:14,2024-10-11 15:52:46,2023-01-14 15:41:29,,,generics;kotlin;kotlin-reified-type-parameters,hl3mukkel,6149,2489327,registered,true,45952201,,CC BY-SA 4.0,,350,215,1,1,0,3,true,false,false,true,true,true,44,8,true,0.024,0.0027,3371,2017,8,23,Tuesday,false,false,false,false,false,false,false
75263047,Duplicate class in Kotlin Android,"![]()
I kept on getting an error that there is a duplicate error in classes.
This is what I have under org.jetbrains.kotlin folder
.idea/libraries
It seems like the problem is because there is two different dependencies for Kotlin, from stdlib and stdlibjdk8, but I don't know how to remove either one from my module/project dependencies. How can I do it?
Here's the full error code:
Duplicate class kotlin.collections.jdk8.CollectionsJDK8Kt found in modules jetified-kotlin-stdlib-1.8.0 (org.jetbrains.kotlin:kotlin-stdlib:1.8.0) and jetified-kotlin-stdlib-jdk8-1.6.0 (org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.6.0)
Duplicate class kotlin.internal.jdk7.JDK7PlatformImplementations found in modules jetified-kotlin-stdlib-1.8.0 (org.jetbrains.kotlin:kotlin-stdlib:1.8.0) and jetified-kotlin-stdlib-jdk7-1.6.0 (org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.6.0)
Duplicate class kotlin.internal.jdk8.JDK8PlatformImplementations found in modules jetified-kotlin-stdlib-1.8.0 (org.jetbrains.kotlin:kotlin-stdlib:1.8.0) and jetified-kotlin-stdlib-jdk8-1.6.0 (org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.6.0)
Duplicate class kotlin.io.path.ExperimentalPathApi found in modules jetified-kotlin-stdlib-1.8.0 (org.jetbrains.kotlin:kotlin-stdlib:1.8.0) and jetified-kotlin-stdlib-jdk7-1.6.0 (org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.6.0)
Duplicate class kotlin.io.path.PathRelativizer found in modules jetified-kotlin-stdlib-1.8.0 (org.jetbrains.kotlin:kotlin-stdlib:1.8.0) and jetified-kotlin-stdlib-jdk7-1.6.0 (org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.6.0)
Duplicate class kotlin.io.path.PathsKt found in modules jetified-kotlin-stdlib-1.8.0 (org.jetbrains.kotlin:kotlin-stdlib:1.8.0) and jetified-kotlin-stdlib-jdk7-1.6.0 (org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.6.0)
Duplicate class kotlin.io.path.PathsKt__PathReadWriteKt found in modules jetified-kotlin-stdlib-1.8.0 (org.jetbrains.kotlin:kotlin-stdlib:1.8.0) and jetified-kotlin-stdlib-jdk7-1.6.0 (org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.6.0)
Duplicate class kotlin.io.path.PathsKt__PathUtilsKt found in modules jetified-kotlin-stdlib-1.8.0 (org.jetbrains.kotlin:kotlin-stdlib:1.8.0) and jetified-kotlin-stdlib-jdk7-1.6.0 (org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.6.0)
Duplicate class kotlin.jdk7.AutoCloseableKt found in modules jetified-kotlin-stdlib-1.8.0 (org.jetbrains.kotlin:kotlin-stdlib:1.8.0) and jetified-kotlin-stdlib-jdk7-1.6.0 (org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.6.0)
Duplicate class kotlin.jvm.jdk8.JvmRepeatableKt found in modules jetified-kotlin-stdlib-1.8.0 (org.jetbrains.kotlin:kotlin-stdlib:1.8.0) and jetified-kotlin-stdlib-jdk8-1.6.0 (org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.6.0)
Duplicate class kotlin.random.jdk8.PlatformThreadLocalRandom found in modules jetified-kotlin-stdlib-1.8.0 (org.jetbrains.kotlin:kotlin-stdlib:1.8.0) and jetified-kotlin-stdlib-jdk8-1.6.0 (org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.6.0)
Duplicate class kotlin.streams.jdk8.StreamsKt found in modules jetified-kotlin-stdlib-1.8.0 (org.jetbrains.kotlin:kotlin-stdlib:1.8.0) and jetified-kotlin-stdlib-jdk8-1.6.0 (org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.6.0)
Duplicate class kotlin.streams.jdk8.StreamsKt$asSequence$$inlined$Sequence$1 found in modules jetified-kotlin-stdlib-1.8.0 (org.jetbrains.kotlin:kotlin-stdlib:1.8.0) and jetified-kotlin-stdlib-jdk8-1.6.0 (org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.6.0)
Duplicate class kotlin.streams.jdk8.StreamsKt$asSequence$$inlined$Sequence$2 found in modules jetified-kotlin-stdlib-1.8.0 (org.jetbrains.kotlin:kotlin-stdlib:1.8.0) and jetified-kotlin-stdlib-jdk8-1.6.0 (org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.6.0)
Duplicate class kotlin.streams.jdk8.StreamsKt$asSequence$$inlined$Sequence$3 found in modules jetified-kotlin-stdlib-1.8.0 (org.jetbrains.kotlin:kotlin-stdlib:1.8.0) and jetified-kotlin-stdlib-jdk8-1.6.0 (org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.6.0)
Duplicate class kotlin.streams.jdk8.StreamsKt$asSequence$$inlined$Sequence$4 found in modules jetified-kotlin-stdlib-1.8.0 (org.jetbrains.kotlin:kotlin-stdlib:1.8.0) and jetified-kotlin-stdlib-jdk8-1.6.0 (org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.6.0)
Duplicate class kotlin.text.jdk8.RegexExtensionsJDK8Kt found in modules jetified-kotlin-stdlib-1.8.0 (org.jetbrains.kotlin:kotlin-stdlib:1.8.0) and jetified-kotlin-stdlib-jdk8-1.6.0 (org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.6.0)
Duplicate class kotlin.time.jdk8.DurationConversionsJDK8Kt found in modules jetified-kotlin-stdlib-1.8.0 (org.jetbrains.kotlin:kotlin-stdlib:1.8.0) and jetified-kotlin-stdlib-jdk8-1.6.0 (org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.6.0)
I've tried deleting the files from the org.jetbrains.kotlin, but whenever I build the app in Android Studio, the files will be redownloaded again.
This is my module app Gradle code:
plugins {
id 'com.android.application'
id 'com.google.gms.google-services'
}
android {
compileSdk 33
defaultConfig {
applicationId "com.example.umfs"
minSdk 21
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
buildFeatures {
viewBinding true
}
namespace 'com.example.umfs'
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation 'com.google.firebase:firebase-database:20.1.0'
implementation 'androidx.preference:preference:1.2.0'
implementation 'com.google.firebase:firebase-auth:21.1.0'
implementation 'com.google.firebase:firebase-core:21.1.1'
implementation 'androidx.navigation:navigation-fragment:2.5.3'
implementation 'androidx.navigation:navigation-ui:2.5.3'
implementation 'com.google.firebase:firebase-firestore:24.4.1'
implementation 'androidx.recyclerview:recyclerview:1.2.1'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.4'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.0'
implementation 'de.hdodenhof:circleimageview:3.1.0'
implementation "androidx.cardview:cardview:1.0.0"
implementation 'com.google.firebase:firebase-firestore:24.4.1'
implementation 'com.google.firebase:firebase-storage:20.1.0'
implementation 'com.google.firebase:firebase-database'
implementation platform('com.google.firebase:firebase-bom:28.4.0')
implementation 'com.squareup.picasso:picasso:2.71828'
implementation 'com.makeramen:roundedimageview:2.3.0'
implementation 'com.github.bumptech.glide:glide:4.14.2'
implementation 'com.github.marlonlom:timeago:4.0.3'
implementation "androidx.core:core-ktx:+"
}
apply plugin: 'com.google.gms.google-services'
",https://stackoverflow.com/questions/75263047/duplicate-class-in-kotlin-android,453,307881.0,70.0,,,2023-01-27 20:28:19,2025-06-19 21:09:36,2023-12-03 03:30:30,,,java;android;kotlin;dependencies,midnighthowlers,4521,21058541,registered,true,,,CC BY-SA 4.0,2024-08-09 07:51:05,7571,7165,2,3,1,4,false,false,false,true,true,true,33,5,false,0.227,0.0015,1394,2023,1,20,Friday,false,false,false,true,false,false,false
44595529,"Smart cast to 'Type' is impossible, because 'variable' is a mutable property that could have been changed by this time","And the Kotlin newbie asks, "why won't the following code compile?":
var left: Node? = null
fun show() {
if (left != null) {
queue.add(left) // ERROR HERE
}
}
Smart cast to 'Node' is impossible, because 'left' is a mutable
property that could have been changed by this time
I get that left is mutable variable, but I'm explicitly checking left != null and left is of type Node so why can't it be smart-casted to that type?
How can I fix this elegantly?
",https://stackoverflow.com/questions/44595529/smart-cast-to-type-is-impossible-because-variable-is-a-mutable-property-tha,434,196014.0,13.0,,,2017-06-16 18:11:15,2023-03-02 14:04:23,2020-07-23 21:01:22,,,kotlin,frankelot,14559,1949554,registered,true,44596284,,CC BY-SA 4.0,,616,487,5,0,0,1,true,false,false,true,true,true,134,20,false,0.066,0.0022,3445,2017,6,18,Friday,false,false,false,false,false,false,false
31366229,How to initialize an array in Kotlin with values?,"In Java an array can be initialized such as:
int numbers[] = new int[] {10, 20, 30, 40, 50}
How does Kotlin's array initialization look like?
",https://stackoverflow.com/questions/31366229/how-to-initialize-an-array-in-kotlin-with-values,421,431563.0,27.0,,,2015-07-12 09:20:06,2023-01-10 08:19:15,2018-03-04 21:09:11,,,arrays;kotlin,Lars Blumberg,21909,543875,registered,true,31366276,,CC BY-SA 3.0,,183,145,1,0,0,2,true,false,false,true,true,true,49,9,true,0.063,0.001,4150,2015,7,9,Sunday,true,false,false,false,false,false,false
62131564,A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptExecution,"All of sudden I start getting this error, and I am not getting idea why if anyone just let me know where this error is, will be enough helpful. As much I am able to get is this because of new update of android studio.
Detailed summary of error I am getting.
Task :app:kaptDebugKotlin
ANTLR Tool version 4.5.3 used for code generation does not match the current runtime version 4.7.1ANTLR Runtime version 4.5.3 used for parser compilation does not match the current runtime version 4.7.1ANTLR Tool version 4.5.3 used for code generation does not match the current runtime version 4.7.1ANTLR Runtime version 4.5.3 used for parser compilation does not match the current runtime version 4.7.1C:\Users\shubh\Downloads\MarginCalculator\app\build\generated\source\kapt\debug\com\kotlin_developer\margincalculator\DataBinderMapperImpl.java:10: error: cannot find symbol
import com.kotlin_developer.margincalculator.databinding.FragmentCalculatorScreenBindingImpl;
symbol: class FragmentCalculatorScreenBindingImpl
Task :app:kaptDebugKotlin FAILED
location: package com.kotlin_developer.margincalculator.databinding
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:kaptDebugKotlin'.
> A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptExecution
> java.lang.reflect.InvocationTargetException (no error message)
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 17s
29 actionable tasks: 27 executed, 2 up-to-date
",https://stackoverflow.com/questions/62131564/a-failure-occurred-while-executing-org-jetbrains-kotlin-gradle-internal-kaptexec,414,620487.0,63.0,,,2020-06-01 11:52:47,2024-10-09 16:16:45,2020-10-09 11:38:40,,,android;android-studio;kotlin,Shubham Tater,4168,3686670,registered,true,,,CC BY-SA 4.0,2020-08-17 06:58:00,1709,1678,1,0,0,3,false,false,false,true,true,true,85,6,false,0.102,0.0007,2364,2020,6,11,Monday,false,false,false,false,false,false,false
44200075,What is the difference between var and val in Kotlin?,"What is the difference between var and val in Kotlin?
I have gone through this link:
KotlinLang: Properties and Fields
As stated on this link:
The full syntax of a read-only property declaration differs from a
mutable one in two ways: it starts with val instead of var and does
not allow a setter.
But just before there is an example which uses a setter.
fun copyAddress(address: Address): Address {
val result = Address() // there's no 'new' keyword in Kotlin
result.name = address.name // accessors are called
result.street = address.street
// ...
return result
}
What is the exact difference between var and val?
Why do we need both?
This is not a duplicate of Variables in Kotlin, differences with Java: 'var' vs. 'val'? as I am asking about the doubt related to the particular example in the documentation and not just in general.
",https://stackoverflow.com/questions/44200075/what-is-the-difference-between-var-and-val-in-kotlin,410,221256.0,30.0,,,2017-05-26 11:11:18,2024-09-09 09:14:29,2021-05-20 16:53:14,,,kotlin;variables,Akshar Patel,9508,6156989,registered,true,44200189,,CC BY-SA 4.0,2019-07-09 13:36:11,1253,875,5,2,0,2,true,false,false,true,true,true,53,10,true,0.136,0.0019,3466,2017,5,11,Friday,false,false,false,false,false,false,false
67699823,"Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15","In Stripe, my client wants email and cardholder name, but the Stripe payment UI doesn't provide that option in com.stripe.android.view.CardMultilineWidget. I wanted to give it a try with the latest stripe version,
I was using Stripe version (14.1.1). So I updated it to the latest one (16.8.0)
The build showed me the error that it doesn't take minSdkVersion 19. It requires 21 in manifest merger. So I updated minSdkVersion to 21.
I got
caches/transforms-2/files-2.1/4541b0189187e0017d23bbb0afebd16a/jetified-kotlin-stdlib-common-1.5.0.jar!/META-INF/kotlin-stdlib-common.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
I tried changing the Gradle version, but I am still getting the same error. How can I solve the incompatible error and add the email and cardholder name in Stripe?
",https://stackoverflow.com/questions/67699823/module-was-compiled-with-an-incompatible-version-of-kotlin-the-binary-version-o,408,675345.0,45.0,,,2021-05-26 06:45:07,2026-04-15 15:06:12,2023-10-08 12:53:07,,,android;flutter;kotlin;gradle;stripe-payments,Karthy Sbk,4203,11576007,registered,true,67801441,,CC BY-SA 4.0,2023-08-17 09:40:41,1180,890,7,1,0,5,true,false,false,true,true,true,131,21,false,0.067,0.0006,2005,2021,5,6,Wednesday,false,false,false,false,false,false,false
44038721,Constants in Kotlin -- what's a recommended way to create them?,"How is it recommended to create constants in Kotlin? And what's the naming convention? I've not found that in the documentation.
companion object {
//1
val MY_CONST = ""something""
//2
const val MY_CONST = ""something""
//3
val myConst = ""something""
}
Or ...?
",https://stackoverflow.com/questions/44038721/constants-in-kotlin-whats-a-recommended-way-to-create-them,407,370457.0,15.0,,,2017-05-18 04:42:00,2023-02-23 22:43:31,2022-01-18 18:38:42,,,kotlin;constants,Jodimoro,4835,7978068,registered,true,,,CC BY-SA 4.0,,323,285,1,0,0,2,false,false,false,true,true,true,67,11,true,0.04,0.0011,3474,2017,5,4,Thursday,false,false,false,false,false,false,false
33278869,How do I initialize Kotlin's MutableList to empty MutableList?,"Seems so simple, but, how do I initialize Kotlin's MutableList to empty MutableList?
I could hack it this way, but I'm sure there is something easier available:
var pusta: List<Kolory> = emptyList()
var cos: MutableList<Kolory> = pusta.toArrayList()
",https://stackoverflow.com/questions/33278869/how-do-i-initialize-kotlins-mutablelist-to-empty-mutablelist,406,274566.0,6.0,,,2015-10-22 10:28:29,2023-05-13 09:10:48,2017-03-07 08:07:36,,,kotlin,ssuukk,8432,1332872,registered,true,33278970,,CC BY-SA 3.0,,329,265,3,0,0,1,true,false,false,true,true,true,66,9,true,0.022,0.0015,4048,2015,10,10,Thursday,false,false,false,false,false,false,false
48898102,How to get the current index in for each Kotlin,"How to get the index in a for each loop? I want to print numbers for every second iteration
For example
for (value in collection) {
if (iteration_no % 2) {
//do something
}
}
In java, we have the traditional for loop
for (int i = 0; i < collection.length; i++)
How to get the i?
",https://stackoverflow.com/questions/48898102/how-to-get-the-current-index-in-for-each-kotlin,405,313776.0,10.0,,,2018-02-21 04:18:47,2025-05-23 13:24:51,2020-07-24 10:40:53,,,android;for-loop;kotlin,Adolf Dsilva,14660,1729085,registered,true,48898523,,CC BY-SA 4.0,,389,300,3,0,0,3,true,false,false,true,true,true,47,10,false,0.032,0.0013,3195,2018,2,4,Wednesday,false,false,false,false,false,false,false
4459058,Alarm Manager Example,"I want to implement a schedule function in my project. So I Googled for an Alarm manager program but I can`t find any examples.
Can anyone help me with a basic alarm manager program?
",https://stackoverflow.com/questions/4459058/alarm-manager-example,398,379496.0,10.0,,,2010-12-16 09:12:17,2022-05-01 18:36:16,2018-12-30 18:42:57,,,java;android;kotlin;alarmmanager,Rajamohan Sugumaran,4509,513162,registered,true,8801990,,CC BY-SA 4.0,2015-04-21 22:53:03,199,185,0,0,0,4,true,false,false,true,true,true,21,3,false,0.026,0.001,5819,2010,12,9,Thursday,false,false,false,true,false,false,false
37259159,Sort collection by multiple fields in Kotlin,"Let's say I have a list of People which I need to sort by Age first and then by Name.
Coming from a C#-background, I can easily achieve this in said language by using LINQ:
var list = new List<Person>();
list.Add(new Person(25, "Tom"));
list.Add(new Person(25, "Dave"));
list.Add(new Person(20, "Kate"));
list.Add(new Person(20, "Alice"));
// will produce: Alice, Kate, Dave, Tom
var sortedList = list.OrderBy(person => person.Age).ThenBy(person => person.Name).ToList();
How does one accomplish this using Kotlin?
This is what I tried (it's obviously wrong since the output of the first "sortedBy" clause gets overridden by the second one, which results in a list sorted by Name only)
val sortedList = ArrayList(list.sortedBy { it.age }.sortedBy { it.name })) // wrong
",https://stackoverflow.com/questions/37259159/sort-collection-by-multiple-fields-in-kotlin,393,187755.0,2.0,,,2016-05-16 16:51:36,2025-04-03 16:29:48,2025-04-03 16:29:48,2016-05-17 17:34:08,Duplicate,kotlin,Fire095,4015,5790273,registered,true,37259451,,,,988,836,2,0,0,1,true,true,false,true,true,true,44,7,false,0.011,0.0021,3841,2016,5,16,Monday,false,false,false,false,false,false,false
61023968,What do I use now that Handler() is deprecated?,"How do I fix the deprecation warning in this code? Alternatively, are there any other options for doing this?
Handler().postDelayed({
context?.let {
//code
}
}, 3000)
",https://stackoverflow.com/questions/61023968/what-do-i-use-now-that-handler-is-deprecated,384,197997.0,20.0,,,2020-04-04 04:58:49,2023-11-07 09:12:19,2020-12-29 11:45:05,,,java;android;kotlin;android-handler,Bolt UIX,7262,7585388,registered,true,63851895,,CC BY-SA 4.0,2023-04-13 07:03:05,215,184,1,0,0,4,true,false,false,true,true,true,47,9,true,0.101,0.0019,2422,2020,4,4,Saturday,true,false,false,true,false,false,false
53191468,"No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator","I am trying to consume an API using Retrofit and Jackson to deserialize. I am getting the onFailure error No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator.
",https://stackoverflow.com/questions/53191468/no-creators-like-default-construct-exist-cannot-deserialize-from-object-valu,380,689880.0,36.0,,,2018-11-07 14:29:25,2024-12-24 11:21:13,2024-12-24 11:21:13,,,android;kotlin;serialization;jackson;retrofit2,José Nobre,5127,5927732,registered,true,53192674,,CC BY-SA 4.0,2022-08-07 16:24:35,249,229,1,0,0,5,true,false,false,true,true,true,121,16,false,0.052,0.0006,2936,2018,11,14,Wednesday,false,false,false,false,false,false,false
26444145,Extend data class in Kotlin,"Data classes seem to be the replacement to the old-fashioned POJOs in Java. It is quite expectable that these classes would allow for inheritance, but I can see no convenient way to extend a data class. What I need is something like this:
open data class Resource (var id: Long = 0, var location: String = """")
data class Book (var isbn: String) : Resource()
The code above fails because of clash of component1() methods. Leaving data annotation in only one of classes does not do the work, too.
Perhaps there is another idiom to extend data classes?
UPD: I might annotate only child child class, but data annotation only handles properties declared in the constructor. That is, I would have to declare all parent's properties open and override them, which is ugly:
open class Resource (open var id: Long = 0, open var location: String = """")
data class Book (
override var id: Long = 0,
override var location: String = """",
var isbn: String
) : Resource()
",https://stackoverflow.com/questions/26444145/extend-data-class-in-kotlin,372,276883.0,15.0,,,2014-10-18 20:18:38,2024-03-17 05:48:31,2020-01-08 12:13:17,,,inheritance;kotlin;abstract;data-class,Dmitry,4472,1625024,registered,true,26467380,,CC BY-SA 4.0,,1101,973,6,0,0,4,true,false,false,true,true,true,27,5,false,0.054,0.0013,4417,2014,10,20,Saturday,true,false,false,false,false,false,false
36262305,Difference between List and Array types in Kotlin,"What is the difference between List and Array types?
It seems can make same operations with them (loops, filter expression, etc..), is there any difference in behavior or usage?
val names1 = listOf(""Joe"",""Ben"",""Thomas"")
val names2 = arrayOf(""Joe"",""Ben"",""Thomas"")
for (name in names1)
println(name)
for (name in names2)
println(name)
",https://stackoverflow.com/questions/36262305/difference-between-list-and-array-types-in-kotlin,371,170449.0,5.0,,,2016-03-28 12:27:52,2024-09-25 16:50:16,2020-12-15 09:01:48,,,arrays;list;kotlin,Daniel Hári,7884,1386911,registered,true,36263748,,CC BY-SA 4.0,,405,344,3,0,0,3,true,false,false,true,true,true,49,8,false,0.029,0.0022,3890,2016,3,12,Monday,false,false,false,false,false,false,false
51610420,"Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0","I've got a gradle FAILURE:
...""Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0.""
Case description:
- Attached to the project codebase the next libs:
APP/build.gradle
//(Required) Writing and executing Unit Tests on the JUnit Platform
testImplementation ""org.junit.jupiter:junit-jupiter-api:5.2.0""
testRuntimeOnly ""org.junit.jupiter:junit-jupiter-engine:5.2.0""
// (Optional) If you need ""Parameterized Tests""
testImplementation ""org.junit.jupiter:junit-jupiter-params:5.2.0""
// (Optional) If you also have JUnit 4-based tests
testImplementation ""junit:junit:4.12""
testRuntimeOnly ""org.junit.vintage:junit-vintage-engine:5.2.0""
testImplementation ""io.mockk:mockk:1.8.5""
Updated the gradle-wrapper.properties
distributionUrl=https....gradle-4.4-all.zip to 4.7-all
after all of that gradle was built success
created the test calss
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class TestClass {
@Test
internal fun testName() {
Assert.assertEquals(2, 1 + 1)
}
}
ran the Gradle build with a command line argument ./gradlew --warning-mode=all to see what exactly the deprecated features are.
![]()
As a result I couldn't build the app and I've got that FAILURE: message.
",https://stackoverflow.com/questions/51610420/deprecated-gradle-features-were-used-in-this-build-making-it-incompatible-with,371,1262675.0,36.0,,,2018-07-31 09:47:21,2025-10-13 18:22:49,2019-05-30 14:41:32,,,android;unit-testing;gradle;kotlin;junit5,Philipp Buhaievskiy,3947,6094213,registered,true,51610775,,CC BY-SA 4.0,2022-07-22 18:08:55,1865,1288,4,2,2,5,true,false,false,true,true,true,90,14,false,0.029,0.0003,3035,2018,7,9,Tuesday,false,false,false,false,false,false,false
16120697,Kotlin: how to pass a function as parameter to another?,"Given function foo :
fun foo(m: String, bar: (m: String) -> Unit) {
bar(m)
}
We can do:
foo(""a message"", { println(""this is a message: $it"") } )
//or
foo(""a message"") { println(""this is a message: $it"") }
Now, lets say we have the following function:
fun buz(m: String) {
println(""another message: $m"")
}
Is there a way I can pass ""buz"" as a parameter to ""foo"" ?
Something like:
foo(""a message"", buz)
",https://stackoverflow.com/questions/16120697/kotlin-how-to-pass-a-function-as-parameter-to-another,370,282540.0,11.0,,,2013-04-20 13:04:06,2024-09-27 11:51:54,2017-06-15 17:08:41,,,kotlin,mhshams,17142,393786,registered,true,33402863,,CC BY-SA 3.0,,548,424,4,0,0,1,true,false,false,true,true,true,55,10,true,0.039,0.0013,4963,2013,4,13,Saturday,true,false,false,false,false,false,false
44109700,How to make primary key as autoincrement for Room Persistence lib,"I am creating an Entity (Room Persistence Library) class Food, where I want to make foodId as autoincrement.
@Entity
class Food(var foodName: String, var foodDesc: String, var protein: Double, var carbs: Double, var fat: Double)
{
@PrimaryKey
var foodId: Int = 0
var calories: Double = 0.toDouble()
}
How can I set foodId an autoincrement field?
",https://stackoverflow.com/questions/44109700/how-to-make-primary-key-as-autoincrement-for-room-persistence-lib,345,234192.0,9.0,,,2017-05-22 09:44:54,2025-05-26 13:40:59,2020-07-23 21:11:00,,,android;kotlin;android-room,Sachin Chandil,17989,5039950,registered,true,44109830,,CC BY-SA 4.0,2025-05-26 14:02:04,518,359,3,1,0,3,true,false,false,true,true,true,65,11,false,0.038,0.0015,3470,2017,5,9,Monday,false,false,false,false,false,false,false
34342413,What is the Kotlin double-bang (!!) operator?,"I'm converting Java to Kotlin with Android Studio. I get double bang after the instance variable. What is the double bang and more importantly where is this documented?
mMap!!.addMarker(MarkerOptions().position(london).title(""Marker in London""))
",https://stackoverflow.com/questions/34342413/what-is-the-kotlin-double-bang-operator,345,192714.0,7.0,,,2015-12-17 19:10:19,2022-10-09 13:38:16,2018-01-20 16:20:17,,,kotlin;kotlin-null-safety,mbr_at_ml,3805,3069849,registered,true,34342561,,CC BY-SA 3.0,2021-04-26 12:19:52,279,248,1,0,0,2,true,false,false,true,true,true,45,7,true,0.036,0.0018,3992,2015,12,19,Thursday,false,false,false,false,false,false,false
49512629,Default interface methods are only supported starting with Android 7.0 (Nougat),"I upgraded to Android Studio 3.1 and I'm getting the following error:
Default interface methods are only supported starting with Android N (--min-api 24): void android.arch.lifecycle.DefaultLifecycleObserver.onCreate(android.arch.lifecycle.LifecycleOwner)
Message{kind=ERROR, text=Default interface methods are only supported starting with Android N (--min-api 24): void android.arch.lifecycle.DefaultLifecycleObserver.onCreate(android.arch.lifecycle.LifecycleOwner), sources=[Unknown source file], tool name=Optional.of(D8)}
Here is my Gradle configuration:
compileSdkVersion 27
//buildToolsVersion '27.0.3'
defaultConfig {
minSdkVersion 16
targetSdkVersion 27
multiDexEnabled true
//...
}
As you can see, I am targeting 27 which is already ahead of 24 that it's complaining about. What exactly should I do to fix this? If I change to 1.8 Java, won't I be missing a lot of customers? Why was I not getting this error before I upgraded Android Studio?
I do not know if this is about the LifecycleObserver class I recently put in. It was in Kotlin and now I changed it to Java, but I still get the same error after cleaning the project:
public class LifeCycleAwareObserver implements LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onAppBackgrounded() {
AnalyticsUtils.trackStartSession(true);
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onAppForegrounded() {
AnalyticsUtils.trackStartSession(false);
}
}
How can I trace where the error is coming from so I can fix it?
Here are my version dependencies:
project.ext {
firebase_version = '12.0.0'
supportlib_version = '27.0.2'
room_version = '1.0.0'
espresso_version = '3.0.1'
archLifecycleVersion = '1.1.1'
}
",https://stackoverflow.com/questions/49512629/default-interface-methods-are-only-supported-starting-with-android-7-0-nougat,343,151296.0,10.0,,,2018-03-27 12:16:38,2021-06-20 10:23:23,2021-05-10 14:53:20,,,android;java-8;kotlin,j2emanue,62897,835883,registered,true,49525685,,CC BY-SA 4.0,2019-05-13 11:52:50,2143,1819,3,1,1,3,true,false,false,true,true,true,79,11,false,0.066,0.0023,3161,2018,3,12,Tuesday,false,false,false,false,false,false,false
69079963,How to set compileJava' task ( 11) and 'compileKotlin' task (1.8) jvm target compatibility to the same Java version in build.gradle.kts?,"Build.gradle.kts
buildscript {
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
dependencies {
classpath ("com.android.tools.build:gradle:7.0.2")
classpath ("org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.30")
classpath("gradle.plugin.com.github.spotbugs.snom:spotbugs-gradle-plugin:${Versions.spotbugsGradlePluginVersion}")
classpath("se.bjurr.violations:violations-gradle-plugin:${Versions.violationsVersion}")
}
}
//android {
// compileOptions {
// sourceCompatibility = JavaVersion.VERSION_11
// targetCompatibility = JavaVersion.VERSION_11
// }
//
// kotlinOptions {
// jvmTarget = JavaVersion.VERSION_11.toString()
// }
//}
plugins {
`maven-publish`
`java-gradle-plugin`
`kotlin-dsl`
id ("io.gitlab.arturbosch.detekt") version ("1.18.1")
}
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
dependencies {
compileOnly(gradleApi())
testImplementation(gradleTestKit())
testImplementation("junit:junit:${Versions.jUnitVersion}")
}
val generatedSources = tasks.register<GenerateVersionsFileTask>("generateSources")
I get the following error:
ERROR : 'compileJava' task (current target is 11) and 'compileKotlin' task (current target is 1.8) jvm target compatibility should be set to the same Java version.
When I uncomment android {}, I get:
Error : Script compilation errors:
Line 15: android {
^ Unresolved reference: android
",https://stackoverflow.com/questions/69079963/how-to-set-compilejava-task-11-and-compilekotlin-task-1-8-jvm-target-com,335,345189.0,26.0,,,2021-09-06 20:25:16,2024-11-28 13:30:06,2023-08-07 11:05:02,,,java;kotlin;android-gradle-plugin;dependencies;gradle-kotlin-dsl,jitendra kumar,3581,8899640,registered,true,,,CC BY-SA 4.0,2024-11-12 21:08:58,1760,1614,3,0,0,5,false,false,false,true,true,true,148,21,true,0.075,0.001,1902,2021,9,20,Monday,false,false,false,true,false,false,false
47871868,What does a suspend function mean in Kotlin coroutines?,"I'm reading Kotlin coroutines and know that it is based on suspend functions. But what does suspend mean?
Can a coroutine or a function get suspended?
From https://kotlinlang.org/docs/reference/coroutines.html
Basically, coroutines are computations that can be suspended without blocking a thread
I heard people often say "suspend function". But I think it is the coroutine that gets suspended because it is waiting for the function to get finished? "suspend" usually means "cease operation", in this case, the coroutine is idle.
Should we say the coroutine is suspended?
Which coroutine gets suspended?
From https://kotlinlang.org/docs/reference/coroutines.html
To continue the analogy, await() can be a suspending function (hence also callable from within an async {} block) that suspends a coroutine until some computation is done and returns its result:
async { // Here I call it the outer async coroutine
...
// Here I call computation the inner coroutine
val result = computation.await()
...
}
It says "that suspends a coroutine until some computation is done", but coroutine is like a lightweight thread. So if the coroutine is suspended, how can the computation be done?
We see await is called on computation, so it might be async that returns Deferred, which means it can start another coroutine
fun computation(): Deferred<Boolean> {
return async {
true
}
}
In the quote, it is mentioned that suspends a coroutine. Does it mean suspend the outer async coroutine, or suspend the inner computation coroutine?
Does suspend mean that while outer async coroutine is waiting (await) for the inner computation coroutine to finish, it (the outer async coroutine) idles (hence the name suspend) and returns thread to the thread pool, and when the child computation coroutine finishes, it (the outer async coroutine) wakes up, takes another thread from the pool and continues?
The reason I mention the thread is because of: https://kotlinlang.org/docs/tutorials/coroutines-basic-jvm.html
The thread is returned to the pool while the coroutine is waiting, and when the waiting is done, the coroutine resumes on a free thread in the pool
",https://stackoverflow.com/questions/47871868/what-does-a-suspend-function-mean-in-kotlin-coroutines,335,278746.0,11.0,,,2017-12-18 15:47:31,2025-07-13 08:57:31,2025-07-13 08:57:31,,,kotlin;async-await;kotlin-coroutines;coroutine;suspend,onmyway133,48536,1418457,registered,true,,,CC BY-SA 4.0,,2997,2223,19,3,0,5,false,false,false,true,true,true,55,9,true,0.039,0.0012,3260,2017,12,15,Monday,false,false,false,false,false,false,false
32540947,`break` and `continue` in `forEach` in Kotlin,"Kotlin has very nice iterating functions, like forEach or repeat, but I am not able to make the break and continue operators work with them (both local and non-local):
repeat(5) {
break
}
(1..5).forEach {
continue@forEach
}
The goal is to mimic usual loops with the functional syntax as close as it might be. It was definitely possible in some older versions of Kotlin, but I struggle to reproduce the syntax.
The problem might be a bug with labels (M12), but I think that the first example should work anyway.
It seems to me that I've read somewhere about a special trick/annotation, but I could not find any reference on the subject. Might look like the following:
public inline fun repeat(times: Int, @loop body: (Int) -> Unit) {
for (index in 0..times - 1) {
body(index)
}
}
",https://stackoverflow.com/questions/32540947/break-and-continue-in-foreach-in-kotlin,332,281861.0,12.0,,,2015-09-12 16:11:54,2025-05-16 09:44:27,2018-05-07 09:42:35,,,loops;foreach;lambda;kotlin,voddan,34224,3144601,registered,true,32541601,,CC BY-SA 4.0,,943,815,6,0,0,4,true,false,false,true,true,true,45,7,false,0.043,0.0012,4088,2015,9,16,Saturday,true,false,false,false,false,false,false
45685026,How can I get a random number in Kotlin?,"A generic method that can return a random integer between 2 parameters like ruby does with rand(0..n).
Any suggestion?
",https://stackoverflow.com/questions/45685026/how-can-i-get-a-random-number-in-kotlin,331,317113.0,25.0,,,2017-08-15 00:49:25,2025-06-25 10:48:27,2019-03-28 14:14:41,,,random;kotlin;jvm,Yago Azedias,4988,6516044,registered,true,45687695,,CC BY-SA 4.0,,147,120,1,0,0,3,true,false,false,true,true,true,40,9,true,0.079,0.001,3385,2017,8,0,Tuesday,false,false,false,false,false,false,false
23086291,Kotlin – String formatting,"Kotlin has an excellent feature called string templates.
val i = 10
val s = "i = $i" // evaluates to "i = 10"
But is it possible to have any formatting in the templates? For example, I would like to format Double in string templates in kotlin, at least to set a number of digits after a decimal separator:
val pi = 3.14159265358979323
val s = "pi = $pi??" // How to make it "pi = 3.14"?
",https://stackoverflow.com/questions/23086291/kotlin-string-formatting,328,342063.0,10.0,,,2014-04-15 14:12:42,2023-09-08 10:32:51,2022-10-06 16:50:30,,,string-formatting;kotlin,Dmitry Romanov,14239,548894,registered,true,23088000,,CC BY-SA 4.0,,492,430,2,0,0,2,true,false,false,true,true,true,26,4,false,0.029,0.001,4603,2014,4,14,Tuesday,false,false,false,false,false,false,false
29945087,Kotlin and new ActivityTestRule : The @Rule must be public,"I'm trying to make UI test for my android app in Kotlin. Since the new system using ActivityTestRule, I can't make it work: it compiles correctly, and at runtime, I get:
java.lang.Exception: The @Rule 'mActivityRule' must be public.
at org.junit.internal.runners.rules.RuleFieldValidator.addError(RuleFieldValidator.java:90)
at org.junit.internal.runners.rules.RuleFieldValidator.validatePublic(RuleFieldValidator.java:67)
at org.junit.internal.runners.rules.RuleFieldValidator.validateField(RuleFieldValidator.java:55)
at org.junit.internal.runners.rules.RuleFieldValidator.validate(RuleFieldValidator.java:50)
at org.junit.runners.BlockJUnit4ClassRunner.validateFields(BlockJUnit4ClassRunner.java:170)
at org.junit.runners.BlockJUnit4ClassRunner.collectInitializationErrors(BlockJUnit4ClassRunner.java:103)
at org.junit.runners.ParentRunner.validate(ParentRunner.java:344)
at org.junit.runners.ParentRunner.<init>(ParentRunner.java:74)
at org.junit.runners.BlockJUnit4ClassRunner.<init>(BlockJUnit4ClassRunner.java:55)
at android.support.test.internal.runner.junit4.AndroidJUnit4ClassRunner.<init>(AndroidJUnit4ClassRunner.java:38)
at android.support.test.runner.AndroidJUnit4.<init>(AndroidJUnit4.java:36)
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
at android.support.test.internal.runner.junit4.AndroidAnnotatedBuilder.buildAndroidRunner(AndroidAnnotatedBuilder.java:57)
at android.support.test.internal.runner.junit4.AndroidAnnotatedBuilder.runnerForClass(AndroidAnnotatedBuilder.java:45)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:29)
at org.junit.runner.Computer.getRunner(Computer.java:38)
at org.junit.runner.Computer$1.runnerForClass(Computer.java:29)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57)
at org.junit.runners.model.RunnerBuilder.runners(RunnerBuilder.java:98)
at org.junit.runners.model.RunnerBuilder.runners(RunnerBuilder.java:84)
at org.junit.runners.Suite.<init>(Suite.java:79)
at org.junit.runner.Computer.getSuite(Computer.java:26)
at android.support.test.internal.runner.TestRequestBuilder.classes(TestRequestBuilder.java:691)
at android.support.test.internal.runner.TestRequestBuilder.build(TestRequestBuilder.java:654)
at android.support.test.runner.AndroidJUnitRunner.buildRequest(AndroidJUnitRunner.java:329)
at android.support.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:226)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1584)
Here is how I declared mActivityRule:
RunWith(javaClass<AndroidJUnit4>())
LargeTest
public class RadisTest {
Rule
public val mActivityRule: ActivityTestRule<MainActivity> = ActivityTestRule(javaClass<MainActivity>())
...
}
It is already public :/
",https://stackoverflow.com/questions/29945087/kotlin-and-new-activitytestrule-the-rule-must-be-public,321,54721.0,6.0,,,2015-04-29 13:22:12,2023-09-12 15:31:53,2019-05-05 15:04:52,,,android;testing;android-espresso;kotlin,Geobomatic,6089,600351,registered,true,32827600,,CC BY-SA 4.0,,3226,3118,2,0,0,4,true,false,false,true,true,true,58,10,false,0.11,0.0059,4224,2015,4,13,Wednesday,false,false,false,false,false,false,false
38250022,What does 'by' keyword do in Kotlin?,"While developing for android I sometimes come across something that looks like this:
var someModel: someViewModel by notNullAndObservable { vm ->
...
}
I don't understand what the significance of the by keyword is.
",https://stackoverflow.com/questions/38250022/what-does-by-keyword-do-in-kotlin,317,110253.0,4.0,,,2016-07-07 15:52:44,2025-05-15 00:35:27,2025-05-15 00:35:27,,,kotlin;delegates;keyword,Mark,11338,5781737,registered,true,38250239,,CC BY-SA 4.0,2024-03-31 13:40:11,274,223,2,0,0,3,true,false,false,true,true,true,44,7,true,0.036,0.0029,3789,2016,7,15,Thursday,false,false,false,false,false,false,false
49956051,Warning "Kotlin plugin version is not the same as library version" (but it is!),"I have an Android studio project in which I have added a Java library module, which I call core. My three Gradle build files look like this.
project/build.gradle
buildscript {
ext.kotlin_version = '1.2.40'
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
classpath ""org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version""
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
core/build.gradle
apply plugin: 'java-library'
apply plugin: 'kotlin'
dependencies {
implementation ""org.jetbrains.kotlin:kotlin-stdlib-jdk7""
...
}
app/build.gradle
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android { ... }
dependencies {
implementation project(':core')
implementation ""org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version""
implementation 'com.android.support.constraint:constraint-layout:1.1.0'
implementation 'com.android.support:appcompat-v7:27.1.1'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
testImplementation 'junit:junit:4.12'
}
The problem I have is that, in core/build.gradle, the kotlin-stdlib-jdk7 line is giving me the warning Plugin version (1.2.40) is not the same as library version (jdk7-1.2.40). I have tried changing it to:
implementation ""org.jetbrains.kotlin:kotlin-stdlib""
implementation ""org.jetbrains.kotlin:kotlin-stdlib:1.2.40""
implementation ""org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.2.40""
implementation ""org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version""
implementation ""org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version""
But the warning is still there. The build still runs successfully, and I know I can surpress the warning without any problems and ignore it, but I really want to know why this is happening and how I can get rid of it. I am using Android Studio 3.0.1. Does anyone know of a solution to this?
",https://stackoverflow.com/questions/49956051/warning-kotlin-plugin-version-is-not-the-same-as-library-version-but-it-is,310,111890.0,9.0,,,2018-04-21 13:04:56,2023-03-12 05:48:35,,,,android;android-studio;gradle;kotlin,Leo Aso,12573,1426469,registered,true,64988522,,CC BY-SA 3.0,,2568,2179,12,0,0,4,true,false,false,true,true,false,89,14,false,0.08,0.0028,3136,2018,4,13,Saturday,true,false,false,false,false,false,false
8077530,Android Get Current timestamp?,"I want to get the current timestamp like that : 1320917972
int time = (int) (System.currentTimeMillis());
Timestamp tsTemp = new Timestamp(time);
String ts = tsTemp.toString();
",https://stackoverflow.com/questions/8077530/android-get-current-timestamp,301,396462.0,14.0,,,2011-11-10 09:41:02,2023-11-25 14:33:52,2019-11-26 14:05:08,,,java;android;kotlin;timestamp;epoch,Rjaibi Mejdi,6888,524045,registered,true,25264666,,CC BY-SA 4.0,,228,180,1,0,0,5,true,false,false,true,true,true,30,4,true,0.035,0.0008,5490,2011,11,9,Thursday,false,false,false,true,false,false,false
45854994,Convert Kotlin Array to Java varargs,"How can I convert my Kotlin Array to a varargs Java String[]?
val angularRoutings =
arrayOf<String>(""/language"", ""/home"")
// this doesn't work
web.ignoring().antMatchers(angularRoutings)
How to pass an ArrayList to a varargs method parameter?
",https://stackoverflow.com/questions/45854994/convert-kotlin-array-to-java-varargs,300,129585.0,2.0,,,2017-08-24 07:01:50,2024-07-26 13:55:16,2019-02-24 18:02:57,,,java;kotlin;interop;kotlin-interop,robie2011,3948,2248405,registered,true,45855062,,CC BY-SA 4.0,,443,266,3,1,0,4,true,false,false,true,true,true,36,6,false,0.015,0.0023,3376,2017,8,7,Thursday,false,false,false,true,false,false,false
37873995,How to create empty constructor for data class in Kotlin Android,"I have 10+ variables declared in Kotlin data class, and I would like to create an empty constructor for it like how we typically do in Java.
Data class:
data class Activity(
var updated_on: String,
var tags: List<String>,
var description: String,
var user_id: List<Int>,
var status_id: Int,
var title: String,
var created_at: String,
var data: HashMap<*, *>,
var id: Int,
var counts: LinkedTreeMap<*, *>,
)
Expected usage:
val activity = Activity();
activity.title = "New Computer"
sendToServer(activity)
But the data class requires all arguments to be passed while creating a constructor. How can we simplify this like the Java POJO class constructor?
val activity = Activity(null,null,null,null,null,"New Computer",null,null,null,null)
sendToServer(activity)
",https://stackoverflow.com/questions/37873995/how-to-create-empty-constructor-for-data-class-in-kotlin-android,299,227988.0,8.0,,,2016-06-17 05:47:01,2022-10-02 12:19:34,2020-11-30 10:39:50,,,android;kotlin,Sai,15818,2102794,registered,true,37874665,,CC BY-SA 4.0,,950,850,3,0,0,2,true,false,false,true,true,true,64,11,false,0.035,0.0013,3809,2016,6,5,Friday,false,false,false,false,false,false,false
46226518,What is the difference between launch/join and async/await in Kotlin coroutines,"In the kotlinx.coroutines library you can start new coroutine using either launch (with join) or async (with await). What is the difference between them?
",https://stackoverflow.com/questions/46226518/what-is-the-difference-between-launch-join-and-async-await-in-kotlin-coroutines,291,95780.0,8.0,,,2017-09-14 19:02:59,2025-07-08 19:04:09,2019-03-19 07:46:50,,,asynchronous;kotlin;coroutine;kotlin-coroutines,Roman Elizarov,29158,1051598,registered,true,46226519,,CC BY-SA 4.0,,227,155,5,0,0,4,true,false,false,true,true,true,79,11,false,0.084,0.003,3355,2017,9,19,Thursday,false,false,false,false,false,false,false
43348623,How to call a function after delay in Kotlin?,"As the title, is there any way to call a function after delay (1 second for example) in Kotlin?
",https://stackoverflow.com/questions/43348623/how-to-call-a-function-after-delay-in-kotlin,289,360335.0,16.0,,,2017-04-11 14:19:17,2025-07-02 11:52:10,2017-04-11 14:33:12,,,android;kotlin,Nguyen Minh Binh,24579,523325,registered,true,43348715,,CC BY-SA 3.0,,116,96,1,0,0,2,true,false,false,true,true,true,45,9,true,0.044,0.0008,3511,2017,4,14,Tuesday,false,false,false,false,false,false,false
6029495,How can I generate random number in specific range in Android?,"I want to generate random number in a specific range. (Ex. Range Between 65 to 80)
I try as per below code, but it is not very use full. It also returns the value greater then max. value(greater then 80).
Random r = new Random();
int i1 = (r.nextInt(80) + 65);
How can I generate random number between a range?
",https://stackoverflow.com/questions/6029495/how-can-i-generate-random-number-in-specific-range-in-android,289,483776.0,2.0,,,2011-05-17 10:27:55,2023-09-12 10:44:58,2021-08-26 11:16:09,2020-01-31 06:51:00,Duplicate,java;android;kotlin;random,Mohit Kanada,16174,544512,registered,true,6029519,,,,357,312,1,0,0,4,true,true,false,true,true,true,62,11,true,0.004,0.0006,5667,2011,5,10,Tuesday,false,false,false,true,false,false,false
44493908,Setting text in EditText Kotlin,"I am trying to set text in a EditText but it says:
Type mismatch.
Required: Editable
Found: String
My code is as follow:
String name = ""Paramjeet""
val nametxt = findViewById (R.id.nametxt) as EditText
nametxt.text = name
Don't say to use setText because I am using kotlin, not Java.
",https://stackoverflow.com/questions/44493908/setting-text-in-edittext-kotlin,284,210177.0,15.0,,,2017-06-12 07:41:30,2023-03-13 03:59:03,2019-07-30 12:18:45,,,android;kotlin;android-edittext,Paramjeet Singh,3100,8134703,registered,true,44494105,,CC BY-SA 4.0,,373,291,3,0,0,3,true,false,false,true,true,true,31,5,false,0.071,0.0014,3449,2017,6,7,Monday,false,false,false,false,false,false,false
43848845,Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details,"Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details
build:gradle(Module:app)
buildscript {
repositories {
maven {
url 'https://jitpack.io'
url 'https://maven.fabric.io/public'
}
}
dependencies {
classpath 'io.fabric.tools:gradle:1.+'
}
}
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'io.fabric'
apply plugin: 'kotlin-android-extensions'
repositories {
maven { url 'https://maven.fabric.io/public' }
mavenCentral()
}
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
useLibrary 'org.apache.http.legacy'
lintOptions {
checkReleaseBuilds false
abortOnError false
}
defaultConfig {
applicationId "uxx.xx.xxe"
minSdkVersion 18
targetSdkVersion 25
versionCode 17
versionName "0.1.14"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
debuggable false
minifyEnabled true
shrinkResources true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
debug {
ext.enableCrashlytics = false
debuggable true
minifyEnabled true
shrinkResources true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
sourceSets {
main {
jniLibs.srcDirs = ['libs']
assets.srcDirs = ['src/main/assets', 'src/main/assets/']
res.srcDirs = ['src/main/res', 'src/main/assets/fonts']
}
}
dexOptions {
jumboMode true
javaMaxHeapSize "4g"
}
packagingOptions {
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/NOTICE'
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
exclude 'META-INF/ECLIPSE_.SF'
exclude 'META-INF/ECLIPSE_.RSA'
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile "com.android.support:cardview-v7:${rootProject.supportLibraryVersion}"
compile "com.google.android.gms:play-services-ads:${rootProject.googlePlayServicesVersion}"
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
compile 'org.igniterealtime.smack:smack-android-extensions:4.1.9'
compile 'org.igniterealtime.smack:smack-tcp:4.1.9'
compile 'org.igniterealtime.smack:smack-experimental:4.1.9'
testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.getkeepsafe.dexcount'
build:gradle(Project)
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = '1.1.2-2'
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.1'
classpath 'com.google.gms:google-services:3.0.0'
//visualize the method count
classpath 'com.getkeepsafe.dexcount:dexcount-gradle-plugin:0.6.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
allprojects {
repositories {
jcenter()
maven { url "https://jitpack.io" }
}
}
ext.googlePlayServicesVersion = '10.2.0'
ext.supportLibraryVersion = '25.3.1'
task clean(type: Delete) {
delete rootProject.buildDir
}
Solution Tried:
- Invalidate Caches/Restart
- Build -> Clean Project
- Update kotlin plugin, used lastest version of kotlin, google APIs.
EDIT
./gradlew build --stacktrace > logs.txt 2>logErrors.txt
logErrors.txt
* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:compileDebugKotlin'.
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:84)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:55)
at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:62)
at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:88)
at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:46)
at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:51)
at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.execute(DefaultTaskGraphExecuter.java:236)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.execute(DefaultTaskGraphExecuter.java:228)
at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:61)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:228)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:215)
at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:77)
at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:58)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:32)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:113)
at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:23)
at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:43)
at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:30)
at org.gradle.initialization.DefaultGradleLauncher$3.execute(DefaultGradleLauncher.java:196)
at org.gradle.initialization.DefaultGradleLauncher$3.execute(DefaultGradleLauncher.java:193)
at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:56)
at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:193)
at org.gradle.initialization.DefaultGradleLauncher.doBuild(Default",https://stackoverflow.com/questions/43848845/errorexecution-failed-for-task-appcompiledebugkotlin-compilation-error,281,599963.0,45.0,,,2017-05-08 13:21:57,2025-02-20 05:24:45,2020-10-26 06:47:15,,,android;kotlin;gradle;build;gradle-kotlin-dsl,Ankur_009,3790,1640009,registered,true,,,CC BY-SA 4.0,2019-07-29 16:25:11,13139,12907,5,0,0,5,false,false,false,true,true,true,115,13,false,0.075,0.0005,3484,2017,5,13,Monday,false,false,false,false,false,false,false
67448034,""Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.16"","The following error occurs when I tried to build the app:
C:/Users/Lenovo/.gradle/caches/transforms-2/files-2.1/32f0bb3e96b47cf79ece6482359b6ad2/jetified-kotlin-stdlib-jdk7-1.5.0.jar!/META-INF/kotlin-stdlib-jdk7.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.16
Is it about updating the module? Then how to update it?
",https://stackoverflow.com/questions/67448034/module-was-compiled-with-an-incompatible-version-of-kotlin-the-binary-version,281,464977.0,43.0,,,2021-05-08 13:21:36,2025-11-10 03:38:55,2023-04-14 09:55:22,,,android;android-studio;kotlin,Saheel Sapovadia,3529,14099703,registered,true,67816693,,CC BY-SA 4.0,2022-11-09 10:25:21,596,418,0,1,1,3,true,false,false,true,true,true,143,21,false,0.092,0.0006,2023,2021,5,13,Saturday,true,false,false,false,false,false,false
32935470,How to convert List to Map in Kotlin?,"For example I have a list of strings like:
val list = listOf(""a"", ""b"", ""c"", ""d"")
and I want to convert it to a map, where the strings are the keys.
I know I should use the .toMap() function, but I don't know how, and I haven't seen any examples of it.
",https://stackoverflow.com/questions/32935470/how-to-convert-list-to-map-in-kotlin,278,159058.0,6.0,,,2015-10-04 16:03:10,2019-10-16 19:08:59,2019-05-31 13:45:12,,,dictionary;kotlin,LordScone,3555,3757113,registered,true,32938733,,CC BY-SA 4.0,2018-07-04 05:32:14,314,256,2,0,0,2,true,false,false,true,true,true,37,8,true,0.038,0.0017,4066,2015,10,16,Sunday,true,false,false,false,false,false,false
44098780,How to check "instanceof " class in Kotlin?,"In Kotlin class, I have method parameter as object (See Kotlin doc here ) for class type T. As object I am passing different classes when I am calling method.
In Java we can able to compare class using instanceof of object which class it is.
So I want to check and compare at runtime which Class it is?
How can I check instanceof class in Kotlin?
",https://stackoverflow.com/questions/44098780/how-to-check-instanceof-class-in-kotlin,278,247368.0,9.0,,,2017-05-21 15:47:12,2023-09-24 06:33:43,2023-09-24 06:33:43,,,kotlin;kotlin-extension,pRaNaY,25480,2949612,registered,true,44098842,,CC BY-SA 4.0,,524,347,2,1,0,2,true,false,false,true,true,true,53,8,true,0.036,0.0011,3471,2017,5,15,Sunday,true,false,false,false,false,false,false
34541650,NullPointerException when trying to access views in a Kotlin fragment,"How to use Kotlin Android Extensions with Fragments?
If I use them inside onCreateView(), I get this NullPointerException exception:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'android.view.View android.view.View.findViewById(int)' on a
null object reference
Here is the fragment code:
package com.obaied.testrun.Fragment
import android.os.Bundle
import android.support.v4.app.Fragment
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.obaied.acaan.R
import kotlinx.android.synthetic.main.fragment_card_selector.*
public class CardSelectorFragment : Fragment() {
val TAG = javaClass.canonicalName
companion object {
fun newInstance(): CardSelectorFragment {
return CardSelectorFragment()
}
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
var rootView = inflater?.inflate(R.layout.fragment_card_selector, container, false)
btn_K.setOnClickListener { Log.d(TAG, ""onViewCreated(): hello world""); }
return rootView
}
}
`
",https://stackoverflow.com/questions/34541650/nullpointerexception-when-trying-to-access-views-in-a-kotlin-fragment,269,65504.0,9.0,,,2015-12-31 05:41:43,2019-08-16 07:32:09,2018-09-17 12:43:25,,,android;kotlin;kotlin-android-extensions,solidak,5121,3870025,registered,true,34543172,,CC BY-SA 4.0,,1293,1184,4,0,0,3,true,false,false,true,true,true,69,10,false,0.137,0.0041,3978,2015,12,5,Thursday,false,false,false,false,false,false,false
33428957,Kotlin : Public get private set var,"What is the correct way to define a var in kotlin that has a public getter and private (only internally modifiable) setter?
",https://stackoverflow.com/questions/33428957/kotlin-public-get-private-set-var,269,101767.0,2.0,,,2015-10-30 04:58:55,2025-02-26 08:21:50,,,,kotlin,Jasper Blues,28876,404201,registered,true,33430227,,CC BY-SA 3.0,,131,124,0,0,0,1,true,false,false,true,true,false,35,7,false,0.02,0.0026,4040,2015,10,4,Friday,false,false,false,false,false,false,false
46723729,Swift 'if let' statement equivalent in Kotlin,"In Kotlin is there an equivalent to the Swift code below?
if let a = b.val {
} else {
}
",https://stackoverflow.com/questions/46723729/swift-if-let-statement-equivalent-in-kotlin,268,171678.0,17.0,,,2017-10-13 06:25:58,2024-11-12 03:23:37,2020-09-17 15:03:11,,,kotlin,iadcialim24,4085,8258130,registered,true,46726337,,CC BY-SA 4.0,,122,91,1,0,0,1,true,false,false,true,true,true,53,7,false,0.099,0.0016,3326,2017,10,6,Friday,false,false,false,false,false,false,false
47531742,startForeground fail after upgrade to Android 8.1,"After upgrading my phone to 8.1 Developer Preview my background service no longer starts up properly.
In my long-running service I've implemented a startForeground method to start the ongoing notification which is called in on create.
@TargetApi(Build.VERSION_CODES.O)
private fun startForeground() {
// Safe call, handled by compat lib.
val notificationBuilder = NotificationCompat.Builder(this, DEFAULT_CHANNEL_ID)
val notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.build()
startForeground(101, notification)
}
Error message:
11-28 11:47:53.349 24704-24704/$PACKAGE_NAMEE/AndroidRuntime: FATAL EXCEPTION: main
Process: $PACKAGE_NAME, PID: 24704
android.app.RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=My channel pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x42 color=0x00000000 vis=PRIVATE)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1768)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
invalid channel for service notification, apparently my old channel the DEFAULT_CHANNEL_ID is no longer appropriate for API 27 I assume. What would be the proper channel? I've tried to look through the documentation
",https://stackoverflow.com/questions/47531742/startforeground-fail-after-upgrade-to-android-8-1,268,163592.0,13.0,,,2017-11-28 12:32:58,2023-08-10 13:48:56,2020-07-23 21:14:08,,,android;service;kotlin;android-notifications;background-service,Rawa,13998,1724097,registered,true,47533338,,CC BY-SA 4.0,,1848,1733,5,0,0,5,true,false,false,true,true,true,49,7,false,0.079,0.0016,3280,2017,11,12,Tuesday,false,false,false,false,false,false,false
53138172,How to implement switch-case statement in Kotlin,"How to implement equivalent of following Java switch statement code in Kotlin?
switch (5) {
case 1:
// Do code
break;
case 2:
// Do code
break;
case 3:
// Do code
break;
}
",https://stackoverflow.com/questions/53138172/how-to-implement-switch-case-statement-in-kotlin,262,336011.0,10.0,,,2018-11-04 05:58:58,2025-11-18 13:22:54,2020-04-30 20:25:42,,,kotlin;switch-statement,Mayur Dabhi,4016,8265484,registered,true,53138234,,CC BY-SA 4.0,,254,210,2,0,0,2,true,false,false,true,true,true,48,7,false,0.03,0.0008,2939,2018,11,5,Sunday,true,false,false,false,false,false,false
58680028,How to make "inappropriate blocking method call" appropriate?,"I am currently trying to leverage kotlin coroutines more. But I face a problem: when using moshi or okhttp inside these coroutines I get a warning:
""inappropriate blocking method call""
What is the best way to fix these? I really do not want to be inappropriate ;-)
",https://stackoverflow.com/questions/58680028/how-to-make-inappropriate-blocking-method-call-appropriate,262,105579.0,11.0,,,2019-11-03 12:11:39,2023-05-08 04:03:05,2019-11-27 09:51:20,,,kotlin;okhttp;kotlin-coroutines;moshi,ligi,39649,322642,registered,true,58684320,,CC BY-SA 4.0,,288,267,0,0,0,4,true,false,false,true,true,true,71,8,true,0.104,0.0025,2575,2019,11,12,Sunday,true,false,false,false,false,false,false
46846025,How to clone or copy a list in kotlin,"How to copy list in Kotlin?
I'm using
val selectedSeries = mutableListOf<String>()
selectedSeries.addAll(series)
Is there a easier way?
",https://stackoverflow.com/questions/46846025/how-to-clone-or-copy-a-list-in-kotlin,260,188660.0,15.0,,,2017-10-20 09:19:31,2023-01-22 07:13:17,2018-12-31 10:55:47,,,list;copy;kotlin,Adolf Dsilva,14660,1729085,registered,true,46846074,,CC BY-SA 4.0,,193,148,1,0,0,3,true,false,false,true,true,true,37,9,false,0.08,0.0014,3319,2017,10,9,Friday,false,false,false,false,false,false,false
69034879,How can I resolve the error "The minCompileSdk (31) specified in a dependency's AAR metadata" in native Java or Kotlin?,"The error message:
The minCompileSdk (31) specified in a dependency's AAR metadata
(META-INF/com/android/build/gradle/aar-metadata.properties) is greater
than this module's compileSdkVersion (android-30). Dependency:
androidx.core:core-ktx:1.7.0-alpha02.
AAR metadata file:
C:\Users\mohammad.zeeshan1.gradle\caches\transforms-2\files-2.1\a20beb0771f59a8ddbbb8d416ea06a9d\jetified-core-ktx-1.7.0-alpha02\META-INF\com\android\build\gradle\aar-metadata.properties.
",https://stackoverflow.com/questions/69034879/how-can-i-resolve-the-error-the-mincompilesdk-31-specified-in-a-dependencys,258,414137.0,8.0,,,2021-09-02 17:36:44,2022-05-14 12:10:46,2022-01-01 17:45:18,2021-09-23 15:08:14,Duplicate,java;android;kotlin;gradle,Mohammad Zeeshan,4731,8359705,registered,true,69043734,,,,517,465,0,0,0,4,true,true,false,true,true,true,133,20,true,0.019,0.0006,1906,2021,9,17,Thursday,false,false,false,true,false,false,false
28294509,Accessing Kotlin extension functions from Java,"Is it possible to access extension functions from Java code?
I defined the extension function in a Kotlin file.
package com.test.extensions
import com.test.model.MyModel
/**
*
*/
public fun MyModel.bar(): Int {
return this.name.length()
}
Where MyModel is a (generated) java class.
Now, I wanted to access it in my normal java code:
MyModel model = new MyModel();
model.bar();
However, that doesn't work. The IDE won't recognize the bar() method and compilation fails.
What does work is using with a static function from kotlin:
public fun bar(): Int {
return 2*2
}
by using import com.test.extensions.ExtensionsPackage so my IDE seems to be configured correctly.
I searched through the whole Java-interop file from the kotlin docs and also googled a lot, but I couldn't find it.
What am I doing wrong? Is this even possible?
",https://stackoverflow.com/questions/28294509/accessing-kotlin-extension-functions-from-java,258,96100.0,9.0,,,2015-02-03 08:37:56,2021-02-27 18:32:08,2015-02-03 08:55:46,,,java;kotlin;extension-function,Lovis,10157,1096567,registered,true,28364983,,CC BY-SA 3.0,,1035,851,6,0,0,3,true,false,false,true,true,true,46,6,false,0.094,0.0027,4309,2015,2,8,Tuesday,false,false,false,true,false,false,false
68554294,android:exported needs to be explicitly specified for <activity>. Apps targeting Android 12 and higher are required to specify,"After upgrading to android 12, the application is not compiling. It shows
"Manifest merger failed with multiple errors, see logs"
Error showing in Merged manifest:
Merging Errors:
Error: android:exported needs to be explicitly specified for . Apps targeting Android 12 and higher are required to specify an explicit value for android:exported when the corresponding component has an intent filter defined. See https://developer.android.com/guide/topics/manifest/activity-element#exported for details. main manifest (this file)
I have set all the activity with android:exported="false". But it is still showing this issue.
My manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="eu.siacs.conversations">
<uses-sdk tools:overrideLibrary="net.ypresto.androidtranscoder" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission
android:name="android.permission.READ_PHONE_STATE"
android:maxSdkVersion="22" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-feature
android:name="android.hardware.location"
android:required="false" />
<uses-feature
android:name="android.hardware.location.gps"
android:required="false" />
<uses-feature
android:name="android.hardware.location.network"
android:required="false" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-feature
android:name="android.hardware.camera"
android:required="false" />
<uses-feature
android:name="android.hardware.camera.autofocus"
android:required="false" />
<uses-feature
android:name="android.hardware.microphone"
android:required="false" />
<application
android:name=".Application"
android:allowBackup="false"
android:allowClearUserData="true"
android:appCategory="social"
android:hardwareAccelerated="true"
android:icon="@mipmap/ic_app_launch"
android:label="@string/app_name"
android:largeHeap="true"
android:networkSecurityConfig="@xml/network_security_configuration"
android:requestLegacyExternalStorage="true"
android:roundIcon="@mipmap/ic_app_launch_round"
android:theme="@style/ConversationsTheme"
android:usesCleartextTraffic="true"
android:windowSoftInputMode="adjustPan|adjustResize"
tools:replace="android:label"
tools:targetApi="q">
<activity
android:name=".ui.search.GroupSearchActivity"
android:exported="true" />
<activity
android:name=".ui.profileUpdating.FavouritesActivity"
android:exported="true" />
<activity
android:name=".ui.profileUpdating.NameActivity"
android:exported="true" />
<activity
android:name=".ui.CompulsoryUpdateActivity"
android:exported="true" />
<activity android:name=".ui.payments.doPayment.DoPaymentActivity"
android:exported="true" />
<activity android:name=".ui.individualList.IndividualListActivity"
android:exported="true" />
<activity android:name=".ui.payments.setPayment.SetPaymentActivity"
android:exported="true" />
<activity android:name=".ui.login.otpActivity.OTPActivity"
android:exported="true" />
<activity android:name=".ui.login.loginActivity.LoginActivity"
android:exported="true" />
<service android:name=".services.XmppConnectionService" android:exported="true" />
<receiver android:name=".services.EventReceiver"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.intent.action.ACTION_SHUTDOWN" />
<action android:name="android.media.RINGER_MODE_CHANGED" />
</intent-filter>
</receiver>
<activity
android:name=".ui.ShareLocationActivity"
android:label="@string/title_activity_share_location"
android:exported="true"/>
<activity
android:name=".ui.SearchActivity"
android:label="@string/search_messages"
android:exported="true" />
<activity
android:name=".ui.RecordingActivity"
android:configChanges="orientation|screenSize"
android:theme="@style/ConversationsTheme.Dialog"
android:exported="true" />
<activity
android:name=".ui.ShowLocationActivity"
android:label="@string/title_activity_show_location"
android:exported="true" />
<activity
android:name=".ui.SplashActivity"
android:theme="@style/SplashTheme"
android:exported="true">
<intent-filter>
",https://stackoverflow.com/questions/68554294/androidexported-needs-to-be-explicitly-specified-for-activity-apps-targeting,256,289123.0,39.0,,,2021-07-28 04:09:31,2025-05-23 10:20:54,2021-07-28 09:12:57,,,java;android;kotlin;android-manifest;android-12,Ashique Bava,2726,14280831,registered,true,68648841,,CC BY-SA 4.0,2022-11-22 09:07:42,32336,32132,5,0,0,5,true,false,false,true,true,true,132,18,false,0.135,0.0009,1942,2021,7,4,Wednesday,false,false,false,true,false,false,false
44239869,What's the Kotlin equivalent of Java's String[]?,"I see that Kotlin has ByteArray, ShortArray, IntArray, CharArray, DoubleArray, FloatArray, which are equivalent to byte[], short[], int[],char[], double[], float[] in Java.
Now I'm wondering, is there any StringArray equivalent to Java's String[]?
",https://stackoverflow.com/questions/44239869/whats-the-kotlin-equivalent-of-javas-string,254,223668.0,8.0,,,2017-05-29 10:10:12,2024-07-28 06:27:58,2020-09-22 05:38:56,,,java;kotlin,chancyWu,14523,1544790,registered,true,44239940,,CC BY-SA 4.0,,315,249,4,0,0,2,true,false,false,true,true,true,56,7,true,0.036,0.0011,3463,2017,5,10,Monday,false,false,false,true,false,false,false
58767733,The AsyncTask API is deprecated in Android 11. What are the alternatives?,"Google is deprecating Android AsyncTask API in Android 11 and suggesting to use java.util.concurrent instead. you can check out the commit here
*
* @deprecated Use the standard <code>java.util.concurrent</code> or
* <a href="https://developer.android.com/topic/libraries/architecture/coroutines">
* Kotlin concurrency utilities</a> instead.
*/
@Deprecated
public abstract class AsyncTask<Params, Progress, Result> {
If you’re maintaining an older codebase with asynchronous tasks in Android, you’re likely going to have to change it in future. My question is that what should be proper replacement of the code snippet shown below using java.util.concurrent. It is a static inner class of an Activity. I am looking for something that will work with minSdkVersion 16
private static class LongRunningTask extends AsyncTask<String, Void, MyPojo> {
private static final String TAG = MyActivity.LongRunningTask.class.getSimpleName();
private WeakReference<MyActivity> activityReference;
LongRunningTask(MyActivity context) {
activityReference = new WeakReference<>(context);
}
@Override
protected MyPojo doInBackground(String... params) {
// Some long running task
}
@Override
protected void onPostExecute(MyPojo data) {
MyActivity activity = activityReference.get();
activity.progressBar.setVisibility(View.GONE);
populateData(activity, data) ;
}
}
",https://stackoverflow.com/questions/58767733/the-asynctask-api-is-deprecated-in-android-11-what-are-the-alternatives,251,241121.0,19.0,,,2019-11-08 13:43:02,2024-09-03 18:48:32,2022-01-12 09:41:33,,,java;android;kotlin;android-asynctask;kotlin-coroutines,Zeeshan,12469,2032823,registered,true,58767934,,CC BY-SA 4.0,2020-12-21 12:25:13,1790,1581,5,1,0,5,true,false,false,true,true,true,73,12,true,0.079,0.001,2570,2019,11,13,Friday,false,false,false,true,false,false,false
72634225,onBackPressed() is deprecated. What is the alternative?,"I have upgraded targetSdkVersion and compileSdkVersion to 33.
I am now getting a warning telling me that onBackPressed is deprecated.
I see suggestions to use android.window.OnBackInvokedCallback or androidx.activity.OnBackPressedCallback to handle back navigation instead. Can anyone can help me use the updated method?
Example
Use Case
I use if (isTaskRoot) {} inside the onBackPressed() method to check whether the activity is the last one on the activity stack.
override fun onBackPressed() {
if (isTaskRoot) { // Check whether this activity is last on the activity stack. (Check whether this activity opened from a Push Notification.)
startActivity(Intent(mContext, Dashboard::class.java))
finish()
} else {
finishWithResultOK()
}
}
",https://stackoverflow.com/questions/72634225/onbackpressed-is-deprecated-what-is-the-alternative,249,185627.0,27.0,,,2022-06-15 15:42:10,2026-08-04 09:21:41,2023-07-21 11:44:31,,,android;kotlin;navigation;deprecation-warning;android-tiramisu,Rumit Patel,13267,2289835,registered,true,72634975,,CC BY-SA 4.0,,1478,776,5,5,1,5,true,false,false,true,true,true,55,7,true,0.145,0.0013,1620,2022,6,15,Wednesday,false,false,false,false,false,false,false
37913252,"Kotlin's List missing "add", "remove", Map missing "put", etc?","In Java we could do the following
public class TempClass {
List<Integer> myList = null;
void doSomething() {
myList = new ArrayList<>();
myList.add(10);
myList.remove(10);
}
}
But if we rewrite it to Kotlin directly as below
class TempClass {
var myList: List<Int>? = null
fun doSomething() {
myList = ArrayList<Int>()
myList!!.add(10)
myList!!.remove(10)
}
}
I got the error of not finding add and remove function from my List
I work around casting it to ArrayList, but that is odd needing to cast it, while in Java casting is not required. And that defeats the purpose of having the abstract class List
class TempClass {
var myList: List<Int>? = null
fun doSomething() {
myList = ArrayList<Int>()
(myList!! as ArrayList).add(10)
(myList!! as ArrayList).remove(10)
}
}
Is there a way for me to use List but not needing to cast it, like what could be done in Java?
",https://stackoverflow.com/questions/37913252/kotlins-list-missing-add-remove-map-missing-put-etc,249,186674.0,10.0,,,2016-06-20 00:30:48,2022-10-02 12:14:56,2019-09-15 21:44:12,,,collections;kotlin,Elye,61515,3286489,registered,true,37913264,,CC BY-SA 4.0,,1152,1019,5,0,0,2,true,false,false,true,true,true,96,9,true,0.054,0.0013,3806,2016,6,0,Monday,false,false,false,false,false,false,false
68344424,unrecognized Attribute name MODULE (class com.sun.tools.javac.util.SharedNameTable$NameImpl),"I received this build error having updated my native android project to Android S (Pre release of android 12).
Googling for the error threw up no valuable hits. One hit from Netbeans a few years back and some Xamarin problems.
The stack trace is below :
FAILURE: Build completed with 2 failures.
1: Task failed with an exception.
-----------
* What went wrong:
Execution failed for task ':dependencies:android:kaptDebugKotlin'.
> A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptWithoutKotlincTask$KaptExecutionWorkAction
> java.lang.reflect.InvocationTargetException (no error message)
* Try:
Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':dependencies:android:kaptDebugKotlin'.
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.lambda$executeIfValid$1(ExecuteActionsTaskExecuter.java:200)
at org.gradle.internal.Try$Failure.ifSuccessfulOrElse(Try.java:263)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeIfValid(ExecuteActionsTaskExecuter.java:198)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:179)
at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:109)
at org.gradle.api.internal.tasks.execution.FinalizePropertiesTaskExecuter.execute(FinalizePropertiesTaskExecuter.java:46)
at org.gradle.api.internal.tasks.execution.ResolveTaskExecutionModeExecuter.execute(ResolveTaskExecutionModeExecuter.java:62)
at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:57)
at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:56)
at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:36)
at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.executeTask(EventFiringTaskExecuter.java:77)
at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:55)
at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:52)
at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:200)
at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:195)
at org.gradle.internal.operations.DefaultBuildOperationRunner$3.execute(DefaultBuildOperationRunner.java:75)
at org.gradle.internal.operations.DefaultBuildOperationRunner$3.execute(DefaultBuildOperationRunner.java:68)
at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:153)
at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:68)
at org.gradle.internal.operations.DefaultBuildOperationRunner.call(DefaultBuildOperationRunner.java:62)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.lambda$call$2(DefaultBuildOperationExecutor.java:76)
at org.gradle.internal.operations.UnmanagedBuildOperationWrapper.callWithUnmanagedSupport(UnmanagedBuildOperationWrapper.java:54)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:76)
at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:52)
at org.gradle.execution.plan.LocalTaskNodeExecutor.execute(LocalTaskNodeExecutor.java:41)
at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:372)
at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:359)
at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:352)
at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:338)
at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.lambda$run$0(DefaultPlanExecutor.java:127)
at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.execute(DefaultPlanExecutor.java:191)
at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.executeNextNode(DefaultPlanExecutor.java:182)
at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.run(DefaultPlanExecutor.java:124)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
Caused by: org.gradle.workers.internal.DefaultWorkerExecutor$WorkExecutionException: A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptWithoutKotlincTask$KaptExecutionWorkAction
at org.gradle.workers.internal.DefaultWorkerExecutor$WorkItemExecution.waitForCompletion(DefaultWorkerExecutor.java:336)
at org.gradle.internal.work.DefaultAsyncWorkTracker.waitForItemsAndGatherFailures(DefaultAsyncWorkTracker.java:142)
at org.gradle.internal.work.DefaultAsyncWorkTracker.waitForItemsAndGatherFailures(DefaultAsyncWorkTracker.java:94)
at org.gradle.internal.work.DefaultAsyncWorkTracker.waitForAll(DefaultAsyncWorkTracker.java:80)
at org.gradle.internal.work.DefaultAsyncWorkTracker.waitForCompletion(DefaultAsyncWorkTracker.java:68)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$3.run(ExecuteActionsTaskExecuter.java:563)
at org.gradle.internal.operations.DefaultBuildOperationRunner$1.execute(DefaultBuildOperationRunner.java:29)
at org.gradle.internal.operations.DefaultBuildOperationRunner$1.execute(DefaultBuildOperationRunner.java:26)
at org.gradle.internal.operations.DefaultBuildOperationRunner$3.execute(DefaultBuildOperationRunner.java:75)
at org.gradle.internal.operations.DefaultBuildOperationRunner$3.execute(DefaultBuildOperationRunner.java:68)
at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:153)
at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:68)
at org.gradle.internal.operations.DefaultBuildOperationRunner.run(DefaultBuildOperationRunner.java:56)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.lambda$run$1(DefaultBuildOperationExecutor.java:71)
at org.gradle.internal.operations.UnmanagedBuildOperationWrapper.runWithUnmanagedSupport(UnmanagedBuildOperationWrapper.java:45)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:71)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:540)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:523)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.access$300(ExecuteActionsTaskExecuter.java:108)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$TaskExecution.executeWithPreviousOutputFiles(ExecuteActionsTaskExecuter.java:271)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$TaskExecution.execute(ExecuteActionsTaskExecuter.java:260)
at org.gradle.internal.execution.steps.ExecuteStep.lambda$execute$0(ExecuteStep.java:33)
at org.gradle.internal.execution.steps.ExecuteStep.execute(ExecuteStep.java:33)
",https://stackoverflow.com/questions/68344424/unrecognized-attribute-name-module-class-com-sun-tools-javac-util-sharednametab,245,148337.0,19.0,,,2021-07-12 08:46:44,2025-05-02 14:31:30,,,,java;android;kotlin;gradle,Chris,5361,2199001,registered,true,69250502,,CC BY-SA 4.0,,20949,20897,1,0,0,4,true,false,false,true,true,false,92,6,false,0.128,0.0017,1958,2021,7,8,Monday,false,false,false,true,false,false,false
44167111,Android Room - simple select query - Cannot access database on the main thread,"I am trying a sample with Room Persistence Library.
I created an Entity:
@Entity
public class Agent {
@PrimaryKey
public String guid;
public String name;
public String email;
public String password;
public String phone;
public String licence;
}
Created a DAO class:
@Dao
public interface AgentDao {
@Query(""SELECT COUNT(*) FROM Agent where email = :email OR phone = :phone OR licence = :licence"")
int agentsCount(String email, String phone, String licence);
@Insert
void insertAgent(Agent agent);
}
Created the Database class:
@Database(entities = {Agent.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
public abstract AgentDao agentDao();
}
Exposed database using below subclass in Kotlin:
class MyApp : Application() {
companion object DatabaseSetup {
var database: AppDatabase? = null
}
override fun onCreate() {
super.onCreate()
MyApp.database = Room.databaseBuilder(this, AppDatabase::class.java, ""MyDatabase"").build()
}
}
Implemented below function in my activity:
void signUpAction(View view) {
String email = editTextEmail.getText().toString();
String phone = editTextPhone.getText().toString();
String license = editTextLicence.getText().toString();
AgentDao agentDao = MyApp.DatabaseSetup.getDatabase().agentDao();
//1: Check if agent already exists
int agentsCount = agentDao.agentsCount(email, phone, license);
if (agentsCount > 0) {
//2: If it already exists then prompt user
Toast.makeText(this, ""Agent already exists!"", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(this, ""Agent does not exist! Hurray :)"", Toast.LENGTH_LONG).show();
onBackPressed();
}
}
Unfortunately on execution of above method it crashes with below stack trace:
FATAL EXCEPTION: main
Process: com.example.me.MyApp, PID: 31592
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5612)
at android.view.View$PerformClick.run(View.java:22288)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5612)
at android.view.View$PerformClick.run(View.java:22288)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
Caused by: java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long periods of time.
at android.arch.persistence.room.RoomDatabase.assertNotMainThread(RoomDatabase.java:137)
at android.arch.persistence.room.RoomDatabase.query(RoomDatabase.java:165)
at com.example.me.MyApp.RoomDb.Dao.AgentDao_Impl.agentsCount(AgentDao_Impl.java:94)
at com.example.me.MyApp.View.SignUpActivity.signUpAction(SignUpActivity.java:58)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5612)
at android.view.View$PerformClick.run(View.java:22288)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
Seems like that problem is related to execution of db operation on main thread. However the sample test code provided in above link does not run on a separate thread:
@Test
public void writeUserAndReadInList() throws Exception {
User user = TestUtil.createUser(3);
user.setName(""george"");
mUserDao.insert(user);
List<User> byName = mUserDao.findUsersByName(""george"");
assertThat(byName.get(0), equalTo(user));
}
Am I missing anything over here? How can I make it execute without crash? Please suggest.
",https://stackoverflow.com/questions/44167111/android-room-simple-select-query-cannot-access-database-on-the-main-thread,238,270392.0,24.0,,,2017-05-24 19:36:33,2023-04-25 16:05:55,2017-05-25 04:24:23,,,android;crash;kotlin;android-studio-3.0;android-room,Devarshi,16796,217586,registered,true,44167951,,CC BY-SA 3.0,,5644,5320,7,1,0,5,true,false,false,true,true,true,78,14,false,0.089,0.0009,3468,2017,5,19,Wednesday,false,false,false,false,false,false,false
41928803,How to parse JSON in Kotlin?,"I'm receiving a quite deep JSON object string from a service which I must parse to a JSON object and then map it to classes.
How can I transform a JSON string to object in Kotlin?
After that the mapping to the respective classes, I was using StdDeserializer from Jackson. The problem arises at the moment the object had properties that also had to be deserialized into classes. I was not able to get the object mapper, at least I didn't know how, inside another deserializer.
Preferably, natively, I'm trying to reduce the number of dependencies I need so if the answer is only for JSON manipulation and parsing it'd be enough.
",https://stackoverflow.com/questions/41928803/how-to-parse-json-in-kotlin,238,559073.0,17.0,,,2017-01-30 03:56:48,2024-02-14 13:25:55,2021-08-11 23:31:43,,,java;json;kotlin,AJ_1310,3443,3243124,registered,true,41929124,,CC BY-SA 4.0,,656,628,0,0,0,3,true,false,false,true,true,true,28,6,true,0.03,0.0004,3582,2017,1,3,Monday,false,false,false,true,false,false,false
45977011,"Example of when should we use run, let, apply, also and with on Kotlin","I wish to have a good example for each function run, let, apply, also, with
I have read medium.com : The difference between Kotlin’s functions: ‘let’, ‘apply’, ‘with’, ‘run’ and ‘also’ but still lack of an example
",https://stackoverflow.com/questions/45977011/example-of-when-should-we-use-run-let-apply-also-and-with-on-kotlin,237,89322.0,7.0,,,2017-08-31 08:40:35,2024-10-20 21:13:40,2024-10-20 21:07:29,,,kotlin,UmAnusorn,11424,1025935,registered,true,45977254,,CC BY-SA 4.0,,435,214,5,1,0,1,true,false,false,true,true,true,70,14,false,0.078,0.0027,3369,2017,8,8,Thursday,false,false,false,false,false,false,false
43826699,Single exclamation mark in Kotlin,"What does a single exclamation mark mean in Kotlin? I've seen it a few times especially when using Java APIs. But I couldn't find it in the documentation nor on StackOverflow.
",https://stackoverflow.com/questions/43826699/single-exclamation-mark-in-kotlin,233,72714.0,7.0,,,2017-05-07 00:36:27,2021-10-04 22:23:30,2017-05-07 00:40:05,,,kotlin,Mibac,9548,3533380,registered,true,43826700,,CC BY-SA 3.0,,183,176,0,0,0,1,true,false,false,true,true,true,33,5,false,0.096,0.0032,3485,2017,5,0,Sunday,true,false,false,false,false,false,false
36140791,How to implement Builder pattern in Kotlin?,"Hi I am a newbie in the Kotlin world. I like what I see so far and started to think to convert some of our libraries we use in our application from Java to Kotlin.
These libraries are full of Pojos with setters, getters and Builder classes. Now I have googled to find what is the best way to implement Builders in Kotlin but no success.
2nd Update: The question is how to write a Builder design-pattern for a simple pojo with some parameters in Kotlin? The code below is my attempt by writing java code and then using the eclipse-kotlin-plugin to convert to Kotlin.
class Car private constructor(builder:Car.Builder) {
var model:String? = null
var year:Int = 0
init {
this.model = builder.model
this.year = builder.year
}
companion object Builder {
var model:String? = null
private set
var year:Int = 0
private set
fun model(model:String):Builder {
this.model = model
return this
}
fun year(year:Int):Builder {
this.year = year
return this
}
fun build():Car {
val car = Car(this)
return car
}
}
}
",https://stackoverflow.com/questions/36140791/how-to-implement-builder-pattern-in-kotlin,232,153794.0,18.0,,,2016-03-21 20:19:55,2023-10-18 03:31:02,2016-03-22 13:48:50,,,design-patterns;kotlin,Keyhan,2539,2423030,registered,true,36150989,,CC BY-SA 3.0,,1240,1195,1,0,0,2,true,false,false,true,true,true,43,7,true,0.117,0.0015,3897,2016,3,20,Monday,false,false,false,false,false,false,false
51060762,IllegalArgumentException: navigation destination xxx is unknown to this NavController,"I am having an issue with the new Android Navigation Architecture component when I try to navigate from one Fragment to another, I get this weird error:
java.lang.IllegalArgumentException: navigation destination XXX
is unknown to this NavController
Every other navigation works fine except this particular one.
I use findNavController() function of Fragment to get access to the NavController.
Any help will be appreciated.
",https://stackoverflow.com/questions/51060762/illegalargumentexception-navigation-destination-xxx-is-unknown-to-this-navcontr,231,124043.0,42.0,,,2018-06-27 10:42:37,2024-09-24 01:20:54,2021-03-04 06:28:07,,,android;kotlin;android-architecture-navigation;android-navigation;android-jetpack-navigation,Jerry Okafor,4172,5702219,registered,true,,,CC BY-SA 4.0,2021-05-09 20:02:12,520,425,3,0,0,5,false,false,false,true,true,true,85,9,false,0.339,0.0019,3069,2018,6,10,Wednesday,false,false,false,false,false,false,false
19519468,How to convert String to Long in Kotlin?,"So, due to lack of methods like Long.valueOf(String s) I am stuck.
How to convert String to Long in Kotlin?
",https://stackoverflow.com/questions/19519468/how-to-convert-string-to-long-in-kotlin,231,154807.0,12.0,,,2013-10-22 13:36:00,2023-09-24 06:24:41,2023-09-24 06:24:41,,,kotlin;string-parsing,Jerome,2487,1806224,registered,true,45835140,,CC BY-SA 4.0,,161,108,3,0,0,2,true,false,false,true,true,true,40,8,true,0.078,0.0015,4778,2013,10,13,Tuesday,false,false,false,false,false,false,false
51902629,How to allow all Network connection types HTTP and HTTPS in Android (9) Pie?,"From Android 9 Pie now, requests without encryption will never work. And by default, the System will expect you to use TLS by default.You can read this feature here So if you only make requests via HTTPS you are safe. But what about apps that make requests through different sites, for instance, browser-like apps.
How can I enable requests to all types of connections HTTP and HTTPS in Android 9 Pie?
",https://stackoverflow.com/questions/51902629/how-to-allow-all-network-connection-types-http-and-https-in-android-9-pie,230,282822.0,11.0,,,2018-08-17 20:44:47,2023-12-14 11:32:01,2019-03-05 21:52:23,,,java;android;kotlin;android-9.0-pie;android-network-security-config,Xenolion,12821,6740698,registered,true,51902630,,CC BY-SA 4.0,2019-06-08 16:19:08,529,403,0,1,0,5,true,false,false,true,true,true,76,14,true,0.039,0.0008,3018,2018,8,20,Friday,false,false,false,true,false,false,false
58743541,How to get Context in Jetpack Compose,"I am trying to show a Toast message when I click on the item, but how do I get the context to pass the Toast class?
fun createListItem(itemIndex: Int) {
Padding(left = 8.dp, right = 8.dp, top = 8.dp, bottom = 8.dp) {
FlexRow(crossAxisAlignment = CrossAxisAlignment.Center) {
expanded(1.0f) {
Text("Item $itemIndex")
}
inflexible {
Button(
"Button $itemIndex",
style = ContainedButtonStyle(),
onClick = {
Toast.makeText(
this@MainActivity,
"Item name $itemIndex",
Toast.LENGTH_SHORT
).show()
})
}
}
}
}
",https://stackoverflow.com/questions/58743541/how-to-get-context-in-jetpack-compose,227,160278.0,13.0,,,2019-11-07 07:05:20,2025-06-20 12:26:43,2025-03-03 06:59:48,,,android;kotlin;android-jetpack;android-jetpack-compose,Mr. Tayyab MuGhal,2441,7155849,registered,true,58834244,,CC BY-SA 4.0,2022-10-09 11:54:42,906,849,3,0,0,4,true,false,false,true,true,true,37,7,false,0.081,0.0014,2571,2019,11,7,Thursday,false,false,false,false,false,false,false
48253107,What does ?: do in Kotlin? (Elvis Operator),"I can't figure out what ?: does in for example this case
val list = mutableList ?: mutableListOf()
and why can it be modified to this
val list = if (mutableList != null) mutableList else mutableListOf()
",https://stackoverflow.com/questions/48253107/what-does-do-in-kotlin-elvis-operator,227,286069.0,11.0,,,2018-01-14 19:02:06,2023-10-31 01:39:51,2019-02-27 15:03:05,,,kotlin,Jorge,2355,9206630,registered,true,48254829,,CC BY-SA 4.0,,286,211,3,0,0,1,true,false,false,true,true,true,43,8,false,0.038,0.0008,3233,2018,1,19,Sunday,true,false,false,false,false,false,false
34416869,Idiomatic way of logging in Kotlin,"Kotlin doesn't have the same notion of static fields as used in Java. In Java, the generally accepted way of doing logging is:
public class Foo {
private static final Logger LOG = LoggerFactory.getLogger(Foo.class);
}
Question is what is the idiomatic way of performing logging in Kotlin?
",https://stackoverflow.com/questions/34416869/idiomatic-way-of-logging-in-kotlin,222,87650.0,17.0,,,2015-12-22 13:20:33,2024-11-28 12:59:06,2017-07-15 06:32:33,2023-10-20 07:57:05,Opinion-based,kotlin;kotlin-logging,mchlstckl,3542,544454,registered,true,34462577,,,,351,296,1,0,0,2,true,true,false,true,true,true,34,6,false,0.194,0.0025,3987,2015,12,13,Tuesday,false,false,false,false,false,false,false
34642254,What Java 8 Stream.collect equivalents are available in the standard Kotlin library?,"In Java 8, there is Stream.collect which allows aggregations on collections. In Kotlin, this does not exist in the same way, other than maybe as a collection of extension functions in the stdlib. But it isn't clear what the equivalences are for different use cases.
For example, at the top of the JavaDoc for Collectors are examples written for Java 8, and when porting them to Kolin you can't use the Java 8 classes when on a different JDK version, so likely they should be written differently.
In terms of resources online showing examples of Kotlin collections, they are typically trivial and don't really compare to the same use cases. What are good examples that really match the cases such as documented for Java 8 Stream.collect? The list there is:
- Accumulate names into a List
- Accumulate names into a TreeSet
- Convert elements to strings and concatenate them, separated by commas
- Compute sum of salaries of employee
- Group employees by department
- Compute sum of salaries by department
- Partition students into passing and failing
With details in the JavaDoc linked above.
Note: this question is intentionally written and answered by the author (Self-Answered Questions), so that the idiomatic answers to commonly asked Kotlin topics are present in SO. Also to clarify some really old answers written for alphas of Kotlin that are not accurate for current-day Kotlin.
",https://stackoverflow.com/questions/34642254/what-java-8-stream-collect-equivalents-are-available-in-the-standard-kotlin-libr,220,65527.0,4.0,,,2016-01-06 20:34:35,2023-02-05 16:08:32,2019-03-07 13:47:11,,,java;kotlin;collections;java-8;java-stream,Jayson Minard,86376,3679676,registered,true,34642255,,CC BY-SA 4.0,,1885,1387,3,3,0,5,true,false,false,true,true,true,84,12,true,0.061,0.0034,3972,2016,1,20,Wednesday,false,false,false,true,false,false,false
44429419,"Difference between fold and reduce in Kotlin, When to use which?","I am pretty confused with both functions fold() and reduce() in Kotlin, can anyone give me a concrete example that distinguishes both of them?
",https://stackoverflow.com/questions/44429419/difference-between-fold-and-reduce-in-kotlin-when-to-use-which,218,103309.0,7.0,,,2017-06-08 07:35:09,2023-03-21 19:15:38,2021-08-19 13:05:56,,,kotlin;reduce;fold,TapanHP,6249,5476209,registered,true,44429568,,CC BY-SA 4.0,,176,143,2,0,0,3,true,false,false,true,true,true,64,11,true,0.068,0.0021,3453,2017,6,7,Thursday,false,false,false,false,false,false,false
40138923,Difference between "*" and "Any" in Kotlin generics,"I am not sure I fully understand the difference between SomeGeneric<*> and SomeGeneric<Any>. I think * represents anything (wild card) and Any represents the object which ALL objects inherit from. So it seems they should be the same, but are they?
",https://stackoverflow.com/questions/40138923/difference-between-and-any-in-kotlin-generics,218,53843.0,4.0,,,2016-10-19 18:24:27,2022-12-24 22:46:14,2020-02-06 13:51:54,,,generics;kotlin,Wheel Builder,3825,3439919,registered,true,40139892,,CC BY-SA 4.0,,338,262,4,0,0,2,true,false,false,true,true,true,71,8,false,0.074,0.004,3685,2016,10,18,Wednesday,false,false,false,false,false,false,false
70919127,Your project requires a newer version of the Kotlin Gradle plugin. (Android Studio),"I've just updated my flutter project packages to be null-safety compliant and now Android Studio wants me to update my project to use the latest version of Kotling Gradle Plugin. Can't see where to change this though. I have tried to change "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" into "org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.6.10" but this has no effect.
My build.grade-file looks like this:
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}
def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}
def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
flutterVersionCode = '1'
}
def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
flutterVersionName = '1.0'
}
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
def keystoreProperties = new Properties()
def keystorePropertiesFile = rootProject.file('key.properties')
if (keystorePropertiesFile.exists()) {
keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
}
android {
compileSdkVersion 31
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
lintOptions {
disable 'InvalidPackage'
}
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "*********"
minSdkVersion 30
targetSdkVersion 30
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
signingConfigs {
release {
keyAlias keystoreProperties['keyAlias']
keyPassword keystoreProperties['keyPassword']
storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null
storePassword keystoreProperties['storePassword']
}
}
buildTypes {
release {
signingConfig signingConfigs.release
}
}
}
flutter {
source '../..'
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
implementation 'com.google.firebase:firebase-analytics:17.2.2'
}
apply plugin: 'com.google.gms.google-services'
Build output:
BUILD FAILED in 8s
[!] Your project requires a newer version of the Kotlin Gradle plugin.
Find the latest version on https://kotlinlang.org/docs/gradle.html#plugin-and-versions, then update project/android/build.gradle:
ext.kotlin_version = '<latest-version>'
Exception: Gradle task assembleDebug failed with exit code 1
",https://stackoverflow.com/questions/70919127/your-project-requires-a-newer-version-of-the-kotlin-gradle-plugin-android-stud,217,375645.0,28.0,,,2022-01-30 21:33:24,2025-07-11 06:18:16,,,,flutter;android-studio;kotlin;gradle-kotlin-dsl,jeffmayn,2677,9723049,registered,true,70919344,,CC BY-SA 4.0,2022-03-02 06:06:20,3464,3356,5,0,0,4,true,false,false,true,true,false,83,13,false,0.075,0.0006,1756,2022,1,21,Sunday,true,false,false,false,false,false,false
26969800,Try-with-resources in Kotlin,"When I tried to write an equivalent of a Java try-with-resources statement in Kotlin, it didn't work for me.
I tried different variations of the following:
try (writer = OutputStreamWriter(r.getOutputStream())) {
// ...
}
But neither works. Does anyone know what should be used instead?
Apparently Kotlin grammar doesn't include such a construct, but maybe I'm missing something. It defines the grammar for a try block as follows:
try : "try" block catchBlock* finallyBlock?;
",https://stackoverflow.com/questions/26969800/try-with-resources-in-kotlin,213,67881.0,5.0,,,2014-11-17 09:48:24,2022-06-03 11:31:57,2022-05-15 13:23:38,,,kotlin;try-with-resources,Alex,3136,769097,registered,true,26979481,,CC BY-SA 4.0,,789,492,4,2,0,2,true,false,false,true,true,true,28,3,false,0.074,0.0031,4387,2014,11,9,Monday,false,false,false,false,false,false,false
63875411,"Type 'State<List<User>?>' has no method 'getValue(Nothing?, KProperty<*>)' and thus it cannot serve as a delegate","I'm trying to get a value from LiveData with observeAsState in jetpack compose, but I get a weird error
Type 'State<List?>' has no method 'getValue(Nothing?,
KProperty<*>)' and thus it cannot serve as a delegate
Code
@Composable
fun UserScreen(userViewModel:UserViewModel){
val items: List<User> by userViewModel.fetchUserList.observeAsState()
UserList(userList = items)
}
ViewModel
class UserViewModel: ViewModel() {
private val dataSource = UserDataSource()
val fetchUserList = liveData {
emit(dataSource.dummyUserList)
}
}
",https://stackoverflow.com/questions/63875411/type-statelistuser-has-no-method-getvaluenothing-kproperty-and-t,211,71021.0,13.0,,,2020-09-13 20:45:58,2024-11-21 06:30:19,,,,android;kotlin;android-jetpack;android-jetpack-compose,SNM,6995,10870164,registered,true,63877349,,CC BY-SA 4.0,,833,578,2,1,1,4,true,false,false,true,true,false,147,15,false,0.183,0.003,2260,2020,9,20,Sunday,true,false,false,false,false,false,false
28210188,Static extension methods in Kotlin,"How do you define a static extension method in Kotlin? Is this even possible? I currently have an extension method as shown below.
public fun Uber.doMagic(context: Context) {
// ...
}
The above extension can be invoked on an instance.
uberInstance.doMagic(context) // Instance method
but how do I make it static method like shown below.
Uber.doMagic(context) // Static or class method
",https://stackoverflow.com/questions/28210188/static-extension-methods-in-kotlin,211,81603.0,10.0,,,2015-01-29 08:35:24,2026-02-26 15:05:51,2017-10-05 12:33:26,,,static-methods;kotlin,Ragunath Jawahar,19833,421372,registered,true,33853233,,CC BY-SA 3.0,,498,405,3,0,0,2,true,false,false,true,true,true,34,5,false,0.123,0.0026,4314,2015,1,8,Thursday,false,false,false,false,false,false,false
68473542,MediaSessionCompat:Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent,"I'm trying to update my application to Android SDK 31 but I'm having an issue with MediaSessionCompat.
I have a MediaService that extends the MediaBrowserServiceCompat() and in method onCreate of that service I initialise the MediaSessionCompat.
override fun onCreate() {
super.onCreate()
mediaSession = MediaSessionCompat(this, TAG).apply {
setCallback(mediaSessionCallback)
isActive = true
}
...
But I'm having the following error
java.lang.RuntimeException: Unable to create service com.radio.core.service.MediaService: java.lang.IllegalArgumentException: com.xxx.xxx: Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.
Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles.
at android.app.ActivityThread.handleCreateService(ActivityThread.java:4498)
at android.app.ActivityThread.access$1500(ActivityThread.java:250)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2064)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7829)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:982)
Caused by: java.lang.IllegalArgumentException: com.xxx.xxx: Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.
Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles.
at android.app.PendingIntent.checkFlags(PendingIntent.java:375)
at android.app.PendingIntent.getBroadcastAsUser(PendingIntent.java:645)
at android.app.PendingIntent.getBroadcast(PendingIntent.java:632)
at android.support.v4.media.session.MediaSessionCompat.<init>(MediaSessionCompat.java:567)
at android.support.v4.media.session.MediaSessionCompat.<init>(MediaSessionCompat.java:537)
at android.support.v4.media.session.MediaSessionCompat.<init>(MediaSessionCompat.java:501)
at android.support.v4.media.session.MediaSessionCompat.<init>(MediaSessionCompat.java:475)
at com.radio.core.service.MediaService.onCreate(MediaService.kt:63)
at android.app.ActivityThread.handleCreateService(ActivityThread.java:4485)
... 9 more
I'm using the most recent version of media library ("androidx.media:media:1.4.0") that is able to handle the this requirement from the Andriod "S"". As it's possible to see in the MediaSessionCompact.java class.
// TODO(b/182513352): Use PendingIntent.FLAG_MUTABLE instead from S.
/**
* @hide
*/
@RestrictTo(LIBRARY)
public static final int PENDING_INTENT_FLAG_MUTABLE =
Build.VERSION.CODENAME.equals("S") ? 0x02000000 : 0;
...
if (mbrComponent != null && mbrIntent == null) {
// construct a PendingIntent for the media button
Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
// the associated intent will be handled by the component being registered
mediaButtonIntent.setComponent(mbrComponent);
mbrIntent = PendingIntent.getBroadcast(context,
0/* requestCode, ignored */, mediaButtonIntent,
PENDING_INTENT_FLAG_MUTABLE);
}
Source code demonstrating the problem - https://github.com/adelinolobao/issue-media-session-compat
Do you guys have any idea how can I fix the error?
",https://stackoverflow.com/questions/68473542/mediasessioncompattargeting-s-version-31-and-above-requires-that-one-of-flag,208,181825.0,24.0,,,2021-07-21 16:51:07,2025-03-10 09:54:41,2021-07-27 21:18:18,,,java;android;android-studio;kotlin;android-mediaplayer,Adelino,3140,650700,registered,true,69152986,,CC BY-SA 4.0,,4099,3895,3,1,0,5,true,false,false,true,true,true,149,19,false,0.132,0.0011,1949,2021,7,16,Wednesday,false,false,false,true,false,false,false
34498562,"In Kotlin, what is the idiomatic way to deal with nullable values, referencing or converting them","If I have a nullable type Xyz?, I want to reference it or convert it to a non-nullable type Xyz. What is the idiomatic way of doing so in Kotlin?
For example, this code is in error:
val something: Xyz? = createPossiblyNullXyz()
something.foo() // Error: "Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type Xyz?"
But if I check null first it is allowed, why?
val something: Xyz? = createPossiblyNullXyz()
if (something != null) {
something.foo()
}
How do I change or treat a value as not null without requiring the if check, assuming I know for sure it is truly never null? For example, here I am retrieving a value from a map that I can guarantee exists and the result of get() is not null. But I have an error:
val map = mapOf("a" to 65,"b" to 66,"c" to 67)
val something = map.get("a")
something.toLong() // Error: "Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type Int?"
The method get() thinks it is possible that the item is missing and returns type Int?. Therefore, what is the best way to force the type of the value to be not nullable?
Note: this question is intentionally written and answered by the author (Self-Answered Questions), so that the idiomatic answers to commonly asked Kotlin topics are present in SO. Also to clarify some really old answers written for alphas of Kotlin that are not accurate for current-day Kotlin.
",https://stackoverflow.com/questions/34498562/in-kotlin-what-is-the-idiomatic-way-to-deal-with-nullable-values-referencing-o,208,101343.0,4.0,,,2015-12-28 18:13:06,2022-03-12 05:20:52,2021-01-18 12:39:36,,,nullable;kotlin;non-nullable,Jayson Minard,86376,3679676,registered,true,34498563,,CC BY-SA 4.0,,1972,1494,12,1,0,3,true,false,false,true,true,true,97,16,false,0.039,0.0021,3981,2015,12,18,Monday,false,false,false,false,false,false,false
35513636,Multiple variable let in Kotlin,"Is there any way to chain multiple lets for multiple nullable variables in kotlin?
fun example(first: String?, second: String?) {
first?.let {
second?.let {
// Do something just if both are != null
}
}
}
I mean, something like this:
fun example(first: String?, second: String?) {
first?.let && second?.let {
// Do something just if both are != null
}
}
",https://stackoverflow.com/questions/35513636/multiple-variable-let-in-kotlin,206,91079.0,16.0,,,2016-02-19 19:42:23,2023-09-08 07:08:40,,,,kotlin,Daniel Gomez Rico,16095,273119,registered,true,55736101,,CC BY-SA 3.0,,481,419,2,0,0,1,true,false,false,true,true,false,31,5,false,0.176,0.0023,3928,2016,2,19,Friday,false,false,false,false,false,false,false
42739807,How to read a text file from resources in Kotlin?,"I want to write a Spek test in Kotlin.
How to read an HTML file from the src/test/resources folder?
class MySpec : Spek(
{
describe("blah blah") {
given("blah blah") {
var fileContent: String = ""
beforeEachTest {
// How to read the file.html in src/test/resources/html/
fileContent = ...
}
it("should blah blah") {
...
}
}
}
}
)
",https://stackoverflow.com/questions/42739807/how-to-read-a-text-file-from-resources-in-kotlin,203,217092.0,15.0,,,2017-03-11 19:45:56,2024-09-11 23:09:54,2023-02-17 20:48:48,,,kotlin;file-io;classpath;classloader,Olaf,4056,538318,registered,true,42740416,,CC BY-SA 4.0,,650,559,2,0,0,4,true,false,false,true,true,true,49,10,true,0.069,0.0009,3542,2017,3,19,Saturday,true,false,false,false,false,false,false
38381748,Why do we use "companion object" as a kind of replacement for Java static fields in Kotlin?,"What is the intended meaning of ""companion object""? So far I have been using it just to replace Java's static when I need it.
I am confused with:
- Why is it called ""companion""?
- Does it mean that to create multiple static properties, I have to group it together inside
companion object block?
- To instantly create a singleton instance that is scoped to a class, I often write
:
companion object {
val singleton by lazy { ... }
}
which seems like an unidiomatic way of doing it. What's the better way?
",https://stackoverflow.com/questions/38381748/why-do-we-use-companion-object-as-a-kind-of-replacement-for-java-static-fields,203,71866.0,5.0,,,2016-07-14 18:35:04,2021-02-06 16:13:59,2017-11-13 05:31:38,,,kotlin;kotlin-companion,Randy Sugianto 'Yuku',73883,11238,registered,true,38382433,,CC BY-SA 3.0,,634,511,3,0,0,2,true,false,false,true,true,true,101,17,true,0.07,0.0028,3782,2016,7,18,Thursday,false,false,false,false,false,false,false
44298702,What is out keyword in kotlin,"I am not able to understand and I couldn't find the meaning of out keyword in kotlin.
You can check example here:
List<out T>
If any one can explain the meaning of this. It would be really appreciated.
",https://stackoverflow.com/questions/44298702/what-is-out-keyword-in-kotlin,202,69411.0,10.0,,,2017-06-01 04:44:13,2024-02-06 13:48:04,2017-08-21 11:17:25,,,generics;kotlin,Akshay Sood,6854,5431173,registered,true,44641349,,CC BY-SA 3.0,,275,213,1,0,0,2,true,false,false,true,true,true,29,6,false,0.144,0.0029,3460,2017,6,4,Thursday,false,false,false,false,false,false,false
32914499,Error: Execution failed for task ':app:clean'. Unable to delete file,"I'm trying to rebuild my Android Studio Gradle project (containing mostly Kotlin code), but it started to throw an UnableToDeleteFileException during the cleaning/rebuilding process:
Execution failed for task ':app:clean'.
> Unable to delete file: C:\Users\User\KotlinGameEngine\app\build\intermediates\exploded-aar\com.android.support\appcompat-v7\23.0.1\jars\classes.jar
This started happening after I tried to change my project's package structure. Unfortunately, I did it by renaming and moving the source folders rather than refactoring through Android Studio, which was a bad idea.
I've been searching for a solution to this problem all day, and these are the things I have tried to no avail:
- Doing a Gradle sync;
- Reinstalling Java JRE and Java SDK;
- Reinstalling the latest version of Android Studio (1.4);
- Rolling back to the previous AS version (1.3);
- Invalidating the AS cache and restarting;
- Deleting the
gradle and .gradle directories in the project directory;
- Deleting the
.gradle directory in my user directory;
- Running
gradlew clean from the AS terminal;
- Manually copying the sources over to a new project (weird that it somehow persists across projects...)
Things that I've tried with a little success, but only let me perform one more clean and rebuild before the error occurs again:
- Closing AS, manually deleting the build files, and opening it again;
- Killing the
java.exe process while AS is running (this could technically be done every time, but it's tedious and slows down the build process)
So it seems that compile the Java process may put a lock on the build files for some reason, but it might also be something to do with Kotlin. I have a (more mature) Java Android project that I'm working on, though I can't reproduce this error when cleaning it. It seems to only happen to my Kotlin project.
Update:
I've found that the problem is being caused by the Kotlin Android plugin. The problem disappears when I remove apply plugin: 'kotlin-android' from the module's build.gradle file and comes back when I reinsert it. Feel free to offer any insight into this.
Update 2:
The last update isn't the cause. I found that if a project contains a Kotlin file then rebuilding and cleaning fails. It continues to fail, even if all the Kotlin files are removed, until the background Java process is killed, meaning it has some kind of lock on the build files. I submitted a bug here with more details and steps to reproduce the bug: KT-9440
",https://stackoverflow.com/questions/32914499/error-execution-failed-for-task-appclean-unable-to-delete-file,198,286496.0,45.0,,,2015-10-02 19:30:11,2024-08-19 19:20:25,2019-05-05 14:47:37,,,android;android-studio;android-gradle-plugin;kotlin;kotlin-android-extensions,Bryony,2398,5401587,registered,true,32924320,,CC BY-SA 4.0,2016-08-10 15:16:45,2878,2474,9,1,0,5,true,false,false,true,true,true,76,10,false,0.157,0.0007,4068,2015,10,19,Friday,false,false,false,false,false,false,false
32038177,Kotlin with JPA: default constructor hell,"As JPA requires, @Entity classes should have a default (non-arg) constructor to instantiate the objects when retrieving them from the database.
In Kotlin, properties are very convenient to declare within the primary constructor, as in the following example:
class Person(val name: String, val age: Int) { /* ... */ }
But when the non-arg constructor is declared as a secondary one it requires values for the primary constructor to be passed, so some valid values are needed for them, like here:
@Entity
class Person(val name: String, val age: Int) {
private constructor(): this("""", 0)
}
In case when the properties have some more complex type than just String and Int and they're non-nullable, it looks totally bad to provide the values for them, especially when there's much code in primary constructor and init blocks and when the parameters are actively used -- when they're to be reassigned through reflection most of the code is going to be executed again.
Moreover, val-properties cannot be reassigned after the constructor executes, so immutability is also lost.
So the question is: how can Kotlin code be adapted to work with JPA without code duplication, choosing ""magic"" initial values and loss of immutability?
P.S. Is it true that Hibernate aside of JPA can construct objects with no default constructor?
",https://stackoverflow.com/questions/32038177/kotlin-with-jpa-default-constructor-hell,197,90790.0,15.0,,,2015-08-16 17:54:01,2023-12-07 14:48:00,,,,hibernate;jpa;default-constructor;kotlin,hotkey,149467,2196460,registered,true,41365380,,CC BY-SA 3.0,,1493,1331,7,0,0,4,true,false,false,true,true,false,41,6,false,0.165,0.0022,4115,2015,8,17,Sunday,true,false,false,false,false,false,false
59713224,Jetpack Compose - Column - Gravity center,"I'm creating a layout with Jetpack Compose and there is a column. I would like center items inside this column:
Column(modifier = ExpandedWidth) {
Text(text = item.title)
Text(text = item.description)
}
",https://stackoverflow.com/questions/59713224/jetpack-compose-column-gravity-center,194,283481.0,19.0,,,2020-01-13 08:54:03,2025-04-17 16:00:47,2022-12-21 09:40:15,,,android;kotlin;android-jetpack-compose;android-jetpack;android-jetpack-compose-layout,mac229,5049,4312751,registered,true,62152703,,CC BY-SA 4.0,,254,223,1,0,0,5,true,false,false,true,true,true,41,7,false,0.067,0.0007,2504,2020,1,8,Monday,false,false,false,false,false,false,false
36760489,How to catch many exceptions at the same time in Kotlin?,"try {
} catch (ex: MyException1, MyException2 ) {
logger.warn("""", ex)
}
or
try {
} catch (ex: MyException1 | MyException2 ) {
logger.warn("""", ex)
}
As a result, a compilation error: Unresolved reference: MyException2.
How can I catch many exceptions at the same time on Kotlin?
",https://stackoverflow.com/questions/36760489/how-to-catch-many-exceptions-at-the-same-time-in-kotlin,194,110297.0,5.0,,,2016-04-21 05:34:51,2021-12-30 13:33:35,2021-11-11 11:18:15,,,kotlin;exception,Ant20,2303,6233653,registered,true,36760590,,CC BY-SA 4.0,,378,296,3,0,0,2,true,false,false,true,true,true,56,11,true,0.045,0.0018,3866,2016,4,5,Thursday,false,false,false,false,false,false,false
55953052,Kotlin - Void vs. Unit vs. Nothing,"Kotlin has three types that are very similar in nature:
Void
Unit
Nothing
It almost seems like they're making the JavaScript mistake:
null
undefined
void(0)
Assuming that they haven't fallen into the same mistake, what are they all for, and how do they differ?
",https://stackoverflow.com/questions/55953052/kotlin-void-vs-unit-vs-nothing,192,73806.0,3.0,,,2019-05-02 12:59:17,2022-12-24 21:05:52,2020-12-19 17:54:52,,,kotlin;generics;types;functional-programming,Matthew Layton,43069,1033686,registered,true,55953300,,CC BY-SA 4.0,,449,269,6,0,0,4,true,false,false,true,true,true,34,7,false,0.041,0.0026,2760,2019,5,12,Thursday,false,false,false,false,false,false,false
44301301,Android - How to achieve setOnClickListener in Kotlin?,"I wanted to know that how we set basic onClickListener in Kotlin for Android Development.
",https://stackoverflow.com/questions/44301301/android-how-to-achieve-setonclicklistener-in-kotlin,191,273083.0,33.0,,,2017-06-01 07:34:30,2023-11-10 16:26:43,2017-07-21 16:10:17,,,android;listener;kotlin,Anirudh Agarwal,2184,4445471,registered,true,,,CC BY-SA 3.0,2021-08-21 10:59:57,97,90,0,0,0,3,false,false,false,true,true,true,54,8,true,0.121,0.0007,3460,2017,6,7,Thursday,false,false,false,false,false,false,false
44471284,when to use an inline function in Kotlin?,"I know that an inline function will maybe improve performance & cause the generated code to grow, but I'm not sure when it is correct to use one.
lock(l) { foo() }
Instead of creating a function object for the parameter and generating a call, the compiler could emit the following code. (Source)
l.lock()
try {
foo()
}
finally {
l.unlock()
}
but I found that there is no function object created by kotlin for a non-inline function. why?
/**non-inline function**/
fun lock(lock: Lock, block: () -> Unit) {
lock.lock();
try {
block();
} finally {
lock.unlock();
}
}
",https://stackoverflow.com/questions/44471284/when-to-use-an-inline-function-in-kotlin,190,82838.0,7.0,,,2017-06-10 08:36:56,2022-03-23 11:01:47,2020-04-11 11:58:17,,,function;kotlin;inline-functions,holi-java,30888,7607923,registered,true,,,CC BY-SA 4.0,,828,619,3,1,0,3,false,false,false,true,true,true,41,8,true,0.085,0.0023,3451,2017,6,8,Saturday,true,false,false,false,false,false,false
61807520,How to fix ERROR: No signature of method: build_ap86oam3dut3pxce3x49rdtma.android()?,"ERROR: No signature of method: build_ap86oam3dut3pxce3x49rdtma.android() is applicable for argument types: (build_ap86oam3dut3pxce3x49rdtma$_run_closure1) values: [build_ap86oam3dut3pxce3x49rdtma$_run_closure1@47588b04]
The build gradle is:
apply plugin: 'com.android.application'
android{
implementationSdkVersion 28
buildToolsVersion ""29.0.3""
defaultConfig {
applicationId ""com.uiresource.taksiku""
minSdkVersion 16
targetSdkVersion 28
versionCode 1
versionName ""1.0""
testInstrumentationRunner ""android.support.test.runner.AndroidJUnitRunner""
vectorDrawables.useSupportLibrary = true
}
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
androidTestImplementation('com.android.support.test.espresso:espresso-core:2.3-alpha', {
exclude group: 'com.android.support', module: 'support-annotations'
})
implementation ""com.android.support:appcompat-v7:$var""
implementation 'com.android.support:design:28.0.0'
testimplementation 'junit:junit:4.13'
implementation 'com.android.support.constraint:constraint-layout:2.0.0-beta5'
implementation 'de.hdodenhof:circleimageview:3.1.0'
}
",https://stackoverflow.com/questions/61807520/how-to-fix-error-no-signature-of-method-build-ap86oam3dut3pxce3x49rdtma-androi,190,229936.0,55.0,,,2020-05-14 21:15:45,2024-07-21 07:18:23,2020-05-14 22:38:53,,,android;android-studio;kotlin,Usman Liaqat,1901,8672766,registered,true,,,CC BY-SA 4.0,2021-09-25 17:43:57,1489,1451,1,0,0,3,false,false,false,true,true,true,84,9,true,0.239,0.0008,2382,2020,5,21,Thursday,false,false,false,false,false,false,false
36569421,Kotlin: How to work with List casts: Unchecked Cast: kotlin.collections.List<Kotlin.Any?> to kotlin.colletions.List<Waypoint>,"I want to write a function that returns every item in a List that is not the first or the last item (a via point). The function gets a generic List<*> as input. A result should only be returned if the elements of the list are of the type Waypoint:
fun getViaPoints(list: List<*>): List<Waypoint>? {
list.forEach { if(it !is Waypoint ) return null }
val waypointList = list as? List<Waypoint> ?: return null
return waypointList.filter{ waypointList.indexOf(it) != 0 && waypointList.indexOf(it) != waypointList.lastIndex}
}
When casting the List<*> to List<Waypoint>, I get the warning:
Unchecked Cast: kotlin.collections.List
to kotlin.colletions.List
I can't figure out a way to implement it otherwise. What's the right way to implement this function without this warning?
",https://stackoverflow.com/questions/36569421/kotlin-how-to-work-with-list-casts-unchecked-cast-kotlin-collections-listkot,189,125882.0,6.0,,,2016-04-12 09:41:26,2021-09-08 13:09:03,2018-08-16 17:01:44,,,list;generics;casting;kotlin,Lukas Lechner,8221,2660462,registered,true,36570969,,CC BY-SA 4.0,,986,844,6,0,0,4,true,false,false,true,true,true,137,12,false,0.048,0.0015,3875,2016,4,9,Tuesday,false,false,false,false,false,false,false
32830904,Use of Boolean? in if expression,"If I have a nullable Boolean b, I can do the following comparison in Java:
Boolean b = ...;
if (b != null && b) {
/* Do something */
} else {
/* Do something else */
}
In Kotlin, I can achieve the same by using the !! operator:
val b: Boolean? = ...
if (b != null && b!!) {
/* Do something */
} else {
/* Do something else */
}
However, the use of !! feels a bit sketchy to me, circumventing the null safety system.
Is there a more elegant approach for this?
Edit It seems I oversimplicated a bit. For local variables, as Banthar shows, it does work. However, my Boolean b is actually a ""property with a backing field"" (I'm not really up to speed yet what this imposes). This is the result:
",https://stackoverflow.com/questions/32830904/use-of-boolean-in-if-expression,189,150744.0,13.0,,,2015-09-28 20:05:45,2025-01-07 14:47:50,2019-03-19 15:47:56,,,kotlin;null,nhaarman,100739,675383,registered,true,32848624,,CC BY-SA 4.0,,1085,731,6,2,1,2,true,false,false,true,true,true,32,6,false,0.086,0.0013,4072,2015,9,20,Monday,false,false,false,false,false,false,false
43737785,Kotlin: Interface ... does not have constructors,"I am converting some of my Java code to Kotlin and I do not quite understand how to instantiate interfaces that are defined in Kotlin code. As an example, I have an interface (defined in Java code):
public interface MyInterface {
void onLocationMeasured(Location location);
}
And then further in my Kotlin code I instantiate this interface:
val myObj = new MyInterface { Log.d(""..."", ""..."") }
and it works fine. However, when I convert MyInterface to Kotlin:
interface MyInterface {
fun onLocationMeasured(location: Location)
}
I get an error message: Interface MyListener does not have constructors when I try to instantiate it - though it seems to me that nothing has changed except syntax. Do I misunderstand how interfaces work in Kotlin?
",https://stackoverflow.com/questions/43737785/kotlin-interface-does-not-have-constructors,189,83011.0,8.0,,,2017-05-02 12:21:47,2024-03-03 09:45:37,,,,java;kotlin,Aleph Aleph,5405,4534687,registered,true,43737962,,CC BY-SA 3.0,,873,760,4,0,0,2,true,false,false,true,true,false,48,7,false,0.096,0.0023,3490,2017,5,12,Tuesday,false,false,false,true,false,false,false
44644524,kotlin version that is used for building with gradle (1.1.2-5) differs from the one bundled into the IDE plugin (1.1.2-4),"Has anyone solved this issue?
kotlin version that is used for building with gradle (1.1.2-5) differs from the one bundled into the IDE plugin (1.1.2-4)
I am using AS 3.0 Canary 4
",https://stackoverflow.com/questions/44644524/kotlin-version-that-is-used-for-building-with-gradle-1-1-2-5-differs-from-the,187,99949.0,8.0,,,2017-06-20 05:29:27,2023-04-11 09:15:08,2019-09-13 12:04:39,,,android-studio;kotlin,raditya gumay,3011,5435658,registered,true,,,CC BY-SA 4.0,,231,185,0,0,0,2,false,false,false,true,true,true,121,20,false,0.08,0.0019,3441,2017,6,5,Tuesday,false,false,false,false,false,false,false
44184769,Android Room - Select query with LIKE,"I'm trying to make a query to search all objects whose names contain text:
@Query("SELECT * FROM hamster WHERE name LIKE %:arg0%")
fun loadHamsters(search: String?): Flowable<List<Hamster>>
Messages:
Error:no viable alternative at input 'SELECT * FROM hamster WHERE name LIKE %'
Error:There is a problem with the query: [SQLITE_ERROR] SQL error or missing database (near "%": syntax error)
Error:Unused parameter: arg0
Also, I'm trying:
@Query("SELECT * FROM hamster WHERE name LIKE '%:arg0%'")
fun loadHamsters(search: String?): Flowable<List<Hamster>>
Messages:
Error:Unused parameter: arg0
How to fix this?
",https://stackoverflow.com/questions/44184769/android-room-select-query-with-like,186,86000.0,4.0,,,2017-05-25 15:53:41,2022-07-25 12:38:41,2022-07-25 12:37:22,,,android;kotlin;android-room,Denis Buzmakov,1862,6002079,registered,true,44185385,,CC BY-SA 4.0,,799,668,4,0,0,3,true,false,false,true,true,true,37,7,false,0.047,0.0022,3467,2017,5,15,Thursday,false,false,false,false,false,false,false
67744002,Hilt Unsupported metadata version in Kotlin,"I was tried to run my code in Kotlin 1.5.10
With plugin as
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'kotlin-kapt'
id 'dagger.hilt.android.plugin'
}
and dependencies as below
dependencies {
...
//Dagger - Hilt
implementation "com.google.dagger:hilt-android:2.33-beta"
kapt "com.google.dagger:hilt-android-compiler:2.33-beta"
implementation "androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha03"
kapt "androidx.hilt:hilt-compiler:1.0.0-beta01"
implementation 'androidx.hilt:hilt-navigation-compose:1.0.0-alpha01'
implementation 'com.android.support:palette-v7:28.0.0'
}
When I migrate to kotlin_version = "1.5.10", it just errors out stating
error: [Hilt]
Unsupported metadata version. Check that your Kotlin version is >= 1.0: java.lang.IllegalStateException: Unsupported metadata version. Check that your Kotlin version is >= 1.0
at dagger.internal.codegen.kotlin.KotlinMetadata.metadataOf(KotlinMetadata.java:206)
at dagger.internal.codegen.kotlin.KotlinMetadata.from(KotlinMetadata.java:186)
at java.base/java.util.HashMap.computeIfAbsent(HashMap.java:1133)
...
Can anyone help me? I spent a lot of time on it, your answer will help me a lot
",https://stackoverflow.com/questions/67744002/hilt-unsupported-metadata-version-in-kotlin,186,170053.0,28.0,,,2021-05-28 18:35:07,2025-09-05 06:37:59,2025-09-05 06:37:59,,,android-studio;kotlin;mobile;android-jetpack-compose;dagger-hilt,Lang Minh Nguyên,5685,14690139,registered,true,68319048,,CC BY-SA 4.0,2022-03-16 12:50:50,1460,1274,2,0,0,5,true,false,false,true,true,true,43,6,false,0.165,0.0011,2003,2021,5,18,Friday,false,false,false,false,false,false,false
53304347,MutableLiveData: Cannot invoke setValue on a background thread from Coroutine,"I'm trying to trigger an update on LiveData from a coroutine:
object AddressList: MutableLiveData<List<Address>>()
fun getAddressesLiveData(): LiveData<List<Address>> {
AddressList.value = listOf()
GlobalScope.launch {
AddressList.value = getAddressList()
}
return AddressList
}
but I get the following error:
IllegalStateException: Cannot invoke setValue on a background thread
Is there a way to make it work with coroutines?
",https://stackoverflow.com/questions/53304347/mutablelivedata-cannot-invoke-setvalue-on-a-background-thread-from-coroutine,186,81758.0,9.0,,,2018-11-14 16:06:14,2023-11-04 02:18:54,2019-03-19 07:28:51,,,kotlin;android-livedata;kotlin-coroutines,kike,4503,2145504,registered,true,60126585,,CC BY-SA 4.0,,561,484,1,0,0,3,true,false,false,true,true,true,77,10,false,0.11,0.0023,2929,2018,11,16,Wednesday,false,false,false,false,false,false,false
42569445,warning: Kotlin runtime JAR files in the classpath should have the same version,"I get the following warning, but I'm not sure where v1.0.6 resides.
Is it possible this error comes from a Kotlin library somehow including an old Kotlin version?
Any ideas how to fix it or at least how can I follow the suggestion to make kotlin-reflect explicit (1.1) ?
",https://stackoverflow.com/questions/42569445/warning-kotlin-runtime-jar-files-in-the-classpath-should-have-the-same-version,186,213685.0,15.0,,,2017-03-03 02:15:29,2023-02-22 12:31:21,,,,kotlin,ycomp,8653,270143,registered,true,42577381,,CC BY-SA 3.0,,444,275,0,1,1,1,true,false,false,true,true,false,79,13,false,0.07,0.0009,3550,2017,3,2,Friday,false,false,false,false,false,false,false
41617042,How to access "Activity.this" in Kotlin?,"I have this piece of Java code:
MaterialDialog builder = new MaterialDialog.Builder(MainActivity.this)
I want to get the MainActivity object in Kotlin. The automatic conversion breaks at MainActivity.this.
",https://stackoverflow.com/questions/41617042/how-to-access-activity-this-in-kotlin,185,93031.0,8.0,,,2017-01-12 15:31:49,2021-11-12 01:35:58,2017-01-13 08:59:39,,,java;android;kotlin,Rado,2054,6440190,registered,true,41620834,,CC BY-SA 3.0,,260,209,2,0,0,3,true,false,false,true,true,true,50,6,true,0.086,0.002,3600,2017,1,15,Thursday,false,false,false,true,false,false,false
47204146,How to iterate over hashmap in Kotlin?,"How to iterate over HashMap in Kotlin?
typealias HashMap<K, V> = HashMap<K, V> (source)
",https://stackoverflow.com/questions/47204146/how-to-iterate-over-hashmap-in-kotlin,184,138478.0,5.0,,,2017-11-09 14:18:34,2022-05-03 11:19:18,2018-06-19 08:21:02,,,kotlin;kotlin-extension,Nomi,2021,8784244,registered,true,47204401,,CC BY-SA 4.0,,262,102,2,1,0,2,true,false,false,true,true,true,38,7,true,0.036,0.0013,3299,2017,11,14,Thursday,false,false,false,false,false,false,false
37231560,Best way to null check in Kotlin?,"Should I use double =, or triple =?
if(a === null) {
//do something
}
or
if(a == null) {
//do something
}
Similarly for 'not equals':
if(a !== null) {
//do something
}
or
if(a != null) {
//do something
}
",https://stackoverflow.com/questions/37231560/best-way-to-null-check-in-kotlin,182,283955.0,6.0,,,2016-05-14 20:33:35,2023-05-20 09:50:39,2019-03-12 12:41:27,,,kotlin;kotlin-null-safety,pdeva,45971,14316,registered,true,37232201,,CC BY-SA 4.0,,371,221,6,0,0,2,true,false,false,true,true,true,33,7,true,0.021,0.0006,3843,2016,5,20,Saturday,true,false,false,false,false,false,false
45195370,How to use @link and @code in kotlin kDoc,"I'm trying to document a method and trying to use @link and @code as in JavaDoc.
I know in kotlin there is a kDoc but I can't find them or at least something similar.
",https://stackoverflow.com/questions/45195370/how-to-use-link-and-code-in-kotlin-kdoc,182,97187.0,10.0,,,2017-07-19 15:46:44,2024-10-28 22:56:33,,,,documentation;kotlin;kdoc,humazed,77302,3998402,registered,true,45195371,,CC BY-SA 3.0,,390,168,2,2,0,3,true,false,false,true,true,false,41,9,false,0.103,0.0019,3412,2017,7,15,Wednesday,false,false,false,false,false,false,false
40352879,What is the equivalent of Java static final fields in Kotlin?,"In Java, to declare a constant, you do something like:
class Hello {
public static final int MAX_LEN = 20;
}
What is the equivalent in Kotlin?
",https://stackoverflow.com/questions/40352879/what-is-the-equivalent-of-java-static-final-fields-in-kotlin,181,100203.0,4.0,,,2016-11-01 01:20:55,2022-06-19 04:22:05,2020-07-24 10:42:30,,,java;kotlin,pdeva,45971,14316,registered,true,40354557,,CC BY-SA 4.0,,186,148,1,0,0,2,true,false,false,true,true,true,61,11,true,0.04,0.0018,3672,2016,11,1,Tuesday,false,false,false,true,false,false,false
40430297,How to remove duplicate strings from an array in Kotlin,"How to remove duplicates from an Array<String?> in Kotlin?
",https://stackoverflow.com/questions/40430297/how-to-remove-duplicate-strings-from-an-array-in-kotlin,180,112981.0,2.0,,,2016-11-04 19:18:45,2023-10-19 14:27:07,2023-10-19 14:27:07,,,algorithm;kotlin,ju_293847293,6766,1052504,registered,true,40430451,,CC BY-SA 4.0,,85,65,1,0,0,2,true,false,false,true,true,true,55,10,false,0.018,0.0016,3669,2016,11,19,Friday,false,false,false,false,false,false,false
33551972,Is there a convenient way to create Parcelable data classes in Android with Kotlin?,"I'm currently using the excellent AutoParcel in my Java project, which facilitates the creation of Parcelable classes.
Now, Kotlin, which I consider for my next project, has this concept of data classes, that automatically generate the equals, hashCode and toString methods.
Is there a convenient way to make a Kotlin data class Parcelable in a convenient way (without implementing the methods manually)?
",https://stackoverflow.com/questions/33551972/is-there-a-convenient-way-to-create-parcelable-data-classes-in-android-with-kotl,178,120412.0,16.0,,,2015-11-05 18:19:30,2021-10-26 19:49:14,,,,android;parcelable;kotlin,thalesmello,3499,835591,registered,true,45698927,,CC BY-SA 3.0,,486,407,0,1,0,3,true,false,false,true,true,false,83,14,true,0.133,0.0015,4034,2015,11,18,Thursday,false,false,false,false,false,false,false
33165324,Kotlin-android: unresolved reference databinding,"I have following fragment class written in Java using the new databinding library
import com.example.app.databinding.FragmentDataBdinding;
public class DataFragment extends Fragment {
@Nullable
private FragmentDataBinding mBinding;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_data, container, false);
return mBinding.getRoot();
}
}
It compiles and runs fine.
I tried to rewrite it in Kotlin and came up with the following:
import com.example.app.databinding.FragmentDataBdinding
class ProfileFragment : Fragment() {
private var mBinding: FragmentDataBinding? = null
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_data, container, false)
return mBinding!!.getRoot()
}
}
But now step :app:compileDebugKotlin outputs the following:
Error:(16, 38) Unresolved reference: databinding
Error:(37, 27) Unresolved reference: FragmentDataBinding
How can I use android-databinding library with Kotlin?
My top-level build.gradle:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.3.0'
classpath 'com.android.databinding:dataBinder:1.0-rc4'
}
}
allprojects {
repositories {
jcenter()
}
}
My build.gradle in app dir (only relevant parts):
apply plugin: 'com.android.application'
apply plugin: 'com.android.databinding'
apply plugin: 'kotlin-android'
dependencies {
compile ""org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version""
}
buildscript {
ext.kotlin_version = '0.14.451'
repositories {
mavenCentral()
}
dependencies {
classpath ""org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version""
classpath ""org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version""
}
}
repositories {
mavenCentral()
maven {
url 'http://oss.sonatype.org/content/repositories/snapshots'
}
}
I'm using Android Studio 1.4, Build tools version 23.0.1, Android SDK 23, SDK tools 24.4.0
",https://stackoverflow.com/questions/33165324/kotlin-android-unresolved-reference-databinding,178,118396.0,23.0,,,2015-10-16 07:58:42,2026-06-28 09:08:01,2019-05-05 14:50:59,,,java;android;kotlin;android-databinding,Mikhail,3756,4261613,registered,true,,,CC BY-SA 4.0,,2515,2291,7,0,0,4,false,false,false,true,true,true,48,4,false,0.194,0.0015,4054,2015,10,7,Friday,false,false,false,true,false,false,false
40569436,Kotlin addTextChangeListener lambda?,"How do you build a lambda expression for the EditText addTextChangeListener in Kotlin? Below gives an error:
passwordEditText.addTextChangedListener { charSequence ->
try {
password = charSequence.toString()
} catch (error: Throwable) {
raise(error)
}
}
",https://stackoverflow.com/questions/40569436/kotlin-addtextchangelistener-lambda,176,181064.0,13.0,,,2016-11-13 01:00:56,2024-07-30 09:43:00,2018-03-07 18:52:30,,,android;kotlin;textview;anko,LEMUEL ADANE,8904,1347816,registered,true,40569869,,CC BY-SA 3.0,,319,288,1,0,0,4,true,false,false,true,true,true,36,3,true,0.072,0.001,3660,2016,11,1,Sunday,true,false,false,false,false,false,false
43114367,Difference between ArrayList<String>() and mutableListOf<String>() in Kotlin,"private val repositories = mutableListOf<String>()
private val repositories = ArrayList<String>()
Both are mutable list, then what is the point of two keywords mutableListOf or ArrayList?
or is there any major difference?
",https://stackoverflow.com/questions/43114367/difference-between-arrayliststring-and-mutablelistofstring-in-kotlin,176,69858.0,4.0,,,2017-03-30 09:54:17,2024-09-24 16:11:55,,,,kotlin,Sai,15818,2102794,registered,true,43116238,,CC BY-SA 3.0,,303,239,3,0,0,1,true,false,false,true,true,false,88,7,false,0.057,0.0025,3523,2017,3,9,Thursday,false,false,false,false,false,false,false
39389003,Kotlin asterisk operator before variable name or Spread Operator in Kotlin,"I want to know what exactly an asterisk does before a variable name in Kotlin.
I saw this (*args) in a Spring boot Kotlin example:
@SpringBootApplication
open class Application {
@Bean
open fun init(repository: CustomerRepository) = CommandLineRunner {
repository.save(Customer("Jack", "Bauer"))
repository.save(Customer("Chloe", "O'Brian"))
repository.save(Customer("Kim", "Bauer"))
repository.save(Customer("David", "Palmer"))
repository.save(Customer("Michelle", "Dessler"))
}
}
fun main(args: Array<String>) {
SpringApplication.run(Application::class.java, *args)
}
",https://stackoverflow.com/questions/39389003/kotlin-asterisk-operator-before-variable-name-or-spread-operator-in-kotlin,175,78571.0,5.0,,,2016-09-08 10:50:22,2024-08-21 12:47:54,2020-10-06 13:21:01,,,syntax;kotlin,mojtab23,2685,3291867,registered,true,39389045,,CC BY-SA 4.0,,892,735,2,1,0,2,true,false,false,true,true,true,74,11,false,0.064,0.0022,3726,2016,9,10,Thursday,false,false,false,false,false,false,false
43928118,Outdated Kotlin Runtime warning in Android Studio,"After downloaded and installed latest Kotlin plugin I have Outdated Kotlin Runtime warning from Android Studio that telling me:
Your version of Kotlin runtime in 'kotlin-stdlib-1.1.2' library is
1.1.2, while plugin version is 1.1.2-release-Studio2.3-3. Runtime library should be updated to avoid compatibility problems.
I tried to click Update Runtime button but getting another message:
Automatic library version update for Gradle projects is currently
unsupported. Please update your build.gradle manually.
How to solve this issue?
",https://stackoverflow.com/questions/43928118/outdated-kotlin-runtime-warning-in-android-studio,174,90923.0,15.0,,,2017-05-12 01:53:43,2019-05-05 14:40:52,2017-12-28 00:55:28,,,android;android-studio;kotlin;kotlin-android-extensions,Arsenius,5822,3278271,registered,true,,,CC BY-SA 3.0,,661,550,0,0,0,4,false,false,false,true,true,true,49,7,false,0.165,0.0019,3480,2017,5,1,Friday,false,false,false,false,false,false,false
19299525,Kotlin secondary constructor,"How do I declare a secondary constructor in Kotlin?
Is there any documentation about that?
Following does not compile...
class C(a : Int) {
// Secondary constructor
this(s : String) : this(s.length) { ... }
}
",https://stackoverflow.com/questions/19299525/kotlin-secondary-constructor,172,179360.0,13.0,,,2013-10-10 15:07:32,2023-01-16 09:49:14,,,,syntax;constructor;kotlin,ironic,9038,236099,registered,true,19310740,,CC BY-SA 3.0,,263,218,1,0,0,3,true,false,false,true,true,false,28,3,false,0.072,0.001,4790,2013,10,15,Thursday,false,false,false,false,false,false,false
49726385,ListAdapter not updating item in RecyclerView,"I'm using the new support library ListAdapter. Here's my code for the adapter
class ArtistsAdapter : ListAdapter<Artist, ArtistsAdapter.ViewHolder>(ArtistsDiff()) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(parent.inflate(R.layout.item_artist))
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(getItem(position))
}
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
fun bind(artist: Artist) {
itemView.artistDetails.text = artist.artistAlbums
.plus("" Albums"")
.plus("" \u2022 "")
.plus(artist.artistTracks)
.plus("" Tracks"")
itemView.artistName.text = artist.artistCover
itemView.artistCoverImage.loadURL(artist.artistCover)
}
}
}
I'm updating the adapter with
musicViewModel.getAllArtists().observe(this, Observer {
it?.let {
artistAdapter.submitList(it)
}
})
My diff class
class ArtistsDiff : DiffUtil.ItemCallback<Artist>() {
override fun areItemsTheSame(oldItem: Artist?, newItem: Artist?): Boolean {
return oldItem?.artistId == newItem?.artistId
}
override fun areContentsTheSame(oldItem: Artist?, newItem: Artist?): Boolean {
return oldItem == newItem
}
}
What's happening is when submitList is called the first time the adapter renders all the items, but when submitList is called again with updated object properties it does not re-render the view which has changed.
It re-renders the view as I scroll the list, which in turn calls bindView()
Also, I've noticed that calling adapter.notifyDatasSetChanged() after submit list renders the view with updated values, but I don't want to call notifyDataSetChanged() because the list adapter has diff utils built-in
Can anyone help me here?
",https://stackoverflow.com/questions/49726385/listadapter-not-updating-item-in-recyclerview,169,91774.0,29.0,,,2018-04-09 05:55:46,2023-07-03 14:08:23,2019-09-20 08:12:16,,,android;kotlin;listadapter,Veeresh Charantimath,4729,4644853,registered,true,50031492,,CC BY-SA 4.0,2023-03-09 08:55:50,2143,1970,7,0,0,3,true,false,false,true,true,true,45,6,false,0.316,0.0018,3148,2018,4,5,Monday,false,false,false,false,false,false,false
39500045,"In Kotlin, how do I read the entire contents of an InputStream into a String?","I recently saw code for reading entire contents of an InputStream into a String in Kotlin, such as:
// input is of type InputStream
val baos = ByteArrayOutputStream()
input.use { it.copyTo(baos) }
val inputAsString = baos.toString()
And also:
val reader = BufferedReader(InputStreamReader(input))
try {
val results = StringBuilder()
while (true) {
val line = reader.readLine()
if (line == null) break
results.append(line)
}
val inputAsString = results.toString()
} finally {
reader.close()
}
And even this that looks smoother since it auto-closes the InputStream:
val inputString = BufferedReader(InputStreamReader(input)).useLines { lines ->
val results = StringBuilder()
lines.forEach { results.append(it) }
results.toString()
}
Or slight variation on that one:
val results = StringBuilder()
BufferedReader(InputStreamReader(input)).forEachLine { results.append(it) }
val resultsAsString = results.toString()
Then this functional fold thingy:
val inputString = input.bufferedReader().useLines { lines ->
lines.fold(StringBuilder()) { buff, line -> buff.append(line) }.toString()
}
Or a bad variation which doesn't close the InputStream:
val inputString = BufferedReader(InputStreamReader(input))
.lineSequence()
.fold(StringBuilder()) { buff, line -> buff.append(line) }
.toString()
But they are all clunky and I keep finding newer and different versions of the same... and some of them never even close the InputStream. What is a non-clunky (idiomatic) way to read the InputStream?
Note: this question is intentionally written and answered by the author (Self-Answered Questions), so that the idiomatic answers to commonly asked Kotlin topics are present in SO.
",https://stackoverflow.com/questions/39500045/in-kotlin-how-do-i-read-the-entire-contents-of-an-inputstream-into-a-string,168,109829.0,4.0,,,2016-09-14 21:40:09,2022-03-12 05:07:33,2021-01-18 12:39:36,,,inputstream;kotlin,Jayson Minard,86376,3679676,registered,true,39500046,,CC BY-SA 4.0,,2426,1774,11,1,0,2,true,false,false,true,true,true,77,15,true,0.036,0.0015,3720,2016,9,21,Wednesday,false,false,false,false,false,false,false
42843441,Kotlin Error : Could not find org.jetbrains.kotlin:kotlin-stdlib-jre7:1.0.7,"I installed the Kotlin plugin into my app (v. v1.1.1-release-Studio2.2-1) and then selected "Configure Kotlin in Project" I selected compiler and runtime version of 1.0.7. Kotlin updated my Gradle files. Now when I try to build in I get:
Error: A problem occurred configuring project ':app'.
Could not resolve all dependencies for configuration ':app:_debugApkCopy'.
Could not find org.jetbrains.kotlin:kotlin-stdlib-jre7:1.0.7.
Required by:
MyApplication:app:unspecified
I'm not sure what I'm missing here.
",https://stackoverflow.com/questions/42843441/kotlin-error-could-not-find-org-jetbrains-kotlinkotlin-stdlib-jre71-0-7,167,333698.0,21.0,,,2017-03-16 19:42:36,2023-05-13 09:56:14,2020-06-20 09:12:55,,,android;kotlin;android-gradle-plugin,Mike6679,6186,517733,registered,true,53358817,,CC BY-SA 4.0,,575,522,0,0,0,3,true,false,false,true,true,true,75,7,false,0.063,0.0005,3537,2017,3,19,Thursday,false,false,false,false,false,false,false
50198067,Kotlin equivalent of Java's equalsIgnoreCase,"What is the equivalent of Java equalsIgnoreCase in Kotlin to compare String values?
I have used equals but it's not case insensitive.
",https://stackoverflow.com/questions/50198067/kotlin-equivalent-of-javas-equalsignorecase,167,64909.0,6.0,,,2018-05-06 09:11:11,2023-02-10 10:20:16,,,,android;kotlin,Farwa,7224,8700937,registered,true,50198091,,CC BY-SA 4.0,,189,136,3,0,0,2,true,false,false,true,true,false,48,5,false,0.092,0.0026,3121,2018,5,9,Sunday,true,false,false,false,false,false,false
17516930,How to create an instance of anonymous class of abstract class in Kotlin?,"Assume that KeyAdapter is an abstract class with several methods that can be overridden.
In java I can do:
KeyListener keyListener = new KeyAdapter() {
@Override public void keyPressed(KeyEvent keyEvent) {
// ...
}
};
How to do the same in Kotlin?
",https://stackoverflow.com/questions/17516930/how-to-create-an-instance-of-anonymous-class-of-abstract-class-in-kotlin,167,77282.0,2.0,,,2013-07-07 22:14:28,2021-07-20 16:35:29,2016-06-16 06:13:52,,,java;abstract-class;kotlin,Tvaroh,6803,312708,registered,true,17516998,,CC BY-SA 3.0,,326,268,2,0,0,3,true,false,false,true,true,true,73,13,true,0.026,0.0022,4885,2013,7,22,Sunday,true,false,false,true,false,false,false
30331806,Test expected exceptions in Kotlin,"In Java, the programmer can specify expected exceptions for JUnit test cases like this:
@Test(expected = ArithmeticException.class)
public void omg()
{
int blackHole = 1 / 0;
}
How would I do this in Kotlin? I have tried two syntax variations, but none of them worked:
import org.junit.Test
// ...
@Test(expected = ArithmeticException) fun omg()
Please specify constructor invocation;
classifier 'ArithmeticException' does not have a companion object
@Test(expected = ArithmeticException.class) fun omg()
name expected ^
^ expected ')'
",https://stackoverflow.com/questions/30331806/test-expected-exceptions-in-kotlin,166,122099.0,12.0,,,2015-05-19 17:01:27,2024-01-31 14:46:23,2020-10-15 20:17:45,,,unit-testing;kotlin;testing;exception;junit4,fredoverflow,265356,252000,registered,true,30575351,,CC BY-SA 4.0,,687,625,2,0,0,5,true,false,false,true,true,true,34,5,false,0.098,0.0014,4204,2015,5,17,Tuesday,false,false,false,false,false,false,false
32655216,Kotlin: Equivalent of getClass() for KClass,"In Java we can resolve a variable's class through getClass() like something.getClass(). In Kotlin I am aware of something.javaClass which is nice but I want to be able to get the KClass in a similar way. I've seen the Something::class syntax but this is not what I need. I need to get the KClass of a variable. Does such functionality exist?
",https://stackoverflow.com/questions/32655216/kotlin-equivalent-of-getclass-for-kclass,164,162614.0,7.0,,,2015-09-18 15:03:35,2023-12-10 22:54:22,2019-06-24 12:48:03,,,java;class;kotlin,Jire,10438,1938929,registered,true,32655996,,CC BY-SA 4.0,,414,342,5,0,0,3,true,false,false,true,true,true,43,6,false,0.043,0.001,4082,2015,9,15,Friday,false,false,false,true,false,false,false
31712046,Kotlin unresolved reference in IntelliJ,"I started off with this tutorial for learning Kotlin in IntelliJ IDEA.
When I tried running the following example,
fun main(args: Array<String>) {
println("lol")
}
Build fails with the following error:
Error:(5, 5) Kotlin: Unresolved reference: println
This is the first time I am using IntelliJ. I have never worked on a Java project either. Am I missing something?
I have already seen this other question, though it is not valid for my situation.
",https://stackoverflow.com/questions/31712046/kotlin-unresolved-reference-in-intellij,163,455342.0,32.0,,,2015-07-29 22:07:56,2025-11-15 17:48:51,2025-11-15 17:48:51,,,intellij-idea;jvm;kotlin,Anony-mouse,2181,3589634,registered,true,34625454,,CC BY-SA 4.0,2023-02-24 09:38:33,739,471,2,2,0,3,true,false,false,true,true,true,39,5,false,0.07,0.0004,4133,2015,7,22,Wednesday,false,false,false,false,false,false,false
47006254,How to get current local date and time in Kotlin,"How to get current Date (day month and year) and time (hour, minutes and seconds) all in local time in Kotlin?
I tried through LocalDateTime.now() but it is giving me an error saying Call requires API Level 26 (curr min is 21).
How could I get time and date in Kotlin?
",https://stackoverflow.com/questions/47006254/how-to-get-current-local-date-and-time-in-kotlin,163,315896.0,16.0,,,2017-10-29 23:18:16,2024-05-08 23:31:30,2017-10-29 23:56:43,,,android;datetime;kotlin,rgoncalv,6055,6096029,registered,true,47006613,,CC BY-SA 3.0,,318,271,2,0,0,3,true,false,false,true,true,true,48,10,false,0.051,0.0005,3310,2017,10,23,Sunday,true,false,false,false,false,false,false
19517417,Opening Android Settings programmatically,"How can I open settings programmatically?
",https://stackoverflow.com/questions/19517417/opening-android-settings-programmatically,162,236557.0,11.0,,,2013-10-22 12:06:49,2023-12-28 09:50:41,2020-06-25 06:12:32,,,android;kotlin;android-settings,Behnam,6640,1576010,registered,true,62092663,,CC BY-SA 4.0,2016-11-29 09:22:04,49,42,0,0,0,3,true,false,false,true,true,true,41,4,false,0.047,0.0007,4778,2013,10,12,Tuesday,false,false,false,false,false,false,false
53823451,Could not find method kapt() for arguments,"I'm facing a problem for over 3 days now and I can't solve.
since I started to use Kotlin for Android,I stopped using ""annotationProcessor"" and started using ""kapt"", all things were working great with kapt until I started to build an Android Instant App, when I add ""kapt"" to any dependency like Glide or ButterKnife Gradle always displaying error that cound't find method kapt()
Could not find method kapt() for arguments [com.github.bumptech.glide:compiler:4.7.1] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.
Here are my project Gradle files
Project gradle file
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = '1.2.71'
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.2.1'
classpath ""org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version""
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
app module gradle file
apply plugin: 'com.android.application'
apply plugin: 'kotlin-kapt'
android {
compileSdkVersion 28
defaultConfig {
applicationId ""com.demo.instantapptest.app""
minSdkVersion 17
targetSdkVersion 28
versionCode 1
versionName ""1.0""
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation project(':feature')
implementation project(':base')
}
base module gradle file
apply plugin: 'com.android.feature'
apply plugin: 'kotlin-kapt'
android {
compileSdkVersion 28
baseFeature true
defaultConfig {
minSdkVersion 17
targetSdkVersion 28
versionCode 1
versionName ""1.0""
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
api 'com.android.support:appcompat-v7:28.0.0'
api 'com.android.support.constraint:constraint-layout:1.1.3'
application project(':app')
feature project(':feature')
implementation ""android.arch.lifecycle:extensions:1.1.1""
kapt ""android.arch.lifecycle:compiler:1.1.1""
implementation 'com.github.bumptech.glide:glide:4.7.1'
kapt 'com.github.bumptech.glide:compiler:4.7.1'
implementation 'com.google.dagger:dagger:2.15.0'
kapt 'com.google.dagger:dagger-compiler:2.15.0'
implementation 'com.jakewharton:butterknife:9.0.0-rc2'
kapt 'com.jakewharton:butterknife-compiler:9.0.0-rc2'
}
feature module gradle file
apply plugin: 'com.android.feature'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
android {
compileSdkVersion 28
defaultConfig {
minSdkVersion 17
targetSdkVersion 28
versionCode 1
versionName ""1.0""
testInstrumentationRunner ""android.support.test.runner.AndroidJUnitRunner""
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation""org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version""
implementation project(':base')
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
instantapp gradle file
apply plugin: 'com.android.instantapp'
dependencies {
implementation project(':feature')
implementation project(':base')
}
==========
Solved
by adding kotlin-android plugin to the base module
apply plugin: 'kotlin-android'
",https://stackoverflow.com/questions/53823451/could-not-find-method-kapt-for-arguments,160,97013.0,10.0,,,2018-12-17 21:48:02,2025-01-15 20:34:20,2018-12-18 08:44:17,,,android;gradle;kotlin;android-gradle-plugin;android-instant-apps,O.Ahmed,1830,5538207,registered,true,,,CC BY-SA 4.0,,4275,4020,7,0,0,5,false,false,false,true,true,true,42,7,false,0.103,0.0016,2896,2018,12,21,Monday,false,false,false,false,false,false,false
46984770,"RegisterResGeneratingTask is deprecated, use registerGeneratedFolders(FileCollection)","Using new android studio with new 3.0.0 Gradle pluging.
When building some warning happened:
registerResGeneratingTask is deprecated, use
registerGeneratedFolders(FileCollection)
",https://stackoverflow.com/questions/46984770/registerresgeneratingtask-is-deprecated-use-registergeneratedfoldersfilecollec,160,61620.0,10.0,,,2017-10-27 23:34:24,2021-08-13 12:01:35,2019-04-24 08:21:45,,,android;android-studio;gradle;kotlin;android-studio-3.0,Valentin Baryshev,2215,4201925,registered,true,,,CC BY-SA 4.0,2018-05-01 19:41:15,216,181,1,0,0,5,false,false,false,true,true,true,85,5,false,0.162,0.0026,3312,2017,10,23,Friday,false,false,false,false,false,false,false
38492103,Override getter for Kotlin data class,"Given the following Kotlin class:
data class Test(val value: Int)
How would I override the Int getter so that it returns 0 if the value negative?
If this isn't possible, what are some techniques to achieve a suitable result?
",https://stackoverflow.com/questions/38492103/override-getter-for-kotlin-data-class,158,160222.0,9.0,,,2016-07-20 22:46:07,2025-03-20 19:55:19,,,,kotlin,spierce7,15996,471744,registered,true,46376746,,CC BY-SA 3.0,,287,229,2,0,0,1,true,false,false,true,true,false,37,6,false,0.056,0.001,3776,2016,7,22,Wednesday,false,false,false,false,false,false,false
37672023,How to create an instance of anonymous interface in Kotlin?,"I have a third party Java library which an object with interface like this:
public interface Handler<C> {
void call(C context) throws Exception;
}
How can I concisely implement it in Kotlin similar to Java anonymous class like this:
Handler<MyContext> handler = new Handler<MyContext> {
@Override
public void call(MyContext context) throws Exception {
System.out.println(""Hello world"");
}
}
handler.call(myContext) // Prints ""Hello world""
",https://stackoverflow.com/questions/37672023/how-to-create-an-instance-of-anonymous-interface-in-kotlin,157,107122.0,5.0,,,2016-06-07 06:30:34,2021-04-11 08:14:21,2016-06-07 06:48:00,,,java;lambda;kotlin;anonymous,Peter Lamberg,8761,1148030,registered,true,37672334,,CC BY-SA 3.0,,542,480,2,0,0,4,true,false,false,true,true,true,59,10,true,0.047,0.0015,3819,2016,6,6,Tuesday,false,false,false,true,false,false,false
55356837,What is the difference between init block and constructor in kotlin?,"I have started learning Kotlin. I would like to know the difference between init block and constructor.
What is the difference between this and how we can use this to improve?
class Person constructor(var name: String, var age: Int) {
var profession: String = ""test""
init {
println(""Test"")
}
}
",https://stackoverflow.com/questions/55356837/what-is-the-difference-between-init-block-and-constructor-in-kotlin,156,85431.0,4.0,,,2019-03-26 12:10:35,2022-11-22 06:51:13,2020-07-16 09:38:12,,,kotlin;constructor;initialization-block,Samir Bhatt,3299,3364266,registered,true,55374474,,CC BY-SA 4.0,,379,322,3,0,0,3,true,false,false,true,true,true,68,11,true,0.047,0.0018,2797,2019,3,12,Tuesday,false,false,false,false,false,false,false
44255946,Difference between a class and object in Kotlin,"I'm new to Kotlin and have recently converted a simple file from java to Kotlin. I am wondering why the Android converter changed my java class to a Kotlin object.
Java:
public class MyClass {
static public int GenerateChecksumCrc16(byte bytes[]) {
int crc = 0xFFFF;
int temp;
int crc_byte;
for (byte aByte : bytes) {
crc_byte = aByte;
for (int bit_index = 0; bit_index < 8; bit_index++) {
temp = ((crc >> 15)) ^ ((crc_byte >> 7));
crc <<= 1;
crc &= 0xFFFF;
if (temp > 0) {
crc ^= 0x1021;
crc &= 0xFFFF;
}
crc_byte <<= 1;
crc_byte &= 0xFF;
}
}
return crc;
}
}
Converted Kotlin:
object MyClass {
fun GenerateChecksumCrc16(bytes: ByteArray): Int {
var crc = 0xFFFF
var temp: Int
var crc_byte: Int
for (aByte in bytes) {
crc_byte = aByte.toInt()
for (bit_index in 0..7) {
temp = crc shr 15 xor (crc_byte shr 7)
crc = crc shl 1
crc = crc and 0xFFFF
if (temp > 0) {
crc = crc xor 0x1021
crc = crc and 0xFFFF
}
crc_byte = crc_byte shl 1
crc_byte = crc_byte and 0xFF
}
}
return crc
}
}
Why wasn't it:
class MyClass {
... etc ...
}
Any help would be greatly appreciated thanks.
",https://stackoverflow.com/questions/44255946/difference-between-a-class-and-object-in-kotlin,155,66480.0,6.0,,,2017-05-30 07:20:27,2024-04-16 07:36:51,2017-05-30 09:13:59,,,java;android;kotlin,Crunchy234,1957,4294726,registered,true,44256121,,CC BY-SA 3.0,2022-11-06 08:52:29,1744,1637,3,0,0,3,true,false,false,true,true,true,47,8,false,0.09,0.0023,3462,2017,5,7,Tuesday,false,false,false,true,false,false,false
37794850,Effective Enums in Kotlin with reverse lookup?,"I'm trying to find the best way to do a 'reverse lookup' on an enum in Kotlin. One of my takeaways from Effective Java was that you introduce a static map inside the enum to handle the reverse lookup. Porting this over to Kotlin with a simple enum leads me to code that looks like this:
enum class Type(val value: Int) {
A(1),
B(2),
C(3);
companion object {
val map: MutableMap<Int, Type> = HashMap()
init {
for (i in Type.values()) {
map[i.value] = i
}
}
fun fromInt(type: Int?): Type? {
return map[type]
}
}
}
My question is, is this the best way to do this, or is there a better way? What if I have several enums that follow a similar pattern? Is there a way in Kotlin to make this code more re-usable across enums?
",https://stackoverflow.com/questions/37794850/effective-enums-in-kotlin-with-reverse-lookup,155,81994.0,17.0,,,2016-06-13 16:30:46,2024-02-26 22:54:17,2017-10-22 11:09:43,,,enums;kotlin,Baron,1575,2108961,registered,true,37795810,,CC BY-SA 3.0,,882,844,1,0,0,2,true,false,false,true,true,true,46,7,true,0.207,0.0019,3813,2016,6,16,Monday,false,false,false,false,false,false,false
44117970,Kotlin Data Class from Json using GSON,"I have Java POJO class like this:
class Topic {
@SerializedName(""id"")
long id;
@SerializedName(""name"")
String name;
}
and I have a Kotlin data class Like this
data class Topic(val id: Long, val name: String)
How to provide the json key to any variables of the kotlin data class like the @SerializedName annotation in java variables ?
",https://stackoverflow.com/questions/44117970/kotlin-data-class-from-json-using-gson,155,162873.0,3.0,,,2017-05-22 16:34:13,2025-04-26 12:32:08,2018-04-15 04:23:26,,,java;json;gson;kotlin;data-class,erluxman,19715,2581314,registered,true,44118828,,CC BY-SA 3.0,,466,358,5,0,0,5,true,false,false,true,true,true,38,7,false,0.018,0.001,3470,2017,5,16,Monday,false,false,false,true,false,false,false
34169562,Unresolved reference: kotlinx,"I am trying to try out Kotlin and the Kotlin Android extensions in Android Studio. I have tried this both in Android Studio v 1.5.1 on Ubuntu 14.04, and in Android Studio v 1.5.1 on OS X El Capitan with the same result.
Here is what I am doing:
- I install the Kotlin plugin 1.0.0-beta-35950-IJ141-11
- Create a new blank Android project
- Convert the MainActivity file to Kotlin (via help->findaction->convert file to kotlin)
- Configure the project for Kotlin
I then go into the generated content_main.xml file and add an id (hello) for the ""Hello World!"" TextView.
<?xml version=""1.0"" encoding=""utf-8""?>
<RelativeLayout xmlns:android=""http://schemas.android.com/apk/res/android""
xmlns:app=""http://schemas.android.com/apk/res-auto""
xmlns:tools=""http://schemas.android.com/tools""
android:layout_width=""match_parent""
android:layout_height=""match_parent""
android:paddingBottom=""@dimen/activity_vertical_margin""
android:paddingLeft=""@dimen/activity_horizontal_margin""
android:paddingRight=""@dimen/activity_horizontal_margin""
android:paddingTop=""@dimen/activity_vertical_margin""
app:layout_behavior=""@string/appbar_scrolling_view_behavior""
tools:context=""com.gmail.npnster.mykotlinfirstproject.MainActivity""
tools:showIn=""@layout/activity_main"">
<TextView
android:layout_width=""wrap_content""
android:layout_height=""wrap_content""
android:text=""Hello World!""
android:id=""@+id/hello""
/>
</RelativeLayout>
Then in the converted MainActivity I add a line to set the TextView. (shown below).
Android Studio then prompts me (via alt-enter) to insert this line (also shown below)
import kotlinx.android.synthetic.main.content_main.*
So at this point everything seems fine
but then when I try to compile this I get
Unresolved reference: kotlinx
Unresolved reference: kotlinx
Unresolved reference: hello
Notice that I did not install the Kotlin Android extensions plugin. As of a couple of days ago this is now supposed to be included in the main plug in and is marked as obsolete. (In fact if you try to install it when you have the latest plugin, nothing new is installed)
Anyone see what I am doing wrong?
MainActivity
import android.os.Bundle
import android.support.design.widget.FloatingActionButton
import android.support.design.widget.Snackbar
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.view.View
import android.view.Menu
import android.view.MenuItem
import kotlinx.android.synthetic.main.content_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val toolbar = findViewById(R.id.toolbar) as Toolbar
setSupportActionBar(toolbar)
print(""setting text view value to hey"")
hello.text = ""hey""
val fab = findViewById(R.id.fab) as FloatingActionButton
fab.setOnClickListener { view -> Snackbar.make(view, ""Replace this with your own action"", Snackbar.LENGTH_LONG).setAction(""Action"", null).show() }
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
val id = item.itemId
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true
}
return super.onOptionsItemSelected(item)
}
}
",https://stackoverflow.com/questions/34169562/unresolved-reference-kotlinx,154,203955.0,21.0,,,2015-12-09 02:04:00,2022-08-03 20:08:38,,,,android-studio;kotlin;kotlin-android-extensions,nPn,16880,2612259,registered,true,34173727,,CC BY-SA 3.0,,4120,3890,4,0,0,3,true,false,false,true,true,false,29,3,false,0.103,0.0008,4000,2015,12,2,Wednesday,false,false,false,false,false,false,false
50686907,Safeargs library doesnt generate direction class,"I use navigation library and safeargs for passing data. I define argument to fragment like that.
<fragment
android:id=""@+id/otherFragment""
android:name=""com.asd.navigate.OtherFragment""
android:label=""OtherFragment"">
<argument
android:name=""screenTitle""
android:defaultValue=""0""
app:type=""string"" />
</fragment>
OtherFragmentArgs generated, I can use it but OtherFragmentDirection class doesnt generate when I click ""make project"". Is that bug or I have to do something different.
Thnx for advice.
buildscript {
...
dependencies {
...
classpath ""android.arch.navigation:navigation-safe-args-gradle-plugin:1.0.0-alpha01""
}
}
build.gradle
apply plugin: ""androidx.navigation.safeargs""
MainActivity.kt
",https://stackoverflow.com/questions/50686907/safeargs-library-doesnt-generate-direction-class,154,77107.0,28.0,,,2018-06-04 18:43:47,2025-07-15 09:38:45,2018-06-05 10:50:20,,,kotlin;android-navigation;android-jetpack,6155031,4367,6155031,registered,true,51198551,,CC BY-SA 4.0,2021-07-20 04:34:37,1082,827,3,1,1,3,true,false,false,true,true,true,48,6,false,0.363,0.002,3092,2018,6,18,Monday,false,false,false,false,false,false,false
26472839,Are there constructor references in Kotlin?,"In Java we have the Class::new syntax for constructor references. I know, there are callable references for methods, but how about constructors? A typical use case for me would be factories.
",https://stackoverflow.com/questions/26472839/are-there-constructor-references-in-kotlin,154,23769.0,1.0,,,2014-10-20 18:51:39,2021-11-24 15:51:47,2021-11-24 15:51:47,,,kotlin;function-reference;constructor-reference,Kirill Rakhman,44151,615306,registered,true,26479515,,CC BY-SA 4.0,,211,191,1,0,0,3,true,false,false,true,true,true,43,6,true,0.042,0.0065,4415,2014,10,18,Monday,false,false,false,false,false,false,false
33381384,How to use TypeToken + generics with Gson in Kotlin,"I'm unable to get a List of generic type from a custom class (Turns):
val turnsType = TypeToken<List<Turns>>() {}.type
val turns = Gson().fromJson(pref.turns, turnsType)
it said:
cannot access '<init>' it is 'public /*package*/' in 'TypeToken'
",https://stackoverflow.com/questions/33381384/how-to-use-typetoken-generics-with-gson-in-kotlin,153,75497.0,7.0,,,2015-10-28 01:29:08,2021-06-25 13:43:45,,,,generics;gson;kotlin;typetoken,Juan Saravia,7721,3212266,registered,true,33381385,,CC BY-SA 3.0,,330,268,2,0,0,4,true,false,false,true,true,false,51,10,false,0.093,0.002,4042,2015,10,1,Wednesday,false,false,false,false,false,false,false
50343634,Android P visibilityawareimagebutton.setVisibility can only be called from the same library group,"I'm trying to use the new Android P FloatingActionButton that's part of the com.google.android.material.floatingactionbutton.FloatingActionButton and I'm getting this warning:
VisibilityAwareImageButton.setVisibility can only be called from the same library group (groupId=com.google.android.material)
import com.google.android.material.floatingactionbutton.FloatingActionButton
import android.view.View
class MainActivity : AppCompatActivity() {
lateinit var demoFab: FloatingActionButton
override fun onCreate(savedInstanceState: Bundle?) {
demoFab = findViewById(R.id.demoFab)
demoFab.visibility = View.VISIBLE // the warning is here
}
}
I've tried searching and the only search result is in regards to responding to UI visibility changes:
Respond to UI visibility changes
I tried exploring how I could to see if there was a VISIBLE int value in that com.google.android.material package and the only one I found was com.google.android.material.floatingactionbutton.FloatingActionButton.VISIBLE, but the warning still remains.
Top-level build.gradle
buildscript {
ext.kotlin_version = '1.2.41'
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.2.0-alpha14'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "com.google.gms:oss-licenses:0.9.2"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
mavenCentral()
maven { url "http://oss.sonatype.org/content/repositories/snapshots/" }
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
Project-level build.gradle
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'com.google.gms.oss.licenses.plugin'
android {
compileSdkVersion 'android-P'
defaultConfig {
applicationId "com.codeforsanjose.maps.pacmap"
minSdkVersion 21
targetSdkVersion 'P'
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
splits {
abi {
enable true
reset()
include 'arm64-v8a', 'armeabi', 'armeabi-v7a', 'mips', 'x86', 'x86_64'
universalApk false
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
buildTypes {
release {
minifyEnabled true
shrinkResources true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.0.0-alpha1'
implementation 'androidx.constraintlayout:constraintlayout:1.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.1.0-alpha2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha2'
implementation 'com.mapbox.mapboxsdk:mapbox-android-sdk:5.5.2'
//implementation 'com.mapbox.mapboxsdk:mapbox-android-sdk:6.1.0'
implementation 'com.mapbox.mapboxsdk:mapbox-android-plugin-locationlayer:0.5.0'
implementation 'com.mapbox.mapboxsdk:mapbox-android-navigation:0.13.0'
implementation 'com.mapbox.mapboxsdk:mapbox-android-navigation-ui:0.13.0'
implementation 'com.google.android.gms:play-services-oss-licenses:15.0.1'
implementation 'com.google.code.gson:gson:2.8.2'
implementation 'com.squareup.moshi:moshi:1.5.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.10.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
implementation 'com.squareup.retrofit2:converter-moshi:2.4.0'
implementation "com.squareup.retrofit2:adapter-rxjava2:2.3.0"
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
implementation 'io.reactivex.rxjava2:rxkotlin:2.2.0'
}
edit:
I should note that I'm using Android Studio version 3.2 canary 14. It seems there have been some reported bugs for this version, and I suspect this is one of them.
edit 2:
Issue still exists with Android Studio version 3.2 canary 15, but I found a workaround for it using show() and hide()
override fun onCreate(savedInstanceState: Bundle?) {
demoFab = findViewById(R.id.demoFab)
demoFab.show() // this works and doesn't have the warning
}
",https://stackoverflow.com/questions/50343634/android-p-visibilityawareimagebutton-setvisibility-can-only-be-called-from-the-s,153,33226.0,8.0,,,2018-05-15 06:30:12,2020-07-24 08:01:23,2020-07-24 08:01:23,,,android;kotlin;android-9.0-pie;android-jetpack,Kyle Falconer,8570,940217,registered,true,51382320,,CC BY-SA 4.0,,5379,4854,10,2,1,4,true,false,false,true,true,true,97,12,false,0.241,0.0046,3112,2018,5,6,Tuesday,false,false,false,false,false,false,false
45518139,Kotlin Android start new Activity,"I want to start another activity on Android but I get this error:
Please specify constructor invocation; classifier 'Page2' does not have a companion object
after instantiating the Intent class. What should I do to correct the error? My code:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun buTestUpdateText2 (view: View) {
val changePage = Intent(this, Page2)
// Error: ""Please specify constructor invocation;
// classifier 'Page2' does not have a companion object""
startActivity(changePage)
}
}
",https://stackoverflow.com/questions/45518139/kotlin-android-start-new-activity,152,265813.0,19.0,,,2017-08-05 04:16:14,2023-09-09 07:46:03,2020-03-11 01:02:17,,,android;kotlin;android-intent;android-activity,J Adonai Dagdag,1965,8084935,registered,true,45518762,,CC BY-SA 4.0,2018-01-26 08:42:56,786,703,2,0,0,4,true,false,false,true,true,true,33,5,false,0.071,0.0006,3395,2017,8,4,Saturday,true,false,false,false,false,false,false
75480173,Android Studio build error - compileDebugJavaWithJavac task (current target is 1.8) and kaptGenerateStubsDebugKotlin task (current target is 17),"Getting the following build error in Android Studio
compileDebugJavaWithJavac task (current target is 1.8) and kaptGenerateStubsDebugKotlin task (current target is 17) jvm target compatibility should be set to the same java version
during the kaptGenerateStubsDebugKotlin step of project build in Android Studio
Am on Android Studio Giraffe | 2022.3.1 Canary 3
Full stack trace below
Execution failed for task ':app:kaptGenerateStubsDebugKotlin'.
> 'compileDebugJavaWithJavac' task (current target is 1.8) and 'kaptGenerateStubsDebugKotlin' task (current target is 17) jvm target compatibility should be set to the same Java version.
Consider using JVM toolchain: https://kotl.in/gradle/jvm/toolchain
* Try:
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:kaptGenerateStubsDebugKotlin'.
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.lambda$executeIfValid$1(ExecuteActionsTaskExecuter.java:149)
at org.gradle.internal.Try$Failure.ifSuccessfulOrElse(Try.java:282)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeIfValid(ExecuteActionsTaskExecuter.java:147)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:135)
at org.gradle.api.internal.tasks.execution.FinalizePropertiesTaskExecuter.execute(FinalizePropertiesTaskExecuter.java:46)
at org.gradle.api.internal.tasks.execution.ResolveTaskExecutionModeExecuter.execute(ResolveTaskExecutionModeExecuter.java:51)
at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:57)
at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:57)
at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:36)
at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.executeTask(EventFiringTaskExecuter.java:77)
at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:55)
at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:52)
at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:204)
at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:199)
at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:66)
at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:59)
at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:157)
at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:59)
at org.gradle.internal.operations.DefaultBuildOperationRunner.call(DefaultBuildOperationRunner.java:53)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:73)
at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:52)
at org.gradle.execution.plan.LocalTaskNodeExecutor.execute(LocalTaskNodeExecutor.java:42)
at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:338)
at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:325)
at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:318)
at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:304)
at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.execute(DefaultPlanExecutor.java:463)
at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.run(DefaultPlanExecutor.java:380)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:49)
Caused by: org.gradle.api.GradleException: 'compileDebugJavaWithJavac' task (current target is 1.8) and 'kaptGenerateStubsDebugKotlin' task (current target is 17) jvm target compatibility should be set to the same Java version.
Consider using JVM toolchain: https://kotl.in/gradle/jvm/toolchain
at org.jetbrains.kotlin.gradle.tasks.KotlinCompile.validateKotlinAndJavaHasSameTargetCompatibility(Tasks.kt:797)
at org.jetbrains.kotlin.gradle.tasks.KotlinCompile.callCompilerAsync$kotlin_gradle_plugin_common(Tasks.kt:722)
at org.jetbrains.kotlin.gradle.tasks.KotlinCompile.callCompilerAsync$kotlin_gradle_plugin_common(Tasks.kt:530)
at org.jetbrains.kotlin.gradle.tasks.AbstractKotlinCompile.executeImpl(Tasks.kt:450)
at org.jetbrains.kotlin.gradle.tasks.AbstractKotlinCompile.execute(Tasks.kt:417)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:125)
at org.gradle.api.internal.project.taskfactory.IncrementalTaskAction.doExecute(IncrementalTaskAction.java:45)
at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:51)
at org.gradle.api.internal.project.taskfactory.IncrementalTaskAction.execute(IncrementalTaskAction.java:26)
at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:29)
at org.gradle.api.internal.tasks.execution.TaskExecution$3.run(TaskExecution.java:242)
at org.gradle.internal.operations.DefaultBuildOperationRunner$1.execute(DefaultBuildOperationRunner.java:29)
at org.gradle.internal.operations.DefaultBuildOperationRunner$1.execute(DefaultBuildOperationRunner.java:26)
at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:66)
at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:59)
at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:157)
at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:59)
at org.gradle.internal.operations.DefaultBuildOperationRunner.run(DefaultBuildOperationRunner.java:47)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:68)
at org.gradle.api.internal.tasks.execution.TaskExecution.executeAction(TaskExecution.java:227)
at org.gradle.api.internal.tasks.execution.TaskExecution.executeActions(TaskExecution.java:210)
at org.gradle.api.internal.tasks.execution.TaskExecution.executeWithPreviousOutputFiles(TaskExecution.java:193)
at org.gradle.api.internal.tasks.execution.TaskExecution.execute(TaskExecution.java:166)
at org.gradle.internal.execution.steps.ExecuteStep.executeInternal(ExecuteStep.java:93)
at org.gradle.internal.execution.steps.ExecuteStep.access$000(ExecuteStep.java:44)
at org.gradle.internal.execution.steps.ExecuteStep$1.call(ExecuteStep.java:57)
at org.gradle.internal.execution.steps.ExecuteStep$1.call(ExecuteStep.java:54)
at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execut",https://stackoverflow.com/questions/75480173/android-studio-build-error-compiledebugjavawithjavac-task-current-target-is-1,152,127711.0,25.0,,,2023-02-17 04:10:50,2025-04-21 17:21:03,2023-11-06 08:56:44,,,android;android-studio;kotlin;gradle;android-gradle-plugin,Arunabh Das,14458,303347,registered,true,,,CC BY-SA 4.0,2025-04-21 17:31:33,18131,18055,2,0,0,5,false,false,false,true,true,true,144,18,false,0.196,0.0012,1373,2023,2,4,Friday,false,false,false,false,false,false,false
45267041,"Not enough information to infer parameter T" with Kotlin and Android,"I'm trying to replicate the following ListView in my Android app using Kotlin: https://github.com/bidrohi/KotlinListView.
Unfortunately I'm getting an error I'm unable to resolve myself.
Here's my code:
MainActivity.kt:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val listView = findViewById(R.id.list) as ListView
listView.adapter = ListExampleAdapter(this)
}
private class ListExampleAdapter(context: Context) : BaseAdapter() {
internal var sList = arrayOf(""Eins"", ""Zwei"", ""Drei"")
private val mInflator: LayoutInflater
init {
this.mInflator = LayoutInflater.from(context)
}
override fun getCount(): Int {
return sList.size
}
override fun getItem(position: Int): Any {
return sList[position]
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View? {
val view: View?
val vh: ListRowHolder
if(convertView == null) {
view = this.mInflator.inflate(R.layout.list_row, parent, false)
vh = ListRowHolder(view)
view.tag = vh
} else {
view = convertView
vh = view.tag as ListRowHolder
}
vh.label.text = sList[position]
return view
}
}
private class ListRowHolder(row: View?) {
public val label: TextView
init {
this.label = row?.findViewById(R.id.label) as TextView
}
}
}
The layouts are exactly as here: https://github.com/bidrohi/KotlinListView/tree/master/app/src/main/res/layout
The full error message I'm getting is this:
Error:(92, 31) Type inference failed: Not enough information to infer parameter T in fun findViewById(p0: Int): T!
Please specify it explicitly.
I'd appreciate any help I can get.
",https://stackoverflow.com/questions/45267041/not-enough-information-to-infer-parameter-t-with-kotlin-and-android,151,145557.0,7.0,,,2017-07-23 15:53:52,2022-06-06 18:10:49,2017-08-22 18:11:26,,,android;kotlin;android-8.0-oreo,Timo Güntner,2861,2874407,registered,true,45297610,,CC BY-SA 3.0,,2194,1936,1,2,0,3,true,false,false,true,true,true,79,11,false,0.048,0.001,3408,2017,7,15,Sunday,true,false,false,false,false,false,false
67663728,Spring Boot 2.5.0 generates plain.jar file. Can I remove it?,"After the Spring Boot 2.5.0 update, it generates the myprogram-0.0.1-plain.jar file alongside the usual myprogram-0.0.1.jar. Can I disallow gradle to generate the *.plain.jar file? I use Gradle 7.0.2.
What I get:
build/
libs/
myprogram-0.0.1.jar
myprogram-0.0.1-plain.jar
What I want:
build/
libs/
myprogram-0.0.1.jar
build.gradle:
plugins {
id 'org.springframework.boot' version '2.5.0'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
test {
useJUnitPlatform()
}
",https://stackoverflow.com/questions/67663728/spring-boot-2-5-0-generates-plain-jar-file-can-i-remove-it,150,82913.0,8.0,,,2021-05-23 19:45:05,2025-04-01 11:06:57,2021-06-12 16:13:00,,,java;spring;spring-boot;kotlin;gradle,Tien Do Nam,4698,11127438,registered,true,67663956,,CC BY-SA 4.0,,939,800,6,0,0,5,true,false,false,true,true,true,60,10,true,0.096,0.0018,2008,2021,5,19,Sunday,true,false,false,true,false,false,false
37906607,Getters and Setters in Kotlin,"In Java, for example, I can write getters on my own (generated by IDE) or use Annotations like @Getter in lombok - which was pretty simple.
Kotlin however has getters and setters by default.
But I can't understand how to use them.
I want to make it, lets say - similar to Java:
private val isEmpty: String
get() = this.toString() //making this thing public rises an error: Getter visibility must be the same as property visibility.
So how do getters work?
",https://stackoverflow.com/questions/37906607/getters-and-setters-in-kotlin,146,192123.0,8.0,,,2016-06-19 11:14:03,2023-08-28 14:14:53,2017-09-15 15:00:00,,,kotlin;getter-setter,nutella_eater,3644,2787507,registered,true,37906803,,CC BY-SA 3.0,,607,470,1,1,0,2,true,false,false,true,true,true,29,5,false,0.042,0.0008,3807,2016,6,11,Sunday,true,false,false,false,false,false,false
59133100,How to close the virtual keyboard from a Jetpack Compose TextField?,"I'm using the Jetpack Compose TextField and I want to close the virtual keyboard when the user press the the action button (imeActionPerformed parameter).
val text = +state { """" }
TextField(
value = text.value,
keyboardType = KeyboardType.Text,
imeAction = ImeAction.Done,
onImeActionPerformed = {
// TODO Close the virtual keyboard here <<<
}
onValueChange = { s -> text.value = s }
)
",https://stackoverflow.com/questions/59133100/how-to-close-the-virtual-keyboard-from-a-jetpack-compose-textfield,143,86876.0,10.0,,,2019-12-02 05:25:46,2024-06-14 06:12:26,2021-02-18 11:34:44,,,android;kotlin;android-jetpack-compose;android-input-method;android-compose-textfield,nglauber,24715,1094333,registered,true,66259111,,CC BY-SA 4.0,,490,433,3,0,0,5,true,false,false,true,true,true,67,11,true,0.115,0.0016,2546,2019,12,5,Monday,false,false,false,false,false,false,false
9562605,In Kotlin can I create a range that counts backwards?,"I looked at the documentation for the Ranges and I see no mention of backwards ranges.
Is it possible to do something like:
for (n in 100..1) {
println(n)
}
And get results:
100
99
98
...
",https://stackoverflow.com/questions/9562605/in-kotlin-can-i-create-a-range-that-counts-backwards,143,64183.0,5.0,,,2012-03-05 06:42:18,2022-12-05 09:14:22,,,,range;kotlin,jjnguy,139540,2598,registered,true,12646945,,CC BY-SA 3.0,,352,198,2,1,0,2,true,false,false,true,true,false,53,10,true,0.078,0.0022,5374,2012,3,6,Monday,false,false,false,false,false,false,false
33849811,Property must be initialized or be abstract,"How to declare class field? Like we can have it in java:
protected SharedPreferences mSharedPreferences;
And later in onCreate():
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
Now I can use it anywhere I want (in subclasses of this base activity).
I try to do same in Kotlin:
protected var sharedPreferences : SharedPreferences
And in onCreate():
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
But I get a warning: "Property must be initialized or be abstract"
",https://stackoverflow.com/questions/33849811/property-must-be-initialized-or-be-abstract,142,68781.0,2.0,,,2015-11-21 23:21:58,2022-04-21 09:31:12,2022-04-21 09:31:12,,,android;kotlin,Anton Shkurenko,4347,4142087,registered,true,33849879,,CC BY-SA 4.0,,691,527,6,0,0,2,true,false,false,true,true,true,43,7,false,0.029,0.0021,4018,2015,11,23,Saturday,true,false,false,false,false,false,false
43857824,static methods and variables in Kotlin?,"I want to be able to save a class instance to a private/public static variable, but I can't figure out how to do this in Kotlin.
public class Foo {
private static Foo instance;
public Foo() {
if (instance == null) {
instance = this;
}
}
public static Foo get() {
return instance;
}
}
",https://stackoverflow.com/questions/43857824/static-methods-and-variables-in-kotlin,140,200098.0,4.0,,,2017-05-08 21:52:17,2023-04-29 03:58:39,2023-04-29 03:29:32,,,java;kotlin;static-methods,Caleb Bassham,1963,7977034,registered,true,43857895,,CC BY-SA 4.0,,378,347,1,0,0,3,true,false,false,true,true,true,39,6,true,0.02,0.0007,3484,2017,5,21,Monday,false,false,false,true,false,false,false
35253368,How can I create an array in Kotlin like in Java by just providing a size?,"How can I create a Array like we do in java?
int A[] = new int[N];
How can I do this in Kotlin?
",https://stackoverflow.com/questions/35253368/how-can-i-create-an-array-in-kotlin-like-in-java-by-just-providing-a-size,140,122282.0,6.0,,,2016-02-07 12:18:11,2022-09-11 02:26:24,,,,java;arrays;arraylist;kotlin,Kevin Mathew,1527,3578039,registered,true,35253626,,CC BY-SA 3.0,,137,99,1,0,0,4,true,false,false,true,true,false,74,16,true,0.049,0.0011,3940,2016,2,12,Sunday,true,false,false,true,false,false,false
44188240,Kotlin - How to correctly concatenate a String,"A very basic question, what is the right way to concatenate a String in Kotlin?
In Java you would use the concat() method, e.g.
String a = ""Hello "";
String b = a.concat(""World""); // b = Hello World
The concat() function isn't available for Kotlin though. Should I use the + sign?
",https://stackoverflow.com/questions/44188240/kotlin-how-to-correctly-concatenate-a-string,139,217533.0,15.0,,,2017-05-25 19:18:17,2023-06-02 22:00:14,2017-05-26 06:07:12,,,string;kotlin,Daniele,4373,6427630,registered,true,44188301,,CC BY-SA 3.0,,368,284,4,0,0,2,true,false,false,true,true,true,46,8,false,0.069,0.0006,3467,2017,5,19,Thursday,false,false,false,false,false,false,false
62577645,android.view.View.systemUiVisibility deprecated. What is the replacement?,"I have updated the project target API version to 30, and now I see that the systemUiVisibility property is deprecated.
The following kotlin code is the one I'm using which is actually equivalent to setSystemUiVisibility method in Java.
playerView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LOW_PROFILE
or View.SYSTEM_UI_FLAG_FULLSCREEN
or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION)
Please let me know if you have got any stable replacement for this deprecated code. The google's recommendation is to use WindowInsetsController, but I don't how to do that.
",https://stackoverflow.com/questions/62577645/android-view-view-systemuivisibility-deprecated-what-is-the-replacement,139,114856.0,22.0,,,2020-06-25 14:24:41,2023-11-24 05:16:49,,,,android;kotlin,Doctiger,2557,5348553,registered,true,,,CC BY-SA 4.0,,907,733,2,1,0,2,false,false,false,true,true,false,73,6,true,0.192,0.0012,2340,2020,6,14,Thursday,false,false,false,false,false,false,false
64925126,How to use @Parcelize now that kotlin-android-extensions is being deprecated?,"How do I replace annotation class Parcelize from package kotlinx.android.parcel with @Parcelize which is not coming from the kotlin-android-extensions plugin?
",https://stackoverflow.com/questions/64925126/how-to-use-parcelize-now-that-kotlin-android-extensions-is-being-deprecated,138,124432.0,7.0,,,2020-11-20 07:02:03,2025-02-15 13:55:30,2022-10-22 14:16:43,,,android;kotlin;annotations;parcelable,vepzfe,4653,3090120,registered,true,64948848,,CC BY-SA 4.0,,218,159,4,0,0,4,true,false,false,true,true,true,77,10,true,0.056,0.0011,2192,2020,11,7,Friday,false,false,false,false,false,false,false
29046636,Mark unused parameters in Kotlin,"I am defining some functions to be used as callbacks and not all of them use all their parameters.
How can I mark unused parameters so that the compiler won't give me warnings about them?
",https://stackoverflow.com/questions/29046636/mark-unused-parameters-in-kotlin,138,64136.0,4.0,,,2015-03-14 07:39:17,2020-09-09 20:52:44,,,,suppress-warnings;kotlin;unused-variables,TheTeaMan,2503,1009356,registered,true,29046925,,CC BY-SA 3.0,,203,189,0,0,0,3,true,false,false,true,true,false,32,5,false,0.062,0.0022,4270,2015,3,7,Saturday,true,false,false,false,false,false,false
47307782,How to return multiple values from a function in Kotlin like we do in Swift?,"How to return 3 separate data values of the same type (Int) from a function in Kotlin?
I'm attempting to return the time of day, I need to return the Hour, Minute and Second as separate integers, but all in one go from the same function, is this possible?
In swift we do it like following,
func getTime() -> (Int, Int, Int) {
...
return ( hour, minute, second)
}
can we achieve this in Kotlin?
P.S: I know I can use Array or Hashmap for this but I want to know if there exists something in Kotlin like it is in Swift.
",https://stackoverflow.com/questions/47307782/how-to-return-multiple-values-from-a-function-in-kotlin-like-we-do-in-swift,134,112458.0,9.0,,,2017-11-15 12:45:06,2025-05-21 22:16:38,2025-05-21 22:16:38,,,kotlin,AwaisMajeed,2314,7676637,registered,true,47308092,,CC BY-SA 4.0,,602,530,2,0,0,1,true,false,false,true,true,true,76,15,true,0.08,0.0012,3293,2017,11,12,Wednesday,false,false,false,false,false,false,false
48391217,Extend and implement at the same time in Kotlin,"In Java, you can do such thing as:
class MyClass extends SuperClass implements MyInterface, ...
Is it possible to do the same thing in Kotlin? Assuming SuperClass is abstract and does not implement MyInterface
",https://stackoverflow.com/questions/48391217/extend-and-implement-at-the-same-time-in-kotlin,134,78943.0,2.0,,,2018-01-22 22:22:02,2020-04-04 11:01:39,2018-01-22 22:26:15,,,java;kotlin,chntgomez,2139,931724,registered,true,48391246,,CC BY-SA 3.0,,277,213,3,0,0,2,true,false,false,true,true,true,47,9,false,0.025,0.0017,3225,2018,1,22,Monday,false,false,false,true,false,false,false
50230466,Kotlin: withContext() vs Async-await,"I have been reading kotlin docs, and if I understood correctly the two Kotlin functions work as follows :
withContext(context): switches the context of the current coroutine, when the given block executes, the coroutine switches back to previous context.
async(context): Starts a new coroutine in the given context and if we call .await() on the returned Deferred task, it will suspends the calling coroutine and resume when the block executing inside the spawned coroutine returns.
Now for the following two versions of code :
Version1:
launch(){
block1()
val returned = async(context){
block2()
}.await()
block3()
}
Version2:
launch(){
block1()
val returned = withContext(context){
block2()
}
block3()
}
- In both versions block1(), block3() execute in default context(commonpool?) where as block2() executes in the given context.
- The overall execution is synchronous with block1() -> block2() -> block3() order.
- Only difference I see is that version1 creates another coroutine, where as version2 executes only one coroutine while switching context.
My questions are :
Isn't it always better to use withContext rather than async-await as it is functionally similar, but doesn't create another coroutine. Large numbers of coroutines, although lightweight, could still be a problem in demanding applications.
Is there a case async-await is more preferable to withContext?
Update:
Kotlin 1.2.50 now has a code inspection where it can convert async(ctx) { }.await() to withContext(ctx) { }.
",https://stackoverflow.com/questions/50230466/kotlin-withcontext-vs-async-await,134,42450.0,3.0,,,2018-05-08 09:35:56,2022-08-05 10:22:36,2020-08-19 19:01:53,,,kotlin;kotlin-coroutines,Mangat Rai Modi,5746,1699956,registered,true,50231191,,CC BY-SA 4.0,,2134,1556,12,2,0,2,true,false,false,true,true,true,36,4,false,0.071,0.0032,3119,2018,5,9,Tuesday,false,false,false,false,false,false,false
42234775,How to check if an array of strings contains a value in Kotlin,"How can I check if an array of strings contains a value in Kotlin? Just like ruby's #include?.
I thought about:
array.filter { it == "value" }.any()
Is there another way?
",https://stackoverflow.com/questions/42234775/how-to-check-if-an-array-of-strings-contains-a-value-in-kotlin,133,168376.0,7.0,,,2017-02-14 19:39:44,2024-10-07 22:33:56,2023-10-19 14:31:48,,,arrays;kotlin,ju_293847293,6766,1052504,registered,true,42234854,,CC BY-SA 4.0,,281,182,2,0,0,2,true,false,false,true,true,true,62,13,false,0.042,0.0008,3567,2017,2,19,Tuesday,false,false,false,false,false,false,false
48242437,How to add a maven repository by url using kotlinscript DSL (build.gradle.kts),"Whats the equivalent of the following code snippet from a build.gradle in a build.gradle.kts version?
repositories {
mavenCentral()
maven {
url '<MAVEN REPO URL>'
}
}
",https://stackoverflow.com/questions/48242437/how-to-add-a-maven-repository-by-url-using-kotlinscript-dsl-build-gradle-kts,133,77524.0,5.0,,,2018-01-13 17:31:01,2024-10-30 14:21:01,2018-01-13 20:47:06,,,gradle;kotlin;gradle-kotlin-dsl,Florian Reisinger,3198,1870799,registered,true,48243501,,CC BY-SA 3.0,,242,185,3,0,0,3,true,false,false,true,true,true,78,12,false,0.064,0.0017,3234,2018,1,17,Saturday,true,false,false,false,false,false,false
45090808,IntArray vs Array<Int> in Kotlin,"I'm not sure what the difference between an IntArray and an Array<Int> is in Kotlin and why I can't used them interchangeably:
I know that IntArray translates to int[] when targeting the JVM, but what does Array<Int> translate to?
Also, you can also have String[] or YourObject[]. Why Kotlin has classes of the type {primitive}Array when pretty much anything can be arranged into an array, not only primitives.
",https://stackoverflow.com/questions/45090808/intarray-vs-arrayint-in-kotlin,133,41427.0,3.0,,,2017-07-13 21:00:42,2018-10-26 12:42:57,,,,kotlin,frankelot,14559,1949554,registered,true,45094889,,CC BY-SA 3.0,,694,427,9,1,1,1,true,false,false,true,true,false,38,5,false,0.072,0.0032,3418,2017,7,21,Thursday,false,false,false,false,false,false,false
49112190,Error : Program type already present: android.support.design.widget.CoordinatorLayout$Behavior,"I am getting the following error while building the project. haven't used CoordinatorLayout in this project. just added as a dependency in build.gradle :
I am using Android Studio 3.2 Canary 4.
LogCat
AGPBI: {""kind"":""error"",""text"":""Program type already present: android.support.design.widget.CoordinatorLayout$Behavior"",""sources"":[{}],""tool"":""D8""}
:app:transformDexArchiveWithExternalLibsDexMergerForDebug FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
com.android.builder.dexing.DexArchiveMergerException: Error while merging dex archives: /windows/Other/app/build/intermediates/transforms/dexBuilder/debug/0.jar, /windows/Other/app/build/intermediates/transforms/dexBuilder/debug/1.jar, /windows/Other/app/build/intermediates/transforms/dexBuilder/debug/4.jar,
.
.
...................
/windows/Other/app/build/intermediates/transforms/dexBuilder/debug/294.jar
Program type already present: android.support.design.widget.CoordinatorLayout$Behavior
build.gradle
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
android {
compileSdkVersion 27
buildToolsVersion ""27.0.3""
defaultConfig {
applicationId ""com.dagkot""
minSdkVersion 16
targetSdkVersion 27
versionCode 1
versionName ""1.0""
testInstrumentationRunner ""android.support.test.runner.AndroidJUnitRunner""
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
buildConfigField ""String"", ""BASE_URL"", ""\""http://api.openweathermap.org/data/2.5/\""""
buildConfigField ""String"", ""API_KEY"", ""\""435e9075f348868c2714fe7c6895efa5\""""
}
debug {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
buildConfigField ""String"", ""BASE_URL"", ""\""http://api.openweathermap.org/data/2.5/\""""
buildConfigField ""String"", ""API_KEY"", ""\""xxxx\""""
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:27.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation('com.android.support.test.espresso:espresso-core:3.0.1', {
exclude group: 'com.android.support', module: 'support-annotations'
})
implementation""org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version""
// Dagger dependencies
compileOnly 'org.glassfish:javax.annotation:10.0-b28'
implementation ""com.google.dagger:dagger:$rootProject.daggerVersion""
implementation ""com.google.dagger:dagger-android:$rootProject.daggerVersion""
implementation ""com.google.dagger:dagger-android-support:$rootProject.daggerVersion""
kapt ""com.google.dagger:dagger-android-processor:$rootProject.daggerVersion""
kapt ""com.google.dagger:dagger-compiler:$rootProject.daggerVersion""
//Butterknife dependencies
implementation 'com.jakewharton:butterknife:8.8.1'
kapt 'com.jakewharton:butterknife-compiler:8.8.1'
// Architecture Components Dependencies
kapt ""android.arch.lifecycle:compiler:$rootProject.lifeCycle""
implementation ""android.arch.lifecycle:extensions:$rootProject.lifeCycle""
implementation ""android.arch.lifecycle:reactivestreams:$rootProject.lifeCycle""
implementation ""com.android.support:cardview-v7:$rootProject.supportLibraryVersion""
// Retrofit/RxJava Dependencies
implementation ""com.squareup.retrofit2:retrofit:$rootProject.retrofitVersion""
implementation ""com.squareup.retrofit2:adapter-rxjava2:$rootProject.retrofitVersion""
implementation ""com.squareup.retrofit2:converter-gson:$rootProject.retrofitVersion""
implementation ""io.reactivex.rxjava2:rxandroid:$rootProject.rxAndroidVersion""
implementation 'com.squareup.okhttp3:logging-interceptor:3.6.0'
implementation 'com.jakewharton.rxbinding2:rxbinding-kotlin:2.1.1'
// GSON
implementation ""com.google.code.gson:gson:$rootProject.gsonVersion""
// Rx Location Manager
implementation 'io.nlopez.smartlocation:library:3.3.3'
implementation 'io.nlopez.smartlocation:rx:3.3.1'
//Anko Dependencies
implementation ""org.jetbrains.anko:anko-commons:$rootProject.anko_version""
implementation ""org.jetbrains.anko:anko-design:$rootProject.anko_version""
implementation 'com.android.support:design:27.0.2'
implementation(""com.github.hotchemi:permissionsdispatcher:3.1.0"") {
// if you don't use android.app.Fragment you can exclude support for them
exclude module: ""support-v13""
}
kapt ""com.github.hotchemi:permissionsdispatcher-processor:3.1.0""
}
",https://stackoverflow.com/questions/49112190/error-program-type-already-present-android-support-design-widget-coordinatorl,132,191147.0,22.0,,,2018-03-05 14:02:32,2019-09-05 13:27:55,2019-04-05 19:55:23,,,android;kotlin;dagger-2;android-coordinatorlayout,Ankit Mehta,4269,5129039,registered,true,49155448,,CC BY-SA 4.0,,5096,4957,1,0,0,4,true,false,false,true,true,true,94,7,false,0.115,0.0007,3183,2018,3,14,Monday,false,false,false,false,false,false,false
64181930,Request Focus on TextField in jetpack compose,"How to auto focus on textfield in jetpack compose. When i click on textfield and start typing on it. Meantime when i click back button,then when i'm try to click on textfield, nothing happens.
val textState = remember { mutableStateOf(TextFieldValue()) }
TextField(
modifier = Modifier.fillMaxWidth(),
value = textState.value,
onValueChange = { value : TextFieldValue ->
textState.value = value
}
)
",https://stackoverflow.com/questions/64181930/request-focus-on-textfield-in-jetpack-compose,132,95998.0,7.0,,,2020-10-03 07:51:13,2024-07-01 08:20:49,2022-10-03 17:40:28,,,android;kotlin;android-jetpack-compose;android-compose-textfield,Mukul jangir,1421,14383717,registered,true,,,CC BY-SA 4.0,,499,427,1,0,0,4,false,false,false,true,true,true,45,7,false,0.073,0.0014,2240,2020,10,7,Saturday,true,false,false,false,false,false,false
45875491,What is a "receiver" in Kotlin?,"How is it related to extension functions? Why is with a function, not a keyword?
There appears to be no explicit documentation for this topic, only the assumption of knowledge in reference to extensions.
",https://stackoverflow.com/questions/45875491/what-is-a-receiver-in-kotlin,131,37098.0,8.0,,,2017-08-25 06:22:05,2025-10-15 15:29:09,2023-11-26 10:39:51,,,kotlin;terminology,F. George,5474,7079453,registered,true,45875492,,CC BY-SA 4.0,,410,205,1,2,0,2,true,false,false,true,true,true,41,6,true,0.216,0.0035,3375,2017,8,6,Friday,false,false,false,false,false,false,false
34470703,Generic extending class AND implements interface in Kotlin,"Say I want a type variable, T, that extends a certain class and implements an interface. Something like:
class Foo <T : Bar implements Baz> { ... }
What is the syntax for this in Kotlin?
",https://stackoverflow.com/questions/34470703/generic-extending-class-and-implements-interface-in-kotlin,131,69589.0,1.0,,,2015-12-26 11:02:50,2018-05-11 23:23:30,,,,generics;kotlin,frenchdonuts,1412,4127239,registered,true,34470853,,CC BY-SA 3.0,,234,196,1,0,0,2,true,false,false,true,true,false,58,8,false,0.014,0.0019,3983,2015,12,11,Saturday,true,false,false,false,false,false,false
36896801,How to initialize List<T> in Kotlin?,"I see Kotlin has a List<out E> collection and I was wondering about different ways to initialize one. In Java, I could write:
List<String> geeks = Arrays.asList(""Fowler"", ""Beck"", ""Evans"");
How can I achieve the same in Kotlin?
",https://stackoverflow.com/questions/36896801/how-to-initialize-listt-in-kotlin,131,147500.0,7.0,,,2016-04-27 17:25:50,2021-04-15 01:45:33,2020-03-12 22:01:32,,,list;kotlin,Ali Dehghani,48479,1393484,registered,true,36897638,,CC BY-SA 4.0,,405,242,2,1,0,2,true,false,false,true,true,true,42,6,true,0.047,0.0009,3860,2016,4,17,Wednesday,false,false,false,false,false,false,false
48780003,Why and when to use @JvmStatic with companion objects?,"I'm trying to understand the difference between using/not using @JvmStatic, and when I should use either one.
So, with Kotlin and Java, I can do this:
TestKotlin.kt
class TestKotlin {
companion object {
val someString = ""hello world""
}
}
Which is then called by Java, like this:
TestJava.java
public class TestJava {
String kotlinStaticString = TestKotlin.Companion.getSomeString();
}
but then, there's this option 2:
TestKotlin.kt v2
class TestKotlin {
companion object {
@JvmStatic // <-- notice the @JvmStatic annotation
val someString = ""hello world""
}
}
And then, call it from Java, like this:
TestJava.java v2
public class TestJava {
String kotlinStaticString = TestKotlin.getSomeString();
}
So my questions are:
- Are these 2 cases any different, in terms of behavior or memory allocation?
- Is there a preference on which one to use?
- Do both create a pseudo static singleton object, like Java static does?
Thanks!
",https://stackoverflow.com/questions/48780003/why-and-when-to-use-jvmstatic-with-companion-objects,130,75635.0,5.0,,,2018-02-14 05:05:29,2022-09-21 09:01:23,2018-02-14 05:24:26,,,java;android;kotlin;kotlin-companion,TooManyEduardos,4502,1564652,registered,true,48781460,,CC BY-SA 3.0,,1252,991,8,0,0,4,true,false,false,true,true,true,54,9,true,0.066,0.0017,3202,2018,2,5,Wednesday,false,false,false,true,false,false,false
35914095,Package protected alternative in Kotlin,"In Java, we have the package protected (default) modifier for classes, which allows us to have many classes in a single package but exposes only a few and keeps the logic encapsulated.
With Kotlin this doesn't seem to be the case. If I want a few classes to be visible to each other but no further, I have to use a private modifier which limits visibility to a single file.
So if you want 10 classes in a package but only one of them to be public, you'd have to have one huge file with all the classes in it (and private all over the place).
Is this normal practice or there is a way to achieve some similar modularity in Kotlin?
I don't understand: if they have the notion of a package, why did they get rid of package protected access?
Update: We might have package protected visibility after all
see the discussion here
Update: If you read through the discussion and still think this is a must-have feature for the language, please vote here
",https://stackoverflow.com/questions/35914095/package-protected-alternative-in-kotlin,130,47383.0,5.0,,,2016-03-10 10:39:42,2022-09-26 16:17:56,2021-08-02 13:21:44,,,visibility;kotlin,vach,11605,654799,registered,true,35916484,,CC BY-SA 4.0,,1240,945,1,2,0,2,true,false,false,true,true,true,39,5,false,0.106,0.0027,3908,2016,3,10,Thursday,false,false,false,false,false,false,false
49011924,Round Double to 1 decimal place kotlin: from 0.044999 to 0.1,"I have a Double variable that is 0.0449999 and I would like to round it to 1 decimal place 0.1 .
I am using Kotlin but the Java solution is also helpful.
val number:Double = 0.0449999
I tried getting 1 decimal place with these two solutions:
val solution = Math.round(number * 10.0) / 10.0
val solution = String.format(""%.1f"", number)
The problem is that I get 0.0 in both cases because it rounds the number from 0.04 to 0.0. It doesn't take all decimals and round it.
I would like to obtain 0.1: 0.045 -> 0.05 -> 0.1
",https://stackoverflow.com/questions/49011924/round-double-to-1-decimal-place-kotlin-from-0-044999-to-0-1,129,224435.0,15.0,,,2018-02-27 15:09:48,2024-09-02 16:31:47,2020-04-11 00:42:45,,,java;android;kotlin;rounding,Noelia,4224,7131507,registered,true,49432344,,CC BY-SA 4.0,,705,532,8,0,0,4,true,false,false,true,true,true,60,11,false,0.067,0.0006,3189,2018,2,15,Tuesday,false,false,false,true,false,false,false
57795263,"Test events were not received" when running tests using IntelliJ,"I have a Kotlin project and when I run my JUnit tests, I can't see tests execution result in IntelliJ and get this message instead:
Test events were not received
I'm using this setup:
macOS Mojave
Intellij CE 2019.2
JDK 11.0.3
Kotlin 1.3.50
Gradle 5.2.1
JUnit 4.12
Can you help me?
",https://stackoverflow.com/questions/57795263/test-events-were-not-received-when-running-tests-using-intellij,129,134330.0,31.0,,,2019-09-04 20:28:44,2025-10-23 07:43:24,2025-10-23 07:43:24,,,kotlin;gradle;testing;intellij-idea;junit,Héctor Valls,26424,3026283,registered,true,57795360,,CC BY-SA 4.0,,367,290,1,0,0,5,true,false,false,true,true,true,75,10,false,0.231,0.001,2635,2019,9,20,Wednesday,false,false,false,false,false,false,false
47941537,Notify Observer when item is added to List of LiveData,"I need to get an Observer event when the item is added to the List of LiveData. But as far as I understand the event receives only when I replace the old list with a new one.
For example when I do the next:
list.value = mutableListOf(IssuePost(UserEntity(name, email, photoUrl), issueEntity))
Observer gets event. But when I just add item to value, Observer is silent.
Could you please give me advice on how I can implement what I need?
",https://stackoverflow.com/questions/47941537/notify-observer-when-item-is-added-to-list-of-livedata,128,102166.0,10.0,,,2017-12-22 12:25:43,2021-08-26 23:01:14,2021-03-28 14:28:11,,,android;kotlin;android-livedata,Ruslan Leshchenko,4303,6128708,registered,true,,,CC BY-SA 4.0,,476,438,1,0,0,3,false,false,false,true,true,true,54,10,false,0.098,0.0013,3256,2017,12,12,Friday,false,false,false,false,false,false,false
50570262,How to convert String to Int in Kotlin?,"I am working on a console application in Kotlin where I accept multiple arguments in main() function
fun main(args: Array<String>) {
// validation & String to Integer conversion
}
I want to check whether the String is a valid integer and convert the same or else I have to throw some exception.
How can I resolve this?
",https://stackoverflow.com/questions/50570262/how-to-convert-string-to-int-in-kotlin,128,203663.0,12.0,,,2018-05-28 16:19:11,2023-09-11 03:23:51,2019-01-18 18:34:17,,,kotlin,Sai Sarath C P,1662,6284931,registered,true,50570561,,CC BY-SA 4.0,,408,337,3,0,0,1,true,false,false,true,true,true,39,8,true,0.059,0.0006,3099,2018,5,16,Monday,false,false,false,false,false,false,false
43814616,Kotlin: Difference between object and companion object in a class,"What is the difference between an object and a companion object in a class in kotlin?
Example:
class MyClass {
object Holder {
//something
}
companion object {
//something
}
}
I already read that companion object shall be used, if the containing parameters/methods are closely related to its class.
But why is there also the possibility of declaring a normal object in the class? Because it behaves exactly like the companion, but it must have a name.
Is there maybe a difference in its ""static"" (I'm from the java side) lifecycle?
",https://stackoverflow.com/questions/43814616/kotlin-difference-between-object-and-companion-object-in-a-class,128,53779.0,6.0,,,2017-05-05 22:29:28,2021-08-03 12:52:08,,,,object;kotlin;companion-object,Poweranimal,1718,5446845,registered,true,46156988,,CC BY-SA 3.0,,632,573,1,0,0,3,true,false,false,true,true,false,65,10,false,0.112,0.0024,3487,2017,5,22,Friday,false,false,false,false,false,false,false
34143564,Create an instance of an abstract class in Kotlin,"I'm new to Kotlin and I'm trying to use it in my Android project. I have this code:
public var oneTouchTimer: CountDownTimer = CountDownTimer(500, 100) {
override fun onTick(l: Long) {
}
override fun onFinish() {
}
}
And it's throwing the error:
Cannot create an instance of an abstract class.
Basically I'm trying to create an instance of CountDownTimer and cannot figure out how to convert it to Kotlin.
Here is the code in Java:
CountDownTimer oneTouchTimer = new CountDownTimer(500, 100) {
@Override
public void onTick(long l) {
}
@Override
public void onFinish() {
}
};
",https://stackoverflow.com/questions/34143564/create-an-instance-of-an-abstract-class-in-kotlin,127,55675.0,1.0,,,2015-12-07 21:28:17,2022-11-22 07:45:24,2020-07-25 10:30:43,,,kotlin,Sloganho,2121,3388716,registered,true,34143646,,CC BY-SA 4.0,,724,624,3,0,0,1,true,false,false,true,true,true,49,9,false,0.018,0.0023,4002,2015,12,21,Monday,false,false,false,false,false,false,false
35520583,Why are there no concurrency keywords in Kotlin?,"Why are there no keywords for synchronization and concurrency?
So far my research gives me one solution, you wrap some high level classes and use them to handle concurrency.
Given a project in pure Kotlin, what should one do if there is a need for a small, highly optimized component that handles concurrency in a thread-safe manner?
My impression is that Kotlin is an assisting language for Java, to write 90% of the code in Kotlin but have some Java code that is not possible to express with Kotlin.
Is this right? Is this how it was intended to be?
",https://stackoverflow.com/questions/35520583/why-are-there-no-concurrency-keywords-in-kotlin,127,92520.0,4.0,,,2016-02-20 07:51:12,2023-08-06 22:20:51,2023-08-06 22:20:51,,,kotlin;concurrency,vach,11605,654799,registered,true,35521983,,CC BY-SA 4.0,,587,552,0,0,0,2,true,false,false,true,true,true,48,8,true,0.043,0.0014,3927,2016,2,7,Saturday,true,false,false,false,false,false,false
35479631,How to use spring annotations like @Autowired in kotlin?,"Is it possible to do something like following in Kotlin?
@Autowired
internal var mongoTemplate: MongoTemplate
@Autowired
internal var solrClient: SolrClient
",https://stackoverflow.com/questions/35479631/how-to-use-spring-annotations-like-autowired-in-kotlin,126,129024.0,6.0,,,2016-02-18 11:03:25,2024-07-10 04:29:57,2018-04-14 20:35:43,,,spring;kotlin,eendroroy,1520,2396067,registered,true,35480801,,CC BY-SA 3.0,,191,160,1,0,0,2,true,false,false,true,true,true,56,9,true,0.047,0.001,3929,2016,2,11,Thursday,false,false,false,false,false,false,false
40760625,How to check permission in fragment,"I want to check a permission inside a fragment.
my code:
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
android.Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(getActivity(),
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
1);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
but onRequestPermissionsResult not called after allow or deny.
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
Log.e(""test"",""0"");
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
//yes
Log.e(""test"",""1"");
Intent intent = new Intent(getActivity(), MapsActivity.class);
intent.putExtra(""latitude"", 35.694828);
intent.putExtra(""longitude"", 51.378129);
startActivity(intent);
} else {
utilityFunctions.showSweetAlertWarning(getActivity(),r.getString(R.string.str_warning_title_empty),
r.getString(R.string.str_you_must_allow_this_permission_toast),
r.getString(R.string.str_warning_btn_login));
Log.e(""test"",""2"");
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
",https://stackoverflow.com/questions/40760625/how-to-check-permission-in-fragment,125,153999.0,16.0,,,2016-11-23 09:35:33,2022-11-11 14:25:17,2021-12-21 20:43:21,,,java;android;kotlin;android-fragments;android-permissions,S.M_Emamian,17451,3369042,registered,true,40760760,,CC BY-SA 4.0,,2673,2591,3,0,0,5,true,false,false,true,true,true,35,6,false,0.104,0.0008,3650,2016,11,9,Wednesday,false,false,false,true,false,false,false
46235579,How to add an item to an ArrayList in Kotlin?,"How to add an item to an ArrayList in Kotlin?
",https://stackoverflow.com/questions/46235579/how-to-add-an-item-to-an-arraylist-in-kotlin,125,223199.0,6.0,,,2017-09-15 08:55:28,2022-05-14 10:51:42,2018-06-17 11:33:37,,,kotlin;kotlin-android-extensions,Ramesh,1792,6032811,registered,true,,,CC BY-SA 4.0,,66,46,1,0,0,2,false,false,false,true,true,true,45,10,true,0.027,0.0006,3354,2017,9,8,Friday,false,false,false,false,false,false,false
44515031,Is Kotlin "pass-by-value" or "pass-by-reference"?,"As I know Java is pass-by-value from this post. I am from Java background I wonder what Kotlin is using for passing values in between. Like in Extensions or Methods etc.
",https://stackoverflow.com/questions/44515031/is-kotlin-pass-by-value-or-pass-by-reference,125,114331.0,9.0,,,2017-06-13 07:32:52,2025-02-07 07:37:14,2018-04-20 12:28:25,,,kotlin,Rahul Khurana,8904,4079010,registered,true,54689951,,CC BY-SA 3.0,2024-01-03 14:45:09,405,170,0,3,0,1,true,false,false,true,true,true,69,5,true,0.079,0.0011,3448,2017,6,7,Tuesday,false,false,false,false,false,false,false
34122450,How to get generic parameter class in Kotlin,"Firebase's snapshot.getValue() expects to be called as follows:
snapshot?.getValue(Person::class.java)
However I would like to substitute Person with a generic parameter that is passed into the class via the class declaration i.e.
class DataQuery<T : IModel>
and use that generic parameter to do something like this:
snapshot?.getValue(T::class.java)
but when I attempt that I get an error stating that
only classes can be used on the left-hand side of a class literal
Is it possible to provide a class constraint on the generic parameter like in C# or is there some other syntax I can use to get the type info for the generic param?
",https://stackoverflow.com/questions/34122450/how-to-get-generic-parameter-class-in-kotlin,125,124758.0,6.0,,,2015-12-06 20:40:04,2022-03-12 05:11:47,2020-04-04 13:42:08,,,generics;kotlin,Jaja Harris,4518,756630,registered,true,34463352,,CC BY-SA 4.0,,823,658,5,0,0,2,true,false,false,true,true,true,44,8,false,0.048,0.001,4003,2015,12,20,Sunday,true,false,false,false,false,false,false
42066066,How Kotlin coroutines are better than RxKotlin?,"Why would I want to use Kotlin's coroutines?
It seems that the RxKotlin library is much more versatile.
Kotlin's coroutines look significantly less powerful and more cumbersome to use in comparison.
I base my opinion on coroutines on this design talk by Andrey Breslav (JetBrains)
Slideshow from the talk is accessible here.
EDIT (thanks to @hotkey):
Better source on the current state of coroutines here.
",https://stackoverflow.com/questions/42066066/how-kotlin-coroutines-are-better-than-rxkotlin,124,50957.0,6.0,,,2017-02-06 10:55:51,2024-02-27 17:25:51,2020-07-26 21:55:18,,,kotlin;rx-kotlin,charlie_pl,3154,3160531,registered,true,42126960,,CC BY-SA 4.0,,727,407,0,3,0,2,true,false,false,true,true,true,47,7,true,0.118,0.0024,3575,2017,2,10,Monday,false,false,false,false,false,false,false
64476827,How to resolve the error "LifecycleOwners must call register before they are STARTED","I am using registerForActivityResult for google sign in implementation in my development. Everything was working fine until I upgraded my fragment dependency to 1.3.0-beta01. The application current crash with the error
java.lang.IllegalStateException: LifecycleOwner SignupChoicesFragment{8e0e269} (193105b9-afe2-4941-a368-266dbc433258) id=0x7f090139} is attempting to register while current state is RESUMED. LifecycleOwners must call register before they are STARTED.
I have used the function before oncreate using lazy loading but it wont work still.
class SignupChoicesFragment : DaggerFragment() {
@Inject
lateinit var viewModelProviderFactory: ViewModelFactory
val userViewModel: UserViewModel by lazy {
ViewModelProvider(this, viewModelProviderFactory).get(UserViewModel::class.java)
}
@Inject
lateinit var mGoogleSignInClient:GoogleSignInClient
val arg:SignupChoicesFragmentArgs by navArgs()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_signup_choices, container, false)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
google_sign_in_button.setOnClickListener {
val intent = mGoogleSignInClient.signInIntent
val launcher = registerForActivityResult(ActivityResultContracts.StartActivityForResult(), ActivityResultCallback {result->
if (result.resultCode == Activity.RESULT_OK) {
val task = GoogleSignIn.getSignedInAccountFromIntent(result.data)
task.addOnCompleteListener {
if (it.isSuccessful) {
val account: GoogleSignInAccount? =
it.getResult(ApiException::class.java)
val idToken = it.result?.idToken
val email = account?.email
val lastName = account?.familyName
val firstName = account?.givenName
val otherName = account?.displayName
val imageUrl = account?.photoUrl
val category = arg.category
val newUser = User()
newUser.firstName = firstName
newUser.lastName = lastName
newUser.otherName = otherName
newUser.category = category
newUser.email = email
newUser.imageUrl = imageUrl.toString()
userViewModel.currentUser = newUser
newUser.token = idToken
i(title, "idToken $idToken")
requireActivity().gdToast("Authentication successful", Gravity.BOTTOM)
val action = SignupChoicesFragmentDirections.actionSignupChoicesFragmentToEmailSignupFragment()
action.newUser = newUser
goto(action)
} else {
requireActivity().gdToast(
"Authentication Unsuccessful",
Gravity.BOTTOM
)
Log.i(title, "Task not successful")
}
}
} else {
Log.i(title, "OKCODE ${Activity.RESULT_OK} RESULTCODE ${result.resultCode}")
}
}).launch(intent)
}
}
",https://stackoverflow.com/questions/64476827/how-to-resolve-the-error-lifecycleowners-must-call-register-before-they-are-sta,124,76774.0,9.0,,,2020-10-22 06:55:25,2024-04-23 09:23:01,2022-04-27 13:15:29,,,android;kotlin;android-fragments,Darotudeen,2598,7358866,registered,true,64477786,,CC BY-SA 4.0,,3932,3849,2,0,0,3,true,false,false,true,true,true,95,13,false,0.117,0.0016,2221,2020,10,6,Thursday,false,false,false,false,false,false,false
45377386,"Using Kotlin WHEN clause for <, <=, >=, > comparisons","I'm trying to use the WHEN clause with a > or < comparison.
This doesn't compile. Is there a way of using the normal set of boolean operators (< <=, >= >) in a comparison to enable this?
val foo = 2
// doesn't compile
when (foo) {
> 0 -> doSomethingWhenPositive()
0 -> doSomethingWhenZero()
< 0 -> doSomethingWhenNegative()
}
I tried to find an unbounded range comparison, but couldn't make this work either? Is it possible to write this as an unbounded range?
// trying to get an unbounded range - doesn't compile
when (foo) {
in 1.. -> doSomethingWhenPositive()
else -> doSomethingElse()
}
You can put the whole expression in the second part, which is OK but seems like unnecessary duplication. At least it compiles and works.
when {
foo > 0 -> doSomethingWhenPositive()
foo < 0 -> doSomethingWhenNegative()
else -> doSomethingWhenZero()
}
But I'm not sure that is any simpler than the if-else alternative we have been doing for years. Something like:
if ( foo > 0 ) {
doSomethingWhenPositive()
}
else if (foo < 0) {
doSomethingWhenNegative()
}
else {
doSomethingWhenZero()
}
Of course, real world problems are more complex than the above, and the WHEN clause is attractive but doesn't work as I expect for this type of comparison.
",https://stackoverflow.com/questions/45377386/using-kotlin-when-clause-for-comparisons,124,72010.0,7.0,,,2017-07-28 15:34:45,2025-12-08 04:54:17,2017-08-01 16:26:05,,,kotlin,Jim Leask,6517,5135551,registered,true,45377756,,CC BY-SA 3.0,,1538,1348,8,0,0,1,true,false,false,true,true,true,65,10,false,0.097,0.0017,3403,2017,7,15,Friday,false,false,false,false,false,false,false
52631827,Why can't 'kotlin.Result' be used as a return type?,"I've created a method, and the return is Result<R> in a class of MyClass<R>, but the error message is: 'kotlin.Result' cannot be used as a return type
I've also looked into the Result source code for some hints; why is this so?
Test code (using v. 1.3-RC).
class MyClass<R>(val r: R) {
fun f(): Result<R> { // error here
return Result.success(r)
}
}
fun main(args: Array<String>) {
val s = Result.success(1)
val m = MyClass(s)
}
",https://stackoverflow.com/questions/52631827/why-cant-kotlin-result-be-used-as-a-return-type,124,37581.0,4.0,,,2018-10-03 16:36:21,2021-07-14 14:57:05,2020-09-30 16:48:44,,,function;kotlin;return-type,ersin-ertan,2301,2713242,registered,true,52632328,,CC BY-SA 4.0,,686,488,3,1,0,3,true,false,false,true,true,true,63,9,true,0.106,0.0033,2971,2018,10,16,Wednesday,false,false,false,false,false,false,false
34950111,"Prefer to run the dagger processor over that class instead" in Kotlin,"I'm getting this note in the build whenever I do an inject into a kotlin class (btw, I have a mixed android project with both kotlin and java).
For example, after this gradle task: compileStagingDebugJavaWithJavac (StagingDebug is my build variant), I get this message:
""Note: Generating a MembersInjector or Factory for com.packageNameXXX.CourseDiscoveryMapFragment. Prefer to run the dagger processor over that class instead.""
My CourseDiscoveryMapFragment code can be seen here:
class CourseDiscoveryMapFragment : Fragment(){
@Inject
lateinit var presenter: CourseDiscoveryMapPresenter
lateinit var mapView: MapView
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_discovery_map, container, false)
MapsInitializer.initialize(activity)
mapView = view.mapView
mapView.onCreate(savedInstanceState?.getBundle(BUNDLE_KEY_MAP_STATE))
(activity as BaseActivity)
.activityComponent.inject(this)
}
And my ActivityComponent is :
@ActivityScope
@Subcomponent(modules = ActivityModule.class)
public interface ActivityComponent {
void inject(BaseActivity baseActivity);
void inject(CourseDiscoveryMapFragment fragment);
//Exposed to sub-graphs.
Activity activity();
}
So, I'm having dagger component and modules written in Java, while having dagger injections in Kotlin.
Is this anything that I should be worried about?
Thank you.
",https://stackoverflow.com/questions/34950111/prefer-to-run-the-dagger-processor-over-that-class-instead-in-kotlin,124,4439.0,1.0,,,2016-01-22 15:24:05,2018-02-13 02:39:21,2016-01-26 17:03:11,,,android;kotlin;dagger,Fábio Carballo,3285,1277555,registered,true,,,CC BY-SA 3.0,,1721,1545,3,0,0,3,false,false,false,true,true,true,80,12,false,0.225,0.0279,3956,2016,1,15,Friday,false,false,false,false,false,false,false
35421699,How to invoke external command from within Kotlin code?,"I want to invoke an external command from Kotlin code.
- In C/Perl, I would use the
system() function.
- In Python, I would use the subprocess module.
- In Go, I would use os/exec, and etc.
But how do I do this in Kotlin?
",https://stackoverflow.com/questions/35421699/how-to-invoke-external-command-from-within-kotlin-code,123,85497.0,10.0,,,2016-02-16 00:39:13,2022-08-30 08:25:48,2021-02-19 01:11:44,,,exec;kotlin,Big Tummy,1261,5932543,registered,true,,,CC BY-SA 4.0,,281,218,1,0,0,2,false,false,false,true,true,true,55,9,true,0.117,0.0014,3931,2016,2,0,Tuesday,false,false,false,false,false,false,false
72382146,The project is using an incompatible version (AGP 7.3.0-alpha07) of the Android Gradle plugin,"I want to use architecture project (todo list) but get this error when i want to run project
The project is using an incompatible version (AGP 7.3.0-alpha07) of the Android Gradle plugin. Latest supported version is AGP 7.2.1
",https://stackoverflow.com/questions/72382146/the-project-is-using-an-incompatible-version-agp-7-3-0-alpha07-of-the-android,123,392236.0,21.0,,,2022-05-25 17:45:37,2025-06-21 04:14:40,2022-06-20 06:44:09,,,android;kotlin;gradle;android-gradle-plugin;build.gradle,Moha.AZ,2093,17761085,registered,true,74054672,,CC BY-SA 4.0,,240,226,0,0,0,5,true,false,false,true,true,true,93,14,false,0.054,0.0003,1641,2022,5,17,Wednesday,false,false,false,false,false,false,false
47400942,what does "::" mean in kotlin?,"I'm new to Kotlin
I used this code for opening another activity:
startActivity(Intent(this,IntroAndLang::class.java))
current activity and target activity are written in Kotlin
I can't understand why there is not single : instead of :: at IntroAndLang::class.java
",https://stackoverflow.com/questions/47400942/what-does-mean-in-kotlin,123,67146.0,4.0,,,2017-11-20 20:58:21,2023-11-29 11:04:07,2022-08-04 15:21:43,,,android;kotlin,Winner1,1556,8543147,registered,true,52463397,,CC BY-SA 4.0,,355,265,4,0,0,2,true,false,false,true,true,true,40,6,true,0.06,0.0018,3288,2017,11,20,Monday,false,false,false,false,false,false,false
59368360,How to use Compose inside Fragment?,"The documentation describes how to create UI Jetpack Compose inside Activity.
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Text("Hello world!")
}
}
}
But how can I use it inside fragment?
",https://stackoverflow.com/questions/59368360/how-to-use-compose-inside-fragment,123,91304.0,6.0,,,2019-12-17 06:00:09,2024-08-26 13:05:23,2022-09-08 06:37:24,,,android;kotlin;android-jetpack-compose,Nurseyit Tursunkulov,9630,5993479,registered,true,63635221,,CC BY-SA 4.0,,435,320,1,1,0,3,true,false,false,true,true,true,35,6,true,0.066,0.0013,2531,2019,12,6,Tuesday,false,false,false,false,false,false,false
29743160,How to create an empty array in kotlin?,"I'm using Array(0, {i -> """"}) currently, and I would like to know if there's a better implementation such as Array()
plus, if I'm using arrayOfNulls<String>(0) as Array<String>, the compiler will alert me that this cast can never succeed. But it's the default implementation inside Array(0, {i -> """"}). Do I miss something?
",https://stackoverflow.com/questions/29743160/how-to-create-an-empty-array-in-kotlin,123,117913.0,8.0,,,2015-04-20 08:51:36,2022-03-15 11:30:23,2020-04-26 22:00:23,,,arrays;kotlin,huangcd,2449,302199,registered,true,30887200,,CC BY-SA 4.0,,409,343,4,0,0,2,true,false,false,true,true,true,39,8,true,0.068,0.001,4233,2015,4,8,Monday,false,false,false,false,false,false,false
50772230,How to do bulk (multi row) inserts with JpaRepository?,"When calling the saveAll method of my JpaRepository with a long List<Entity> from the service layer, trace logging of Hibernate shows single SQL statements being issued per entity.
Can I force it to do a bulk insert (i.e. multi-row) without needing to manually fiddle with EntityManger, transactions etc. or even raw SQL statement strings?
With multi-row insert I mean not just transitioning from:
start transaction
INSERT INTO table VALUES (1, 2)
end transaction
start transaction
INSERT INTO table VALUES (3, 4)
end transaction
start transaction
INSERT INTO table VALUES (5, 6)
end transaction
to:
start transaction
INSERT INTO table VALUES (1, 2)
INSERT INTO table VALUES (3, 4)
INSERT INTO table VALUES (5, 6)
end transaction
but instead to:
start transaction
INSERT INTO table VALUES (1, 2), (3, 4), (5, 6)
end transaction
In PROD I'm using CockroachDB, and the difference in performance is significant.
Below is a minimal example that reproduces the problem (H2 for simplicity).
./src/main/kotlin/ThingService.kt:
package things
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.data.jpa.repository.JpaRepository
import javax.persistence.Entity
import javax.persistence.Id
import javax.persistence.GeneratedValue
interface ThingRepository : JpaRepository<Thing, Long> {
}
@RestController
class ThingController(private val repository: ThingRepository) {
@GetMapping(""/test_trigger"")
fun trigger() {
val things: MutableList<Thing> = mutableListOf()
for (i in 3000..3013) {
things.add(Thing(i))
}
repository.saveAll(things)
}
}
@Entity
data class Thing (
var value: Int,
@Id
@GeneratedValue
var id: Long = -1
)
@SpringBootApplication
class Application {
}
fun main(args: Array<String>) {
runApplication<Application>(*args)
}
./src/main/resources/application.properties:
jdbc.driverClassName = org.h2.Driver
jdbc.url = jdbc:h2:mem:db
jdbc.username = sa
jdbc.password = sa
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.hbm2ddl.auto=create
spring.jpa.generate-ddl = true
spring.jpa.show-sql = true
spring.jpa.properties.hibernate.jdbc.batch_size = 10
spring.jpa.properties.hibernate.order_inserts = true
spring.jpa.properties.hibernate.order_updates = true
spring.jpa.properties.hibernate.jdbc.batch_versioned_data = true
./build.gradle.kts:
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
val kotlinVersion = ""1.2.30""
id(""org.springframework.boot"") version ""2.0.2.RELEASE""
id(""org.jetbrains.kotlin.jvm"") version kotlinVersion
id(""org.jetbrains.kotlin.plugin.spring"") version kotlinVersion
id(""org.jetbrains.kotlin.plugin.jpa"") version kotlinVersion
id(""io.spring.dependency-management"") version ""1.0.5.RELEASE""
}
version = ""1.0.0-SNAPSHOT""
tasks.withType<KotlinCompile> {
kotlinOptions {
jvmTarget = ""1.8""
freeCompilerArgs = listOf(""-Xjsr305=strict"")
}
}
repositories {
mavenCentral()
}
dependencies {
compile(""org.springframework.boot:spring-boot-starter-web"")
compile(""org.springframework.boot:spring-boot-starter-data-jpa"")
compile(""org.jetbrains.kotlin:kotlin-stdlib-jdk8"")
compile(""org.jetbrains.kotlin:kotlin-reflect"")
compile(""org.hibernate:hibernate-core"")
compile(""com.h2database:h2"")
}
Run:
./gradlew bootRun
Trigger DB INSERTs:
curl http://localhost:8080/test_trigger
Log output:
Hibernate: select thing0_.id as id1_0_0_, thing0_.value as value2_0_0_ from thing thing0_ where thing0_.id=?
Hibernate: call next value for hibernate_sequence
Hibernate: select thing0_.id as id1_0_0_, thing0_.value as value2_0_0_ from thing thing0_ where thing0_.id=?
Hibernate: call next value for hibernate_sequence
Hibernate: select thing0_.id as id1_0_0_, thing0_.value as value2_0_0_ from thing thing0_ where thing0_.id=?
Hibernate: call next value for hibernate_sequence
Hibernate: select thing0_.id as id1_0_0_, thing0_.value as value2_0_0_ from thing thing0_ where thing0_.id=?
Hibernate: call next value for hibernate_sequence
Hibernate: select thing0_.id as id1_0_0_, thing0_.value as value2_0_0_ from thing thing0_ where thing0_.id=?
Hibernate: call next value for hibernate_sequence
Hibernate: select thing0_.id as id1_0_0_, thing0_.value as value2_0_0_ from thing thing0_ where thing0_.id=?
Hibernate: call next value for hibernate_sequence
Hibernate: select thing0_.id as id1_0_0_, thing0_.value as value2_0_0_ from thing thing0_ where thing0_.id=?
Hibernate: call next value for hibernate_sequence
Hibernate: select thing0_.id as id1_0_0_, thing0_.value as value2_0_0_ from thing thing0_ where thing0_.id=?
Hibernate: call next value for hibernate_sequence
Hibernate: select thing0_.id as id1_0_0_, thing0_.value as value2_0_0_ from thing thing0_ where thing0_.id=?
Hibernate: call next value for hibernate_sequence
Hibernate: select thing0_.id as id1_0_0_, thing0_.value as value2_0_0_ from thing thing0_ where thing0_.id=?
Hibernate: call next value for hibernate_sequence
Hibernate: select thing0_.id as id1_0_0_, thing0_.value as value2_0_0_ from thing thing0_ where thing0_.id=?
Hibernate: call next value for hibernate_sequence
Hibernate: select thing0_.id as id1_0_0_, thing0_.value as value2_0_0_ from thing thing0_ where thing0_.id=?
Hibernate: call next value for hibernate_sequence
Hibernate: select thing0_.id as id1_0_0_, thing0_.value as value2_0_0_ from thing thing0_ where thing0_.id=?
Hibernate: call next value for hibernate_sequence
Hibernate: select thing0_.id as id1_0_0_, thing0_.value as value2_0_0_ from thing thing0_ where thing0_.id=?
Hibernate: call next value for hibernate_sequence
Hibernate: insert into thing (value, id) values (?, ?)
Hibernate: insert into thing (value, id) values (?, ?)
Hibernate: insert into thing (value, id) values (?, ?)
Hibernate: insert into thing (value, id) values (?, ?)
Hibernate: insert into thing (value, id) values (?, ?)
Hibernate: insert into thing (value, id) values (?, ?)
Hibernate: insert into thing (value, id) values (?, ?)
Hibernate: insert into thing (value, id) values (?, ?)
Hibernate: insert into thing (value, id) values (?, ?)
Hibernate: insert into thing (value, id) values (?, ?)
Hibernate: insert into thing (value, id) values (?, ?)
Hibernate: insert into thing (value, id) values (?, ?)
Hibernate: insert into thing (value, id) values (?, ?)
Hibernate: insert into thing (value, id) values (?, ?)
",https://stackoverflow.com/questions/50772230/how-to-do-bulk-multi-row-inserts-with-jparepository,123,266107.0,6.0,,,2018-06-09 08:11:10,2023-03-29 13:13:44,2018-06-16 11:41:50,,,hibernate;spring-boot;kotlin;spring-data-jpa;cockroachdb,Tobias Hermann,11375,1866775,registered,true,50882952,,CC BY-SA 4.0,,7085,6671,16,0,0,5,true,false,false,true,true,true,54,9,true,0.023,0.0005,3087,2018,6,8,Saturday,true,false,false,false,false,false,false
43021816,Difference between a thread and a coroutine in Kotlin,"Is there a specific language implementation in Kotlin which differs from another language's implementation of coroutines?
- What does it mean that a coroutine is like a lightweight thread?
- What is the difference?
- Are Kotlin coroutines actually running in parallel (concurrently)?
- Even in a multi-core system, is there only one coroutine running at any given time?
Here I'm starting 100,000 coroutines. What happens behind this code?
for (i in 0..100000) {
async(CommonPool) {
// Run long-running operations
}
}
",https://stackoverflow.com/questions/43021816/difference-between-a-thread-and-a-coroutine-in-kotlin,123,38262.0,3.0,,,2017-03-25 20:50:57,2025-10-03 08:23:25,2023-09-06 16:08:40,,,multithreading;kotlin;concurrency;kotlin-coroutines;coroutine,Jemo Mgebrishvili,5577,4585387,registered,true,43232925,,CC BY-SA 4.0,,652,528,1,0,0,5,true,false,false,true,true,true,53,9,false,0.078,0.0032,3528,2017,3,20,Saturday,true,false,false,false,false,false,false
53535977,Coroutines: runBlocking vs coroutineScope,"I was reading Coroutine Basics trying to understand and learn it.
There is a part there with this code:
fun main() = runBlocking { // this: CoroutineScope
launch {
delay(200L)
println("Task from runBlocking")
}
coroutineScope { // Creates a new coroutine scope
launch {
delay(900L)
println("Task from nested launch")
}
delay(100L)
println("Task from coroutine scope") // This line will be printed before nested launch
}
println("Coroutine scope is over") // This line is not printed until nested launch completes
}
The output goes like so:
Task from coroutine scope
Task from runBlocking
Task from nested launch
Coroutine scope is over
My question is why this line:
println("Coroutine scope is over") // This line is not printed until nested launch completes
is called always last?
Shouldn't it be called since the:
coroutineScope { // Creates a new coroutine scope
....
}
is suspended?
There is also a note there:
The main difference between runBlocking and coroutineScope is that the latter does not block the current thread while waiting for all children to complete.
I dont understand how coroutineScope and runBlocking are different here? coroutineScope looks like its blocking since it only gets to the last line when it is done.
Can anyone enlighten me here?
",https://stackoverflow.com/questions/53535977/coroutines-runblocking-vs-coroutinescope,123,52664.0,7.0,,,2018-11-29 09:43:04,2024-02-16 12:17:13,2022-12-18 23:02:54,,,kotlin;kotlin-coroutines,Archie G. Quiñones,13998,9291997,registered,true,53536713,,CC BY-SA 4.0,,1714,1424,4,1,0,2,true,false,false,true,true,true,41,4,false,0.133,0.0023,2914,2018,11,9,Thursday,false,false,false,false,false,false,false
44213446,Cannot find setter for field - using Kotlin with Room database,"I'm integrating with the Room persistence library. I have a data class in Kotlin like:
@Entity(tableName = ""story"")
data class Story (
@PrimaryKey val id: Long,
val by: String,
val descendants: Int,
val score: Int,
val time: Long,
val title: String,
val type: String,
val url: String
)
The @Entity and @PrimaryKey annotations are for the Room library. When I try to build, it is failing with error:
Error:Cannot find setter for field.
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.
I also tried providing a default constructor:
@Entity(tableName = ""story"")
data class Story (
@PrimaryKey val id: Long,
val by: String,
val descendants: Int,
val score: Int,
val time: Long,
val title: String,
val type: String,
val url: String
) {
constructor() : this(0, """", 0, 0, 0, """", """", """")
}
But this doesn't work as well. A thing to note is that it works if I convert this Kotlin class into a Java class with getters and setters. Any help is appreciated!
",https://stackoverflow.com/questions/44213446/cannot-find-setter-for-field-using-kotlin-with-room-database,122,60613.0,20.0,,,2017-05-27 05:54:18,2025-01-02 08:44:02,,,,android;kotlin;android-room,gsb,5648,819911,registered,true,44213583,,CC BY-SA 3.0,,1298,1172,5,0,0,3,true,false,false,true,true,false,62,11,false,0.33,0.002,3465,2017,5,5,Saturday,true,false,false,false,false,false,false
70037537,Proguard Missing classes detected while running R8 after adding package names in proguard-rules.pro,"AGPBI gives this as output:
> Task :app:minifyReleaseWithR8
AGPBI: {"kind":"warning","text":"Unexpected reference to missing service class: META-INF/services/reactor.blockhound.integration.BlockHoundIntegration.","sources":[{"file":"/app/build/intermediates/merged_java_res/release/base.jar"}],"tool":"R8"}
AGPBI: {"kind":"warning","text":"Missing classes detected while running R8. Please add the missing classes or apply additional keep rules that are generated in /app/build/outputs/mapping/release/missing_rules.txt.\n","sources":[{}]}
AGPBI: {"kind":"warning","text":"Missing class com.aayushatharva.brotli4j.Brotli4jLoader (referenced from: void io.netty.handler.codec.compression.Brotli.<clinit>() and 2 other contexts)\n
Missing class com.aayushatharva.brotli4j.decoder.DecoderJNI$Status (referenced from: void io.netty.handler.codec.compression.BrotliDecoder$1.<clinit>() and 1 other context)\n
Missing class com.aayushatharva.brotli4j.decoder.DecoderJNI$Wrapper (referenced from: com.aayushatharva.brotli4j.decoder.DecoderJNI$Wrapper io.netty.handler.codec.compression.BrotliDecoder.decoder and 4 other contexts)\n
Missing class com.aayushatharva.brotli4j.encoder.Encoder$Mode (referenced from: void io.netty.handler.codec.compression.BrotliOptions.<clinit>())\n
Missing class com.aayushatharva.brotli4j.encoder.Encoder$Parameters (referenced from: com.aayushatharva.brotli4j.encoder.Encoder$Parameters io.netty.handler.codec.compression.BrotliEncoder.parameters and 7 other contexts)\n
Missing class com.aayushatharva.brotli4j.encoder.Encoder (referenced from: io.netty.buffer.ByteBuf io.netty.handler.codec.compression.BrotliEncoder.allocateBuffer(io.netty.channel.ChannelHandlerContext, io.netty.buffer.ByteBuf, boolean))\n
Missing class com.android.org.conscrypt.SSLParametersImpl (referenced from: void org.conscrypt.KitKatPlatformOpenSSLSocketImplAdapter.<init>(org.conscrypt.AbstractConscryptSocket))\n
Missing class com.github.luben.zstd.Zstd (referenced from: io.netty.buffer.ByteBuf io.netty.handler.codec.compression.ZstdEncoder.allocateBuffer(io.netty.channel.ChannelHandlerContext, io.netty.buffer.ByteBuf, boolean) and 1 other context)\n
Missing class com.google.protobuf.ExtensionRegistry (referenced from: void io.netty.handler.codec.protobuf.ProtobufDecoder.<init>(com.google.protobuf.MessageLite, com.google.protobuf.ExtensionRegistry))\n
Missing class com.google.protobuf.ExtensionRegistryLite (referenced from: com.google.protobuf.ExtensionRegistryLite io.netty.handler.codec.protobuf.ProtobufDecoder.extensionRegistry and 2 other contexts)\n
The missing files seem to be part of the bouncycastle library. Here is my proguard file:
-keep class org.spongycastle.** { *; }
-dontwarn org.spongycastle.**
# When I remove this, java.security.cert.CertificateException: X.509 not found is thrown
-keep class org.bouncycastle.** { *; }
-keep interface org.bouncycastle.**
# I got the missing classes from missing_rules.txt and added the package names that created the problem here:
-keep class org.conscrypt.** { *; }
-keep class io.netty.** { *; }
-keep class com.aayushatharva.** { *; }
-keep class ** { *; }
build.gradle (app):
implementation "org.conscrypt:conscrypt-android:$conscrypt"
implementation 'org.bouncycastle:bcprov-jdk15on:1.69'
implementation 'org.bouncycastle:bcpkix-jdk15on:1.69'
Why does it still gives the error while I add the correct missing package names?
",https://stackoverflow.com/questions/70037537/proguard-missing-classes-detected-while-running-r8-after-adding-package-names-in,122,150856.0,25.0,,,2021-11-19 15:51:58,2025-10-01 07:46:52,,,,android;kotlin;proguard,Jim Clermonts,2890,898307,registered,true,,,CC BY-SA 4.0,,3787,3631,6,0,0,3,false,false,false,true,true,false,99,13,false,0.166,0.0008,1828,2021,11,15,Friday,false,false,false,false,false,false,false
49053432,How to clone object in Kotlin?,"The Kotlin documentation describes cloning only in accessing Java and in enum class. In latter case clone is just throwing an exception.
So, how would I / should I clone arbitrary Kotlin object?
Should I just use clone() as in Java?
",https://stackoverflow.com/questions/49053432/how-to-clone-object-in-kotlin,121,163083.0,10.0,,,2018-03-01 15:45:31,2022-11-28 04:01:31,2020-12-11 15:52:59,,,kotlin;clone,Dims,51954,258483,registered,true,49053542,,CC BY-SA 4.0,,360,233,1,1,0,2,true,false,false,true,true,true,30,6,true,0.061,0.0007,3187,2018,3,15,Thursday,false,false,false,false,false,false,false
46177133,HTTP Request in Android with Kotlin,"I want to do a login validation using POST method and to get some information using GET method.
I've URL, server Username and Password already of my previous project.
",https://stackoverflow.com/questions/46177133/http-request-in-android-with-kotlin,121,267267.0,11.0,,,2017-09-12 13:01:26,2024-01-21 07:23:12,2021-07-27 14:46:02,,,android;rest;http;kotlin,Rajkumar K,1579,7860624,registered,true,46179139,,CC BY-SA 4.0,,181,167,0,0,0,4,true,false,false,true,true,true,35,6,false,0.041,0.0005,3357,2017,9,13,Tuesday,false,false,false,false,false,false,false
69234206,Why am I getting Backend Internal error: "Exception during IR lowering error" when using Jetpack Compose clickable-Modifier?,"I am creating a custom Checkbox within a Surface which has a Modifier.clickable:
Surface(
modifier = Modifier
.clickable(
enabled = enabled,
interactionSource = interactionSource,
indication = rememberRipple(),
role = Role.Checkbox,
onClick = { onCheckedChange(!checked) }
)
.then(modifier),
) {
Row {
Checkbox(checked = checked, onCheckedChange = {}, colors = colors)
Text(text = text ?: "")
}
}
When I try to build that, I get the Exception during IR lowering error error:
org.jetbrains.kotlin.backend.common.BackendException: Backend Internal error: Exception during IR lowering
File being compiled: /home/rene/AndroidStudioProjects/pass13/app/src/main/java/com/aresid/simplepasswordgeneratorapp/ui/widgets/Checkbox.kt
See the full stacktrace here.
Removing the Modifier.clickable solves the build issue.
I already tried up-/downgrading some versions but nothing is working properly.
Currently, I am using those versions:
ext.versions = [
'compileSdk': 31,
'targetSdk' : 30,
'minSdk' : 26,
'kotlin' : '1.5.30',
'navigation': '2.3.5',
'compose' : '1.0.2'
]
Has anybody an idea how to fix that?
",https://stackoverflow.com/questions/69234206/why-am-i-getting-backend-internal-error-exception-during-ir-lowering-error-wh,119,75019.0,19.0,,,2021-09-18 11:26:48,2025-07-15 09:35:03,2021-09-19 10:57:58,,,android;kotlin;android-jetpack-compose,René Jörg Spies,2286,10508928,registered,true,78668239,,CC BY-SA 4.0,2025-07-15 11:19:00,1674,1375,8,1,0,3,true,false,false,true,true,true,134,17,true,0.253,0.0016,1890,2021,9,11,Saturday,true,false,false,false,false,false,false
40160489,Kotlin: Whats does "return@" mean?,"I'm using RxJava in one of my projects, I converted one of my classes to Kotlin using the Android Studio plugin and in one of map flatMap lambda (Func1 in java), intermediates returns looks like the following @Func1.
I have no idea what this means.
something.flatMap(Func1<ArticleCriteria, Observable<Pair<String, String>>> {
val isTemporaryClone = it.isATemporaryClone
val isTheOriginalToken = it.tokenIsOriginalHere
if (isTemporaryClone) {
if (!isTheOriginalToken) {
return@Func1 paramsError(""Token is always original for temp articles"")
}
return@Func1 mJobRunner.doNotRun(DeleteArticleJob.TAG)
.doOnNext(deletePersonalActionById(articleId))
}
runArticleJobAsync(DeleteArticleJob.TAG, it)
})
",https://stackoverflow.com/questions/40160489/kotlin-whats-does-return-mean,119,59338.0,2.0,,,2016-10-20 17:09:33,2024-03-20 06:37:21,2016-10-21 07:39:24,,,android;rx-java;kotlin,Glenn Sonna,1951,2084450,registered,true,40166597,,CC BY-SA 3.0,,867,803,3,0,0,3,true,false,false,true,true,true,44,5,true,0.034,0.002,3684,2016,10,17,Thursday,false,false,false,false,false,false,false
48601549,Why kotlin gradle plugin cannot build with 1.8 target?,"I have the simplest gradle project configured using intellij for kotlin 1.2.10. Here is my build.gradle file:
buildscript {
ext.kotlin_version = '1.2.10'
repositories {
mavenCentral()
}
dependencies {
classpath ""org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version""
}
}
group 'com.ali'
version '1.0-SNAPSHOT'
apply plugin: 'java'
apply plugin: 'kotlin'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile ""org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version""
testCompile group: 'junit', name: 'junit', version: '4.12'
}
compileKotlin {
kotlinOptions.jvmTarget = ""1.8""
}
compileTestKotlin {
kotlinOptions.jvmTarget = ""1.8""
}
And I have a simple java interface:
public interface MyMath {
static int myAbs(int input) {
return Math.abs(input);
}
}
When I import this interface and try to call myAbs method it fails with this error:
Error:(6, 12) Kotlin: Calls to static methods in Java interfaces are prohibited in JVM target 1.6. Recompile with '-jvm-target 1.8'
I have created an intellij kotlin app and it was working correctly. Is it a bug in new Kotlin gradle plugin?
",https://stackoverflow.com/questions/48601549/why-kotlin-gradle-plugin-cannot-build-with-1-8-target,118,102419.0,12.0,,,2018-02-03 20:11:45,2025-01-12 12:45:37,,,,gradle;intellij-idea;kotlin,alisabzevari,8166,692422,registered,true,48607469,,CC BY-SA 3.0,,1308,1195,4,0,0,3,true,false,false,true,true,false,54,9,true,0.117,0.0012,3213,2018,2,20,Saturday,true,false,false,false,false,false,false
44485631,Room Persistence: Error:Entities and Pojos must have a usable public constructor,"I'm converting a project to Kotlin and I'm trying to make my model (which is also my entity) a data class
I intend to use Moshi to convert the JSON responses from the API
@Entity(tableName = ""movies"")
data class MovieKt(
@PrimaryKey
var id : Int,
var title: String,
var overview: String,
var poster_path: String,
var backdrop_path: String,
var release_date: String,
var vote_average: Double,
var isFavorite: Int
)
I can't build the app cause of the following error
Entities and Pojos must have a usable public constructor. You can have an empty constructor or a constructor whose parameters match the fields (by name and type).
Cannot find setter for field.
The examples I found are not far from this
Ideas on how to solve it?
",https://stackoverflow.com/questions/44485631/room-persistence-errorentities-and-pojos-must-have-a-usable-public-constructor,117,83477.0,36.0,,,2017-06-11 15:38:58,2025-05-26 10:45:36,2017-11-28 23:37:17,,,android;kotlin;android-room;android-architecture-components,Leonardo Deleon,2705,6801380,registered,true,,,CC BY-SA 3.0,,1029,775,1,1,0,4,false,false,false,true,true,true,80,11,false,0.431,0.0014,3450,2017,6,15,Sunday,true,false,false,false,false,false,false
40007365,RequiresApi vs TargetApi android annotations,"Whats the difference between RequiresApi and TargetApi?
Sample in kotlin:
@RequiresApi(api = Build.VERSION_CODES.M)
@TargetApi(Build.VERSION_CODES.M)
class FingerprintHandlerM() : FingerprintManager.AuthenticationCallback()
NOTE: FingerprintManager.AuthenticationCallback requires api M
NOTE 2: if I dont use TargetApi lint fail with error class requires api level 23...
",https://stackoverflow.com/questions/40007365/requiresapi-vs-targetapi-android-annotations,117,58826.0,5.0,,,2016-10-12 20:02:50,2024-10-26 14:50:54,,,,android;android-support-library;kotlin;android-annotations,Daniel Gomez Rico,16095,273119,registered,true,45773141,,CC BY-SA 3.0,,511,376,6,0,0,4,true,false,false,true,true,false,44,5,false,0.085,0.002,3692,2016,10,20,Wednesday,false,false,false,false,false,false,false
43220140,What's Kotlin Backing Field For?,"As a Java developer, the concept of a backing field is a bit foreign to me. Given:
class Sample {
var counter = 0 // the initializer value is written directly to the backing field
set(value) {
if (value >= 0) field = value
}
}
What's this backing field good for? Kotlin docs said:
Classes in Kotlin cannot have fields. However, sometimes it is necessary to have a backing field when using custom accessors.
Why? What's the difference with using the properties name itself inside the setter, eg.*
class Sample {
var counter = 0
set(value) {
if (value >= 0) this.counter = value // or just counter = value?
}
}
",https://stackoverflow.com/questions/43220140/whats-kotlin-backing-field-for,117,21788.0,5.0,,,2017-04-05 01:02:17,2020-07-25 10:26:24,2020-07-25 10:26:24,,,android;kotlin;kotlin-android-extensions,Yudhistira Arya,3691,3009822,registered,true,43220314,,CC BY-SA 4.0,,862,667,2,1,0,3,true,false,false,true,true,true,36,5,true,0.229,0.0054,3517,2017,4,1,Wednesday,false,false,false,false,false,false,false
41790357,Close/hide the Android Soft Keyboard with Kotlin,"I'm trying to write a simple Android app in Kotlin. I have an EditText and a Button in my layout. After writing in the edit field and clicking on the Button, I want to hide the virtual keyboard.
There is a popular question Close/hide the Android Soft Keyboard about doing it in Java, but as far as I understand, there should be an alternative version for Kotlin. How should I do it?
",https://stackoverflow.com/questions/41790357/close-hide-the-android-soft-keyboard-with-kotlin,116,122804.0,19.0,,,2017-01-22 11:32:55,2024-06-07 06:13:02,2017-05-23 12:33:38,,,android;android-softkeyboard;kotlin,Eugene Trifonov,1261,6265477,registered,true,,,CC BY-SA 3.0,,511,385,0,1,0,3,false,false,false,true,true,true,48,7,false,0.155,0.0009,3590,2017,1,11,Sunday,true,false,false,false,false,false,false
45213706,Kotlin - Wait function,"Is there a wait function in kotlin? (I don't mean a Timer Schedule, but actually pause the execution). I have read that you can use Thread.sleep(). However, it doesn't work for me, because the function can't be found.
",https://stackoverflow.com/questions/45213706/kotlin-wait-function,116,254178.0,9.0,,,2017-07-20 11:42:42,2024-02-14 15:23:31,2017-07-20 12:07:31,,,kotlin;wait,OhMad,6969,7190575,registered,true,45213749,,CC BY-SA 3.0,,255,218,1,0,0,2,true,false,false,true,true,true,22,4,false,0.035,0.0005,3411,2017,7,11,Thursday,false,false,false,false,false,false,false
35554076,"How do I manage unit test resources in Kotlin, such as starting/stopping a database connection or an embedded elasticsearch server?","In my Kotlin JUnit tests, I want to start/stop embedded servers and use them within my tests.
I tried using the JUnit @Before annotation on a method in my test class and it works fine, but it isn't the right behaviour since it runs every test case instead of just once.
Therefore I want to use the @BeforeClass annotation on a method, but adding it to a method results in an error saying it must be on a static method. Kotlin doesn't appear to have static methods. And then the same applies for static variables, because I need to keep a reference to the embedded server around for use in the test cases.
So how do I create this embedded database just once for all of my test cases?
class MyTest {
@Before fun setup() {
// works in that it opens the database connection, but is wrong
// since this is per test case instead of being shared for all
}
@BeforeClass fun setupClass() {
// what I want to do instead, but results in error because
// this isn't a static method, and static keyword doesn't exist
}
var referenceToServer: ServerType // wrong because is not static either
...
}
Note: this question is intentionally written and answered by the author (Self-Answered Questions), so that the answers to commonly asked Kotlin topics are present in SO.
",https://stackoverflow.com/questions/35554076/how-do-i-manage-unit-test-resources-in-kotlin-such-as-starting-stopping-a-datab,116,48749.0,2.0,,,2016-02-22 12:45:33,2022-03-12 05:14:26,2021-01-18 12:39:36,,,unit-testing;junit;kotlin,Jayson Minard,86376,3679676,registered,true,35554077,,CC BY-SA 4.0,,1523,1314,3,1,0,3,true,false,false,true,true,true,131,20,true,0.041,0.0024,3925,2016,2,12,Monday,false,false,false,false,false,false,false
34145495,2D Array in Kotlin,"How do you make a 2D Int array in Kotlin? I'm trying to convert this code to Kotlin:
int[][] states = new int[][] {
new int[]{-android.R.attr.state_pressed}, // not pressed
new int[] { android.R.attr.state_pressed} // pressed
};
int[] colors = new int[] {
foregroundColor,
accentColor,
accentColor
};
ColorStateList myList = new ColorStateList(states, colors);
Here is one attempt I tried, where the first 2D array didn't work, but I got the 1D array to work:
//This doesn't work:
var states: IntArray = intArrayOf(
intArrayOf(-android.R.attr.state_pressed), // not pressed
intArrayOf(android.R.attr.state_pressed) // pressed
);
//This array works:
var colors: IntArray = intArrayOf(
foregroundColor,
accentColor,
accentColor
);
val myList: ColorStateList = ColorStateList(states, colors);
",https://stackoverflow.com/questions/34145495/2d-array-in-kotlin,115,145720.0,11.0,,,2015-12-07 23:44:32,2023-11-23 17:21:34,2020-10-21 14:52:57,,,arrays;kotlin,Rock Lee,9626,2423194,registered,true,34145673,,CC BY-SA 4.0,2020-10-18 07:26:01,986,844,2,0,0,2,true,false,false,true,true,true,18,4,false,0.075,0.0008,4002,2015,12,23,Monday,false,false,false,false,false,false,false
55488291,How to add an item to a list in Kotlin?,"I'm trying to add an element list to the list of string, but I found Kotlin does not have an add function like Java. How can I add the items to the list?
class RetrofitKotlin : AppCompatActivity() {
var listofVechile:List<Message>?=null
var listofVechileName:List<String>?=null
var listview:ListView?=null
var progressBar:ProgressBar?=null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_retrofit_kotlin)
listview=findViewById<ListView>(R.id.mlist)
var apiInterfacee=ApiClass.client.create(ApiInterfacee::class.java)
val call=apiInterfacee.getTaxiType()
call.enqueue(object : Callback<TaxiTypeResponse> {
override fun onResponse(call: Call<TaxiTypeResponse>, response: Response<TaxiTypeResponse>) {
listofVechile=response.body()?.message!!
println("Sixze is here listofVechile ${listofVechile!!.size}")
if (listofVechile!=null) {
for (i in 0..listofVechile!!.size-1) {
//how to add the name only listofVechileName list
}
}
//println("Sixze is here ${listofVechileName!!.size}")
val arrayadapter=ArrayAdapter<String>(this@RetrofitKotlin,android.R.layout.simple_expandable_list_item_1,listofVechileName)
listview!!.adapter=arrayadapter
}
override fun onFailure(call: Call<TaxiTypeResponse>, t: Throwable) {
}
})
}
}
",https://stackoverflow.com/questions/55488291/how-to-add-an-item-to-a-list-in-kotlin,115,259225.0,8.0,,,2019-04-03 06:18:39,2025-12-26 22:19:18,2025-12-26 22:18:19,,,list;kotlin;collections;kotlin-android-extensions,Mohit Lakhanpal,1535,8348768,registered,true,,,CC BY-SA 4.0,,1714,1683,1,0,0,4,false,false,false,true,true,true,39,10,true,0.031,0.0004,2789,2019,4,6,Wednesday,false,false,false,false,false,false,false
43172947,Kotlin - creating a mutable list with repeating elements,"What would be an idiomatic way to create a mutable list of a given length n with repeating elements of value v (e.g listOf(4,4,4,4,4)) as an expression.
I'm doing val list = listOf((0..n-1)).flatten().map{v} but it can only create an immutable list.
",https://stackoverflow.com/questions/43172947/kotlin-creating-a-mutable-list-with-repeating-elements,114,51799.0,5.0,,,2017-04-02 20:02:10,2024-07-03 09:13:49,,,,list;kotlin,Basel Shishani,8227,804138,registered,true,43173751,,CC BY-SA 3.0,,317,251,4,0,0,2,true,false,false,true,true,false,56,9,false,0.097,0.0022,3520,2017,4,20,Sunday,true,false,false,false,false,false,false
48552925,Existing 3-function callback to Kotlin Coroutines,"I have a general question with a specific example: I'd like to use Kotlin coroutine magic instead of callback hell in Android when taking a picture.
manager.openCamera(cameraId, object : CameraDevice.StateCallback() {
override fun onOpened(openedCameraDevice: CameraDevice) {
println(""Camera onOpened"")
// even more callbacks with openedCameraDevice.createCaptureRequest()....
}
override fun onDisconnected(cameraDevice: CameraDevice) {
println(""Camera onDisconnected"")
cameraDevice.close()
}
...
How would I convert that to something less ugly? Is it possible to take an average callback with three or so functions, and turn it into a promise-chain by designating the primary flow as the promise-result path? And if so, should/do I use coroutines to make it async?
I'd love something with async and .await that would result in
manager.open(cameraId).await().createCaptureRequest()
I'm trying to do it through something like the following, but I don't think I'm using CompletableDeferred right!
suspend fun CameraManager.open(cameraId:String): CameraDevice {
val response = CompletableDeferred<CameraDevice>()
this.openCamera(cameraId, object : CameraDevice.StateCallback() {
override fun onOpened(cameraDevice: CameraDevice) {
println(""camera onOpened $cameraDevice"")
response.complete(cameraDevice)
}
override fun onDisconnected(cameraDevice: CameraDevice) {
response.completeExceptionally(Exception(""Camera onDisconnected $cameraDevice""))
cameraDevice.close()
}
override fun onError(cameraDevice: CameraDevice, error: Int) {
response.completeExceptionally(Exception(""Camera onError $cameraDevice $error""))
cameraDevice.close()
}
}, Handler())
return response.await()
}
",https://stackoverflow.com/questions/48552925/existing-3-function-callback-to-kotlin-coroutines,113,38758.0,3.0,,,2018-01-31 23:07:24,2023-02-25 14:32:28,2020-04-10 14:40:32,,,android;kotlin;kotlin-coroutines,Benjamin H,5564,1117848,registered,true,48562175,,CC BY-SA 4.0,,2019,1880,4,0,0,3,true,false,false,true,true,true,49,6,false,0.077,0.0029,3216,2018,1,23,Wednesday,false,false,false,false,false,false,false
35629159,Kotlin's Iterable and Sequence look exactly same. Why are two types required?,"Both of these interfaces define only one method
public operator fun iterator(): Iterator<T>
Documentation says Sequence is meant to be lazy. But isn't Iterable lazy too (unless backed by a Collection)?
",https://stackoverflow.com/questions/35629159/kotlins-iterable-and-sequence-look-exactly-same-why-are-two-types-required,113,23866.0,4.0,,,2016-02-25 13:48:52,2021-07-20 03:16:55,2016-02-25 15:42:40,,,kotlin;iterable;lazy-sequences,Venkata Raju,5459,1812434,registered,true,35630670,,CC BY-SA 3.0,,288,211,4,0,0,3,true,false,false,true,true,true,81,12,true,0.168,0.0047,3922,2016,2,13,Thursday,false,false,false,false,false,false,false
7908193,how to access downloads folder in android?,"I am new android, i'm making an app in which one can download files to downloads folder (using Download Manager). I can see pictures if i go to downloads folder in emulator. So if i want to show a slideshow of downloaded files how can i get the access to that folder? Secondly how to add progress bar to this code:--
import java.util.Arrays;
import android.app.Activity;
import android.app.DownloadManager;
import android.app.DownloadManager.Query;
import android.app.DownloadManager.Request;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
public class Download_managerActivity extends Activity {
private long quueue_for_url;
private DownloadManager dm;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long downloadId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, 0);
Query query = new Query();
query.setFilterById(quueue_for_url);
Cursor c = dm.query(query);
if (c.moveToFirst()) {
int columnIndex = c
.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c
.getInt(columnIndex)) {
ImageView view = (ImageView) findViewById(R.id.imageView1);
String uri_String_abcd = c
.getString(c
.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
view.setImageURI(Uri.parse(uri_String_abcd));
}
}
}
}
};
registerReceiver(receiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
public void onClick(View view) {
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
Request request_for_url = new Request(
Uri.parse(""http://fc03.deviantart.net/fs14/i/2007/086/9/1/Steve_Jobs_portrait_by_tumb.jpg""));
Request request_for_url1 = new Request(
Uri.parse(""http://2.bp.blogspot.com/_q7Rxg4wqDyc/S5ZRVLxVYuI/AAAAAAAAAvU/fQAUZ2XFcp8/s400/katrina-kaif.jpg""));
Request request_for_url2 = new Request(
Uri.parse(""http://www.buzzreactor.com/sites/default/files/Bill-Gates1.jpg""));
quueue_for_url = dm.enqueue(request_for_url);
quueue_for_url = dm.enqueue(request_for_url1);
quueue_for_url = dm.enqueue(request_for_url2);
}
public void showDownload(View view) {
Intent i = new Intent();
//try more options to show downloading , retrieving and complete
i.setAction(DownloadManager.ACTION_VIEW_DOWNLOADS);
startActivity(i);
}
}
I want to add a button which performs the function of taking the pictures from downloads folder and then display like a slideshow.
<?xml version=""1.0"" encoding=""utf-8""?>
<manifest xmlns:android=""http://schemas.android.com/apk/res/android""
package=""cmpe235.lab1""
android:versionCode=""1""
android:versionName=""1.0"">
<uses-sdk android:minSdkVersion=""9"" />
<uses-permission android:name=""android.permission.INTERNET""></uses-permission>
<application android:icon=""@drawable/icon"" android:label=""@string/app_name"">
<activity android:name="".Download_managerActivity""
android:label=""@string/app_name"">
<intent-filter>
<action android:name=""android.intent.action.MAIN"" />
<category android:name=""android.intent.category.LAUNCHER"" />
</intent-filter>
</activity>
</application>
</manifest>
main.xml:-
<?xml version=""1.0"" encoding=""utf-8""?>
<LinearLayout xmlns:android=""http://schemas.android.com/apk/res/android""
android:orientation=""vertical"" android:layout_width=""fill_parent""
android:layout_height=""fill_parent"">
<Button android:text=""Start Download"" android:id=""@+id/button1""
android:layout_width=""wrap_content"" android:layout_height=""wrap_content""
android:layout_gravity=""center_vertical|center_horizontal|center"" android:textColor=""#0000A0""
android:typeface=""serif"" android:onClick=""onClick""></Button>
<Button android:text=""View Downloads"" android:id=""@+id/button2""
android:layout_width=""wrap_content"" android:layout_height=""wrap_content""
android:layout_gravity=""center_vertical|center_horizontal|center"" android:textColor=""#0000A0""
android:typeface=""serif"" android:onClick=""showDownload""></Button>
<ImageView android:layout_height=""wrap_content"" android:id=""@+id/imageView1""
android:src=""@drawable/icon"" android:layout_width=""wrap_content""></ImageView>
</LinearLayout>
",https://stackoverflow.com/questions/7908193/how-to-access-downloads-folder-in-android,112,253836.0,6.0,,,2011-10-26 20:02:17,2022-02-22 23:19:37,2021-01-06 13:55:42,,,java;android;kotlin;android-progressbar;android-storage,Dhruv,1758,877202,registered,true,7908446,,CC BY-SA 4.0,2020-06-11 15:07:01,5956,5863,3,0,0,5,true,false,false,true,true,true,42,7,true,0.024,0.0004,5505,2011,10,20,Wednesday,false,false,false,true,false,false,false
40398072,Singleton with parameter in Kotlin,"I am trying to convert an Android app from Java to Kotlin. There are a few singletons in the app. I used a companion object for the singletons without constructor parameters. There is another singleton that takes a constructor parameter.
Java code:
public class TasksLocalDataSource implements TasksDataSource {
private static TasksLocalDataSource INSTANCE;
private TasksDbHelper mDbHelper;
// Prevent direct instantiation.
private TasksLocalDataSource(@NonNull Context context) {
checkNotNull(context);
mDbHelper = new TasksDbHelper(context);
}
public static TasksLocalDataSource getInstance(@NonNull Context context) {
if (INSTANCE == null) {
INSTANCE = new TasksLocalDataSource(context);
}
return INSTANCE;
}
}
My solution in kotlin:
class TasksLocalDataSource private constructor(context: Context) : TasksDataSource {
private val mDbHelper: TasksDbHelper
init {
checkNotNull(context)
mDbHelper = TasksDbHelper(context)
}
companion object {
lateinit var INSTANCE: TasksLocalDataSource
private val initialized = AtomicBoolean()
fun getInstance(context: Context) : TasksLocalDataSource {
if(initialized.getAndSet(true)) {
INSTANCE = TasksLocalDataSource(context)
}
return INSTANCE
}
}
}
Am I missing anything? Thread safety? Laziness ?
There were a few similar questions but I don't like the answers :)
",https://stackoverflow.com/questions/40398072/singleton-with-parameter-in-kotlin,112,91513.0,14.0,,,2016-11-03 09:36:20,2021-12-05 17:38:53,,,,android;kotlin,LordRaydenMK,13331,1011435,registered,true,45943282,,CC BY-SA 3.0,,1604,1521,2,0,0,2,true,false,false,true,true,false,34,5,false,0.153,0.0012,3670,2016,11,9,Thursday,false,false,false,false,false,false,false
49024200,What is the difference between 'open' and 'public' in Kotlin?,"I am new to Kotlin and I am confused between open and public keywords. Could anyone please tell me the difference between those keywords?
",https://stackoverflow.com/questions/49024200/what-is-the-difference-between-open-and-public-in-kotlin,112,86817.0,8.0,,,2018-02-28 07:35:17,2023-02-02 13:19:19,,,,kotlin;keyword;public,Sagun Raj Lage,2584,7552217,registered,true,49024246,,CC BY-SA 3.0,,171,138,2,0,0,3,true,false,false,true,true,false,77,10,true,0.092,0.0013,3188,2018,2,7,Wednesday,false,false,false,false,false,false,false
36440295,kotlin.jvm.KotlinReflectionNotSupportedError: Kotlin reflection implementation is not found at runtime. Make sure you have kotlin-reflect.jar,"When I compile I got the above error. My gradle file as below : -
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 23
buildToolsVersion ""24.0.0 rc2""
defaultConfig {
applicationId ""package.name""
minSdkVersion 16
targetSdkVersion 23
versionCode 6
versionName ""2.0""
}
buildTypes {
debug {
minifyEnabled false
signingConfig signingConfigs.debug
}
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
signingConfig signingConfigs.release
}
}
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile ""com.android.support:appcompat-v7:$support_version""
compile ""org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version""
compile ""org.jetbrains.anko:anko-sdk15:$anko_version""
compile ""org.jetbrains.anko:anko-support-v4:$anko_version""
compile ""com.android.support:recyclerview-v7:$support_version""
}
buildscript {
ext.kotlin_version = '1.0.1-2'
repositories {
jcenter()
mavenCentral()
}
dependencies {
classpath ""org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version""
}
}
repositories {
mavenCentral()
}
And my project gradle as below
buildscript {
ext.support_version = '23.2.1'
ext.kotlin_version = '1.0.1'
ext.anko_version = '0.8.3'
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.1.0-alpha3'
classpath ""org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version""
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
Did I miss adding anything?
",https://stackoverflow.com/questions/36440295/kotlin-jvm-kotlinreflectionnotsupportederror-kotlin-reflection-implementation-i,112,45515.0,3.0,,,2016-04-06 02:16:22,2020-01-08 11:03:41,,,,kotlin,Elye,61515,3286489,registered,true,36440329,,CC BY-SA 3.0,,2220,2151,2,0,0,1,true,false,false,true,true,false,141,14,false,0.066,0.0025,3881,2016,4,2,Wednesday,false,false,false,false,false,false,false
39199426,Better way to map Kotlin data objects to data objects,"I want to convert/map some ""data"" class objects to similar ""data"" class objects. For example, classes for web form to classes for database records.
data class PersonForm(
val firstName: String,
val lastName: String,
val age: Int,
// maybe many fields exist here like address, card number, etc.
val tel: String
)
// maps to ...
data class PersonRecord(
val name: String, // ""${firstName} ${lastName}""
val age: Int, // copy of age
// maybe many fields exist here like address, card number, etc.
val tel: String // copy of tel
)
I use ModelMapper for such works in Java, but it can't be used because data classes are final (ModelMapper creates CGLib proxies to read mapping definitions). We can use ModelMapper when we make these classes/fields open, but we must implement features of ""data"" class manually.
(cf. ModelMapper examples: https://github.com/jhalterman/modelmapper/blob/master/examples/src/main/java/org/modelmapper/gettingstarted/GettingStartedExample.java)
How to map such ""data"" objects in Kotlin?
Update:
ModelMapper automatically maps fields that have same name (like tel -> tel) without mapping declarations. I want to do it with data class of Kotlin.
Update:
The purpose of each classes depends on what kind of application, but these are probably placed in the different layer of an application.
For example:
- data from database (Database Entity) to data for HTML form (Model/View Model)
- REST API result to data for database
These classes are similar, but are not the same.
I want to avoid normal function calls for these reasons:
- It depends on the order of arguments. A function for a class with many fields that have same type (like String) will be broken easily.
- Many declarations are nesessary though most mappings can be resolved with naming convention.
Of course, a library that has similar feature is intended, but information of the Kotlin feature is also welcome (like spreading in ECMAScript).
",https://stackoverflow.com/questions/39199426/better-way-to-map-kotlin-data-objects-to-data-objects,112,146985.0,14.0,,,2016-08-29 06:01:01,2023-09-29 07:38:15,2016-08-29 14:10:23,,,java;kotlin;modelmapper,sunnyone,1550,3767132,registered,true,,,CC BY-SA 3.0,,2312,1971,1,1,0,3,false,false,false,true,true,true,53,10,false,0.095,0.0008,3736,2016,8,6,Monday,false,false,false,true,false,false,false
44098709,How can I filter an ArrayList in Kotlin so I only have elements which match my condition?,"I have an array:
var month: List<String> = arrayListOf(""January"", ""February"", ""March"")
I have to filter the list so I am left with only ""January"".
",https://stackoverflow.com/questions/44098709/how-can-i-filter-an-arraylist-in-kotlin-so-i-only-have-elements-which-match-my-c,111,203622.0,7.0,,,2017-05-21 15:40:59,2024-01-10 11:44:49,2019-04-16 16:09:16,,,list;kotlin;filtering,Nitt,1933,7013334,registered,true,44098722,,CC BY-SA 4.0,,207,156,2,0,0,3,true,false,false,true,true,true,89,17,true,0.034,0.0005,3471,2017,5,15,Sunday,true,false,false,false,false,false,false
36184641,Kotlin: Iterate through a JSONArray,"I'm writing an Android app using Kotlin and Realm.
I have a JSONArray, and I want to iterate through the JSONObjects in this array in order to load them in a Realm database class:
Realm class:
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
import io.realm.annotations.Required
open class Person(
@PrimaryKey open var id: Long = 0,
@Required
open var name: String = ""
) : RealmObject() {
}
The JSONArray:
{
"persons":[
{
"id":0,
"name":"Biatrix"
},
{
"id":1,
"name":"Bill"
},
{
"id":2,
"name":"O-Ren"
},
{
"id":3,
"name":"Budd"
},
{
"id":4,
"name":"Elle"
}
]
}
I've tried iterating like the following:
for (item : JSONObject in persons) {
}
... but I get a for-loop range must have an iterator() method error.
",https://stackoverflow.com/questions/36184641/kotlin-iterate-through-a-jsonarray,111,81938.0,5.0,,,2016-03-23 17:16:38,2025-09-11 08:53:45,2025-09-11 08:53:45,,,android;json;kotlin,Ambran,2667,1545435,registered,true,36185280,,CC BY-SA 4.0,,1251,1131,4,0,0,3,true,false,false,true,true,true,35,5,false,0.061,0.0014,3895,2016,3,17,Wednesday,false,false,false,false,false,false,false
54419236,Why a viewmodel factory is needed in Android?,"We have been discussing about this but we don't know the reason of creating a viewmodel factory to create a viewmodel instead of instantiate the viewmodel directly. What is the gain of creating a factory that just creates the viewmodel?
I just put a simple example of how I did it without Factory
here is the kodein module:
val heroesRepositoryModel = Kodein {
bind<HeroesRepository>() with singleton {
HeroesRepository()
}
bind<ApiDataSource>() with singleton {
DataModule.create()
}
bind<MainViewModel>() with provider {
MainViewModel()
}
}
The piece of the Activity where I instantiate the viewmodel without using the factory
class MainActivity : AppCompatActivity() {
private lateinit var heroesAdapter: HeroAdapter
private lateinit var viewModel: MainViewModel
private val heroesList = mutableListOf<Heroes.MapHero>()
private var page = 0
private var progressBarUpdated = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
viewModel = ViewModelProviders.of(this)
.get(MainViewModel::class.java)
initAdapter()
initObserver()
findHeroes()
}
The ViewModel where I instantiate the usecase directly without having it in the constructor
class MainViewModel : ViewModel(), CoroutineScope {
private val heroesRepository: HeroesRepository = heroesRepositoryModel.instance()
val data = MutableLiveData<List<Heroes.MapHero>>()
private var job: Job = Job()
override val coroutineContext: CoroutineContext
get() = uiContext + job
fun getHeroesFromRepository(page: Int) {
launch {
try {
val response = heroesRepository.getHeroes(page).await()
data.value = response.data.results.map { it.convertToMapHero() }
} catch (e: HttpException) {
data.value = null
} catch (e: Throwable) {
data.value = null
}
}
}
override fun onCleared() {
super.onCleared()
job.cancel()
}
}
So here a example using factory
class ListFragment : Fragment(), KodeinAware, ContactsAdapter.OnContactListener {
override val kodein by closestKodein()
private lateinit var adapterContacts: ContactsAdapter
private val mainViewModelFactory: MainViewModelFactory by instance()
private val mainViewModel: MainViewModel by lazy {
activity?.run {
ViewModelProviders.of(this, mainViewModelFactory)
.get(MainViewModel::class.java)
} ?: throw Exception(""Invalid Activity"")
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_list, container, false)
}
The viewmodelfactory:
class MainViewModelFactory (private val getContacts: GetContacts) : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(MainViewModel::class.java)) {
return MainViewModel(getContacts) as T
}
throw IllegalArgumentException(""Unknown ViewModel class"")
}
}
And the viewmodel:
class MainViewModel(private val getContacts: GetContacts) : BaseViewModel() {
lateinit var gamesList: LiveData<PagedList<Contact>>
var contactsSelectedData: MutableLiveData<List<Contact>> = MutableLiveData()
var contactsSelected: ArrayList<Contact> = ArrayList()
private val pagedListConfig by lazy {
PagedList.Config.Builder()
.setEnablePlaceholders(false)
.setInitialLoadSizeHint(PAGES_CONTACTS_SIZE)
.setPageSize(PAGES_CONTACTS_SIZE)
.setPrefetchDistance(PAGES_CONTACTS_SIZE*2)
.build()
}
Here is the complete first example:
https://github.com/ibanarriolaIT/Marvel/tree/mvvm
And the complete second example:
https://github.com/AdrianMeizoso/Payment-App
",https://stackoverflow.com/questions/54419236/why-a-viewmodel-factory-is-needed-in-android,111,78734.0,4.0,,,2019-01-29 10:43:02,2021-11-26 18:09:01,2019-01-29 10:45:13,,,android;mvvm;kotlin;viewmodel;kodein,Iban Arriola,2826,1734982,registered,true,54420034,,CC BY-SA 4.0,,4578,4193,6,2,0,5,true,false,false,true,true,true,45,8,true,0.051,0.0014,2853,2019,1,10,Tuesday,false,false,false,false,false,false,false
55286542,Kotlin could not find the required JDK tools in the Java installation,"When running ./gradlew clean build I get following message:
> Task :compileKotlin FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':compileKotlin'.
> Kotlin could not find the required JDK tools in the Java installation '/usr/lib/jvm/java-8-openjdk-amd64/jre' used by Gradle. Make sure Gradle is running on a JDK, not JRE.
I have JDK, JAVA_HOME is set properly, so is update-alternatives.
# java -version
openjdk version ""1.8.0_191""
OpenJDK Runtime Environment (build 1.8.0_191-8u191-b12-2ubuntu0.16.04.1-b12)
OpenJDK 64-Bit Server VM (build 25.191-b12, mixed mode)
# update-alternatives --config java
There are 3 choices for the alternative java (providing /usr/bin/java).
Selection Path Priority Status
------------------------------------------------------------
* 0 /usr/lib/jvm/default-java/bin/java 1100 auto mode
1 /usr/lib/jvm/default-java/bin/java 1100 manual mode
2 /usr/lib/jvm/java-8-openjdk-amd64/bin/java 1 manual mode
3 /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java 1081 manual mode
Here's gradle build with stacktrace enabled:
* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':compileKotlin'.
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:110)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:77)
at org.gradle.api.internal.tasks.execution.OutputDirectoryCreatingTaskExecuter.execute(OutputDirectoryCreatingTaskExecuter.java:51)
at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:59)
at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:59)
at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:101)
at org.gradle.api.internal.tasks.execution.FinalizeInputFilePropertiesTaskExecuter.execute(FinalizeInputFilePropertiesTaskExecuter.java:44)
at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:91)
at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:62)
at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:59)
at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.run(EventFiringTaskExecuter.java:51)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:300)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:292)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:174)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:46)
at org.gradle.execution.taskgraph.LocalTaskInfoExecutor.execute(LocalTaskInfoExecutor.java:42)
at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareWorkItemExecutor.execute(DefaultTaskExecutionGraph.java:277)
at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareWorkItemExecutor.execute(DefaultTaskExecutionGraph.java:262)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:135)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:130)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker.execute(DefaultTaskPlanExecutor.java:200)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker.executeWithWork(DefaultTaskPlanExecutor.java:191)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker.run(DefaultTaskPlanExecutor.java:130)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:74)
at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph.execute(DefaultTaskExecutionGraph.java:143)
at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:40)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:40)
at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:24)
at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:46)
at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:49)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:40)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:33)
at org.gradle.initialization.DefaultGradleLauncher$ExecuteTasks.run(DefaultGradleLauncher.java:355)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:300)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:292)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:174)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
at org.gradle.initialization.DefaultGradleLauncher.runTasks(DefaultGradleLauncher.java:219)
at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:149)
at org.gradle.initialization.DefaultGradleLauncher.executeTasks(DefaultGradleLauncher.java:124)
at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:77)
at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:74)
at org.gradle.internal.work.DefaultWorkerLeaseService.withLocks(DefaultWorkerLeaseService.java:154)
at org.gradle.internal.work.StopShieldingWorkerLeaseService.withLocks(StopShieldingWorkerLeaseService.java:38)
at org.gradle.internal.invocation.GradleBuildController.doBuild(GradleBuildController.java:96)
at org.gradle.internal.invocation.GradleBuildController.run(GradleBuildController.java:74)
at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
at org.gradle.launcher.exec.ChainingBuildActionRunner.run(Ch",https://stackoverflow.com/questions/55286542/kotlin-could-not-find-the-required-jdk-tools-in-the-java-installation,110,137561.0,23.0,,,2019-03-21 17:56:46,2025-02-09 17:39:28,,,,ubuntu;gradle;kotlin;gradlew,Krzysztof Piszko,1445,1959095,registered,true,,,CC BY-SA 4.0,,18073,17826,11,0,0,4,false,false,false,true,true,false,69,12,false,0.167,0.0008,2802,2019,3,17,Thursday,false,false,false,false,false,false,false
45841067,What is the best way to define log TAG constant in Kotlin?,"I'm creating my first Kotlin classes in my Android application. Usually for logging purposes I have a constant with name TAG. What I would do in Java is:
private static final String TAG = MyClass.class.getSimpleName();
I know that in Kotlin classes I can create TAG using this way:
private val TAG = MyClass::class.java.simpleName
This is OK for projects that use Java and Kotlin but what if I start a new project that is only in Kotlin? How can I define there TAG constant? Is there more Kotlin way where I don't have this strange construction class.java.simpleName?
",https://stackoverflow.com/questions/45841067/what-is-the-best-way-to-define-log-tag-constant-in-kotlin,110,50521.0,20.0,,,2017-08-23 13:25:28,2025-10-10 09:13:11,,,,java;android;kotlin;constants,Mario Kutlev,5144,1726308,registered,true,45841698,,CC BY-SA 3.0,,695,574,6,0,0,4,true,false,false,true,true,false,58,12,true,0.396,0.0022,3377,2017,8,13,Wednesday,false,false,false,true,false,false,false
46847734,Private constructor in Kotlin,"In Java it's possible to hide a class' main constructor by making it private and then accessing it via a public static method inside that class:
public final class Foo {
/* Public static method */
public static final Foo constructorA() {
// do stuff
return new Foo(someData);
}
private final Data someData;
/* Main constructor */
private Foo(final Data someData) {
Objects.requireNonNull(someData);
this.someData = someData;
}
// ...
}
How can the same be reached with Kotlin without separating the class into a public interface and a private implementation? Making a constructor private leads to it not being accessible from outside the class, not even from the same file.
",https://stackoverflow.com/questions/46847734/private-constructor-in-kotlin,110,76984.0,4.0,,,2017-10-20 10:59:43,2020-04-03 16:24:38,,,,java;constructor;kotlin;visibility,Marvin,1932,4385297,registered,true,46848368,,CC BY-SA 3.0,,862,746,7,0,0,4,true,false,false,true,true,false,29,4,false,0.052,0.0014,3319,2017,10,10,Friday,false,false,false,true,false,false,false
67843986,Is there a shorter replacement for Kotlin's deprecated String.capitalize() function?,"Kotlin deprecated the capitalize function on String class, and their suggested replacement is obnoxiously long. This is an example of a situation where they made the right call on deprecating it, but the wrong call on the user experience.
For example, this code:
val x = listOf("foo", "bar", "baz").map { it.capitalize() }
is "cleaned up" by the IDE to become:
val x = listOf("foo", "bar", "baz").map { it.replaceFirstChar {
if (it.isLowerCase()) it.titlecase(
Locale.getDefault()
) else it.toString()
} }
This is preeeeetty ugly. What can we do about it?
",https://stackoverflow.com/questions/67843986/is-there-a-shorter-replacement-for-kotlins-deprecated-string-capitalize-funct,110,47617.0,9.0,,,2021-06-04 21:08:16,2025-02-25 15:11:39,,,,string;kotlin;deprecated;capitalization,Stevey,3352,3562927,registered,true,67845025,,CC BY-SA 4.0,,812,710,4,0,0,4,true,false,false,true,true,false,88,10,true,0.189,0.0023,1996,2021,6,21,Friday,false,false,false,false,false,false,false
36528515,throws Exception in a method with Kotlin,"I'm trying to convert this Java code to Kotlin:
public class HeaderInterceptor implements Interceptor {
@Override public Response intercept(Chain chain) throws IOException {
return null;
}
}
The problem is, when I implement the methods, I get something like
class JsonHeadersInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain?): Response? {
throw UnsupportedOperationException()
}
}
The only info I've found talking about throwing exceptions in Kotlin is THIS.
Apart from removing the question mark, because it's not necessary, why it doesn't handle the IOException the same way? What is the best approach to handle this situation?
",https://stackoverflow.com/questions/36528515/throws-exception-in-a-method-with-kotlin,109,145151.0,2.0,,,2016-04-10 10:21:27,2021-03-13 01:48:43,2019-11-19 04:13:47,,,java;kotlin;kotlin-extension,cesards,16419,689723,registered,true,36528811,,CC BY-SA 4.0,,873,688,3,1,0,3,true,false,false,true,true,true,40,7,false,0.014,0.0008,3877,2016,4,10,Sunday,true,false,false,true,false,false,false
23378610,Android Studio quick documentation always "fetching documentation","I just moved to Android Studio from Eclipse, and I found that it always shows "fetching documentation" when I use quick documentation (Ctrl+Q).
How can I solve this problem?
I downloaded the documentation for API 19, and the problem persists.
",https://stackoverflow.com/questions/23378610/android-studio-quick-documentation-always-fetching-documentation,109,23037.0,13.0,,,2014-04-30 02:22:30,2023-10-08 16:33:45,2022-04-22 06:13:16,,,android-studio;kotlin;intellij-idea;ide;javadoc,Bruce,1695,2680776,registered,true,,,CC BY-SA 4.0,,440,254,0,1,1,5,false,false,false,true,true,true,76,7,false,0.564,0.0047,4588,2014,4,2,Wednesday,false,false,false,false,false,false,false
44391468,Can Kotlin data class have more than one constructor?,"I know that data class are like simple models in kotlin with getters and setter by default and are as simple this:
data class User(val name: String, val age: Int)
Is it possible to declare a second constructor for that data class?
",https://stackoverflow.com/questions/44391468/can-kotlin-data-class-have-more-than-one-constructor,109,114157.0,11.0,,,2017-06-06 13:33:18,2023-10-15 13:28:47,2017-11-03 19:31:03,,,constructor;kotlin,Eder Padilla,1736,8119977,registered,true,57718203,,CC BY-SA 3.0,,272,234,1,0,0,2,true,false,false,true,true,true,53,9,true,0.096,0.001,3455,2017,6,13,Tuesday,false,false,false,false,false,false,false
44035263,Accidental override: The following declarations have the same JVM signature,"I'm getting error in Kotlin in this part:
class GitHubRepoAdapter(
private val context: Context,
private val values: List<GithubRepo>
) : ArrayAdapter<GithubRepo>(
context,
R.layout.list_item,
values
)
private val context: Context
In the log it says:
Error:(14, 25) Accidental override: The following declarations have the same JVM signature
(getContext()Landroid/content/Context;):
fun <get-context>(): Context
fun getContext(): Context!
I'm not able to see what is causing the problem.
",https://stackoverflow.com/questions/44035263/accidental-override-the-following-declarations-have-the-same-jvm-signature,109,79969.0,10.0,,,2017-05-17 21:45:16,2024-06-10 13:06:13,2020-08-01 08:54:20,,,kotlin;kotlin-android-extensions;kotlin-extension,user6683139,,,does_not_exist,true,44035461,,CC BY-SA 4.0,,657,543,3,0,0,3,true,false,false,true,false,true,75,10,false,0.125,0.0014,3475,2017,5,21,Wednesday,false,false,false,false,false,false,false
52869672,Call Kotlin suspend function in Java class,"Assume we have the following suspend function:
suspend fun doSomething(): List<MyClass> { ... }
If I want to call this function in one of my existing Java classes (which I'm not able to convert to Kotlin for now) and get its return value I have to provide a Continuation<? super List<MyClass>> as its parameter (Obviously).
My question is, How can I implement one. Specially its getContext getter.
",https://stackoverflow.com/questions/52869672/call-kotlin-suspend-function-in-java-class,109,64597.0,4.0,,,2018-10-18 08:12:14,2023-03-08 13:32:29,2019-03-19 07:45:40,,,java;kotlin;kotlin-coroutines,mrtaikandi,7048,34623,registered,true,52887677,,CC BY-SA 4.0,,492,421,3,0,0,3,true,false,false,true,true,true,42,7,false,0.062,0.0017,2956,2018,10,8,Thursday,false,false,false,true,false,false,false
46943860,Idiomatic way to generate a random alphanumeric string in Kotlin,"I can generate a random sequence of numbers in a certain range like the following:
fun ClosedRange<Int>.random() = Random().nextInt(endInclusive - start) + start
fun generateRandomNumberList(len: Int, low: Int = 0, high: Int = 255): List<Int> {
(0..len-1).map {
(low..high).random()
}.toList()
}
Then I'll have to extend List with:
fun List<Char>.random() = this[Random().nextInt(this.size)]
Then I can do:
fun generateRandomString(len: Int = 15): String{
val alphanumerics = CharArray(26) { it -> (it + 97).toChar() }.toSet()
.union(CharArray(9) { it -> (it + 48).toChar() }.toSet())
return (0..len-1).map {
alphanumerics.toList().random()
}.joinToString("""")
}
But maybe there's a better way?
",https://stackoverflow.com/questions/46943860/idiomatic-way-to-generate-a-random-alphanumeric-string-in-kotlin,108,87209.0,23.0,,,2017-10-26 00:07:44,2025-12-13 20:59:14,2017-10-26 01:53:29,,,kotlin,breezymri,4453,4438271,registered,true,46944275,,CC BY-SA 3.0,,867,754,4,0,0,1,true,false,false,true,true,true,64,10,false,0.264,0.0012,3313,2017,10,0,Thursday,false,false,false,false,false,false,false
49545037,Android Studio 3.1: Erroneous unresolved references in editor,"I'm running Ubuntu 17.10, and I've just updated Android Studio from version 3.0.1 to 3.1. Here's the version information in Help -> About:
Android Studio 3.1
Build #AI-173.4670197, built on March 22, 2018
JRE: 1.8.0_152-release-1024-b01 amd64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Linux 4.13.0-37-generic
Unfortunately, while the IDE was able to resolve android-specific references before in my (first ever) Kotlin project, in the new version it appears unable to. Here's a screenshot showing what I mean:
In Android Studio 3.1, it's claiming that core Android functions such as setContentView() don't exist, and keeps prompting me to create an abstract function for it - which I clearly don't want to do. However, if I hit the build button, I get a BUILD SUCCESSFUL in 8s.
Why is my editor doing this, and how I get get Android-related functions and classes to resolve correctly again?
- Build → Clean and then Build → Rebuild doesn't help.
- File → Invalidate Caches and Restart doesn't help either
- Neither does a manual Gradle sync.
- A different project that's written in Java instead of Kotlin works fine.
- Link to the project I'm experiencing issues with (it's open-source)
",https://stackoverflow.com/questions/49545037/android-studio-3-1-erroneous-unresolved-references-in-editor,108,92256.0,20.0,,,2018-03-28 22:14:24,2025-01-16 17:42:15,2021-07-21 12:51:51,,,android;android-studio;kotlin;android-studio-3.1,starbeamrainbowlabs,6278,1460422,registered,true,49595693,,CC BY-SA 4.0,,1550,1191,3,2,1,4,true,false,false,true,true,true,61,8,false,0.217,0.0012,3160,2018,3,22,Wednesday,false,false,false,false,false,false,false
28753285,How can I create "static" method for enum in Kotlin?,"Kotlin already have number of ""static"" methods for enum class, like values and valueOf
For example I have enum
public enum class CircleType {
FIRST
SECOND
THIRD
}
How can I add static method such as random(): CircleType? Extension functions seems not for this case.
",https://stackoverflow.com/questions/28753285/how-can-i-create-static-method-for-enum-in-kotlin,108,64110.0,1.0,,,2015-02-26 21:40:51,2022-03-01 13:25:36,2022-03-01 13:25:36,,,enums;static;kotlin,ruX,7532,647381,registered,true,28753602,,CC BY-SA 4.0,,366,282,4,0,0,3,true,false,false,true,true,true,62,10,true,0.016,0.0017,4286,2015,2,21,Thursday,false,false,false,false,false,false,false
13154463,How can I check for generic type in Kotlin,"I'm trying to test for a generic type in Kotlin.
if (value is Map<String, Any>) { ... }
But the compiler complains with
Cannot check for instance of erased type: jet.Map
The check with a normal type works well.
if (value is String) { ... }
Kotlin 0.4.68 is used.
What am I missing here?
",https://stackoverflow.com/questions/13154463/how-can-i-check-for-generic-type-in-kotlin,108,56912.0,6.0,,,2012-10-31 09:07:47,2024-10-17 14:19:03,2024-10-17 14:19:03,,,kotlin;generics;type-erasure,phil,1437,1531199,registered,true,13166690,,CC BY-SA 4.0,,417,306,2,0,0,3,true,false,false,true,true,true,42,9,false,0.105,0.0019,5134,2012,10,9,Wednesday,false,false,false,false,false,false,false
37262468,Static initialisation block in Kotlin,"What is the equivalent of a static initialisation block in Kotlin?
I understand that Kotlin is designed to not have static things. I am looking for something with equivalent semantics - code is run once when the class is first loaded.
My specific use case is that I want to enable the DayNight feature from Android AppCompat library and the instructions say to put some code in static initialisation block of Application class.
",https://stackoverflow.com/questions/37262468/static-initialisation-block-in-kotlin,108,27441.0,2.0,,,2016-05-16 20:11:30,2021-06-11 09:25:02,2018-03-06 10:36:14,,,java;static;kotlin;initializer,Marcin Koziński,11124,1402641,registered,true,37262603,,CC BY-SA 3.0,,671,430,1,2,0,4,true,false,false,true,true,true,37,5,false,0.073,0.0039,3841,2016,5,20,Monday,false,false,false,true,false,false,false
44035504,How to use Data Binding and Kotlin in Android Studio 3.0.0,"I just started to use Android Studio 3.0.0, but every time I try to build my project I get this error:
Error:Circular dependency between the following tasks:
:app:compileDebugKotlin
+--- :app:dataBindingExportBuildInfoDebug
| \--- :app:compileDebugKotlin (*)
\--- :app:kaptDebugKotlin
\--- :app:dataBindingExportBuildInfoDebug (*)
(*) - details omitted (listed previously)
I am using
kapt ""com.android.databinding:compiler:2.2.0""
Before I was using
androidProcessor ""com.android.databinding:compiler:2.2.0""
And it was working just fine... What I am doing wrong??
Thanks!
",https://stackoverflow.com/questions/44035504/how-to-use-data-binding-and-kotlin-in-android-studio-3-0-0,108,43495.0,5.0,,,2017-05-17 22:05:07,2025-04-20 23:46:45,2017-05-25 12:29:20,,,android;android-studio;kotlin;android-databinding;android-studio-3.0,Leandro Borges Ferreira,12822,7101554,registered,true,46429553,,CC BY-SA 3.0,,698,591,3,0,0,5,true,false,false,true,true,true,58,11,false,0.115,0.0025,3475,2017,5,22,Wednesday,false,false,false,false,false,false,false
36625329,Kotlin: Apply vs With,"What is the difference between with and apply. From what I know the following code does the same thing:
swingElement.apply {
minWidth = ENABLED_COLUMN_WIDTH
maxWidth = ENABLED_COLUMN_WIDTH
preferredWidth = ENABLED_COLUMN_WIDTH
}
with(swingElement) {
minWidth = ENABLED_COLUMN_WIDTH
maxWidth = ENABLED_COLUMN_WIDTH
preferredWidth = ENABLED_COLUMN_WIDTH
}
Is there any difference and should I use one over the other?
Also, are there some cases where one would work and the other won't?
",https://stackoverflow.com/questions/36625329/kotlin-apply-vs-with,108,29813.0,6.0,,,2016-04-14 13:56:01,2022-10-09 12:44:31,,,,kotlin,n9Mtq4,1221,5196460,registered,true,36625603,,CC BY-SA 3.0,,549,511,1,0,0,1,true,false,false,true,true,false,21,4,false,0.201,0.0036,3873,2016,4,13,Thursday,false,false,false,false,false,false,false
67400029,Can't create new Kotlin project after updating to Android Studio 4.2,"I updated Android studio 4.2 but I wasn't able to create new project kotlin
A problem occurred configuring root project 'My Application'.
> Could not resolve all artifacts for configuration ':classpath'.
> Could not find org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.0-release-764.
Searched in the following locations:
- https://dl.google.com/dl/android/maven2/org/jetbrains/kotlin/kotlin-gradle-plugin/1.5.0-release-
764/kotlin-gradle-plugin-1.5.0-release-764.pom
- https://repo.maven.apache.org/maven2/org/jetbrains/kotlin/kotlin-gradle-plugin/1.5.0-release-764/kotlin-gradle-plugin-1.5.0-release-764.pom
Required by:
project :
Possible solution:
- Declare repository providing the artifact, see the documentation at
https://docs.gradle.org/current/userguide/declaring_repositories.html
",https://stackoverflow.com/questions/67400029/cant-create-new-kotlin-project-after-updating-to-android-studio-4-2,107,49311.0,15.0,,,2021-05-05 11:02:44,2021-07-29 17:55:19,2021-05-06 00:16:11,,,android;android-studio;kotlin;android-studio-4.2,TEN_KUNG,1229,13833626,registered,true,67400706,,CC BY-SA 4.0,,844,813,1,0,0,4,true,false,false,true,true,true,72,11,false,0.304,0.0022,2026,2021,5,11,Wednesday,false,false,false,false,false,false,false
28548015,How do I create an enum from a string in Kotlin?,"I have an enum with some instances Foo and Bar. If I have a string ""Foo"", how can I instantiate a Foo enum from that? In C# it would be Enum.Parse(...), is there an equivalent in Kotlin?
Currently, the best I have found is to create a factory that switches on all possible strings, but that is error prone and performs poorly for large enumerations.
",https://stackoverflow.com/questions/28548015/how-do-i-create-an-enum-from-a-string-in-kotlin,106,145506.0,8.0,,,2015-02-16 18:29:59,2023-11-17 15:34:02,,,,kotlin,Micah Zoltu,7625,879046,registered,true,28549093,,CC BY-SA 3.0,,432,353,5,0,0,1,true,false,false,true,true,false,48,11,true,0.055,0.0007,4296,2015,2,18,Monday,false,false,false,false,false,false,false
58351239,ViewBinding vs Kotlin Android Extensions with synthetic views,"How does the new ViewBinding compare with the Kotlin Android Extensions with synthetic views bindings?
Apart from the NullSafety and TypeSafety provided by new ViewBindings, why should we consider ditching the Kotlin way of using synthetic bindings on Views?
Is the new ViewBinding more performant since it generates the Binding class beforehand?
",https://stackoverflow.com/questions/58351239/viewbinding-vs-kotlin-android-extensions-with-synthetic-views,106,23005.0,4.0,,,2019-10-12 05:45:03,2021-09-17 09:56:45,2021-01-06 13:03:23,,,android;kotlin;kotlin-android-extensions;android-viewbinding,Rinav,2557,1336154,registered,true,58465306,,CC BY-SA 4.0,,547,347,0,2,0,4,true,false,false,true,true,true,61,8,false,0.174,0.0046,2597,2019,10,5,Saturday,true,false,false,false,false,false,false
56778106,FragmentPagerAdapter deprecated,"Since API 27 FragmentPagerAdapter is deprecated. What's the best alternative to use for this?
In my case, I understand something like super(fragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) would need to be used, but I don't know where within my code this needs to go.
I got these imports in my class:
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
but FragmentPagerAdapter in class MyViewPagerAdapter(manager: FragmentManager) : FragmentPagerAdapter(manager){ is crossed out.
class MyViewPagerAdapter(manager: FragmentManager) : FragmentPagerAdapter(manager){
private val fragmentList : MutableList<androidx.fragment.app.Fragment> = ArrayList()
private val titleList : MutableList<String> = ArrayList()
override fun getItem(position: Int): androidx.fragment.app.Fragment {
return fragmentList[position]
}
override fun getCount(): Int {
return fragmentList.size
}
fun addFragment(fragment: androidx.fragment.app.Fragment, title: String){
fragmentList.add(fragment)
titleList.add(title)
}
override fun getPageTitle(position: Int): CharSequence? {
return titleList[position]
}
}
",https://stackoverflow.com/questions/56778106/fragmentpageradapter-deprecated,106,95002.0,7.0,,,2019-06-26 17:20:23,2022-10-19 20:42:15,2020-03-20 23:08:09,,,android;kotlin;android-viewpager;fragmentmanager;fragmentpageradapter,wbk727,8488,3293579,registered,true,56778143,,CC BY-SA 4.0,,1426,1298,6,0,0,5,true,false,false,true,true,true,31,2,false,0.074,0.0011,2705,2019,6,17,Wednesday,false,false,false,false,false,false,false
63649694,A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptExecution > java.lang.reflect.InvocationTargetException (no error message),"Android studio gave the error:
Execution failed for task ':app:kaptDebugKotlin'.
> A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptExecution
> java.lang.reflect.InvocationTargetException (no error message)
I want to add in my project Kotlin Coroutines and use it with Room database. But after added all libraries I got this error. This is all information from the compiler.
I have identified, This is because of the annotation @Database. If I removed this annotation, the error don't appear, but Room is not working too.
My gradle file:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
//apply plugin: 'androidx.navigation.safeargs'
kotlin {
experimental {
coroutines 'enable'
}
}
android {
compileSdkVersion 29
defaultConfig {
applicationId "com.bestcred.coursetthree"
minSdkVersion 21
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
//vectorDrawables.useSupportLibrary = true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
// Enables data binding.
buildFeatures {
dataBinding true
}
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
// Support libraries
implementation "androidx.appcompat:appcompat:1.2.0"
implementation 'com.google.android.material:material:1.2.0'
implementation "androidx.fragment:fragment:1.2.5"
implementation "androidx.constraintlayout:constraintlayout:2.0.0"
// Android KTX
implementation 'androidx.core:core-ktx:1.3.1'
// Room and Lifecycle dependencies
implementation "androidx.room:room-runtime:$room_version"
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
kapt "android.arch.persistence.room:compiler:$room_version"
// Kotlin Extensions and Coroutines support for Room
implementation "androidx.room:room-ktx:$room_version"
// Coroutines
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutine_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutine_version"
}
kotlin_version = "1.4.0"
room_version = "2.2.5"
coroutine_version = '1.3.9'
I update Room version and add Kotlin Coroutines. What's problem?![]()
",https://stackoverflow.com/questions/63649694/a-failure-occurred-while-executing-org-jetbrains-kotlin-gradle-internal-kaptexec,105,88607.0,26.0,,,2020-08-29 17:07:00,2024-05-24 04:04:21,,,,android;kotlin;android-room;kotlin-coroutines,Alex,1750,1574259,registered,true,63649695,,CC BY-SA 4.0,,2914,2688,2,1,1,4,true,false,false,true,true,false,153,11,false,0.293,0.0012,2275,2020,8,17,Saturday,true,false,false,false,false,false,false
34588117,How can I convert a part of Java source file to Kotlin?,"In my Kotlin project, I have some parts of Java code that I want to convert to Kotlin. The menu item that converts the Java file to Kotlin is disabled because it's not a whole file I want to convert.
How can I convert Java code to Kotlin?
",https://stackoverflow.com/questions/34588117/how-can-i-convert-a-part-of-java-source-file-to-kotlin,105,171912.0,15.0,,,2016-01-04 09:33:08,2021-06-11 17:54:47,2021-06-11 16:47:13,,,java;android;android-studio;kotlin,Alan Coromano,26194,1708058,registered,true,34588153,,CC BY-SA 4.0,,253,239,0,0,0,4,true,false,false,true,true,true,55,12,true,0.087,0.0006,3974,2016,1,9,Monday,false,false,false,true,false,false,false
50594507,Cannot find symbol DataBindingComponent on Android Studio 3.2 Canary 16 Kotlin project,"I just created a new project on Android Studio 3.2 Canary 16 with Kotlin enabled. Then I also enabled data binding, but I'm getting an error saying that it could not find the DataBindingComponent class.
Here's my project gradle:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = '1.2.41'
ext.android_plugin_version = '3.2.0-alpha10'
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.2.0-alpha16'
classpath ""org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version""
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
My module gradle file:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 27
defaultConfig {
applicationId ""net.julianonunes.myapp""
minSdkVersion 22
targetSdkVersion 27
versionCode 1
versionName ""1.0""
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
dataBinding {
enabled = true
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation""org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version""
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support.constraint:constraint-layout:1.1.0'
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
implementation 'com.android.support:design:27.1.1'
kapt ""com.android.databinding:compiler:3.1.2""
}
My activity's xml:
<?xml version=""1.0"" encoding=""utf-8""?>
<layout xmlns:android=""http://schemas.android.com/apk/res/android""
xmlns:app=""http://schemas.android.com/apk/res-auto""
xmlns:tools=""http://schemas.android.com/tools"">
<data>
<variable
name=""data""
type=""net.julianonunes.myapp.RegisterData"" />
</data>
....
</layout>
And here's the build output:
Executing tasks: [clean, :app:assembleDebug]
Configuration on demand is an incubating feature.
> Configure project :app
app: 'annotationProcessor' dependencies won't be recognized as kapt annotation processors. Please change the configuration name to 'kapt' for these artifacts: 'androidx.databinding:databinding-compiler:3.2.0-alpha16'.
> Task :clean
> Task :app:clean
> Task :app:preBuild UP-TO-DATE
> Task :app:preDebugBuild
> Task :app:compileDebugAidl NO-SOURCE
> Task :app:compileDebugRenderscript
> Task :app:checkDebugManifest
> Task :app:generateDebugBuildConfig
> Task :app:prepareLintJar UP-TO-DATE
> Task :app:mainApkListPersistenceDebug
> Task :app:generateDebugResValues
> Task :app:generateDebugResources
> Task :app:mergeDebugResources
> Task :app:createDebugCompatibleScreenManifests
> Task :app:processDebugManifest
> Task :app:splitsDiscoveryTaskDebug
> Task :app:processDebugResources
> Task :app:generateDebugSources
> Task :app:dataBindingExportBuildInfoDebug
> Task :app:transformDataBindingBaseClassLogWithDataBindingMergeGenClassesForDebug
> Task :app:transformDataBindingWithDataBindingMergeArtifactsForDebug
> Task :app:dataBindingGenBaseClassesDebug
Download https://dl.google.com/dl/android/maven2/com/android/databinding/compiler/3.1.2/compiler-3.1.2.pom
Download https://dl.google.com/dl/android/maven2/com/android/databinding/compiler/3.1.2/compiler-3.1.2.jar
> Task :app:kaptGenerateStubsDebugKotlin
e: /home/juliano/Documents/Projetos/myapp/app/build/generated/data_binding_base_class_source_out/debug/dataBindingGenBaseClassesDebug/out/net/julianonunes/myapp/databinding/ActivityMainBinding.java:28: error: cannot find symbol
protected ActivityMainBinding(DataBindingComponent _bindingComponent, View _root,
^
symbol: class DataBindingComponent
location: class ActivityMainBinding
e: /home/juliano/Documents/Projetos/myapp/app/build/generated/data_binding_base_class_source_out/debug/dataBindingGenBaseClassesDebug/out/net/julianonunes/myapp/databinding/ActivityMainBinding.java:46: error: cannot find symbol
@Nullable ViewGroup root, boolean attachToRoot, @Nullable DataBindingComponent component) {
^
symbol: class DataBindingComponent
location: class ActivityMainBinding
e: /home/juliano/Documents/Projetos/myapp/app/build/generated/data_binding_base_class_source_out/debug/dataBindingGenBaseClassesDebug/out/net/julianonunes/myapp/databinding/ActivityMainBinding.java:57: error: cannot find symbol
@Nullable DataBindingComponent component) {
^
symbol: class DataBindingComponent
location: class ActivityMainBinding
e: /home/juliano/Documents/Projetos/myapp/app/build/generated/data_binding_base_class_source_out/debug/dataBindingGenBaseClassesDebug/out/net/julianonunes/myapp/databinding/ActivityMainBinding.java:68: error: cannot find symbol
@Nullable DataBindingComponent component) {
^
symbol: class DataBindingComponent
location: class ActivityMainBinding
e: [kapt] An exception occurred: java.lang.NullPointerException
at java.io.File.<init>(File.java:277)
at android.databinding.annotationprocessor.ProcessExpressions.onHandleStep(ProcessExpressions.java:77)
at android.databinding.annotationprocessor.ProcessDataBinding$ProcessingStep.runStep(ProcessDataBinding.java:203)
at android.databinding.annotationprocessor.ProcessDataBinding$ProcessingStep.access$000(ProcessDataBinding.java:188)
at android.databinding.annotationprocessor.ProcessDataBinding.doProcess(ProcessDataBinding.java:90)
at android.databinding.annotationprocessor.ProcessDataBinding.process(ProcessDataBinding.java:65)
at org.jetbrains.kotlin.kapt3.ProcessorWrapper.process(annotationProcessing.kt:131)
at com.sun.tools.javac.processing.JavacProcessingEnvironment.callProcessor(JavacProcessingEnvironment.java:794)
at com.sun.tools.javac.processing.JavacProcessingEnvironment.discoverAndRunProcs(JavacProcessingEnvironment.java:705)
at com.sun.tools.javac.processing.JavacProcessingEnvironment.access$1800(JavacProcessingEnvironment.java:91)
at com.sun.tools.javac.processing.JavacProcessingEnvironment$Round.run(JavacProcessingEnvironment.java:1035)
at com.sun.tools.javac.processing.JavacProcessingEnvironment.doProcessing(JavacProcessingEnvironment.java:1176)
at com.sun.tools.javac.main.JavaCompiler.processAnnotations(JavaCompiler.java:1170)
at com.sun.tools.javac.main.JavaCompiler.processAnnotations(JavaCompiler.java:1068)
at org.jetbrains.kotlin.kapt3.AnnotationProcessingKt.doAnnotationProcessing(annotationProcessing.kt:87)
at org.jetbrains.kotlin.kapt3.AnnotationProcessingKt.doAnnotationProcessing$default(annotationProcessing.kt:45)
at org.jetbrains.kotlin.kapt3.AbstractKapt3Extension.runAnnotationProcessing(Kapt3Extension.kt:257)
at org.jetbrains.kotlin.kapt3.AbstractKapt3Extension.analysisCompleted(Kapt3Extension.kt:212)
at org.jetbrains.kotlin.kapt3.ClasspathBasedKapt3Extension.analysisCompleted(Kapt3Extension.kt:95)
at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM$analyzeFilesWithJavaIntegration$2.invoke(TopDownAnalyzerFacadeForJVM.kt:97)
at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration(TopDownAna",https://stackoverflow.com/questions/50594507/cannot-find-symbol-databindingcomponent-on-android-studio-3-2-canary-16-kotlin-p,105,75379.0,35.0,,,2018-05-29 23:49:52,2024-10-13 19:36:47,2019-04-27 09:56:34,,,android;kotlin;android-databinding,juliano.net,8235,1184708,registered,true,50637143,,CC BY-SA 4.0,,11956,11811,4,0,0,3,true,false,false,true,true,true,86,12,false,0.464,0.0014,3098,2018,5,23,Tuesday,false,false,false,false,false,false,false
63719072,Jetpack Compose - Centering Text,"I am using Jetpack Compose to create a simple flash card.
The idea is that you click the flash card and it will give you the answer.
However, I am stuck on a basic problem.
Unfortunately... I could not even find the official documentation, so my learning style has been trusting the autocorrect system...
Anyway, I believe the issue is either with Box() or Text().
I have added a Align.CenterEnd for the Gravity of the box. However, this seems to be the only way for centering in terms for the box. On the other hand, Text() does not give any methods to do so (It has gravity but it doesnt seem to be changing anything)
A hand in the right direction would be amazing.
On a side note, I know this would be giving free answers. But how would I change the text of $question inside the on click. As I thought Composables refresh?... thus, should regenerate on the screen? maybe not?
Thanks!
val typography = MaterialTheme.typography
val context = ContextAmbient.current
var question = "How many Bananas should go in my Smoothie?"
Column(modifier = Modifier.padding(30.dp).then(Modifier.fillMaxWidth())
.then(Modifier.wrapContentSize(Alignment.Center))
.clickable(onClick = { Toast.makeText(context, "3 Bananas are needed!", Toast.LENGTH_LONG).show()} ) /*question = "3 Bananas required"*/
.clip(shape = RoundedCornerShape(16.dp))) {
Box(modifier = Modifier.preferredSize(350.dp)
.gravity(align = Alignment.CenterHorizontally)
.border(width = 4.dp, color = Gray, shape = RoundedCornerShape(16.dp)),
shape = RoundedCornerShape(2.dp),
backgroundColor = DarkGray,
gravity = Alignment.CenterEnd) {
Text("$question",
style = typography.h4,
)
}
}
",https://stackoverflow.com/questions/63719072/jetpack-compose-centering-text,105,141259.0,7.0,,,2020-09-03 07:46:24,2024-10-21 15:32:35,2022-12-01 16:21:13,,,android;kotlin;android-layout;android-jetpack-compose;android-compose-layout,PandaPlaysAll,1497,8904301,registered,true,63719588,,CC BY-SA 4.0,,2125,1911,1,1,1,5,true,false,false,true,true,true,32,5,false,0.05,0.0007,2270,2020,9,7,Thursday,false,false,false,false,false,false,false
71917856,'setHasOptionsMenu(Boolean): Unit' is deprecated. Deprecated in Java,"How do I declare a menu inside of Android fragment? The method that I had used previously is now deprecated.
Originally:
override fun onCreateView(...): View {
setHasOptionsMenu(true)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
this.menu = menu
inflater.inflate(R.menu.menu, this.menu)
}
",https://stackoverflow.com/questions/71917856/sethasoptionsmenuboolean-unit-is-deprecated-deprecated-in-java,105,51561.0,10.0,,,2022-04-18 22:56:10,2023-07-25 07:59:56,,,,android;kotlin;menu;fragment;android-inflate,SUR4IDE,1253,14695587,registered,true,71965674,,CC BY-SA 4.0,,567,406,2,0,0,5,true,false,false,true,true,false,76,7,false,0.194,0.002,1678,2022,4,22,Monday,false,false,false,false,false,false,false
44950401,Not able to "findViewById" in Kotlin. Getting error "Type inference failed","I am getting the following error when I try to find a RecycleView by id.
Error:-
Type inference failed: Not enough information to infer parameter T
Code:
class FirstRecycleViewExample : AppCompatActivity() {
val data = arrayListOf<String>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.first_recycleview)
val recycler_view = findViewById(R.id.recycler_view) as RecyclerView ///IN THIS LINE I AM GETTING THE ERROR
data.add(""First Data"")
data.add(""Second Data"")
data.add(""Third Data"")
data.add(""Forth Data"")
data.add(""Fifth Data"")
//creating our adapter
val adapter = CustomRecycleAdapter(data)
//now adding the adapter to recyclerview
recycler_view.adapter = adapter
}
}
",https://stackoverflow.com/questions/44950401/not-able-to-findviewbyid-in-kotlin-getting-error-type-inference-failed,105,110969.0,10.0,,,2017-07-06 13:30:19,2025-04-06 10:28:09,2017-08-10 10:18:02,,,android;android-layout;kotlin;type-inference,Ravindra Kushwaha,8060,3946958,registered,true,44950478,,CC BY-SA 3.0,2018-05-10 05:50:52,1111,869,2,1,1,4,true,false,false,true,true,true,95,11,false,0.09,0.0009,3425,2017,7,13,Thursday,false,false,false,false,false,false,false
33640864,How to sort based on/compare multiple values in Kotlin?,"Say I have a class Foo(val a: String, val b: Int, val c: Date) and I want to sort a list of Foos based on all three properties. How would I go about this?
",https://stackoverflow.com/questions/33640864/how-to-sort-based-on-compare-multiple-values-in-kotlin,105,43361.0,3.0,,,2015-11-10 22:27:46,2020-12-12 17:27:02,,,,comparable;kotlin,Kirill Rakhman,44151,615306,registered,true,33640865,,CC BY-SA 3.0,,188,155,2,0,0,2,true,false,false,true,true,false,55,9,true,0.069,0.0024,4029,2015,11,22,Tuesday,false,false,false,false,false,false,false
36826004,How do you display a Toast using Kotlin on Android?,"In different Kotlin examples for Android I see toast("Some message...") or toastLong("Some long message"). For example:
view.setOnClickListener { toast("Click") }
As I understand, it is an Extension Function for Activity.
How and where do you define this toast() function so that you are able to use it throughout the project?
",https://stackoverflow.com/questions/36826004/how-do-you-display-a-toast-using-kotlin-on-android,104,188437.0,19.0,,,2016-04-24 16:43:28,2024-12-12 19:52:53,2020-07-17 23:05:25,,,android;kotlin,Andrew,38335,2079831,registered,true,36826336,,CC BY-SA 4.0,,455,358,5,0,0,2,true,false,false,true,true,true,51,10,true,0.101,0.0006,3863,2016,4,16,Sunday,true,false,false,false,false,false,false
44536114,What's the difference between !! and ? in Kotlin?,"I am new to Kotlin. I want to know the difference between this two !! and ? in below code.
Below, there are two snippets: the first uses !! for mCurrentDataset and another having ? for same variable.
if(!mCurrentDataset!!.load(mDataSetString.get(mCurrentDataSelectionIndex), STORAGE_TYPE.STORAGE_APPRESOURCE))
{
Log.d(""MyActivity"",""Failed to load data."")
return false
}
if(!mCurrentDataset?.load(mDataSetString.get(mCurrentDataSelectionIndex), STORAGE_TYPE.STORAGE_APPRESOURCE)!!)
{
Log.d(""MyActivity"",""Failed to load data."")
return false
}
",https://stackoverflow.com/questions/44536114/whats-the-difference-between-and-in-kotlin,104,70356.0,6.0,,,2017-06-14 05:27:55,2020-01-19 15:34:29,2020-01-19 15:34:29,,,kotlin,paril,1980,7333260,registered,true,44536346,,CC BY-SA 4.0,,695,564,7,0,0,1,true,false,false,true,true,true,53,9,true,0.085,0.0015,3447,2017,6,5,Wednesday,false,false,false,false,false,false,false
45348820,Using return inside a lambda?,"In the code below, I want to show my empty views if trips is empty and then return and avoid running the below code, but the compiler says ""return is not allowed here"".
mainRepo.fetchUpcomingTrips { trips ->
if (trips.isEmpty()) {
showEmptyViews()
return
}
// run some code if it's not empty
}
Is there a way to return like that?
I know I can just put it in an if else block but I hate writing if else's, it's less understandable/readable in my opinion when there's a few more conditions.
",https://stackoverflow.com/questions/45348820/using-return-inside-a-lambda,104,57848.0,7.0,,,2017-07-27 10:57:56,2024-11-05 03:04:29,2017-10-25 14:13:12,,,lambda;kotlin,JozeRi,3469,3403069,registered,true,45348930,,CC BY-SA 3.0,,570,525,1,0,0,2,true,false,false,true,true,true,29,5,true,0.121,0.0018,3404,2017,7,10,Thursday,false,false,false,false,false,false,false
58773453,Kotlin Flow vs Android LiveData,"I have some questions about Kotlin Flow
- I can observe
LiveData from multiple Fragments. Can I do this with Flow? If yes then how?
- We can have multiple
LiveData from a single LiveData using map& switchMap. Is there any way to have multiple Flow from a single source Flow?
- Using
MutableLiveData I can update data from anywhere using the variable reference. Is there any way to do the same with Flow?
I have a use-case like: I will observe a SharedPreferences using callbackFlow{...} which will give me a single source Flow. From that Flow, I want to create multiple Flow for each key-value pair.
These might sound silly questions. I am new to Rx and Flow world.
",https://stackoverflow.com/questions/58773453/kotlin-flow-vs-android-livedata,104,60196.0,5.0,,,2019-11-08 20:37:27,2024-04-12 22:49:46,2021-03-01 16:24:16,,,android;kotlin;android-livedata;kotlin-coroutines;kotlin-flow,zoha131,1898,6307259,registered,true,58775840,,CC BY-SA 4.0,2023-11-21 07:33:49,896,666,12,0,0,5,true,false,false,true,true,true,31,5,false,0.083,0.0017,2570,2019,11,20,Friday,false,false,false,false,false,false,false
29268526,How to overcome "same JVM signature" error when implementing a Java interface?,"With the code below, I am getting the following error in IntelliJ IDEA 13.1.6 and Kotlin plugin 0.11.91.AndroidStudio.3:
Platform declaration clash: The following declarations have the same JVM signature (getName()Ljava/lang/String;):
• public open fun getName(): kotlin.String?
• internal final fun <get-name>(): kotlin.String?
Java class, JavaInterface.java:
public interface JavaInterface {
public String getName();
}
Kotlin class, KotlinClass.kt
public class KotlinClass(val name: String?) : JavaInterface
I've tried overriding the 'getter' method by
adding override fun getName(): String? = name, but that produces the same error.
I can see one workaround by doing this instead:
public class KotlinClass(val namePrivate: String?) : JavaInterface {
override fun getName(): String? = namePrivate
}
But in my real-world case I have a number of properties to implement and need setters too. Doing this for each property doesn't seem very Kotlin-ish. What am I missing?
",https://stackoverflow.com/questions/29268526/how-to-overcome-same-jvm-signature-error-when-implementing-a-java-interface,103,71229.0,10.0,,,2015-03-25 23:33:55,2023-05-27 10:19:10,,,,kotlin,Michael Rush,4429,57624,registered,true,44719646,,CC BY-SA 3.0,,1174,997,7,0,0,1,true,false,false,true,true,false,88,12,true,0.14,0.0014,4259,2015,3,23,Wednesday,false,false,false,false,false,false,false
44784328,How to obtain all subclasses of a given sealed class?,"Recently we upgraded one of our enum class to sealed class with objects as sub-classes so we can make another tier of abstraction to simplify code. However we can no longer get all possible subclasses through Enum.values() function, which is bad because we heavily rely on that functionality. Is there a way to retrieve such information with reflection or any other tool?
PS: Adding them to a array manually is unacceptable. There are currently 45 of them, and there are plans to add more.
This is how our sealed class looks like:
sealed class State
object StateA: State()
object StateB: State()
object StateC: State()
....// 42 more
If there is an values collection, it will be in this shape:
val VALUES = setOf(StateA, StateB, StateC, StateC, StateD, StateE,
StateF, StateG, StateH, StateI, StateJ, StateK, StateL, ......
Naturally no one wants to maintain such a monster.
",https://stackoverflow.com/questions/44784328/how-to-obtain-all-subclasses-of-a-given-sealed-class,103,60696.0,8.0,,,2017-06-27 15:32:03,2023-09-01 11:37:30,2017-06-28 01:29:28,,,kotlin,glee8e,6508,5818889,registered,true,44789360,,CC BY-SA 3.0,,1018,892,3,0,0,1,true,false,false,true,true,true,53,10,true,0.132,0.0017,3434,2017,6,15,Tuesday,false,false,false,false,false,false,false
49969319,Kotlin: Difference between constant in companion object and top level,"The general pattern to create constants in Kotlin seems to be using companion objects. However, I can also define a constant at the file level. Why is that not so popular? Am I missing something?
With companion object:
class Example {
companion object {
const val CONSTANT = ""something""
}
On top level:
const val CONSTANT = ""something""
class Example {
}
",https://stackoverflow.com/questions/49969319/kotlin-difference-between-constant-in-companion-object-and-top-level,103,31513.0,4.0,,,2018-04-22 18:25:45,2022-01-15 15:19:24,,,,kotlin,Martin Tarjányi,10147,6051176,registered,true,49977253,,CC BY-SA 3.0,,442,373,2,0,0,1,true,false,false,true,true,false,69,10,false,0.127,0.0033,3135,2018,4,18,Sunday,true,false,false,false,false,false,false
45753733,ext in buildscript can not be recognised by Gradle Kotlin DSL,"In these days, I am trying to write some codes to experience the Spring reactive features and kotlin extension in Spring 5, and I also prepared a gradle Kotlin DSL build.gradle.kt to configure the gradle build.
The build.gradle.kt is converted from Spring Boot template codes generated by http://start.spring.io.
But the ext in the buildscript can not be detected by Gradle.
buildscript {
ext { }
}
The ext will cause Gradle build error.
To make the variables in classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion") and compile("org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlinVersion") work, I added the variables in the hard way.
val kotlinVersion = "1.1.4"
val springBootVersion = "2.0.0.M3"
But I have to declare them in global top location and duplicate them in the buildscript.
Code: https://github.com/hantsy/spring-reactive-sample/blob/master/kotlin-gradle/build.gradle.kts
Is there a graceful approach to make ext work?
Update: There are some ugly approaches:
From Gradle Kotlin DSL example, https://github.com/gradle/kotlin-dsl/tree/master/samples/project-properties, declares the properties in gradel.properties.
kotlinVersion = 1.1.4
springBootVersion = 2.0.0.M3
And use it in build.gradle.kts.
buildScript{
val kotlinVersion by project
}
val kotlinVersion by project //another declare out of buildscript block.
Similar with above declare them in buildScript block:
buildScript{
extra["kotlinVersion"] = "1.1.4"
extra["springBootVersion"] = "2.0.0.M3"
val kotlinVersion: String by extra
}
val kotlinVersion: String by extra//another declare out of buildscript block.
How can I avoid the duplication of val kotlinVersion: String by extra?
Update(2023-7-5): The latest Gradle supports libs.versions.toml file to declare dependency versions in a central place, it is also can be recognized by GitHub dependabot. see: https://docs.gradle.org/current/userguide/platforms.html
",https://stackoverflow.com/questions/45753733/ext-in-buildscript-can-not-be-recognised-by-gradle-kotlin-dsl,102,65008.0,13.0,,,2017-08-18 09:53:20,2025-03-05 07:00:03,2023-07-05 02:36:52,,,gradle;kotlin;build.gradle;gradle-kotlin-dsl,Hantsy,9768,893898,registered,true,,,CC BY-SA 4.0,,2804,2019,14,4,0,4,false,false,false,true,true,true,61,11,false,0.2,0.0016,3382,2017,8,9,Friday,false,false,false,false,false,false,false
29424944,RecyclerView itemClickListener in Kotlin,"I'm writing my first app in Kotlin after 3 years of experience with Android.
Just confused as to how to utilize itemClickListener with a RecyclerView in Kotlin.
I have tried the trait (edit: now interface) approach, very Java-like
public class MainActivity : ActionBarActivity() {
protected override fun onCreate(savedInstanceState: Bundle?) {
// set content view etc go above this line
class itemClickListener : ItemClickListener {
override fun onItemClick(view: View, position: Int) {
Toast.makeText(this@MainActivity, ""TEST: "" + position, Toast.LENGTH_SHORT).show()
}
}
val adapter = DrawerAdapter(itemClickListener())
mRecyclerView.setAdapter(adapter)
}
trait ItemClickListener {
fun onItemClick(view: View, position: Int)
}
}
That seemed very redundant so I tried the inner class approach:
inner class ItemClickListener {
fun onItemClick(view: View, position: Int) {
startActivityFromFragmentForResult<SelectExerciseActivity>(SELECT_EXERCISES)
}
}
And then just setting the adapter's click listener like this:
val adapter = WorkoutsAdapter(ItemClickListener())
But I'm still not satisfied with this because I think there might be a better, cleaner way. I'm trying to essentially achieve something like this:
RecyclerView onClick
Any suggestions?
Ended up going with a variation of the approved answer
Defined the function in the activity:
val itemOnClick: (View, Int, Int) -> Unit = { view, position, type ->
Log.d(TAG, ""test"")
}
Passed the function itself on to the adapter like this:
class ExercisesAdapter(val itemClickListener: (View, Int, Int) -> Unit) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
// other stuff up here
val vhExercise = ExerciseVH(view) // view holder
// on to the view holder through the extension function
vhExercise.onClick(itemClickListener)
}
}
Extension function by Loop in the approved answer below.
fun <T : RecyclerView.ViewHolder> T.onClick(event: (view: View, position: Int, type: Int) -> Unit): T {
itemView.setOnClickListener {
event.invoke(it, getAdapterPosition(), getItemViewType())
}
return this
}
",https://stackoverflow.com/questions/29424944/recyclerview-itemclicklistener-in-kotlin,101,185624.0,23.0,,,2015-04-03 01:19:33,2022-12-27 18:48:37,2018-02-06 16:23:36,,,android;android-recyclerview;kotlin,AfzalivE,2603,507142,registered,true,56668693,,CC BY-SA 3.0,,2652,2323,6,1,0,3,true,false,false,true,true,true,40,4,false,0.124,0.0005,4250,2015,4,1,Friday,false,false,false,false,false,false,false
32684739,Kotlin get type as string,"I can't find how to get the type of a variable (or constant) as String, like typeof(variable), with Kotlin language. How to accomplish this?
",https://stackoverflow.com/questions/32684739/kotlin-get-type-as-string,101,79801.0,4.0,,,2015-09-20 21:58:53,2021-10-20 20:22:52,2015-09-21 09:45:11,,,java;kotlin,Alex Facciorusso,2458,2329437,registered,true,32718623,,CC BY-SA 3.0,,174,141,2,0,0,2,true,false,false,true,true,true,25,5,false,0.05,0.0013,4080,2015,9,21,Sunday,true,false,false,true,false,false,false
42081563,Idiomatic way to transform map in kotlin?,"In Scala, it's just the map function. For example, if hashMap is a hashMap of strings, then you can do the following:
val result : HashMap[String,String] = hashMap.map(case(k,v) => (k -> v.toUpperCase))
In Kotlin, however, map turns the map into a list. Is there an idiomatic way of doing the same thing in Kotlin?
",https://stackoverflow.com/questions/42081563/idiomatic-way-to-transform-map-in-kotlin,100,74412.0,4.0,,,2017-02-07 04:08:35,2021-07-02 21:58:08,,,,hashmap;kotlin,U Avalos,6898,555493,registered,true,,,CC BY-SA 3.0,,388,324,3,0,0,2,false,false,false,true,true,false,41,7,true,0.054,0.0013,3574,2017,2,4,Tuesday,false,false,false,false,false,false,false
51834996,Singleton class in Kotlin,"I want to know how to create a singleton class in Kotlin, so that my Util class instantiates it only once per app execution. However, when I converted my Java class to kotlin, the code below was generated.
Is this correct?
companion object {
private var utilProject: UtilProject? = null
val instance: UtilProject
get() {
if (utilProject == null) utilProject = UtilProject()
return utilProject!!
}
}
I could find a related question, but it is with parameters, and I am not getting it convert without params.
",https://stackoverflow.com/questions/51834996/singleton-class-in-kotlin,100,127219.0,10.0,,,2018-08-14 06:29:47,2022-10-13 11:39:19,2020-12-14 19:26:13,,,android;kotlin,Khemraj Sharma,59102,6891563,registered,true,51835156,,CC BY-SA 4.0,,696,558,1,1,0,2,true,false,false,true,true,true,25,4,false,0.079,0.0008,3021,2018,8,6,Tuesday,false,false,false,false,false,false,false
59039991,Difference between usage of Dispatcher IO and Default,"In this question: Kotlin Coroutines choosing Dispatcher
we can understand to use Dispatcher.Default on CPU process, like an image/video conversion and Dispatcher.IO when writing/reading files or API connection.
But in the class Dispatcher.kt documentation, for the IOyou find this:
* This dispatcher shares threads with a [Default][Dispatchers.Default] dispatcher, so using
* `withContext(Dispatchers.IO) { ... }` does not lead to an actual switching to another thread —
* typically execution continues in the same thread.
So basically they run on the same thread anyway. There is a real difference or in the end it won't matter each one to use?
Thanks!
",https://stackoverflow.com/questions/59039991/difference-between-usage-of-dispatcher-io-and-default,100,55020.0,2.0,,,2019-11-25 20:58:13,2023-01-19 18:47:16,,,,kotlin;kotlin-coroutines,Canato,4118,3117650,registered,true,59040920,,CC BY-SA 4.0,,870,669,5,1,0,2,true,false,false,true,true,false,53,8,false,0.036,0.0018,2553,2019,11,20,Monday,false,false,false,false,false,false,false
44042754,Android Studio 3.0 - Unable to find method 'com.android.build.gradle.internal.variant.BaseVariantData.getOutputs()Ljava/util/List',"Trying to start a new Kotlin project with Android Studio 3.0 Canary 1 displays this error. Full trace:
Error:Unable to find method
'com.android.build.gradle.internal.variant.BaseVariantData.getOutputs()Ljava/util/List;'.
Possible causes for this unexpected error include:
- Gradle's
dependency cache may be corrupt (this sometimes occurs after a network
connection timeout.) Re-download dependencies
and sync project (requires network)
- The state of a Gradle
build process (daemon) may be corrupt. Stopping all Gradle daemons may
solve this problem. Stop Gradle build
processes (requires restart)
- Your project may be using a
third-party plugin which is not compatible with the other plugins in
the project or the version of Gradle requested by the
project.
In the case of corrupt Gradle processes, you can
also try closing the IDE and then killing all Java processes.
I've tried the first two options and the third-party plugins are left as default.
gradle-wrapper.properties
#Thu May 18 08:36:52 BST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.0-milestone-1-all.zip
build.gradle
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = '1.1.2-3'
repositories {
maven { url 'https://maven.google.com' }
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.0-alpha1'
classpath ""org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version""
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
maven { url 'https://maven.google.com' }
mavenCentral()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
I haven't touched any of these values myself, they're left as default. Creating a non-Kotlin new project does not have this problem.
",https://stackoverflow.com/questions/44042754/android-studio-3-0-unable-to-find-method-com-android-build-gradle-internal-va,100,20989.0,6.0,,,2017-05-18 08:41:26,2018-06-21 09:19:44,2017-05-30 09:31:14,,,android-studio;kotlin,Josh Laird,7294,4624156,registered,true,44043185,,CC BY-SA 3.0,,2318,2133,2,0,0,2,true,false,false,true,true,true,138,9,false,0.286,0.0048,3474,2017,5,8,Thursday,false,false,false,false,false,false,false
45877140,"Kotlin and idiomatic way to write, 'if not null, else...' based around mutable value","Suppose we have this code:
class QuickExample {
fun function(argument: SomeOtherClass) {
if (argument.mutableProperty != null ) {
doSomething(argument.mutableProperty)
} else {
doOtherThing()
}
}
fun doSomething(argument: Object) {}
fun doOtherThing() {}
}
class SomeOtherClass {
var mutableProperty: Object? = null
}
Unlike in Java, where you could be left alone to worry about null dereferencing at runtime, this doesn't compile - quite rightly. Of course, mutableProperty may no longer be null once within the 'if'.
My question is what's the best way to handle this?
A few options are apparent. Without using any new Kotlin language features, the simplest way is obviously to copy the value to a method-scope one that won't subsequently change.
There's this:
fun function(argument: SomeOtherClass) {
argument.mutableProperty?.let {
doSomething(it)
return
}
doOtherThing()
}
This has the obvious disadvantage that you need to return early or otherwise avoid executing the subsequent code - OK in certain, small contexts, but has a smell to it.
Then there's this possibility:
fun function(argument: SomeOtherClass) {
argument.mutableProperty.let {
when {
it != null -> {
doSomething(it)
}
else -> {
doOtherThing()
}
}
}
}
but whilst it has greater clarity of purpose, arguably it's more unwieldy and verbose than the Java-style way of dealing with this.
Am I missing anything, and is there a preferred idiom with which to achieve this?
",https://stackoverflow.com/questions/45877140/kotlin-and-idiomatic-way-to-write-if-not-null-else-based-around-mutable-v,100,138718.0,8.0,,,2017-08-25 08:17:35,2021-10-09 09:38:30,,,,android;kotlin;idioms,Rob Pridham,4998,635075,registered,true,45877344,,CC BY-SA 3.0,,1809,1661,4,0,0,3,true,false,false,true,true,false,92,14,false,0.058,0.0007,3375,2017,8,8,Friday,false,false,false,false,false,false,false
64984549,Android Studio stuck at "Analyzing...","In my Android project (Android 4.2 Canary 15), completion does not work anymore, and neither does syntax highlighting. This is happening in one Android project only (the others work well).
![]()
I have tried to clean, rebuild the project, create a new project and import files, but no changes... I have tried to delete .idea directory and all .iml files, but not better...
In the "File" menu, I've just tried the option "Invalidate caches / restart" and now all classes in my project are blocked at the state "Analyzing..." and completion still does not work...
![]()
Build and run project work, and my application starts well on my phone, but all intellij features
are inactive.
",https://stackoverflow.com/questions/64984549/android-studio-stuck-at-analyzing,100,34452.0,19.0,,,2020-11-24 10:28:42,2026-01-08 14:59:39,2021-09-22 15:01:06,,,android-studio;kotlin,Matheo26,996,1386697,registered,true,,,CC BY-SA 4.0,2021-10-14 21:44:46,900,700,0,0,2,2,false,false,false,true,true,true,48,5,false,0.551,0.0029,2188,2020,11,10,Tuesday,false,false,false,false,false,false,false
7940765,How to hide the soft keyboard inside a fragment?,"I have a FragmentActivity using a ViewPager to serve several fragments. Each is a ListFragment with the following layout:
<?xml version=""1.0"" encoding=""utf-8""?>
<LinearLayout
xmlns:android=""http://schemas.android.com/apk/res/android""
android:layout_width=""fill_parent""
android:layout_height=""fill_parent"">
<LinearLayout
android:orientation=""vertical""
android:layout_width=""match_parent""
android:layout_height=""match_parent""
android:padding=""8dp"">
<ListView android:id=""@id/android:list""
android:layout_width=""fill_parent""
android:layout_height=""fill_parent"" />
<EditText android:id=""@+id/entertext""
android:layout_width=""fill_parent""
android:layout_height=""wrap_content"" />
</LinearLayout>
</LinearLayout>
When starting the activity, the soft keyboard shows. To remedy this, I did the following inside the fragment:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Save the container view so we can access the window token
viewContainer = container;
//get the input method manager service
imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
. . .
}
@Override
public void onStart() {
super.onStart();
//Hide the soft keyboard
imm.hideSoftInputFromWindow(viewContainer.getWindowToken(), 0);
}
I save the incoming ViewGroup container parameter from onCreateView as a way to access the window token for the main activity. This runs without error, but the keyboard doesn't get hidden from the call to hideSoftInputFromWindow in onStart.
Originally, I tried using the inflated layout instead of container, i.e:
imm.hideSoftInputFromWindow(myInflatedLayout.getWindowToken(), 0);
but this threw a NullPointerException, presumably because the fragment itself isn't an activity and doesn't have a unique window token?
Is there a way to hide the soft keyboard from within a fragment, or should I create a method in the FragmentActivity and call it from within the fragment?
",https://stackoverflow.com/questions/7940765/how-to-hide-the-soft-keyboard-inside-a-fragment,99,120908.0,19.0,,,2011-10-29 18:18:10,2022-06-06 07:15:05,2021-10-11 10:10:25,,,java;android;kotlin;android-fragments;android-softkeyboard,WilHall,12124,586606,registered,true,9981958,,CC BY-SA 4.0,,2410,2166,13,0,0,5,true,false,false,true,true,true,48,9,true,0.157,0.0008,5502,2011,10,18,Saturday,true,false,false,true,false,false,false
53532406,activeNetworkInfo.type is deprecated in API level 28,"
I want to use the Connectivity manager which provide the method activeNetworkInfo.type for checking the type of network in Android. This method was deprecated in API level 28. so what is the solution to check network type in API 28. my code is :
/**
* Check Wi Fi connectivity
*/
fun isWiFiConnected(context: Context): Boolean {
val connManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
return connManager.activeNetworkInfo.type == ConnectivityManager.TYPE_WIFI
}
My Gradle is like :
compileSdkVersion 28
buildToolsVersion '28.0.3'
defaultConfig {
minSdkVersion 21
targetSdkVersion 28
}
",https://stackoverflow.com/questions/53532406/activenetworkinfo-type-is-deprecated-in-api-level-28,99,57930.0,19.0,,,2018-11-29 05:27:48,2025-04-01 09:32:58,2019-12-03 08:28:47,,,android;kotlin;deprecated;android-connectivitymanager,Pitty,2007,5316836,registered,true,53532456,,CC BY-SA 4.0,,863,660,2,1,1,4,true,false,false,true,true,true,52,7,false,0.328,0.0017,2914,2018,11,5,Thursday,false,false,false,false,false,false,false
54416840,Kotlin: Coroutines scope vs Coroutine context,"Can anyone explain the difference between them? I think scope provides a reference(e.g. Job) to cancel them and context provides a reference to underlying thread. Is that so?
",https://stackoverflow.com/questions/54416840/kotlin-coroutines-scope-vs-coroutine-context,99,34878.0,3.0,,,2019-01-29 08:37:02,2023-10-23 20:57:18,2019-03-18 11:00:03,,,kotlin;kotlin-coroutines,Jose,2789,4936616,registered,true,,,CC BY-SA 4.0,,182,175,0,0,0,2,false,false,false,true,true,true,45,6,false,0.086,0.0028,2853,2019,1,8,Tuesday,false,false,false,false,false,false,false
46131289,Kotlin: What is the difference between Apply and Also,"What is the difference between apply and also. From what I know the following code does the same thing:
apply
val person = Person().apply {
name = ""Tony Stark""
age = 52
// More such stuff
}
also
val person = Person().also {
it.name = ""Tony Stark""
it.age = 52
// More such stuff
}
Is there any difference and should I use one over the other? Also, are there some cases where one would work and the other won't?
",https://stackoverflow.com/questions/46131289/kotlin-what-is-the-difference-between-apply-and-also,99,34473.0,3.0,,,2017-09-09 13:36:56,2023-10-18 10:13:45,,,,kotlin,Kanaiya Katarmal,6168,1143026,registered,true,46132223,,CC BY-SA 3.0,,545,435,2,0,0,1,true,false,false,true,true,false,53,9,false,0.087,0.0029,3360,2017,9,13,Saturday,true,false,false,false,false,false,false
35919849,Android N Java 8 features (Jack compiler) and Kotlin interop,"Update 3.
KOTLIN IS NOW OFFICIALLY SUPPORTED FOR ANDROID DEVELOPMENT. BY GOOGLE. YAAAAAAAAS!
Update 2: It looks like JetBrains is really committed to supporting Kotlin for Android in the long run. I'm a happy kotlin user :).
Update: Hadi Hariri, from JetBrains, mentioned they're going to release some info on this topic. I will update this post once they do.
=== DEPRECATED STUFF NEXT ===
Google just released a preview for the upcoming Android N with some interesting features, the most notable being partial Java 8 language support. This is possible due to the new Jack toolchain Google is working on.
The current toolchain using javac or kotlinc:
javac (.java --> .class) --> dx (.class --> .dex)
kotlinc (.kt --> .class) --> dx (.class --> .dex)
New Jack toolchain:
Jack (.java --> .jack --> .dex)
I am assuming Google will push forward towards making Jack the default toolchain for Android development.
Update: Jack is now deprecated. Yas.
My question is how will this new toolchain affect me, in the future, as a kotlin user for Android development? Will I get ""stuck in the past""?
",https://stackoverflow.com/questions/35919849/android-n-java-8-features-jack-compiler-and-kotlin-interop,99,9080.0,8.0,,,2016-03-10 14:52:28,2018-10-02 16:25:08,2017-05-24 10:34:52,,,java;android;kotlin;android-jack-and-jill,Tudor Luca,6449,1392423,registered,true,,,CC BY-SA 3.0,,2100,1102,11,6,0,4,false,false,false,true,true,true,60,10,false,0.881,0.0109,3908,2016,3,14,Thursday,false,false,false,true,false,false,false
6994518,how to delete the content of text file without deleting itself,"I want to copy the content of file 'A' to file 'B'.
after the copying is done I want to clear the content of file 'A' and want to write on it from its beginning.
I can't delete file 'A' as it is related to some other task.
I was able to copy the content using java's file API(readLine() ), but don't know how to clear the content of file and set the file pointer to the beginning of the file.
",https://stackoverflow.com/questions/6994518/how-to-delete-the-content-of-text-file-without-deleting-itself,98,315497.0,17.0,,,2011-08-09 10:07:55,2023-03-14 19:26:29,2023-03-14 19:26:29,,,java;android;kotlin,brig,3803,651545,registered,true,6994664,,CC BY-SA 4.0,,408,394,0,0,0,3,true,false,false,true,true,true,62,11,false,0.054,0.0003,5583,2011,8,10,Tuesday,false,false,false,true,false,false,false
69044514,material-1.5.0-alpha03\res\values-v31\values-v31.xml:3:5-94: AAPT: error: resource android:color/system_neutral1_1000 not found,"<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="m3_ref_palette_dynamic_neutral0">@android:color/system_neutral1_1000</color>
<color name="m3_ref_palette_dynamic_neutral10">@android:color/system_neutral1_900</color>
<color name="m3_ref_palette_dynamic_neutral100">@android:color/system_neutral1_0</color>
<color name="m3_ref_palette_dynamic_neutral20">@android:color/system_neutral1_800</color>
<color name="m3_ref_palette_dynamic_neutral30">@android:color/system_neutral1_700</color>
<color name="m3_ref_palette_dynamic_neutral40">@android:color/system_neutral1_600</color>
<color name="m3_ref_palette_dynamic_neutral50">@android:color/system_neutral1_500</color>
<color name="m3_ref_palette_dynamic_neutral60">@android:color/system_neutral1_400</color>
<color name="m3_ref_palette_dynamic_neutral70">@android:color/system_neutral1_300</color>
<color name="m3_ref_palette_dynamic_neutral80">@android:color/system_neutral1_200</color>
<color name="m3_ref_palette_dynamic_neutral90">@android:color/system_neutral1_100</color>
<color name="m3_ref_palette_dynamic_neutral95">@android:color/system_neutral1_50</color>
<color name="m3_ref_palette_dynamic_neutral99">@android:color/system_neutral1_10</color>
<color name="m3_ref_palette_dynamic_neutral_variant0">@android:color/system_neutral2_1000</color>
<color name="m3_ref_palette_dynamic_neutral_variant10">@android:color/system_neutral2_900</color>
<color name="m3_ref_palette_dynamic_neutral_variant100">@android:color/system_neutral2_0</color>
<color name="m3_ref_palette_dynamic_neutral_variant20">@android:color/system_neutral2_800</color>
<color name="m3_ref_palette_dynamic_neutral_variant30">@android:color/system_neutral2_700</color>
<color name="m3_ref_palette_dynamic_neutral_variant40">@android:color/system_neutral2_600</color>
<color name="m3_ref_palette_dynamic_neutral_variant50">@android:color/system_neutral2_500</color>
<color name="m3_ref_palette_dynamic_neutral_variant60">@android:color/system_neutral2_400</color>
<color name="m3_ref_palette_dynamic_neutral_variant70">@android:color/system_neutral2_300</color>
<color name="m3_ref_palette_dynamic_neutral_variant80">@android:color/system_neutral2_200</color>
<color name="m3_ref_palette_dynamic_neutral_variant90">@android:color/system_neutral2_100</color>
<color name="m3_ref_palette_dynamic_neutral_variant95">@android:color/system_neutral2_50</color>
<color name="m3_ref_palette_dynamic_neutral_variant99">@android:color/system_neutral2_10</color>
<color name="m3_ref_palette_dynamic_primary0">@android:color/system_accent1_1000</color>
<color name="m3_ref_palette_dynamic_primary10">@android:color/system_accent1_900</color>
<color name="m3_ref_palette_dynamic_primary100">@android:color/system_accent1_0</color>
<color name="m3_ref_palette_dynamic_primary20">@android:color/system_accent1_800</color>
<color name="m3_ref_palette_dynamic_primary30">@android:color/system_accent1_700</color>
<color name="m3_ref_palette_dynamic_primary40">@android:color/system_accent1_600</color>
<color name="m3_ref_palette_dynamic_primary50">@android:color/system_accent1_500</color>
<color name="m3_ref_palette_dynamic_primary60">@android:color/system_accent1_400</color>
<color name="m3_ref_palette_dynamic_primary70">@android:color/system_accent1_300</color>
<color name="m3_ref_palette_dynamic_primary80">@android:color/system_accent1_200</color>
<color name="m3_ref_palette_dynamic_primary90">@android:color/system_accent1_100</color>
<color name="m3_ref_palette_dynamic_primary95">@android:color/system_accent1_50</color>
<color name="m3_ref_palette_dynamic_primary99">@android:color/system_accent1_10</color>
<color name="m3_ref_palette_dynamic_secondary0">@android:color/system_accent2_1000</color>
<color name="m3_ref_palette_dynamic_secondary10">@android:color/system_accent2_900</color>
<color name="m3_ref_palette_dynamic_secondary100">@android:color/system_accent2_0</color>
<color name="m3_ref_palette_dynamic_secondary20">@android:color/system_accent2_800</color>
<color name="m3_ref_palette_dynamic_secondary30">@android:color/system_accent2_700</color>
<color name="m3_ref_palette_dynamic_secondary40">@android:color/system_accent2_600</color>
<color name="m3_ref_palette_dynamic_secondary50">@android:color/system_accent2_500</color>
<color name="m3_ref_palette_dynamic_secondary60">@android:color/system_accent2_400</color>
<color name="m3_ref_palette_dynamic_secondary70">@android:color/system_accent2_300</color>
<color name="m3_ref_palette_dynamic_secondary80">@android:color/system_accent2_200</color>
<color name="m3_ref_palette_dynamic_secondary90">@android:color/system_accent2_100</color>
<color name="m3_ref_palette_dynamic_secondary95">@android:color/system_accent2_50</color>
<color name="m3_ref_palette_dynamic_secondary99">@android:color/system_accent2_10</color>
<color name="m3_ref_palette_dynamic_tertiary0">@android:color/system_accent3_1000</color>
<color name="m3_ref_palette_dynamic_tertiary10">@android:color/system_accent3_900</color>
<color name="m3_ref_palette_dynamic_tertiary100">@android:color/system_accent3_0</color>
<color name="m3_ref_palette_dynamic_tertiary20">@android:color/system_accent3_800</color>
<color name="m3_ref_palette_dynamic_tertiary30">@android:color/system_accent3_700</color>
<color name="m3_ref_palette_dynamic_tertiary40">@android:color/system_accent3_600</color>
<color name="m3_ref_palette_dynamic_tertiary50">@android:color/system_accent3_500</color>
<color name="m3_ref_palette_dynamic_tertiary60">@android:color/system_accent3_400</color>
<color name="m3_ref_palette_dynamic_tertiary70">@android:color/system_accent3_300</color>
<color name="m3_ref_palette_dynamic_tertiary80">@android:color/system_accent3_200</color>
<color name="m3_ref_palette_dynamic_tertiary90">@android:color/system_accent3_100</color>
<color name="m3_ref_palette_dynamic_tertiary95">@android:color/system_accent3_50</color>
<color name="m3_ref_palette_dynamic_tertiary99">@android:color/system_accent3_10</color>
<color name="m3_sys_color_dynamic_dark_background">@color/m3_ref_palette_dynamic_neutral10</color>
<color name="m3_sys_color_dynamic_dark_inverse_on_surface">@color/m3_ref_palette_dynamic_neutral20</color>
<color name=",https://stackoverflow.com/questions/69044514/material-1-5-0-alpha03-res-values-v31-values-v31-xml35-94-aapt-error-resour,98,65610.0,7.0,,,2021-09-03 11:54:30,2023-01-20 12:00:54,2021-09-07 14:51:52,,,android;kotlin;android-recyclerview;material-components-android;multiview,Jaanu,1377,16582687,registered,true,,,CC BY-SA 4.0,,20321,20218,3,0,0,5,false,false,false,true,true,true,127,7,false,0.107,0.0015,1905,2021,9,11,Friday,false,false,false,false,false,false,false
30690724,Dollar Sign Character in Multiline Strings,"What is the cleanest method for adding a $ character in a string literal?
The best solution I've come up with so far is """"""${""$""}..."""""", which looks ugly to me.
",https://stackoverflow.com/questions/30690724/dollar-sign-character-in-multiline-strings,98,45387.0,5.0,,,2015-06-07 06:29:52,2025-01-13 07:00:47,2023-10-02 11:31:06,,,string;kotlin;templates;multiline,Travis,1382,1861615,registered,true,30699291,,CC BY-SA 4.0,,202,162,2,0,0,4,true,false,false,true,true,true,42,6,false,0.11,0.0022,4185,2015,6,6,Sunday,true,false,false,false,false,false,false
50304263,Check your module classpath for missing or conflicting dependencies,"I have a project with Java and Kotlin, which I am able to successfully run and build. However, when I open the project in IntelliJ, I see the same error in many of the project files.
The error is "Cannot access class 'java.lang.String'. Check your module classpath for missing or conflicting dependencies"
See the error in the image attached:
![]()
Another example of an error occurs when initializing a Kotlin MultiPlatform Mobile project:
cannot access 'java.lang.Object' which is a supertype of 'org.gradle.api.artifacts.dsl.RepositoryHandler'. Check your module classpath for missing or conflicting dependencies
What is the source of this error? How can I fix it?
",https://stackoverflow.com/questions/50304263/check-your-module-classpath-for-missing-or-conflicting-dependencies,98,152930.0,2.0,,,2018-05-12 08:27:31,2022-05-13 17:52:18,2020-11-23 08:26:09,2019-08-14 06:26:40,Not suitable for this site,java;kotlin;intellij-idea;jvm;kotlin-multiplatform,MadLax,1367,6371209,registered,true,,,,,977,676,1,2,1,5,false,true,false,true,true,true,67,9,false,0.013,0.0006,3115,2018,5,8,Saturday,true,false,false,true,false,false,false
30305217,Is it possible to use Mockito in Kotlin?,"The problem I'm facing is that Matchers.anyObject() returns null. When used to mock method that only accepts non-nullable types it causes a ""Should not be null"" exception to be thrown.
`when`(mockedBackend.login(anyObject())).thenAnswer { invocationOnMock -> someResponse }
Mocked method:
public open fun login(userCredentials: UserCredentials): Response
",https://stackoverflow.com/questions/30305217/is-it-possible-to-use-mockito-in-kotlin,97,53938.0,6.0,,,2015-05-18 13:58:34,2020-09-03 17:17:50,,,,java;mocking;mockito;kotlin,atok,5968,1356130,registered,true,30308199,,CC BY-SA 3.0,,452,364,4,0,0,4,true,false,false,true,true,false,40,8,true,0.111,0.0018,4205,2015,5,13,Monday,false,false,false,true,false,false,false
27699184,How to extend a class that has multiple constructors in Kotlin?,"I am in the processing of learning Kotlin and ran into a problem I couldn't figure out.
I would like to extend the Java class RuntimeException in Kotlin and be able to use any one of three of its constructors, in different circumstances (based on what info I have at the time I want to throw an exception). In java my class would look like this:
public class PhotoLibException extends RuntimeException {
public PhotoLibException(String message, RuntimeException ex) {
super(message, ex);
}
public PhotoLibException(String message) {
super(message);
}
public PhotoLibException(RuntimeException ex) {
super(ex);
}
}
When I try to do this in Kotlin, I used this answer as a guide: Kotlin secondary constructor however, I had a problem trying to figure out how to invoke the appropriate super constructor correctly. For example, using functions seemed to be a good approach, like this:
fun PhotoLibException(message: String): PhotoLibException {
val ex = null
return PhotoLibException(message, ex)
}
fun PhotoLibException(ex: Exception): PhotoLibException {
val message = ""
return PhotoLibException(message, ex)
}
class PhotoLibException(message: String, ex: Exception?): RuntimeException(message, ex) {
}
However, in this Kotlin example above, I am always invoking the super constructor with two args, and not invoking the constructor most appropriate to the situation. So what I have above works, but doesn't do exactly what it would do in Java where a different constructor is invoked in each situation.
I also tried instantiating a new RuntimeException inside each fun above and casting it to PhotoLibException, but I wasn't allowed to do that.
Can anyone suggest how I would do this correctly in Kotlin?
",https://stackoverflow.com/questions/27699184/how-to-extend-a-class-that-has-multiple-constructors-in-kotlin,97,64099.0,2.0,,,2014-12-30 03:17:13,2020-07-26 22:10:51,2020-07-26 22:10:51,,,constructor;kotlin,Steve Moseley,5887,299472,registered,true,27705675,,CC BY-SA 4.0,,1964,1787,3,1,0,2,true,false,false,true,true,true,63,11,true,0.031,0.0015,4344,2014,12,3,Tuesday,false,false,false,false,false,false,false
35517325,Kotlin doesn't see Java Lombok accessors?,"Using Kotlin 1.0.0 release (compiling in IntelliJ 15).
println(myPojoInstance.foo)
When it tries to compile code (in IntelliJ or Gradle) that references Lombok based POJOs it gives the error ""Cannot access 'foo': it is 'private' in ""MyPojo"". Which is true, they're all private and my object has @Value @Builder for lombok annotations.
I've tried specifically calling getFoo(), but it says ""unresolved reference for getFoo"". There's perhaps some trick to make Kotlin aware of how to handle the lombok annotations?
",https://stackoverflow.com/questions/35517325/kotlin-doesnt-see-java-lombok-accessors,97,37623.0,5.0,,,2016-02-20 00:03:40,2024-06-06 01:26:39,2017-05-30 13:02:02,,,kotlin;lombok;println,Chris Kessel,5913,29734,registered,true,35530223,,CC BY-SA 3.0,,563,518,1,0,0,3,true,false,false,true,true,true,45,6,true,0.133,0.0026,3927,2016,2,0,Saturday,true,false,false,false,false,false,false
5677563,Listener for Done button on EditText?,"If I have an EditText and I want to listen for if the user presses the ""done"" button on the keypad.. how would I do this?
",https://stackoverflow.com/questions/5677563/listener-for-done-button-on-edittext,96,61422.0,7.0,,,2011-04-15 13:33:10,2020-07-10 00:07:00,2020-07-10 00:07:00,2020-04-02 10:28:32,Duplicate,java;android;kotlin,Skizit,45216,358438,registered,true,5677676,,,,129,122,0,0,0,3,true,true,false,true,true,true,37,6,true,0.114,0.0016,5699,2011,4,13,Friday,false,false,false,true,false,false,false
45377802,Swap Function in Kotlin,"is there any better way to write generic swap function in kotlin other than java way described in How to write a basic swap function in Java.
Is there any kotlin language feature which can make generic swap function more concise and intuitive?
",https://stackoverflow.com/questions/45377802/swap-function-in-kotlin,96,43931.0,12.0,,,2017-07-28 15:57:54,2022-08-04 21:01:31,,,,kotlin,Akshar Patel,9508,6156989,registered,true,45377921,,CC BY-SA 3.0,,360,245,0,1,0,1,true,false,false,true,true,false,23,4,false,0.273,0.0022,3403,2017,7,15,Friday,false,false,false,false,false,false,false
44149474,Why does this Kotlin method have enclosing backticks?,"What are the backticks used for in the snippet below?
Why add them around the fun is(amount:Int ):Boolean { ... }?
verifier.`is`(amount)
",https://stackoverflow.com/questions/44149474/why-does-this-kotlin-method-have-enclosing-backticks,96,20852.0,6.0,,,2017-05-24 05:12:43,2021-01-27 16:16:51,2020-01-13 15:48:11,,,kotlin;methods;keyword;backticks,LF-DevJourney,28709,6521116,registered,true,44149561,,CC BY-SA 4.0,2019-09-06 09:32:41,192,141,2,0,0,4,true,false,false,true,true,true,53,8,true,0.288,0.0046,3468,2017,5,5,Wednesday,false,false,false,false,false,false,false
78970867,Error :app:kaptGenerateStubsDebugKotlin and Unknown Kotlin JVM target: 21 after changing Android studio from Iguana to LadyBug,"Please help. I changed Android studio from Iguana to LadyBug and the project does not compile. There are two errors during compilation :app:kaptGenerateStubsDebugKotlin' and Unknown Kotlin JVM target: 21:
Execution failed for task ':app:kaptGenerateStubsDebugKotlin'.
> Error while evaluating property 'compilerOptions.jvmTarget' of task ':app:kaptGenerateStubsDebugKotlin'.
> Failed to calculate the value of property 'jvmTarget'.
> Unknown Kotlin JVM target: 21
I reinstalled the JVM and JDK. Like all implementations, I added them in current versions.
Here is my gradle file:
...
plugins {
id("com.android.application")
id("org.jetbrains.kotlin.android")
id("org.jetbrains.kotlin.kapt")
}
android {
namespace = "com.ollo.stopsindicator"
compileSdk = 34
defaultConfig {
applicationId = "com.ollo.stopsindicator"
minSdk = 26
targetSdk = 34
versionCode = 28
versionName = "1.28"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables {
useSupportLibrary = true
}
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
buildFeatures {
compose = true
}
composeOptions {
kotlinCompilerExtensionVersion = "1.5.15"
}
packaging {
resources {
excludes += "/META-INF/{AL2.0,LGPL2.1}"
}
}
}
dependencies {
implementation("androidx.core:core-ktx:1.13.1")
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.6.2")
implementation("androidx.activity:activity-compose:1.8.2")
implementation(platform("androidx.compose:compose-bom:2024.09.00"))
implementation("androidx.compose.ui:ui")
implementation("androidx.compose.ui:ui-graphics")
implementation("androidx.compose.ui:ui-tooling-preview")
implementation("androidx.compose.material3:material3")
implementation("androidx.appcompat:appcompat:1.6.1")
testImplementation("junit:junit:4.13.2")
androidTestImplementation("androidx.test.ext:junit:1.1.5")
androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
implementation("com.tom-roush:pdfbox-android:2.0.27.0")
implementation ("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3")
}
I have no idea why the JVM Target is 21, I haven't set anything like that anywhere.
...
FAILURE: Build failed with an exception.
Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:kaptGenerateStubsDebugKotlin'.
at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:38)
at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.executeTask(EventFiringTaskExecuter.java:77)
at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:55)
at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:52)
at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:209)
at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:204)
at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:66)
at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:59)
at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:166)
at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:59)
at org.gradle.internal.operations.DefaultBuildOperationRunner.call(DefaultBuildOperationRunner.java:53)
at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:52)
at org.gradle.execution.plan.LocalTaskNodeExecutor.execute(LocalTaskNodeExecutor.java:42)
at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:331)
at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:318)
at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.lambda$execute$0(DefaultTaskExecutionGraph.java:314)
at org.gradle.internal.operations.CurrentBuildOperationRef.with(CurrentBuildOperationRef.java:85)
at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:314)
at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:303)
at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.execute(DefaultPlanExecutor.java:459)
at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.run(DefaultPlanExecutor.java:376)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
at org.gradle.internal.concurrent.AbstractManagedExecutor$1.run(AbstractManagedExecutor.java:48)
Caused by: org.gradle.api.internal.tasks.properties.PropertyEvaluationException: Error while evaluating property 'compilerOptions.jvmTarget' of task ':app:kaptGenerateStubsDebugKotlin'.
at org.gradle.api.internal.tasks.properties.InputParameterUtils.prepareInputParameterValue(InputParameterUtils.java:32)
at org.gradle.api.internal.tasks.execution.TaskExecution.lambda$visitRegularInputs$1(TaskExecution.java:317)
at org.gradle.internal.execution.impl.DefaultInputFingerprinter$InputCollectingVisitor.visitInputProperty(DefaultInputFingerprinter.java:103)
at org.gradle.api.internal.tasks.execution.TaskExecution.visitRegularInputs(TaskExecution.java:315)
at org.gradle.internal.execution.impl.DefaultInputFingerprinter.fingerprintInputProperties(DefaultInputFingerprinter.java:63)
at org.gradle.internal.execution.steps.AbstractCaptureStateBeforeExecutionStep.captureExecutionStateWithOutputs(AbstractCaptureStateBeforeExecutionStep.java:109)
at org.gradle.internal.execution.steps.AbstractCaptureStateBeforeExecutionStep.lambda$captureExecutionState$0(AbstractCaptureStateBeforeExecutionStep.java:74)
at org.gradle.internal.execution.steps.BuildOperationStep$1.call(BuildOperationStep.java:37)
at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:209)
at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:204)
at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:66)
at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:59)
at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:166)
at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:59)
at org.gradle.internal.operations.DefaultBuildOperation",https://stackoverflow.com/questions/78970867/error-appkaptgeneratestubsdebugkotlin-and-unknown-kotlin-jvm-target-21-after,96,69580.0,16.0,,,2024-09-10 18:31:26,2025-02-17 11:41:25,,,,android;kotlin;android-studio;jvm;build.gradle,ollo,983,14944790,registered,true,,,CC BY-SA 4.0,2024-10-25 10:29:10,17549,17449,3,0,0,5,false,false,false,true,true,false,126,16,false,0.23,0.0014,802,2024,9,18,Tuesday,false,false,false,false,false,false,false
57088428,Kotlin Flow: How to unsubscribe/stop,"Update Coroutines 1.3.0-RC
Working version:
@FlowPreview
suspend fun streamTest(): Flow<String> = channelFlow {
listener.onSomeResult { result ->
if (!isClosedForSend) {
offer(result)
}
}
awaitClose {
listener.unsubscribe()
}
}
Also checkout this Medium article by Roman Elizarov: Callbacks and Kotlin Flows
Original Question
I have a Flow emitting multiple Strings:
@FlowPreview
suspend fun streamTest(): Flow<String> = flowViaChannel { channel ->
listener.onSomeResult { result ->
if (!channel.isClosedForSend) {
channel.sendBlocking(result)
}
}
}
After some time I want to unsubscribe from the stream. Currently I do the following:
viewModelScope.launch {
beaconService.streamTest().collect {
Timber.i(""stream value $it"")
if(it == ""someString"")
// Here the coroutine gets canceled, but streamTest is still executed
this.cancel()
}
}
If the coroutine gets canceled, the stream is still executed. There is just no subscriber listening to new values. How can I unsubscribe and stop the stream function?
",https://stackoverflow.com/questions/57088428/kotlin-flow-how-to-unsubscribe-stop,95,89966.0,11.0,,,2019-07-18 06:38:50,2024-05-27 12:40:43,2019-07-24 13:46:44,,,kotlin;kotlin-coroutines,devz,2859,2110483,registered,true,64785132,,CC BY-SA 4.0,,1454,1186,4,1,0,2,true,false,false,true,true,true,36,5,false,0.122,0.0011,2683,2019,7,6,Thursday,false,false,false,false,false,false,false
62198361,No such property: scope for class: com.android.build.gradle.internal.variant.ApplicationVariantData,"After updating to Android Studio 4 I got this error:
A problem occurred configuring project ':app'.
groovy.lang.MissingPropertyException: No such property: scope for class: com.android.build.gradle.internal.variant.ApplicationVariantData
My gradle:
classpath 'com.android.tools.build:gradle:4.1.0-alpha10'
gradle-wrapper.properties:
https://services.gradle.org/distributions/gradle-6.5-bin.zip
",https://stackoverflow.com/questions/62198361/no-such-property-scope-for-class-com-android-build-gradle-internal-variant-app,95,64151.0,14.0,,,2020-06-04 15:26:58,2021-07-14 09:52:30,,,,android;android-studio;kotlin;gradle;android-gradle-plugin,Dima,1361,10585833,registered,true,,,CC BY-SA 4.0,,506,405,2,0,0,5,false,false,false,true,true,false,99,7,false,0.218,0.0015,2361,2020,6,15,Thursday,false,false,false,false,false,false,false
46038476,How could I split a String into an array in Kotlin?,"I need to split a String read in from a file into an array of values. I want to split the String at the commas, so for example, if the String read:
""name, 2012, 2017""
The values in the array would be:
- array index 0 - name
- array index 1 - 2012
- array index 2 - 2017
I found this example in Java:
String[] stringArray = string.split("","");
How I could do it in Kotlin?
",https://stackoverflow.com/questions/46038476/how-could-i-split-a-string-into-an-array-in-kotlin,95,176695.0,6.0,,,2017-09-04 13:49:17,2022-07-27 13:13:27,2019-01-02 21:28:14,,,java;arrays;string;kotlin,Michael F.,1012,7866568,registered,true,46038561,,CC BY-SA 4.0,,487,375,2,0,0,4,true,false,false,true,true,true,51,11,true,0.034,0.0005,3365,2017,9,13,Monday,false,false,false,true,false,false,false
45162869,Kotlin - Throw Custom Exception,"How can I throw a custom exception in Kotlin? I didn't really get that much off the docs...
In the docs, it gets described what each exception needs, but how exactly do I implement it?
",https://stackoverflow.com/questions/45162869/kotlin-throw-custom-exception,94,92353.0,6.0,,,2017-07-18 09:34:56,2023-08-05 21:54:18,,,,exception;kotlin,OhMad,6969,7190575,registered,true,45163186,,CC BY-SA 3.0,,200,186,0,0,0,2,true,false,false,true,true,false,31,5,false,0.065,0.001,3413,2017,7,9,Tuesday,false,false,false,false,false,false,false
46850060,Error:Execution failed for task ':app:kaptDebugKotlin',"I'm new to using Kotlin and trying to set it up with Dagger2, I've seen some few examples but none of them seem to work for me.
I keep getting this
Error:Execution failed for task ':app:kaptDebugKotlin'.
Internal compiler error. See log for more details
I have my build.gradle (Module: app)
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 25
buildToolsVersion ""25.0.0""
defaultConfig {
applicationId ""com.exampleapp""
minSdkVersion 14
targetSdkVersion 25
versionCode 1
versionName ""1.0""
testInstrumentationRunner ""android.support.test.runner.AndroidJUnitRunner""
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
kapt {
generateStubs = true
}
dexOptions {
javaMaxHeapSize ""2048M""
}
}
ext {
supportLibVer = '25.0.0'
daggerVer = '2.8'
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
// Support lib
compile ""com.android.support:appcompat-v7:${supportLibVer}""
kapt ""com.google.dagger:dagger-compiler:${daggerVer}""
compile ""com.google.dagger:dagger:${daggerVer}""
provided ""javax.annotation:jsr250-api:${javaxVer}""
compile ""org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version""
}
repositories {
mavenCentral()
}
",https://stackoverflow.com/questions/46850060/errorexecution-failed-for-task-appkaptdebugkotlin,94,176470.0,33.0,,,2017-10-20 13:23:57,2024-01-19 13:36:16,,,,android;kotlin;dagger-2,leggo,957,8768164,registered,true,,,CC BY-SA 3.0,2023-02-01 09:27:54,1652,1543,1,0,0,3,false,false,false,true,true,false,62,5,false,0.187,0.0005,3319,2017,10,13,Friday,false,false,false,false,false,false,false
44481268,"Call super class constructor in Kotlin, Super is not an expression","I have two classes Entity and Account as
abstract class Entity(
var id: String? = null,
var created: Date? = Date()) {
constructor(entity: Entity?) : this() {
fromEntity(entity)
}
fun fromEntity(entity: Entity?): Entity {
id = entity?.id
created = entity?.created
return this;
}
}
and
data class Account(
var name: String? = null,
var accountFlags: Int? = null
) : Entity() {
constructor(entity: Entity) : this() {
super(entity)
}
}
Which gives me the error
Super is not an expression, it can be only used in the left-hand side of
a dot '.'
Why cannot I do that?
The following will pass the compilation error, but I am not sure if it is correct.
constructor(entity: Entity) : this() {
super.fromEntity(entity)
}
",https://stackoverflow.com/questions/44481268/call-super-class-constructor-in-kotlin-super-is-not-an-expression,94,106753.0,5.0,,,2017-06-11 07:10:15,2023-04-26 11:27:53,2017-06-12 07:29:27,,,kotlin,Amr Eladawy,4379,5079380,registered,true,44493549,,CC BY-SA 3.0,,988,823,5,0,0,1,true,false,false,true,true,true,66,11,false,0.047,0.0009,3450,2017,6,7,Sunday,true,false,false,false,false,false,false
3930990,Android: How to Enable/Disable Wifi or Internet Connection Programmatically,"Using the Connectivity Manager Class we can get access to either wifi or Internet Network:
ConnectivityManager connec = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
// ARE WE CONNECTED TO THE NET
if ( connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED ||
connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED ) {
// ...
}
where 0 and 1 respectively refers to mobile and wifi connection
If my Android device is connected to both, can we switch between any of the networks or can we disable any of the networks? Like using a function:
connec.getNetworkInfo(0).setState(NetworkInfo.State.DISCONNECTED);
",https://stackoverflow.com/questions/3930990/android-how-to-enable-disable-wifi-or-internet-connection-programmatically,93,173739.0,10.0,,,2010-10-14 07:28:48,2022-05-27 10:11:06,2021-12-21 20:05:13,,,java;android;kotlin;wifi;hotspot,Rohit Sharma,13835,467592,registered,true,3931094,,CC BY-SA 4.0,2015-01-17 14:09:07,755,660,4,0,0,5,true,false,false,true,true,true,75,9,false,0.058,0.0005,5882,2010,10,7,Thursday,false,false,false,true,false,false,false
53523948,How do I create an enum from an Int in Kotlin?,"I have this enum:
enum class Types(val value: Int) {
FOO(1)
BAR(2)
FOO_BAR(3)
}
How do I create an instance of that enum using an Int?
I tried doing something like this:
val type = Types.valueOf(1)
And I get the error:
Integer literal does not conform to the expected type String
",https://stackoverflow.com/questions/53523948/how-do-i-create-an-enum-from-an-int-in-kotlin,93,86554.0,12.0,,,2018-11-28 16:24:50,2023-09-22 11:12:18,2021-09-27 08:41:39,,,kotlin;enums,pableiros,16267,3701102,registered,true,53524077,,CC BY-SA 4.0,,451,304,5,0,0,2,true,false,false,true,true,true,46,11,true,0.139,0.0011,2915,2018,11,16,Wednesday,false,false,false,false,false,false,false
51305150,MutableLiveData with initial value,"How I can initialize MutableLiveData with initial value?
I'm looking for something like:
val text = MutableLiveData<String>(""initial value"")
",https://stackoverflow.com/questions/51305150/mutablelivedata-with-initial-value,93,92006.0,8.0,,,2018-07-12 12:00:04,2023-03-09 06:39:01,,,,android;kotlin;android-livedata,Francis,7164,4353365,registered,true,53934859,,CC BY-SA 4.0,,192,148,1,0,0,3,true,false,false,true,true,false,34,4,false,0.087,0.001,3054,2018,7,12,Thursday,false,false,false,false,false,false,false
40682918,Kotlin - Most idiomatic way to convert a List to a MutableList,"I have a method (getContacts) that returns a List<Contact> and I need to convert this result to a MutableList<Contact>. Currently the best way I can think of doing it is like this:
val contacts: MutableList<Contact> = ArrayList(presenter.getContacts())
Is there a more idiomatic/"less Java" way to do that?
",https://stackoverflow.com/questions/40682918/kotlin-most-idiomatic-way-to-convert-a-list-to-a-mutablelist,93,53676.0,4.0,,,2016-11-18 17:33:54,2024-07-24 16:59:39,2020-08-01 10:59:42,,,android;kotlin,Mateus Gondim,5592,3752244,registered,true,40683134,,CC BY-SA 4.0,,413,336,4,0,0,2,true,false,false,true,true,true,62,12,false,0.075,0.0017,3655,2016,11,17,Friday,false,false,false,false,false,false,false
59412793,Kotlin Coroutines: Channel vs Flow,"I'm recently studying and reading a lot about Flow and Kotlin Coroutines. But I still get confused about when I should use Flow and when I should use Channel.
At the beginning it looked more simple. Working with hot streams of data? Channel. Cold ones? Flows. Same goes if you need to listen to streams of data from more than a single place; if that's the case Channel is the choice to go. There are still a lot of examples and questions.
But recently FlowChannels where introduced, together with tons of methods and classes that encourage the use of Flow, which facilities transforming Channels into Flows and so on. With all this new stuff coming on each Kotlin release I am getting more and more confused. So the question is:
When should I use Channel and when should I use Flow?
",https://stackoverflow.com/questions/59412793/kotlin-coroutines-channel-vs-flow,93,31716.0,3.0,,,2019-12-19 15:35:12,2024-05-04 18:52:54,2021-06-07 08:26:55,,,kotlin;stream;channel;kotlin-coroutines,Francisco Durdin Garcia,13527,5631145,registered,true,59426789,,CC BY-SA 4.0,,1076,783,9,1,0,4,true,false,false,true,true,true,34,5,false,0.095,0.0029,2529,2019,12,15,Thursday,false,false,false,false,false,false,false
38827186,What is the difference between crossinline and noinline in Kotlin?,"
This code compiles with a warning (insignificant performance impact):
inline fun test(noinline f: () -> Unit) {
thread(block = f)
}
This code does not compile (illegal usage of inline-parameter):
inline fun test(crossinline f: () -> Unit) {
thread(block = f)
}
This code compiles with a warning (insignificant performance impact):
inline fun test(noinline f: () -> Unit) {
thread { f() }
}
This code compiles with no warning or error:
inline fun test(crossinline f: () -> Unit) {
thread { f() }
}
Here are my questions:
- How come (2) does not compile but (4) does?
- What exactly is the difference between
noinline and crossinline?
- If (3) does not generates performance improvements, why would (4) do?
",https://stackoverflow.com/questions/38827186/what-is-the-difference-between-crossinline-and-noinline-in-kotlin,93,18642.0,4.0,,,2016-08-08 10:45:37,2025-01-30 11:05:37,2025-01-30 11:05:37,,,kotlin,Salomon BRYS,9620,1269640,registered,true,51113423,,CC BY-SA 4.0,,1084,751,6,0,0,1,true,false,false,true,true,true,66,10,true,0.215,0.005,3757,2016,8,10,Monday,false,false,false,false,false,false,false
37949024,kotlin.TypeCastException: null cannot be cast to non-null type com.midsizemango.databasekotlin.Note,"I am trying to code my app in Kotlin, but I am getting null cannot be casted to non-null type and app force stops when I open EditNoteActivity at EXTRA_NOTE probably.
Any Help is Highly Appreciated
Code:
class EditNoteActivity : AppCompatActivity() {
var note: Note? = null
private val editNote: TextView? = null
private val fabdrwble: Boolean? = null
private val notesData: MutableList<Note>? = null
private var databaseHelper: DatabaseHelper? = null
private val save: Boolean? = null
private var saveButton: FloatingActionButton? = null
private val tint: ColorStateList? = null
internal var mRowId: Long? = null
internal var spinner: Spinner? = null
internal var spinnertext: String? = null
internal var fav: Int = 0
internal var mSharedFromIntentFilter = false
internal var editTitle: EditText? = null
internal var editContent: EditText? = null
internal var inputlayoutTitle: TextInputLayout? = null
internal var inputlayoutContent: TextInputLayout? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_edit_note)
var toolbar = findViewById(R.id.toolbar_edit) as Toolbar?
setSupportActionBar(toolbar)
if (supportActionBar != null)
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
databaseHelper = DatabaseHelper(applicationContext)
inputlayoutTitle = findViewById(R.id.inputlayoutTitle) as TextInputLayout?
inputlayoutContent = findViewById(R.id.inputlayoutContent) as TextInputLayout?
editTitle = findViewById(R.id.note_title) as EditText
editContent = findViewById(R.id.note_content) as EditText?
val bundle = intent.extras
val s = bundle.getString("edit")
if (s == "add") {
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)
} else if (s == "editv") {
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN)
}
note = intent.getSerializableExtra(EXTRA_NOTE) as Note
if (note != null) {
editTitle?.setText(note!!.getTitle())
editContent?.setText(note!!.getContent())
} else {
note = Note()
//note.setUpdatedAt(new Date());
}
saveButton = findViewById(R.id.add_edit_button) as FloatingActionButton?
saveButton!!.setOnClickListener {
if (isNoteFormOk) {
setNoteResult()
finish()
} else
validateNoteForm()
}
var ll = findViewById(R.id.llmain) as LinearLayout?
var ll1 = findViewById(R.id.ll1) as LinearLayout?
/*if(note.getColor() == Color.TRANSPARENT){
selectedColor = preselect;
}else {
selectedColor = note.getColor();
}
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
systemBarTintManager = new SystemBarTintManager(this);
systemBarTintManager.setStatusBarTintEnabled(true);
ll.setBackgroundColor(selectedColor);
ll1.setBackgroundColor(selectedColor);
toolbar.setBackgroundColor(note.getColor());
systemBarTintManager.setStatusBarTintColor(selectedColor);*/
}
override fun onResume() {
super.onResume()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
onBack()
return true
}
/*
case R.id.speech:
try {
displaySpeechRecognizer();
} catch (ActivityNotFoundException e) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://market.android.com/details?id=com.google.android.googlequicksearchbox"));
startActivity(browserIntent);
}
return true;*/
else -> return super.onOptionsItemSelected(item)
}
}
private fun displaySpeechRecognizer() {
val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
startActivityForResult(intent, SPEECH_REQUEST_CODE)
}
override fun onActivityResult(requestCode: Int, resultCode: Int,
data: Intent) {
if (requestCode == SPEECH_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
val results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
val spokenText = results[0]
editContent?.setText(spokenText)
}
if (requestCode == RequestResultCode.REQUEST_CODE_ADD_NOTE) {
if (resultCode == Activity.RESULT_OK) {
addNote(data)
}
}
}
private val isNoteFormOk: Boolean
get() {
val title = editTitle?.text.toString()
return !(title == null || title.trim { it <= ' ' }.length == 0)
}
private fun validateNoteForm() {
var msg: String? = null
if (isNullOrBlank(editTitle?.text.toString())) {
msg = "Title Required"
inputlayoutTitle?.error = "Title is Missing"
}
if (msg != null) {
Toast.makeText(applicationContext, msg, Toast.LENGTH_LONG).show()
}
}
private fun setNoteResult() {
note!!.setTitle(editTitle?.text.toString().trim { it <= ' ' })
note!!.setContent(editContent?.text.toString().trim { it <= ' ' })
//note.setUpdatedAt(new Date());
val intent = Intent()
intent.putExtra(EXTRA_NOTE, note)
setResult(Activity.RESULT_OK, intent)
//addNote(intent);
Toast.makeText(this@EditNoteActivity, "Note Saved.", Toast.LENGTH_LONG).show()
}
private fun onBack() {
if (isNoteFormOk) {
if (editTitle?.text.toString() == note!!.getTitle() && editContent?.text.toString() == note!!.getContent()) {
setResult(Activity.RESULT_CANCELED, Intent())
finish()
} else {
AlertDialog.Builder(this@EditNoteActivity)
.setTitle("Save")
.setMessage("Do You Want to Save Note")
.setPositiveButton("SAVE") { dialog, which ->
setNoteResult()
finish()
}.setNegativeButton("CANCEL") { dialog, which ->
setResult(Activity.RESULT_CANCELED, Intent())
finish()
}.show()
}
} else {
setResult(Activity.RESULT_CANCELED, Intent())
finish()
}
}
private fun addNote(data: Intent) {
val note = data.getSerializableExtra(EXTRA_NOTE) as Note
val noteId = databaseHelper!!.createNote(note)
note.setId(noteId)
}
override fun onBackPressed() {
onBack()
val intentHome = Intent(this@EditNoteActivity, MainActivity::class.java)
intentHome.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
intentHome.putExtra(EXTRA_NOTE, note)
setResult(Activity.RESULT_OK, intentHome)
}
companion object {
private val EXTRA_NOTE = "EXTRA_NOTE"
private val SPEECH_REQUEST_CODE = 0
fun isNullOrBlank(str: String?): Boolean {
return str == null || str.trim { it <= ' ' }.length == 0
}
}
}
Logs:
java.lang.RuntimeException: Unable to start activity ComponentInfo{
com.midsizemango.databasekotlin/com.midsizemango.databasekotlin.EditNoteActivity}:
kotlin.TypeCastException: null cannot be cast to non-null type
com.midsizemango.databasekotlin.Note
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Met",https://stackoverflow.com/questions/37949024/kotlin-typecastexception-null-cannot-be-cast-to-non-null-type-com-midsizemango,92,132612.0,2.0,,,2016-06-21 15:48:00,2023-10-13 16:30:52,2022-02-15 09:52:51,,,android;kotlin,Prasad Shirvandkar,974,3302296,registered,true,37949190,,CC BY-SA 4.0,,9366,9239,4,0,0,2,true,false,false,true,true,true,99,9,false,0.015,0.0007,3805,2016,6,15,Tuesday,false,false,false,false,false,false,false
53448450,How to resolve error "Failed to resolve: org.jetbrains.kotlin:kotlin-stdlib-jre7..." when building in Android Studio,"I've created a new project by checking the ""include kotlin"" box in Android Studio 3 and out of the box I get an error while compiling
""Failed to resolve: org.jetbrains.kotlin:kotlin-stdlib-jre7...""
I have made sure all plugins are up to date and that the Android SDK is properly installed.
How can I solve for this error?
",https://stackoverflow.com/questions/53448450/how-to-resolve-error-failed-to-resolve-org-jetbrains-kotlinkotlin-stdlib-jre7,92,93903.0,2.0,,,2018-11-23 14:24:37,2020-05-12 15:03:38,2020-05-12 15:03:38,,,kotlin,Google,998,5175097,registered,true,53448758,,CC BY-SA 4.0,2019-07-18 18:27:15,371,326,1,0,0,1,true,false,false,true,true,true,126,13,false,0.021,0.001,2920,2018,11,14,Friday,false,false,false,false,false,false,false
43469241,Passing lambda instead of interface,"I have created an interface:
interface ProgressListener {
fun transferred(bytesUploaded: Long)
}
but can use it only as an anonymous class, not lambda
dataManager.createAndSubmitSendIt(title, message,
object : ProgressListener {
override fun transferred(bytesUploaded: Long) {
System.out.println(bytesUploaded.toString())
}
})
I think it should be a possibility to replace it by lambda:
dataManager.createAndSubmitSendIt(title, message, {System.out.println(it.toString())})
But I am getting error: Type mismatch; required - ProgressListener, found - () -> Unit?
What am I doing wrong?
",https://stackoverflow.com/questions/43469241/passing-lambda-instead-of-interface,92,30050.0,5.0,,,2017-04-18 10:07:19,2022-06-01 19:36:00,2020-07-26 22:12:56,,,lambda;kotlin,Viktor Sinelnikov,1641,4978624,registered,true,43470351,,CC BY-SA 4.0,,731,611,4,0,0,2,true,false,false,true,true,true,35,5,false,0.166,0.0031,3504,2017,4,10,Tuesday,false,false,false,false,false,false,false
46240236,Can "experimental" Kotlin coroutines be used in production?,"Can Kotlin coroutines be used in production, and what does their experimental status mean?
",https://stackoverflow.com/questions/46240236/can-experimental-kotlin-coroutines-be-used-in-production,92,11535.0,1.0,,,2017-09-15 13:01:30,2019-03-19 07:46:57,2019-03-19 07:46:57,,,kotlin;coroutine;kotlin-coroutines,Roman Elizarov,29158,1051598,registered,true,46240340,,CC BY-SA 4.0,,98,91,0,0,0,3,true,false,false,true,true,true,69,8,true,0.087,0.008,3354,2017,9,13,Friday,false,false,false,false,false,false,false
64045082,Live Data: Candidate resolution will be changed soon,"In same cases Android studio displays warning message when I call observe method of LiveData object
viewModel.emailValidationResult.observe(viewLifecycleOwner, {onEmailChanged(it)})
Candidate resolution will be changed soon, please use fully qualified
name to invoke the following closer candidate explicitly:
public open
fun observe(owner: LifecycleOwner, observer: Observer<in Int?>): Unit
defined in androidx.lifecycle.LiveData
As I understand it's happened after updating kotlin 1.4
What does it actually mean ?
",https://stackoverflow.com/questions/64045082/live-data-candidate-resolution-will-be-changed-soon,91,14535.0,6.0,,,2020-09-24 11:01:01,2022-03-31 02:42:49,2020-09-24 15:28:38,,,android;kotlin;android-livedata,Vahe Gharibyan,5763,4515438,registered,true,64045678,,CC BY-SA 4.0,,679,525,3,0,0,3,true,false,false,true,true,true,52,8,false,0.413,0.0063,2249,2020,9,11,Thursday,false,false,false,false,false,false,false
45800036,How do I run a block of code if a nullable type is null?,"In Kotlin, I can run code if an object is not null like this:
data?.let {
// execute this block if not null
}
But how can I execute a block of code if the object is null?
",https://stackoverflow.com/questions/45800036/how-do-i-run-a-block-of-code-if-a-nullable-type-is-null,90,58455.0,9.0,,,2017-08-21 14:45:58,2023-10-18 06:00:39,2022-02-24 19:14:53,,,kotlin;kotlin-null-safety,Toni Joe,8467,4507386,registered,true,45800094,,CC BY-SA 4.0,,214,176,1,0,0,2,true,false,false,true,true,true,56,14,true,0.154,0.0015,3379,2017,8,14,Monday,false,false,false,false,false,false,false
22654932,What is the purpose of Unit-returning in functions,"From the Kotlin documentation:
If a function does not return any useful value, its return type is Unit. Unit is a type with only one value — Unit.VALUE. This value does not have to be returned explicitly:
fun printHello(name : String?) : Unit {
if (name != null)
print(""Hello, $name!"")
else
print(""Hi there!"")
// We don't need to write 'return Unit.VALUE' or 'return', although we could
}
What is the purpose of Unit-returning in functions? Why is VALUE there? What is this VALUE?
",https://stackoverflow.com/questions/22654932/what-is-the-purpose-of-unit-returning-in-functions,90,42506.0,3.0,,,2014-03-26 08:12:06,2018-08-24 20:00:46,,,,kotlin,Dmitry Romanov,14239,548894,registered,true,22655381,,CC BY-SA 3.0,,555,510,1,0,0,1,true,false,false,true,true,false,50,8,false,0.071,0.0021,4623,2014,3,8,Wednesday,false,false,false,false,false,false,false
38525403,Kotlin Android print to console,"I need to print some str to console (Android Studio) using Kotlin.
I've tried the:
Log.v()
Log.d()
Log.i()
Log.w()
Log.e()
methods. But it seems to work only on Java.
What should I use to print using Kotlin?
Thanks
",https://stackoverflow.com/questions/38525403/kotlin-android-print-to-console,90,225529.0,6.0,,,2016-07-22 11:33:01,2021-02-11 13:46:16,2016-07-22 13:20:01,,,android;printing;kotlin,Pavel Bredelev,1481,5892317,registered,true,38525728,,CC BY-SA 3.0,,261,223,1,0,0,3,true,false,false,true,true,true,31,5,false,0.027,0.0004,3774,2016,7,11,Friday,false,false,false,false,false,false,false
68600128,remove default padding on jetpack compose textfield,"I want to customize TextField composable in Jetpack Compose. I am trying to achieve the result in the image below, but somehow TextField has some default paddings which i couldn't find how to change values of. I want to remove default paddings and customize it
(The image on the right one is the result i achieved. I drew a border so that you can see it has padding, btw below that TextField are just Text composables, they aren't TextFields)
Below is my TextField code
TextField(
value = "",
onValueChange = {},
modifier = Modifier
.weight(1F)
.padding(0.dp)
.border(width = 1.dp, color = Color.Red),
placeholder = {
Text(
"5555 5555 5555 5555", style = TextStyle(
color = Color.Gray
)
)
},
colors = TextFieldDefaults.textFieldColors(
backgroundColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent,
focusedIndicatorColor = Color.Transparent
),
)
",https://stackoverflow.com/questions/68600128/remove-default-padding-on-jetpack-compose-textfield,90,62909.0,12.0,,,2021-07-31 07:38:06,2025-08-31 10:37:18,2021-12-15 03:25:03,,,android;kotlin;android-jetpack-compose,nasibeyyubov,2850,11397760,registered,true,68601606,,CC BY-SA 4.0,,1453,1020,7,2,2,3,true,false,false,true,true,true,51,7,false,0.191,0.0014,1939,2021,7,7,Saturday,true,false,false,false,false,false,false
2050391,How to check if a map contains a key in Go?,"I know I can iterate over a map m with
for k, v := range m { ... }
and look for a key, but is there a more efficient way of testing for a key's existence in a map?
",https://stackoverflow.com/questions/2050391/how-to-check-if-a-map-contains-a-key-in-go,1444,1631972.0,12.0,,,2010-01-12 16:18:20,2025-07-30 06:15:37,2022-10-18 23:00:00,,,dictionary;go;go-map,grokus,19472,203091,registered,true,2050629,,CC BY-SA 4.0,2019-01-30 18:27:07,216,165,2,0,0,3,true,false,false,true,true,true,43,11,true,0.007,0.0009,6157,2010,1,16,Tuesday,false,false,false,false,false,false,false
1760757,How to efficiently concatenate strings in go,"In Go, a string is a primitive type, which means it is read-only, and every manipulation of it will create a new string.
So if I want to concatenate strings many times without knowing the length of the resulting string, what's the best way to do it?
The naive way would be:
var s string
for i := 0; i < 1000; i++ {
s += getShortStringFromSomewhere()
}
return s
but that does not seem very efficient.
",https://stackoverflow.com/questions/1760757/how-to-efficiently-concatenate-strings-in-go,1022,810438.0,20.0,,,2009-11-19 03:44:10,2023-10-26 08:04:24,2020-11-10 12:34:53,,,string;go;string-concatenation,Randy Sugianto 'Yuku',73883,11238,registered,true,1766304,,CC BY-SA 4.0,2016-08-29 09:39:20,473,408,2,0,0,3,true,false,false,true,true,true,44,7,false,0.025,0.0013,6211,2009,11,3,Thursday,false,false,false,false,false,false,false
7933460,How do you write multiline strings in Go?,"Does Go have anything similar to Python's multiline strings:
""""""line 1
line 2
line 3""""""
If not, what is the preferred way of writing strings spanning multiple lines?
",https://stackoverflow.com/questions/7933460/how-do-you-write-multiline-strings-in-go,961,589423.0,13.0,,,2011-10-28 18:44:35,2023-10-10 14:01:14,2019-04-11 11:10:11,,,string;go;multiline,aeter,12900,160992,registered,true,7933487,,CC BY-SA 4.0,2023-02-19 00:21:47,249,170,1,0,0,3,true,false,false,true,true,true,41,8,true,0.022,0.0016,5503,2011,10,18,Friday,false,false,false,false,false,false,false
16248241,Concatenate two slices in Go,"I'm trying to combine the slice [1, 2] and the slice [3, 4]. How can I do this in Go?
I tried:
append([]int{1,2}, []int{3,4})
but got:
cannot use []int literal (type []int) as type int in append
However, the documentation seems to indicate this is possible, what am I missing?
slice = append(slice, anotherSlice...)
",https://stackoverflow.com/questions/16248241/concatenate-two-slices-in-go,863,723856.0,11.0,,,2013-04-27 04:08:41,2026-10-21 17:35:53,2016-10-14 07:05:29,,,go;append;slice;variadic-functions,Kevin Burke,66063,329700,registered,true,16248257,,CC BY-SA 3.0,2019-01-30 18:28:30,503,325,5,1,0,4,true,false,false,true,true,true,28,5,false,0.015,0.0012,4956,2013,4,4,Saturday,true,false,false,false,false,false,false
10105935,How to convert an int value to string in Go?,"i := 123
s := string(i)
s is 'E', but what I want is "123"
Please tell me how can I get "123".
",https://stackoverflow.com/questions/10105935/how-to-convert-an-int-value-to-string-in-go,845,892384.0,11.0,,,2012-04-11 12:30:35,2025-11-28 01:14:34,2025-10-14 09:09:46,,,string;go;integer;converters,hardPass,21241,1316684,registered,true,10105983,,CC BY-SA 4.0,,155,117,1,0,0,4,true,false,false,true,true,true,44,10,true,0.012,0.0009,5337,2012,4,12,Wednesday,false,false,false,false,false,false,false
14426366,What is an idiomatic way of representing enums in Go?,"I'm trying to represent a simplified chromosome, which consists of N bases, each of which can only be one of {A, C, T, G}.
I'd like to formalize the constraints with an enum, but I'm wondering what the most idiomatic way of emulating an enum is in Go.
",https://stackoverflow.com/questions/14426366/what-is-an-idiomatic-way-of-representing-enums-in-go,826,711429.0,15.0,,,2013-01-20 16:07:22,2025-05-18 20:55:05,2017-01-20 17:23:52,,,enums;go;genetics,carbocation,9678,199475,registered,true,14426447,,CC BY-SA 3.0,2020-01-19 10:30:50,280,253,1,0,0,3,true,false,false,true,true,true,53,10,true,0.021,0.0012,5053,2013,1,16,Sunday,true,false,false,false,false,false,false
2032149,Optional Parameters in Go?,"Can Go have optional parameters? Or can I just define two different functions with the same name and a different number of arguments?
",https://stackoverflow.com/questions/2032149/optional-parameters-in-go,819,617420.0,15.0,,,2010-01-09 02:38:57,2022-09-13 15:06:12,2022-06-02 22:17:31,,,go;overloading,devyn,17665,371407,registered,true,2032160,,CC BY-SA 4.0,2019-01-30 18:28:07,141,134,0,0,0,2,true,false,false,true,true,true,26,4,true,0.024,0.0013,6160,2010,1,2,Saturday,true,false,false,false,false,false,false
7782411,Is there a foreach loop in Go?,"Is there a foreach construct in the Go language?
Can I iterate over a slice or array using a for?
",https://stackoverflow.com/questions/7782411/is-there-a-foreach-loop-in-go,812,703375.0,9.0,,,2011-10-16 04:47:32,2022-11-09 23:03:56,2022-03-27 09:10:30,,,go;foreach;slice,tatsuhirosatou,25957,64250,registered,true,7782507,,CC BY-SA 4.0,,131,98,2,0,0,3,true,false,false,true,true,true,30,7,true,0.013,0.0012,5515,2011,10,4,Sunday,true,false,false,false,false,false,false
24512112,How to print struct variables in console?,"How can I print (to the console) the Id, Title, Name, etc. of this struct in Golang?
type Project struct {
Id int64 `json:"project_id"`
Title string `json:"title"`
Name string `json:"name"`
Data Data `json:"data"`
Commits Commits `json:"commits"`
}
",https://stackoverflow.com/questions/24512112/how-to-print-struct-variables-in-console,762,838164.0,21.0,,,2014-07-01 13:57:18,2026-08-05 21:55:14,2022-01-11 15:14:58,,,struct;go,fnr,9817,3771173,registered,true,24512194,,CC BY-SA 4.0,2021-06-23 06:28:09,410,340,4,0,0,2,true,false,false,true,true,true,41,7,true,0.025,0.0009,4526,2014,7,13,Tuesday,false,false,false,false,false,false,false
12518876,How to check if a file exists in Go?,"Does the Go standard library have a function which checks if a file exists (like Python's os.path.exists).
Is there an idiomatic way to check file existence / non-existence?
",https://stackoverflow.com/questions/12518876/how-to-check-if-a-file-exists-in-go,729,579676.0,15.0,,,2012-09-20 18:42:02,2024-10-15 04:34:56,2024-10-15 04:34:56,,,file;go;standard-library,Sridhar Ratnakumar,86764,55246,registered,true,12518877,,CC BY-SA 4.0,2019-01-30 18:28:15,308,174,1,1,0,3,true,false,false,true,true,true,36,9,true,0.026,0.0013,5175,2012,9,18,Thursday,false,false,false,false,false,false,false
19979178,What is the idiomatic Go equivalent of C's ternary operator?,"In C/C++ (and many languages of that family), a common idiom to declare and initialize a variable depending on a condition uses the ternary conditional operator :
int index = val > 0 ? val : -val
Go doesn't have the conditional operator. What is the most idiomatic way to implement the same piece of code as above ? I came to the following solution, but it seems quite verbose
var index int
if val > 0 {
index = val
} else {
index = -val
}
Is there something better ?
",https://stackoverflow.com/questions/19979178/what-is-the-idiomatic-go-equivalent-of-cs-ternary-operator,628,588740.0,15.0,,,2013-11-14 13:39:09,2026-01-07 21:20:42,2018-10-03 09:05:40,,,go;ternary-operator;conditional-operator,Fabien,13716,87584,registered,true,19979829,,CC BY-SA 4.0,,558,489,2,0,0,3,true,false,false,true,true,true,64,10,true,0.025,0.0011,4755,2013,11,13,Thursday,false,false,false,false,false,false,false
10858787,What are the use(s) for struct tags in Go?,"In the Go Language Specification, it mentions a brief overview of tags:
A field declaration may be followed by an optional string literal tag,
which becomes an attribute for all the fields in the corresponding
field declaration. The tags are made visible through a reflection
interface but are otherwise ignored.
// A struct corresponding to the TimeStamp protocol buffer.
// The tag strings define the protocol buffer field numbers.
struct {
microsec uint64 ""field 1""
serverIP6 uint64 ""field 2""
process string ""field 3""
}
This is a very short explanation IMO, and I was wondering if anyone could provide me with what use these tags would be?
",https://stackoverflow.com/questions/10858787/what-are-the-uses-for-struct-tags-in-go,623,197249.0,4.0,,,2012-06-02 00:10:27,2023-10-30 19:46:43,2022-07-08 00:21:23,,,go;struct;reflection;tags,liamzebedee,14678,453438,registered,true,30889373,,CC BY-SA 4.0,2019-11-12 05:33:23,809,667,1,1,0,4,true,false,false,true,true,true,42,9,true,0.02,0.0032,5285,2012,6,0,Saturday,true,false,false,false,false,false,false
20170275,How to find the type of an object in Go?,"How do I find the type of an object in Go? In Python, I just use typeof to fetch the type of object. Similarly in Go, is there a way to implement the same ?
Here is the container from which I am iterating:
for e := dlist.Front(); e != nil; e = e.Next() {
lines := e.Value
fmt.Printf(reflect.TypeOf(lines))
}
I am not able to get the type of the object lines in this case which is an array of strings.
",https://stackoverflow.com/questions/20170275/how-to-find-the-type-of-an-object-in-go,600,713419.0,16.0,,,2013-11-24 02:08:13,2022-11-27 20:35:38,2020-04-29 08:30:20,,,go;go-reflect,Rahul,11759,405442,registered,true,20170564,,CC BY-SA 4.0,,471,413,2,0,0,2,true,false,false,true,true,true,40,10,true,0.022,0.0008,4745,2013,11,2,Sunday,true,false,false,false,false,false,false
8757389,Reading a file line by line in Go,"I'm unable to find file.ReadLine function in Go.
How does one read a file line by line?
",https://stackoverflow.com/questions/8757389/reading-a-file-line-by-line-in-go,593,673113.0,13.0,,,2012-01-06 11:50:24,2024-01-28 16:47:35,2022-03-25 20:03:09,,,string;file;parsing;go;line,g06lin,6245,85830,registered,true,8758113,,CC BY-SA 4.0,2018-03-23 08:44:21,115,88,1,0,0,5,true,false,false,true,true,true,33,8,false,0.019,0.0009,5433,2012,1,11,Friday,false,false,false,false,false,false,false
11123865,Format a Go string without printing?,"Is there a simple way to format a string in Go without printing the string?
I can do:
bar := ""bar""
fmt.Printf(""foo: %s"", bar)
But I want the formatted string returned rather than printed so I can manipulate it further.
I could also do something like:
s := ""foo: "" + bar
But this becomes difficult to read when the format string is complex, and cumbersome when one or many of the parts aren't strings and have to be converted first, like
i := 25
s := ""foo: "" + strconv.Itoa(i)
Is there a simpler way to do this?
",https://stackoverflow.com/questions/11123865/format-a-go-string-without-printing,592,465412.0,8.0,,,2012-06-20 16:21:34,2023-05-07 02:11:53,2019-05-21 13:58:26,,,string;go;formatting;string-formatting,Carnegie,6055,763762,registered,true,11124241,,CC BY-SA 4.0,,636,522,3,0,0,4,true,false,false,true,true,true,36,6,true,0.017,0.0013,5267,2012,6,16,Wednesday,false,false,false,false,false,false,false
34031801,Function declaration syntax: things in parenthesis before function name,"I'm sorry I couldn't be more specific in the question title, but I was reading some Go code and I encountered function declarations of this form:
func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
...
}
from https://github.com/mattermost/platform/blob/master/api/context.go
func (s *GracefulServer) BlockingClose() bool {
...
}
from https://github.com/braintree/manners/blob/master/server.go
What does the (h handler) and the (s *GracefulServer) between parenthesis mean? What does the entire function declaration mean, taking into account the meaning of the things between parenthesis?
Edit
This is not a duplicate of Whats the difference of functions and methods in Go? : this question came to me because I didn't know what the things in parenthesis before the function name were, not because I wondered what was the difference between functions and methods... if I knew that this declaration was a method I wouldn't have had this question in the first place. If someone has the same doubt as me one day, I don't believe she will go searching for "golang methods" because she doesn't know that this is the case. It would be like wondering what the letter "sigma" means before a mathematical expression (not knowing it means summation) and someone says it's a duplicate of what's the difference between summation and some other thing.
Also, the short answer to this question ("it's a receiver") is no answer to "what's the difference between functions and methods".
",https://stackoverflow.com/questions/34031801/function-declaration-syntax-things-in-parenthesis-before-function-name,586,94548.0,3.0,,,2015-12-01 22:56:53,2021-12-10 09:42:02,2020-06-20 09:12:55,,,go,Marcus Vinícius Monteiro,8239,819720,registered,true,34031889,,CC BY-SA 4.0,2021-12-10 09:43:38,2015,1535,4,4,0,1,true,false,false,true,true,true,71,9,false,0.032,0.0062,4008,2015,12,22,Tuesday,false,false,false,false,false,false,false
8032170,How to assign string to bytes array,"I want to assign string to bytes array:
var arr [20]byte
str := ""abc""
for k, v := range []byte(str) {
arr[k] = byte(v)
}
Have another method?
",https://stackoverflow.com/questions/8032170/how-to-assign-string-to-bytes-array,580,726439.0,10.0,,,2011-11-07 02:29:57,2022-10-14 06:41:27,,,,go,sofire,5909,1001149,registered,true,,,CC BY-SA 3.0,,185,147,1,0,0,1,false,false,false,true,true,false,35,7,false,0.014,0.0008,5493,2011,11,2,Monday,false,false,false,false,false,false,false
24790175,When does the init() function run?,"I've tried to find a precise explanation of what the init() function does in Go. I read what Effective Go says but I was unsure if I understood fully what it said. The exact sentence I am unsure is the following:
And finally means finally: init is called after all the variable declarations in the package have evaluated their initializers, and those are evaluated only after all the imported packages have been initialized.
What does all the variable declarations in the package have evaluated their initializers mean? Does it mean if you declare "global" variables in a package and its files, init() will not run until all of it is evaluated and then it will run all the init function and then main() when ./main_file_name is ran?
I also read Mark Summerfield's go book the following:
If a package has one or more init() functions they are automatically executed before the main package's main() function is called.
In my understanding, init() is only relevant when you intend to run main() right? Anyone understands more precisely init() feel free to correct me
",https://stackoverflow.com/questions/24790175/when-does-the-init-function-run,569,279111.0,11.0,,,2014-07-16 20:34:44,2024-05-25 17:20:39,2024-05-25 17:20:39,,,go;init,Charlie Parker,6492,1601580,registered,true,24790378,,CC BY-SA 4.0,2019-01-30 18:29:47,1300,1079,4,1,0,2,true,false,false,true,true,true,34,6,true,0.039,0.002,4511,2014,7,20,Wednesday,false,false,false,false,false,false,false
14230145,How can I convert a zero-terminated byte array to string?,"I need to read [100]byte to transfer a bunch of string data.
Because not all of the strings are precisely 100 characters long, the remaining part of the byte array is padded with 0s.
If I convert [100]byte to string by: string(byteArray[:]), the tailing 0s are displayed as ^@^@s.
In C, the string will terminate upon 0, so what's the best way to convert this byte array to string in Go?
",https://stackoverflow.com/questions/14230145/how-can-i-convert-a-zero-terminated-byte-array-to-string,554,510352.0,11.0,,,2013-01-09 07:19:48,2021-06-28 11:04:32,2020-08-25 12:03:43,,,go,Derrick Zhang,21661,639165,registered,true,14230206,,CC BY-SA 4.0,2018-05-03 13:17:27,598,388,14,0,0,1,true,false,false,true,true,true,57,10,true,0.022,0.0011,5064,2013,1,7,Wednesday,false,false,false,false,false,false,false
23542989,Pointers vs. values in parameters and return values,"In Go there are various ways to return a struct value or slice thereof. For individual ones I've seen:
type MyStruct struct {
Val int
}
func myfunc() MyStruct {
return MyStruct{Val: 1}
}
func myfunc() *MyStruct {
return &MyStruct{}
}
func myfunc(s *MyStruct) {
s.Val = 1
}
I understand the differences between these. The first returns a copy of the struct, the second a pointer to the struct value created within the function, the third expects an existing struct to be passed in and overrides the value.
I've seen all of these patterns be used in various contexts, I'm wondering what the best practices are regarding these. When would you use which? For instance, the first one could be ok for small structs (because the overhead is minimal), the second for bigger ones. And the third if you want to be extremely memory efficient, because you can easily reuse a single struct instance between calls. Are there any best practices for when to use which?
Similarly, the same question regarding slices:
func myfunc() []MyStruct {
return []MyStruct{ MyStruct{Val: 1} }
}
func myfunc() []*MyStruct {
return []MyStruct{ &MyStruct{Val: 1} }
}
func myfunc(s *[]MyStruct) {
*s = []MyStruct{ MyStruct{Val: 1} }
}
func myfunc(s *[]*MyStruct) {
*s = []MyStruct{ &MyStruct{Val: 1} }
}
Again: what are best practices here. I know slices are always pointers, so returning a pointer to a slice isn't useful. However, should I return a slice of struct values, a slice of pointers to structs, should I pass in a pointer to a slice as argument (a pattern used in the Go App Engine API)?
",https://stackoverflow.com/questions/23542989/pointers-vs-values-in-parameters-and-return-values,553,170952.0,5.0,,,2014-05-08 13:21:41,2025-03-10 04:43:05,2014-09-23 07:30:43,,,pointers;go,Zef Hemel,6807,113770,registered,true,23551970,,CC BY-SA 3.0,,1817,1626,3,1,0,2,true,false,false,true,true,true,51,8,false,0.029,0.0032,4580,2014,5,13,Thursday,false,false,false,false,false,false,false
10485743,Contains method for a slice,"Is there anything similar to a slice.contains(object) method in Go without having to do a search through each element in a slice?
",https://stackoverflow.com/questions/10485743/contains-method-for-a-slice,543,861312.0,20.0,,,2012-05-07 16:35:37,2024-07-03 19:04:41,2016-08-03 12:52:26,,,go;slice,vosmith,5928,914361,registered,true,10486196,,CC BY-SA 3.0,,151,131,1,0,0,2,true,false,false,true,true,true,27,5,false,0.023,0.0006,5311,2012,5,16,Monday,false,false,false,false,false,false,false
17891226,Difference between := and = operators in Go,"What is the difference between the = and := operators, and what are the use cases for them? They both seem to be for an assignment?
",https://stackoverflow.com/questions/17891226/difference-between-and-operators-in-go,542,237583.0,8.0,,,2013-07-26 21:20:37,2023-03-22 21:12:35,2020-05-05 12:13:23,,,go,Chris,9174,74651,registered,true,17891285,,CC BY-SA 4.0,,165,132,2,0,0,1,true,false,false,true,true,true,43,8,false,0.034,0.0023,4866,2013,7,21,Friday,false,false,false,false,false,false,false
4278430,Convert string to integer type in Go?,"I'm trying to convert a string returned from flag.Arg(n) to an int. What is the idiomatic way to do this in Go?
",https://stackoverflow.com/questions/4278430/convert-string-to-integer-type-in-go,532,832798.0,6.0,,,2010-11-25 15:06:38,2025-11-28 01:17:14,2018-11-05 16:36:34,,,string;go;type-conversion,Matt Joiner,120754,149482,registered,true,4279644,,CC BY-SA 4.0,,145,112,2,0,0,3,true,false,false,true,true,true,37,7,true,0.007,0.0006,5840,2010,11,15,Thursday,false,false,false,false,false,false,false
17573190,How to multiply duration by integer?,"To test concurrent goroutines, I added a line to a function to make it take a random time to return (up to one second)
time.Sleep(rand.Int31n(1000) * time.Millisecond)
However when I compiled, I got this error
.\crawler.go:49: invalid operation: rand.Int31n(1000) * time.Millisecond (mismatched types int32 and time.Duration)
Any ideas? How can I multiply a duration?
",https://stackoverflow.com/questions/17573190/how-to-multiply-duration-by-integer,517,366039.0,9.0,,,2013-07-10 14:23:44,2022-03-10 18:22:41,2019-08-08 15:03:40,,,go;time,Colonel Panic,139037,284795,registered,true,17573390,,CC BY-SA 4.0,,454,377,1,0,0,2,true,false,false,true,true,true,36,6,true,0.025,0.0014,4882,2013,7,14,Wednesday,false,false,false,false,false,false,false
22892120,How to generate a random string of a fixed length in Go?,"I want a random string of characters only (uppercase or lowercase), no numbers, in Go. What is the fastest and simplest way to do this?
",https://stackoverflow.com/questions/22892120/how-to-generate-a-random-string-of-a-fixed-length-in-go,515,489932.0,21.0,,,2014-04-06 09:22:54,2026-04-09 07:39:48,2018-07-13 21:38:43,,,string;random;go,Anish Shah,8239,3138699,registered,true,31832326,,CC BY-SA 4.0,,143,136,0,0,0,3,true,false,false,true,true,true,56,12,true,0.043,0.0011,4612,2014,4,9,Sunday,true,false,false,false,false,false,false
18594330,What is the best way to test for an empty string in Go?,"Which method is best (most idomatic) for testing non-empty strings (in Go)?
if len(mystring) > 0 { }
Or:
if mystring != "" { }
Or something else?
",https://stackoverflow.com/questions/18594330/what-is-the-best-way-to-test-for-an-empty-string-in-go,512,620816.0,11.0,,,2013-09-03 14:02:35,2024-01-03 10:54:59,2022-02-04 20:09:22,,,string;go;is-empty,Richard,10708,99542,registered,true,18595217,,CC BY-SA 4.0,,230,161,2,0,0,3,true,false,false,true,true,true,55,13,true,0.018,0.0008,4827,2013,9,14,Tuesday,false,false,false,false,false,false,false
15323767,Does Go have "if x in" construct similar to Python?,"How can I check if x is in an array without iterating over the entire array, using Go? Does the language have a construct for this?
Like in Python:
if "x" in array:
# do something
",https://stackoverflow.com/questions/15323767/does-go-have-if-x-in-construct-similar-to-python,504,506052.0,9.0,,,2013-03-10 15:15:56,2024-09-11 20:49:02,2022-05-28 17:38:18,2023-09-12 07:15:46,Duplicate,if-statement;go,user1529891,,,does_not_exist,true,15323988,,,,299,194,2,0,0,2,true,true,false,true,false,true,61,10,true,0.018,0.001,5004,2013,3,15,Sunday,true,false,false,false,false,false,false
21743841,How to avoid annoying error "declared and not used","I'm learning Go but I feel it is a bit annoying that when compiling, I should not leave any variable or package unused.
This is really quite slowing me down. For example, I just wanted to declare a new package and plan to use it later or just uncomment some command to test. I always get the error and need to go comment all of those uses.
Is there any way to avoid this kind of check in Go?
",https://stackoverflow.com/questions/21743841/how-to-avoid-annoying-error-declared-and-not-used,491,260499.0,14.0,,,2014-02-13 02:09:48,2025-05-07 13:34:05,2018-07-13 21:39:20,,,go,A-letubby,9272,466432,registered,true,21744129,,CC BY-SA 4.0,2018-01-03 00:05:16,417,396,0,0,0,1,true,false,false,true,true,true,61,9,false,0.054,0.0019,4664,2014,2,2,Thursday,false,false,false,false,false,false,false
7970390,What should be the values of GOPATH and GOROOT?,"I'm trying to install doozer like this:
$ goinstall github.com/ha/doozer
I get these errors.
goinstall: os: go/build: package could not be found locally
goinstall: fmt: go/build: package could not be found locally
goinstall: io: go/build: package could not be found locally
goinstall: reflect: go/build: package could not be found locally
goinstall: math: go/build: package could not be found locally
goinstall: rand: go/build: package could not be found locally
goinstall: url: go/build: package could not be found locally
goinstall: net: go/build: package could not be found locally
goinstall: sync: go/build: package could not be found locally
goinstall: runtime: go/build: package could not be found locally
goinstall: strings: go/build: package could not be found locally
goinstall: sort: go/build: package could not be found locally
goinstall: strconv: go/build: package could not be found locally
goinstall: bytes: go/build: package could not be found locally
goinstall: log: go/build: package could not be found locally
goinstall: encoding/binary: go/build: package could not be found locally
",https://stackoverflow.com/questions/7970390/what-should-be-the-values-of-gopath-and-goroot,481,692128.0,25.0,,,2011-11-01 17:32:52,2024-02-26 07:29:37,2019-09-13 15:35:43,,,go;gopath,jshen,12015,46505,registered,true,10847122,,CC BY-SA 4.0,,1256,1109,2,1,0,2,true,false,false,true,true,true,47,9,true,0.036,0.0007,5499,2011,11,17,Tuesday,false,false,false,false,false,false,false
15311969,Checking the equality of two slices,"How can I check if two slices are equal, given that the operators == and != are not an option?
package main
import "fmt"
func main() {
s1 := []int{1, 2}
s2 := []int{1, 2}
fmt.Println(s1 == s2)
}
This does not compile with:
invalid operation: s1 == s2 (slice can only be compared to nil)
",https://stackoverflow.com/questions/15311969/checking-the-equality-of-two-slices,475,284381.0,13.0,,,2013-03-09 14:46:38,2023-12-11 08:56:00,2022-07-14 09:20:55,,,go;comparison;slice,wei2912,6689,1474402,registered,true,15312097,,CC BY-SA 4.0,,410,314,3,0,0,3,true,false,false,true,true,true,35,6,false,0.046,0.0017,5005,2013,3,14,Saturday,true,false,false,false,false,false,false
32232655,go get results in 'terminal prompts disabled' error for GitHub private repo,"I created the private repo examplesite/myprivaterepo using the GitHub UI from my browser.
Then I went to my go directory (on the desktop) and cloned it:
$ cd $GOPATH
$ go get github.com/examplesite/myprivaterepo
So far so good. Created the file scheduler.go, added to repo and pushed.
$ vim scheduler.go
$ git add scheduler.go
$ git commit
$ git push
Everythng's OK. But when I went to a clean laptop and tried to clone the repo, I got an error:
# Now on laptop, which doesn't yet know about the repo
$ cd $GOPATH
$ go get github.com/examplesite/myprivaterepo
# At this point it should ask for my user ID and password ,right? But it doesn't.
# Instead, this error occurs:
cd .; git clone https://github.com/examplesite/myprivaterepo /Users/tom/go/src/github.com/examplesite/myprivaterepo
Cloning into '/Users/tom/go/src/github.com/examplesite/myprivaterepo'...
fatal: could not read Username for 'https://github.com': terminal prompts disabled
package github.com/examplesite/myprivaterepo: exit status 128
Why is my laptop hating on my own repo and how can I get it to accept its fate?
Thanks.
",https://stackoverflow.com/questions/32232655/go-get-results-in-terminal-prompts-disabled-error-for-github-private-repo,474,669456.0,18.0,,,2015-08-26 17:10:13,2024-10-24 15:25:31,2024-09-25 12:29:28,,,git;go,tomcam,5415,478311,registered,true,60323360,,CC BY-SA 4.0,,1225,1098,4,0,0,2,true,false,false,true,true,true,83,12,false,0.027,0.0007,4105,2015,8,17,Wednesday,false,false,false,false,false,false,false
1841443,Iterating over all the keys of a map,"Is there a way to get a list of all the keys in a Go language map? The number of elements is given by len(), but if I have a map like:
m := map[string]string{ ""key1"":""val1"", ""key2"":""val2"" };
How do I iterate over all the keys?
",https://stackoverflow.com/questions/1841443/iterating-over-all-the-keys-of-a-map,470,479199.0,6.0,,,2009-12-03 17:15:18,2022-07-28 00:15:22,2017-07-19 23:05:05,,,loops;dictionary;go,Martin Redmond,14096,30541,registered,true,1841643,,CC BY-SA 3.0,2019-01-30 18:29:08,282,231,2,0,0,3,true,false,false,true,true,true,36,8,false,0.013,0.001,6197,2009,12,17,Thursday,false,false,false,false,false,false,false
13792254,Removing packages installed with go get,"I ran go get package to download a package before learning that I needed to set my GOPATH otherwise that package sullies my root Go install (I would much prefer to keep my Go install clean and separate core from custom). How do I remove packages installed previously?
",https://stackoverflow.com/questions/13792254/removing-packages-installed-with-go-get,468,534250.0,8.0,,,2012-12-09 21:54:05,2024-01-20 23:37:15,,,,go,Owen Allen,12108,435223,registered,true,13792319,,CC BY-SA 3.0,,301,268,2,0,0,1,true,false,false,true,true,false,39,6,false,0.015,0.0009,5095,2012,12,21,Sunday,true,false,false,false,false,false,false
21362950,Getting a slice of keys from a map,"
Is there any simpler/nicer way of getting a slice of keys from a map in Go?
Currently I am iterating over the map and copying the keys to a slice:
i := 0
keys := make([]int, len(mymap))
for k := range mymap {
keys[i] = k
i++
}
",https://stackoverflow.com/questions/21362950/getting-a-slice-of-keys-from-a-map,457,573895.0,10.0,,,2014-01-26 11:48:24,2024-06-06 07:47:57,2022-07-12 05:41:40,,,dictionary;go;slice,Saswat Padhi,6660,554436,registered,true,21363587,,CC BY-SA 4.0,,319,240,1,0,0,3,true,false,false,true,true,true,34,8,false,0.017,0.0008,4682,2014,1,11,Sunday,true,false,false,false,false,false,false
29164375,Correct way to initialize empty slice,"To declare an empty slice, with a non-fixed size,
is it better to do:
mySlice1 := make([]int, 0)
or:
mySlice2 := []int{}
Just wondering which one is the correct way.
",https://stackoverflow.com/questions/29164375/correct-way-to-initialize-empty-slice,449,577067.0,6.0,,,2015-03-20 10:27:56,2024-08-15 08:21:36,2018-07-20 14:03:53,,,arrays;go;slice,eouti,5748,698329,registered,true,29164565,,CC BY-SA 4.0,,243,174,2,0,0,3,true,false,false,true,true,true,37,6,false,0.01,0.0008,4264,2015,3,10,Friday,false,false,false,false,false,false,false
40823315,X does not implement Y (... method has a pointer receiver),"There are already several Q&As on this ""X does not implement Y (... method has a pointer receiver)"" thing, but to me, they seems to be talking about different things, and not applying to my specific case.
So, instead of making the question very specific, I'm making it broad and abstract -- Seems like there are several different cases that can make this error happen, can someone summary it up please?
I.e., how to avoid the problem, and if it occurs, what are the possibilities? Thx.
",https://stackoverflow.com/questions/40823315/x-does-not-implement-y-method-has-a-pointer-receiver,440,180059.0,4.0,,,2016-11-26 21:24:32,2022-02-26 01:02:08,2018-09-10 16:40:08,,,pointers;go;methods;interface,xpt,23784,2125837,registered,true,40824044,,CC BY-SA 4.0,,522,492,0,0,0,4,true,false,false,true,true,true,58,11,false,0.022,0.0024,3647,2016,11,21,Saturday,true,false,false,false,false,false,false
34018908,Golang why don't we have a set datastructure,"I'm trying to solve a Go language exercise which requires me to have a set. I can create a set type but why doesn't the language come with one?
Go, having come from Google, where Guava also originated, why didn't the language designers opt for adding support for fundamental data structures? Why force your users to create their own implementations for something so basic as a set?
",https://stackoverflow.com/questions/34018908/golang-why-dont-we-have-a-set-datastructure,411,318564.0,4.0,,,2015-12-01 11:09:29,2024-10-20 02:08:23,2024-10-20 02:08:23,2015-12-10 06:34:01,Opinion-based,data-structures;go;set,anjanb,14200,11142,registered,true,,,,,418,382,1,0,0,3,false,true,false,true,true,true,48,8,false,0.013,0.0013,4008,2015,12,11,Tuesday,false,false,false,false,false,false,false
24455147,How do I send a JSON string in a POST request in Go,"I tried working with Apiary and made a universal template to send JSON to mock server and have this code:
package main
import (
"encoding/json"
"fmt"
"github.com/jmcvetta/napping"
"log"
"net/http"
)
func main() {
url := "http://restapi3.apiary.io/notes"
fmt.Println("URL:>", url)
s := napping.Session{}
h := &http.Header{}
h.Set("X-Custom-Header", "myvalue")
s.Header = h
var jsonStr = []byte(`{ "title": "Buy cheese and bread for breakfast."}`)
var data map[string]json.RawMessage
err := json.Unmarshal(jsonStr, &data)
if err != nil {
fmt.Println(err)
}
resp, err := s.Post(url, &data, nil, nil)
if err != nil {
log.Fatal(err)
}
fmt.Println("response Status:", resp.Status())
fmt.Println("response Headers:", resp.HttpResponse().Header)
fmt.Println("response Body:", resp.RawText())
}
This code doesn't send JSON properly, but I don't know why. The JSON string can be different in every call. I can't use Struct for this.
",https://stackoverflow.com/questions/24455147/how-do-i-send-a-json-string-in-a-post-request-in-go,410,657432.0,9.0,,,2014-06-27 15:09:37,2024-01-27 18:08:09,2024-01-27 18:08:09,,,json;rest;go;apiary.io,Ladislav Prskavec,4549,194508,registered,true,24455606,,CC BY-SA 4.0,,1282,1190,2,0,0,4,true,false,false,true,true,true,51,13,false,0.014,0.0006,4530,2014,6,15,Friday,false,false,false,false,false,false,false
20895552,How can I read from standard input in the console?,"I would like to read standard input from the command line, but my attempts have ended with the program exiting before I'm prompted for input. I'm looking for the equivalent of Console.ReadLine() in C#.
This is what I currently have:
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter text: ")
text, _ := reader.ReadString('\n')
fmt.Println(text)
fmt.Println("Enter text: ")
text2 := ""
fmt.Scanln(text2)
fmt.Println(text2)
ln := ""
fmt.Sscanln("%v", ln)
fmt.Println(ln)
}
",https://stackoverflow.com/questions/20895552/how-can-i-read-from-standard-input-in-the-console,410,520222.0,13.0,,,2014-01-03 02:33:40,2023-12-07 09:46:07,2021-05-16 11:03:21,,,go,Dante,11474,1121143,registered,true,20895629,,CC BY-SA 4.0,2019-01-30 18:30:16,824,672,1,1,0,1,true,false,false,true,true,true,50,10,true,0.025,0.0008,4705,2014,1,2,Friday,false,false,false,false,false,false,false
1821811,How to read/write from/to a file using Go,"I've been trying to learn Go on my own, but I've been stumped on trying read from and write to ordinary files.
I can get as far as inFile, _ := os.Open(INFILE, 0, 0), but actually getting the content of the file doesn't make sense, because the read function takes a []byte as a parameter.
func (file *File) Read(b []byte) (n int, err Error)
",https://stackoverflow.com/questions/1821811/how-to-read-write-from-to-a-file-using-go,395,473687.0,11.0,,,2009-11-30 19:17:46,2024-01-06 12:30:45,2021-05-14 21:48:02,,,file;go,Seth Hoenig,7517,221569,registered,true,9739903,,CC BY-SA 4.0,,406,342,3,0,0,2,true,false,false,true,true,true,41,8,false,0.023,0.0008,6200,2009,11,19,Monday,false,false,false,false,false,false,false
37334119,How to delete an element from a Slice in Golang,"fmt.Println(""Enter position to delete::"")
fmt.Scanln(&pos)
new_arr := make([]int, (len(arr) - 1))
k := 0
for i := 0; i < (len(arr) - 1); {
if i != pos {
new_arr[i] = arr[k]
k++
i++
} else {
k++
}
}
for i := 0; i < (len(arr) - 1); i++ {
fmt.Println(new_arr[i])
}
I am using this command to delete an element from a Slice but it is not working, please suggest.
",https://stackoverflow.com/questions/37334119/how-to-delete-an-element-from-a-slice-in-golang,382,805257.0,24.0,,,2016-05-19 21:15:37,2025-06-24 19:43:55,2022-05-05 06:32:53,,,go;slice,Anchal Sarraf,4019,1683398,registered,true,,,CC BY-SA 4.0,2022-04-04 19:37:11,452,421,1,0,0,2,false,false,false,true,true,true,47,10,false,0.03,0.0005,3838,2016,5,21,Thursday,false,false,false,false,false,false,false
18537257,How to get the directory of the currently running file?,"In nodejs I use __dirname . What is the equivalent of this in Golang?
I have googled and found out this article http://andrewbrookins.com/tech/golang-get-directory-of-the-current-file/ . Where he uses below code
_, filename, _, _ := runtime.Caller(1)
f, err := os.Open(path.Join(path.Dir(filename), ""data.csv""))
But is it the right way or idiomatic way to do in Golang?
",https://stackoverflow.com/questions/18537257/how-to-get-the-directory-of-the-currently-running-file,378,390959.0,19.0,,,2013-08-30 16:07:42,2024-12-10 10:46:21,2017-07-19 23:12:39,,,go,ekanna,5842,900097,registered,true,18537792,,CC BY-SA 3.0,,571,374,1,2,0,1,true,false,false,true,true,true,55,10,true,0.049,0.001,4831,2013,8,16,Friday,false,false,false,false,false,false,false
21001387,How do I SET the GOPATH environment variable on Ubuntu? What file must I edit?,"I am trying to do a go get:
go get github.com/go-sql-driver/mysql
and it fails with the following error:
package github.com/go-sql-driver/mysql: cannot download, $GOPATH not set. For more details see: go help gopath
when I do a go env , a list of Go values is shown as below:
ubuntu@ip-xxx-x-xx-x:~$ go env
GOARCH=""amd64""
GOBIN=""""
GOCHAR=""6""
GOEXE=""""
GOHOSTARCH=""amd64""
GOHOSTOS=""linux""
GOOS=""linux""
GOPATH=""""
GORACE=""""
GOROOT=""/usr/lib/go""
GOTOOLDIR=""/usr/lib/go/pkg/tool/linux_amd64""
CC=""gcc""
GOGCCFLAGS=""-g -O2 -fPIC -m64 -pthread""
CGO_ENABLED=""1""
clearly the GOPATH is not set, how and where do I set it?
I see many threads that mention this error but none that provide an answer to my question, which file needs to be edited to provide a value for this path?
",https://stackoverflow.com/questions/21001387/how-do-i-set-the-gopath-environment-variable-on-ubuntu-what-file-must-i-edit,375,836198.0,28.0,,,2014-01-08 16:36:55,2023-10-14 09:57:23,2019-04-01 21:50:20,,,linux;ubuntu;go,David Saintloth,4261,605566,registered,true,,,CC BY-SA 4.0,,907,774,5,0,0,3,false,false,false,true,true,true,78,15,true,0.033,0.0004,4700,2014,1,16,Wednesday,false,false,false,false,false,false,false
9320862,Why would I make() or new()?,"The introduction documents dedicate many paragraphs to explaining the difference between new() and make(), but in practice, you can create objects within local scope and return them.
Why would you use the pair of allocators?
",https://stackoverflow.com/questions/9320862/why-would-i-make-or-new,373,231152.0,12.0,,,2012-02-16 23:42:55,2026-01-12 16:19:11,2019-05-10 16:39:55,,,go,salezica,77817,469300,registered,true,9325620,,CC BY-SA 4.0,,266,226,2,0,0,1,true,false,false,true,true,true,28,6,true,0.052,0.0016,5392,2012,2,23,Thursday,false,false,false,false,false,false,false
19038598,How can I pretty-print JSON using Go?,"Does anyone know of a simple way to pretty-print JSON output in Go?
I'd like to pretty-print the result of json.Marshal, as well as formatting an existing string of JSON so it's easier to read.
",https://stackoverflow.com/questions/19038598/how-can-i-pretty-print-json-using-go,370,393909.0,16.0,,,2013-09-26 20:59:03,2023-10-05 09:59:24,2022-10-18 22:57:03,,,json;go;pretty-print,Brad Peabody,11517,961810,registered,true,19038873,,CC BY-SA 4.0,,221,194,1,0,0,3,true,false,false,true,true,true,37,7,true,0.041,0.0009,4804,2013,9,20,Thursday,false,false,false,false,false,false,false
1736014,Delete key in map,"I have a map:
var sessions = map[string] chan int{}
How do I delete sessions[key]? I tried:
sessions[key] = nil,false;
That didn't work.
Update (November 2011):
The special syntax for deleting map entries is removed in Go version 1:
Go 1 will remove the special map assignment and introduce a new built-in function, delete: delete(m, x) will delete the map entry retrieved by the expression m[x]. ...
",https://stackoverflow.com/questions/1736014/delete-key-in-map,367,442539.0,5.0,,,2009-11-14 23:46:43,2022-04-25 16:15:12,2021-11-24 12:26:17,,,dictionary;go,jonaz,4204,148907,registered,true,1736256,,CC BY-SA 4.0,2024-03-28 18:13:19,717,407,6,1,0,2,true,false,false,true,true,true,17,4,false,0.011,0.0008,6216,2009,11,23,Saturday,true,false,false,false,false,false,false
19310700,What is a rune?,"What is a rune in Go?
I've been googling but Golang only says in one line: rune is an alias for int32.
But how come integers are used all around like swapping cases?
The following is a function swapcase.
What is all the <= and -?
And why doesn't switch have any arguments?
&& should mean and but what is r <= 'z'?
func SwapRune(r rune) rune {
switch {
case 'a' <= r && r <= 'z':
return r - 'a' + 'A'
case 'A' <= r && r <= 'Z':
return r - 'A' + 'a'
default:
return r
}
}
Most of them are from http://play.golang.org/p/H6wjLZj6lW
func SwapCase(str string) string {
return strings.Map(SwapRune, str)
}
I understand this is mapping rune to string so that it can return the swapped string. But I do not understand how exactly rune or byte works here.
",https://stackoverflow.com/questions/19310700/what-is-a-rune,350,216542.0,11.0,,,2013-10-11 05:14:57,2024-07-11 19:10:39,2022-06-13 04:42:40,,,go;terminology;rune,user2671513,,,does_not_exist,true,19311218,,CC BY-SA 4.0,,1176,848,14,1,0,3,true,false,false,true,false,true,15,4,true,0.051,0.0016,4789,2013,10,5,Friday,false,false,false,false,false,false,false
16935965,How to run test cases in a specified file?,"My package test cases are scattered across multiple files, if I run go test <package_name> it runs all test cases in the package.
It is unnecessary to run all of them though. Is there a way to specify a file for go test to run, so that it only runs test cases defined in the file?
",https://stackoverflow.com/questions/16935965/how-to-run-test-cases-in-a-specified-file,349,379177.0,9.0,,,2013-06-05 09:14:29,2024-12-26 23:45:41,,,,go,user972946,,,does_not_exist,true,16936314,,CC BY-SA 3.0,,328,288,2,0,0,1,true,false,false,true,false,false,42,9,true,0.024,0.0009,4917,2013,6,9,Wednesday,false,false,false,false,false,false,false
21197239,Decoding JSON using json.Unmarshal vs json.NewDecoder.Decode,"I'm developing an API client where I need to encode a JSON payload on request and decode a JSON body from the response.
I've read the source code from several libraries and from what I have seen, I have basically two possibilities for encoding and decoding a JSON string.
Use json.Unmarshal passing the entire response string
data, err := ioutil.ReadAll(resp.Body)
if err == nil && data != nil {
err = json.Unmarshal(data, value)
}
or using json.NewDecoder.Decode
err = json.NewDecoder(resp.Body).Decode(value)
In my case, when dealing with HTTP responses that implements io.Reader, the second version seems to be require less code, but since I've seen both I wonder if there is any preference whether I should use a solution rather than the other.
Moreover, the accepted answer from this question says
Please use json.Decoder instead of json.Unmarshal.
but it didn't mention the reason. Should I really avoid using json.Unmarshal?
",https://stackoverflow.com/questions/21197239/decoding-json-using-json-unmarshal-vs-json-newdecoder-decode,342,144028.0,3.0,,,2014-01-17 22:34:55,2026-02-16 21:53:47,2019-08-11 14:38:02,,,json;go,Simone Carletti,177685,123527,registered,true,21198571,,CC BY-SA 4.0,,1334,959,8,2,0,2,true,false,false,true,true,true,60,6,false,0.021,0.0024,4691,2014,1,22,Friday,false,false,false,false,false,false,false
16465705,How to handle configuration in Go,"What is the preferred way to handle configuration parameters for a Go program (the kind of stuff one might use properties files or ini files for, in other contexts)?
",https://stackoverflow.com/questions/16465705/how-to-handle-configuration-in-go,341,262069.0,13.0,,,2013-05-09 15:41:12,2022-12-29 00:50:05,2022-12-29 00:50:05,2015-11-16 22:02:18,Needs more focus,go;configuration-files,theglauber,30105,1118101,registered,true,16466189,,,,191,166,0,0,0,2,true,true,false,true,true,true,33,6,false,0.05,0.0013,4944,2013,5,15,Thursday,false,false,false,false,false,false,false
27500861,What's the proper way to "go get" a private repository?,"I'm searching for the way to get $ go get work with private repository, after many google try.
The first try:
$ go get -v gitlab.com/secmask/awserver-go
Fetching https://gitlab.com/secmask/awserver-go?go-get=1
https fetch failed.
Fetching http://gitlab.com/secmask/awserver-go?go-get=1
Parsing meta tags from http://gitlab.com/secmask/awserver-go?go-get=1 (status code 200)
import ""gitlab.com/secmask/awserver-go"": parse http://gitlab.com/secmask/awserver-go?go-get=1: no go-import meta tags
package gitlab.com/secmask/awserver-go: unrecognized import path ""gitlab.com/secmask/awserver-go
Yep, it did not see the meta tags because I could not know how to provide login information.
The second try:
Follow https://gist.github.com/shurcooL/6927554. Add config to .gitconfig.
[url ""ssh://git@gitlab.com/""]
insteadOf = https://gitlab.com/
$ go get -v gitlab.com/secmask/awserver-go --> not work
$ go get -v gitlab.com/secmask/awserver-go.git --> work but I got src/gitlab.com/secmask/awserer-go.git
Yes it work but with .git extension with my project name, I can rename it to original but do it everytime $ go get is not so good, is there an otherway?
",https://stackoverflow.com/questions/27500861/whats-the-proper-way-to-go-get-a-private-repository,337,403026.0,22.0,,,2014-12-16 09:00:51,2026-10-06 23:44:30,2018-11-16 16:51:49,,,git;go,secmask,8257,304778,registered,true,,,CC BY-SA 4.0,2024-08-28 13:46:33,1370,1169,5,1,0,2,false,false,false,true,true,true,69,10,true,0.055,0.0008,4358,2014,12,9,Tuesday,false,false,false,false,false,false,false
8270816,Converting Go struct to JSON,"I am trying to convert a Go struct to JSON using the json package but all I get is {}. I am certain it is something totally obvious but I don't see it.
package main
import (
""fmt""
""encoding/json""
)
type User struct {
name string
}
func main() {
user := &User{name:""Frank""}
b, err := json.Marshal(user)
if err != nil {
fmt.Printf(""Error: %s"", err)
return;
}
fmt.Println(string(b))
}
Then when I try to run it I get this:
$ 6g test.go && 6l -o test test.6 && ./test
{}
",https://stackoverflow.com/questions/8270816/converting-go-struct-to-json,337,564405.0,2.0,,,2011-11-25 14:54:57,2024-07-15 10:49:17,2024-07-15 10:49:17,2024-07-15 10:50:23,Duplicate,json;go,magiconair,7027,244749,registered,true,8271160,,,,632,544,4,0,0,2,true,true,false,true,true,true,28,5,false,0.004,0.0006,5475,2011,11,14,Friday,false,false,false,false,false,false,false
15672556,Handling JSON Post Request in Go,"So I have the following, which seems incredibly hacky, and I've been thinking to myself that Go has better designed libraries than this, but I can't find an example of Go handling a POST request of JSON data. They are all form POSTs.
Here is an example request: curl -X POST -d ""{\""test\"": \""that\""}"" http://localhost:8082/test
And here is the code, with the logs embedded:
package main
import (
""encoding/json""
""log""
""net/http""
)
type test_struct struct {
Test string
}
func test(rw http.ResponseWriter, req *http.Request) {
req.ParseForm()
log.Println(req.Form)
//LOG: map[{""test"": ""that""}:[]]
var t test_struct
for key, _ := range req.Form {
log.Println(key)
//LOG: {""test"": ""that""}
err := json.Unmarshal([]byte(key), &t)
if err != nil {
log.Println(err.Error())
}
}
log.Println(t.Test)
//LOG: that
}
func main() {
http.HandleFunc(""/test"", test)
log.Fatal(http.ListenAndServe("":8082"", nil))
}
There's got to be a better way, right? I'm just stumped in finding what the best practice could be.
(Go is also known as Golang to the search engines, and mentioned here so others can find it.)
",https://stackoverflow.com/questions/15672556/handling-json-post-request-in-go,333,411630.0,9.0,,,2013-03-28 01:16:07,2025-05-07 09:43:08,,,,json;go,TomJ,5509,983290,registered,true,15685432,,CC BY-SA 3.0,,1286,1214,2,0,0,2,true,false,false,true,true,false,32,6,false,0.022,0.0008,4986,2013,3,1,Thursday,false,false,false,false,false,false,false
18125625,Constructors in Go,"I have a struct and I would like it to be initialised with some sensible default values.
Typically, the thing to do here is to use a constructor but since go isn't really OOP in the traditional sense these aren't true objects and it has no constructors.
I have noticed the init method but that is at the package level. Is there something else similar that can be used at the struct level?
If not what is the accepted best practice for this type of thing in Go?
",https://stackoverflow.com/questions/18125625/constructors-in-go,331,260940.0,11.0,,,2013-08-08 12:06:52,2023-07-25 15:38:46,2014-11-07 12:10:27,,,oop;constructor;go,Marty Wallace,36194,1189880,registered,true,18125763,,CC BY-SA 3.0,,493,465,0,0,0,3,true,false,false,true,true,true,18,3,false,0.042,0.0013,4853,2013,8,12,Thursday,false,false,false,false,false,false,false
14668850,List directory in Go,"I've been trying to figure out how to simply list the files and folders in a single directory in Go.
I've found filepath.Walk, but it goes into sub-directories automatically, which I don't want. All of my other searches haven't turned anything better up.
I'm sure that this functionality exists, but it's been really hard to find. Let me know if anyone knows where I should look. Thanks.
",https://stackoverflow.com/questions/14668850/list-directory-in-go,325,357946.0,7.0,,,2013-02-03 02:17:54,2025-01-06 16:34:10,2016-08-03 13:46:31,,,go,Behram Mistree,4378,841810,registered,true,14668907,,CC BY-SA 3.0,,485,395,1,1,0,1,true,false,false,true,true,true,20,4,false,0.02,0.0009,5039,2013,2,2,Sunday,true,false,false,false,false,false,false
21950244,Is there a way to iterate over a range of integers?,"Go's range can iterate over maps and slices, but I was wondering if there is a way to iterate over a range of numbers, something like this:
for i := range [1..10] {
fmt.Println(i)
}
Or is there a way to represent range of integers in Go like how Ruby does with the class Range?
",https://stackoverflow.com/questions/21950244/is-there-a-way-to-iterate-over-a-range-of-integers,324,375275.0,15.0,,,2014-02-22 05:39:15,2024-04-15 13:28:29,2021-06-01 19:15:59,,,loops;go;integer;range,Vishnu,4845,1553655,registered,true,21951131,,CC BY-SA 4.0,,401,285,1,1,0,4,true,false,false,true,true,true,51,11,true,0.04,0.0009,4655,2014,2,5,Saturday,true,false,false,false,false,false,false
16353016,How to `go test` all tests in my project?,"The go test command covers *_test.go files in only one dir.
I want to go test the whole project, which means the test should cover all *_test.go files in the dir ./ and every children tree dir under the dir ./.
What's the command to do this?
",https://stackoverflow.com/questions/16353016/how-to-go-test-all-tests-in-my-project,322,171502.0,4.0,,,2013-05-03 06:33:28,2026-04-26 19:34:15,2020-11-05 21:58:18,,,testing;go,hardPass,21241,1316684,registered,true,16353449,,CC BY-SA 4.0,,341,242,6,0,0,2,true,false,false,true,true,true,41,9,true,0.023,0.0019,4950,2013,5,6,Friday,false,false,false,false,false,false,false
12753805,Type converting slices of interfaces,"I'm curious why Go does't implicitly convert []T to []interface{} when it will implicitly convert T to interface{}. Is there something non-trivial about this conversion that I'm missing?
Example:
func foo([]interface{}) { /* do something */ }
func main() {
var a []string = []string{""hello"", ""world""}
foo(a)
}
go build complains
cannot use a (type []string) as type []interface {} in function argument
And if I try to do it explicitly, same thing: b := []interface{}(a) complains
cannot convert a (type []string) to type []interface {}
So every time I need to do this conversion (which seems to come up a lot), I've been doing something like this:
b = make([]interface{}, len(a), len(a))
for i := range a {
b[i] = a[i]
}
Is there a better way to do this, or standard library functions to help with these conversions? It seems kind of silly to write 4 extra lines of code every time I want to call a function that can take a list of e.g. ints or strings.
",https://stackoverflow.com/questions/12753805/type-converting-slices-of-interfaces,317,190758.0,10.0,,,2012-10-05 20:48:07,2025-02-27 02:42:28,2019-08-02 10:32:08,,,go;go-reflect;go-interface,danny,10633,480815,registered,true,12754757,,CC BY-SA 4.0,,1224,992,8,0,0,3,true,false,false,true,true,true,36,5,false,0.052,0.0017,5160,2012,10,20,Friday,false,false,false,false,false,false,false
21220077,What does an underscore in front of an import statement mean?,"In this code from go-sqlite3:
import (
"database/sql"
"fmt"
_ "github.com/mattn/go-sqlite3"
"log"
"os"
)
what does the underscore in the import statement mean?
",https://stackoverflow.com/questions/21220077/what-does-an-underscore-in-front-of-an-import-statement-mean,315,81662.0,5.0,,,2014-01-19 17:25:59,2022-11-27 21:52:39,2022-09-16 15:01:51,,,go;import,Adrian,20258,340554,registered,true,21225073,,CC BY-SA 4.0,,407,251,2,1,0,2,true,false,false,true,true,true,61,11,true,0.061,0.0039,4689,2014,1,17,Sunday,true,false,false,false,false,false,false
13514184,How can I read a whole file into a string variable,"I have lots of small files, I don't want to read them line by line.
Is there a function in Go that will read a whole file into a string variable?
",https://stackoverflow.com/questions/13514184/how-can-i-read-a-whole-file-into-a-string-variable,308,297778.0,6.0,,,2012-11-22 13:52:46,2023-08-22 12:05:54,2018-07-13 21:46:28,,,string;file;go,WoooHaaaa,20654,802585,registered,true,13514395,,CC BY-SA 4.0,,161,147,0,0,0,3,true,false,false,true,true,true,50,11,false,0.02,0.001,5112,2012,11,13,Thursday,false,false,false,false,false,false,false
23205419,How do you print in a Go test using the "testing" package?,"I'm running a test in Go with a statement to print something (i.e. for debugging of tests) but it's not printing anything.
func TestPrintSomething(t *testing.T) {
fmt.Println(""Say hi"")
}
When I run go test on this file, this is the output:
ok command-line-arguments 0.004s
The only way to really get it to print, as far as I know, is to print it via t.Error(), like so:
func TestPrintSomethingAgain(t *testing.T) {
t.Error(""Say hi"")
}
Which outputs this:
Say hi
--- FAIL: TestPrintSomethingAgain (0.00 seconds)
foo_test.go:35: Say hi
FAIL
FAIL command-line-arguments 0.003s
gom: exit status 1
I've Googled and looked through the manual but didn't find anything.
",https://stackoverflow.com/questions/23205419/how-do-you-print-in-a-go-test-using-the-testing-package,303,333925.0,9.0,,,2014-04-21 20:27:09,2024-02-28 12:15:58,,,,testing;go,platwp,3405,3284581,registered,true,23205771,,CC BY-SA 3.0,,829,698,4,0,0,2,true,false,false,true,true,false,68,12,true,0.027,0.0009,4597,2014,4,20,Monday,false,false,false,false,false,false,false
17306358,Removing fields from struct or hiding them in JSON Response,"I've created an API in Go that, upon being called, performs a query, creates an instance of a struct, and then encodes that struct as JSON before sending back to the caller. I'd now like to allow the caller to be able to select the specific fields they would like returned by passing in a "fields" GET parameter.
This means depending on the fields value(s), my struct would change. Is there any way to remove fields from a struct? Or at least hide them in the JSON response dynamically? (Note: Sometimes I have empty values so the JSON omitEmpty tag will not work here) If neither of these are possible, is there a suggestion on a better way to handle this?
A smaller version of the structs I'm using are below:
type SearchResult struct {
Date string `json:"date"`
IdCompany int `json:"idCompany"`
Company string `json:"company"`
IdIndustry interface{} `json:"idIndustry"`
Industry string `json:"industry"`
IdContinent interface{} `json:"idContinent"`
Continent string `json:"continent"`
IdCountry interface{} `json:"idCountry"`
Country string `json:"country"`
IdState interface{} `json:"idState"`
State string `json:"state"`
IdCity interface{} `json:"idCity"`
City string `json:"city"`
} //SearchResult
type SearchResults struct {
NumberResults int `json:"numberResults"`
Results []SearchResult `json:"results"`
} //type SearchResults
I then encode and output the response like so:
err := json.NewEncoder(c.ResponseWriter).Encode(&msg)
",https://stackoverflow.com/questions/17306358/removing-fields-from-struct-or-hiding-them-in-json-response,302,348479.0,17.0,,,2013-06-25 19:56:20,2025-08-18 09:34:35,2020-08-31 09:10:45,,,json;go,user387049,6935,387049,registered,true,17306470,,CC BY-SA 4.0,,1852,1776,2,0,0,2,true,false,false,true,true,true,59,10,false,0.049,0.0009,4897,2013,6,19,Tuesday,false,false,false,false,false,false,false
29746123,Convert byte slice to io.Reader,"In my project, I have a byte slice from a request's response.
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
log.Println(""StatusCode为"" + strconv.Itoa(resp.StatusCode))
return
}
respByte, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Println(""fail to read response data"")
return
}
This works, but if I want to get the response's body for io.Reader, how do I convert? I tried the newreader/writer but wasn't successful.
",https://stackoverflow.com/questions/29746123/convert-byte-slice-to-io-reader,302,254340.0,2.0,,,2015-04-20 11:05:35,2023-05-22 11:20:14,2019-04-23 09:53:54,,,go,Chan Willson,3053,2353374,registered,true,,,CC BY-SA 4.0,2022-07-12 20:14:31,507,456,2,0,0,1,false,false,false,true,true,true,31,5,false,0.008,0.0012,4233,2015,4,11,Monday,false,false,false,false,false,false,false
23051973,What is the `zero` value for time.Time in Go?,"In an error condition, I tried to return nil, which throws the error:
cannot use nil as type time.Time in return argument
What is the zero value for time.Time?
",https://stackoverflow.com/questions/23051973/what-is-the-zero-value-for-time-time-in-go,301,288094.0,4.0,,,2014-04-14 04:29:54,2024-01-26 06:14:46,,,,time;go;null,Mingyu,33919,1246262,registered,true,23051997,,CC BY-SA 3.0,,240,163,4,0,0,3,true,false,false,true,true,false,45,9,true,0.014,0.001,4604,2014,4,4,Monday,false,false,false,false,false,false,false
12864302,How to set headers in http get request?,"I'm doing a simple http GET in Go:
client := &http.Client{}
req, _ := http.NewRequest(""GET"", url, nil)
res, _ := client.Do(req)
But I can't found a way to customize the request header in the doc, thanks
",https://stackoverflow.com/questions/12864302/how-to-set-headers-in-http-get-request,298,347991.0,4.0,,,2012-10-12 17:33:03,2022-05-20 06:42:51,2016-03-18 16:32:23,,,http;go,wong2,36168,325241,registered,true,12864342,,CC BY-SA 3.0,,311,210,1,1,0,2,true,false,false,true,true,true,39,8,true,0.011,0.0009,5153,2012,10,17,Friday,false,false,false,false,false,false,false
48882691,Force retesting or disable test caching,"Problem:
When I run the same go test twice the second run is not done at all. The results are the cached ones from the first run.
PASS
ok tester/apitests (cached)
Links
I already checked https://golang.org/cmd/go/#hdr-Testing_flags but there is no cli flag for that purpose.
Question:
Is there a possibility to force go test to always run test and not to cache test results.
",https://stackoverflow.com/questions/48882691/force-retesting-or-disable-test-caching,295,282932.0,5.0,,,2018-02-20 10:10:53,2022-10-12 21:09:32,2018-02-20 10:13:57,,,testing;go,Simon Frey,3139,7533177,registered,true,48882892,,CC BY-SA 3.0,,604,394,1,1,0,2,true,false,false,true,true,true,39,6,false,0.018,0.001,3196,2018,2,10,Tuesday,false,false,false,false,false,false,false
11268943,"Is it possible to capture a Ctrl+C signal (SIGINT) and run a cleanup function, in a "defer" fashion?","I want to capture the Ctrl+C (SIGINT) signal sent from the console and print out some partial run totals.
",https://stackoverflow.com/questions/11268943/is-it-possible-to-capture-a-ctrlc-signal-sigint-and-run-a-cleanup-function-i,295,187094.0,11.0,,,2012-06-29 21:05:52,2025-07-17 12:31:32,2023-02-01 07:22:01,,,signals;go;sigterm,Sebastián Grignoli,33792,290221,registered,true,11269077,,CC BY-SA 4.0,,148,106,1,0,0,3,true,false,false,true,true,true,110,18,true,0.059,0.0016,5258,2012,6,21,Friday,false,false,false,false,false,false,false
22535775,How to get the last element of a slice?,"What is the Go way for extracting the last element of a slice?
var slice []int
slice = append(slice, 2)
slice = append(slice, 7)
slice[len(slice)-1:][0] // Retrieves the last element
The solution above works, but seems awkward.
",https://stackoverflow.com/questions/22535775/how-to-get-the-last-element-of-a-slice,293,283710.0,4.0,,,2014-03-20 14:19:36,2022-10-21 20:42:27,2019-08-13 12:32:00,,,go;slice,Morgan Wilde,17543,860635,registered,true,22535888,,CC BY-SA 4.0,,271,233,1,0,0,2,true,false,false,true,true,true,39,9,true,0.014,0.001,4629,2014,3,14,Thursday,false,false,false,false,false,false,false
53682247,How to point Go module dependency in go.mod to a latest commit in a repo?,"Starting with v1.11 Go added support for modules. Commands
go mod init <package name>
go build
would generate go.mod and go.sum files that contain all found versions for the package dependencies. If a module does not have any releases, the latest commit of that module is used. If a module does have releases, the latest one is picked as a dependency.
However sometimes I would need functionality that is not in a published release yet, but from a commit made after that release. How do I set go.mod to point not to a release of a module, but to a specific commit in the module's repository? It looks like I can do it by hand in go.mod with
module /my/module
require (
...
github.com/someone/some_module v0.0.0-20181121201909-af044c0995fe
...
)
where v0.0.0 does not correspond to the last published release tag, 20181121201909 would be a commit timestamp and af044c0995fe would be the commit hash? Should such information to be found and entered by hand, or there is a better way?
",https://stackoverflow.com/questions/53682247/how-to-point-go-module-dependency-in-go-mod-to-a-latest-commit-in-a-repo,292,349399.0,8.0,,,2018-12-08 11:53:31,2025-03-27 20:55:07,2023-04-26 14:10:36,,,git;go;module,dimus,9530,23080,registered,true,53682399,,CC BY-SA 4.0,,1254,1007,9,0,0,3,true,false,false,true,true,true,73,15,true,0.023,0.0008,2905,2018,12,11,Saturday,true,false,false,false,false,false,false
37135193,How to set default values in Go structs,"There are multiple answers/techniques to the below question:
- How to set default values to golang structs?
- How to initialize structs in golang
I have a couple of answers but further discussion is required.
",https://stackoverflow.com/questions/37135193/how-to-set-default-values-in-go-structs,290,420817.0,9.0,,,2016-05-10 10:00:52,2025-11-14 11:01:09,2018-07-13 21:44:44,,,go;struct;initialization;default-value,Prateek,7276,2077459,registered,true,37521991,,CC BY-SA 4.0,,250,209,0,0,0,4,true,false,false,true,true,true,39,8,false,0.021,0.0007,3847,2016,5,10,Tuesday,false,false,false,false,false,false,false
13137463,Declare a constant array,"I have tried:
const ascii = "abcdefghijklmnopqrstuvwxyz"
const letter_goodness []float32 = { .0817,.0149,.0278,.0425,.1270,.0223,.0202, .0609,.0697,.0015,.0077,.0402,.0241,.0675, .0751,.0193,.0009,.0599,.0633,.0906,.0276, .0098,.0236,.0015,.0197,.0007 }
const letter_goodness = { .0817,.0149,.0278,.0425,.1270,.0223,.0202, .0609,.0697,.0015,.0077,.0402,.0241,.0675, .0751,.0193,.0009,.0599,.0633,.0906,.0276, .0098,.0236,.0015,.0197,.0007 }
const letter_goodness = []float32 { .0817,.0149,.0278,.0425,.1270,.0223,.0202, .0609,.0697,.0015,.0077,.0402,.0241,.0675, .0751,.0193,.0009,.0599,.0633,.0906,.0276, .0098,.0236,.0015,.0197,.0007 }
The first declaration and initialization works fine, but the second, third and fourth don't work.
How can I declare and initialize a const array of floats?
",https://stackoverflow.com/questions/13137463/declare-a-constant-array,285,357258.0,6.0,,,2012-10-30 10:53:27,2025-09-07 19:32:59,2020-08-12 03:07:25,,,arrays;go;constants,ceth,45635,205270,registered,true,13137568,,CC BY-SA 4.0,,852,807,1,0,0,3,true,false,false,true,true,true,24,4,false,0.017,0.0008,5135,2012,10,10,Tuesday,false,false,false,false,false,false,false
8593645,Is it OK to leave a channel open?,"Is it OK to leave a Go channel open forever (never close the channel) if I never check for its state? Will it lead to memory leaks? Is the following code OK?
func (requestCh chan<- Request) GetResponse(data RequestData) Response {
reply := make(chan Response)
requestCh <- Request{data: data, replyCh: reply}
return <-reply
}
",https://stackoverflow.com/questions/8593645/is-it-ok-to-leave-a-channel-open,282,93972.0,8.0,,,2011-12-21 17:12:38,2022-12-12 12:50:18,2013-04-01 04:44:14,,,go;channel,Kluyg,5417,91570,registered,true,8593986,,CC BY-SA 3.0,,380,349,1,0,0,2,true,false,false,true,true,true,33,8,true,0.085,0.003,5449,2011,12,17,Wednesday,false,false,false,false,false,false,false
14289256,cannot convert data (type interface {}) to type string: need type assertion,"I am pretty new to go and I was playing with this notify package.
At first I had code that looked like this:
func doit(w http.ResponseWriter, r *http.Request) {
notify.Post(""my_event"", ""Hello World!"")
fmt.Fprint(w, ""+OK"")
}
I wanted to append newline to Hello World! but not in the function doit above, because that would be pretty trivial, but in the handler afterwards like this below:
func handler(w http.ResponseWriter, r *http.Request) {
myEventChan := make(chan interface{})
notify.Start(""my_event"", myEventChan)
data := <-myEventChan
fmt.Fprint(w, data + ""\n"")
}
After go run:
$ go run lp.go
# command-line-arguments
./lp.go:15: invalid operation: data + ""\n"" (mismatched types interface {} and string)
After a little bit of Googling I found this question on SO.
Then I updated my code to:
func handler(w http.ResponseWriter, r *http.Request) {
myEventChan := make(chan interface{})
notify.Start(""my_event"", myEventChan)
data := <-myEventChan
s:= data.(string) + ""\n""
fmt.Fprint(w, s)
}
Is this what I was supposed to do? My compiler errors are gone so I guess that's pretty good? Is this efficient? Should you do it differently?
",https://stackoverflow.com/questions/14289256/cannot-convert-data-type-interface-to-type-string-need-type-assertion,280,298505.0,5.0,,,2013-01-12 01:27:57,2024-09-24 14:41:36,2017-05-23 12:26:35,,,go;type-mismatch,Alfred,62093,11926,registered,true,14289568,,CC BY-SA 3.0,,1543,1202,8,2,0,2,true,false,false,true,true,true,75,12,false,0.017,0.0009,5061,2013,1,1,Saturday,true,false,false,false,false,false,false
8513609,Does Go provide a REPL?,"The interactive environment is VERY helpful for a programmer. However, it seems Go does not provide it. Is my understanding correct?
",https://stackoverflow.com/questions/8513609/does-go-provide-a-repl,279,83022.0,14.0,,,2011-12-15 00:21:57,2024-04-20 14:21:03,2024-04-20 14:21:03,,,go;read-eval-print-loop,z_axis,8530,777131,registered,true,8517411,,CC BY-SA 4.0,,141,134,0,0,0,2,true,false,false,true,true,true,23,5,true,0.169,0.0034,5455,2011,12,0,Thursday,false,false,false,false,false,false,false
10383498,How does Go update third-party packages?,"Looking how actively golang packages grow and improve I wonder how the problem with package versions is solved?
I see that one way is to store third-party packages under a project folder.
But what if I install it with go get?
",https://stackoverflow.com/questions/10383498/how-does-go-update-third-party-packages,278,252929.0,9.0,,,2012-04-30 12:11:42,2025-04-21 00:50:33,,,,go,shalakhin,4946,1262525,registered,true,10383783,,CC BY-SA 3.0,,262,228,1,0,0,1,true,false,false,true,true,false,40,6,true,0.036,0.0011,5318,2012,4,12,Monday,false,false,false,false,false,false,false
28999735,What is the shortest way to simply sort an array of structs by (arbitrary) field names?,"I just had a problem where I had an array of structs, e.g.
package main
import ""log""
type Planet struct {
Name string `json:""name""`
Aphelion float64 `json:""aphelion""` // in million km
Perihelion float64 `json:""perihelion""` // in million km
Axis int64 `json:""Axis""` // in km
Radius float64 `json:""radius""`
}
func main() {
var mars = new(Planet)
mars.Name = ""Mars""
mars.Aphelion = 249.2
mars.Perihelion = 206.7
mars.Axis = 227939100
mars.Radius = 3389.5
var earth = new(Planet)
earth.Name = ""Earth""
earth.Aphelion = 151.930
earth.Perihelion = 147.095
earth.Axis = 149598261
earth.Radius = 6371.0
var venus = new(Planet)
venus.Name = ""Venus""
venus.Aphelion = 108.939
venus.Perihelion = 107.477
venus.Axis = 108208000
venus.Radius = 6051.8
planets := [...]Planet{*mars, *venus, *earth}
log.Println(planets)
}
Lets say you want to sort it by Axis. How do you do that?
(Note: I have seen http://golang.org/pkg/sort/ and it seems to work, but I have to add about 20 lines just for simple sorting by a very simple key. I have a python background where it is as simple as sorted(planets, key=lambda n: n.Axis) - is there something similar simple in Go?)
",https://stackoverflow.com/questions/28999735/what-is-the-shortest-way-to-simply-sort-an-array-of-structs-by-arbitrary-field,275,244369.0,8.0,,,2015-03-12 00:07:48,2024-01-12 19:47:44,2019-10-03 03:19:09,,,sorting;go,Martin Thoma,139375,562769,registered,true,29000001,,CC BY-SA 4.0,,1414,1284,3,1,0,2,true,false,false,true,true,true,87,16,true,0.033,0.0011,4272,2015,3,0,Thursday,false,false,false,false,false,false,false
28256923,Import cycle not allowed,"I have a problem with
import cycle not allowed
It appears when I am trying to test my controller. Here is the output:
can't load package: import cycle not allowed
package project/controllers/account
imports project/controllers/base
imports project/components/mux
imports project/controllers/account
import cycle not allowed
package project/controllers/account
imports project/controllers/base
imports project/components/mux
imports project/controllers/account
import cycle not allowed
package project/controllers/account
imports project/controllers/base
imports project/components/mux
imports project/controllers/routes
imports project/controllers/base
How do I read or understand this error? Where is the dependency wrong?
",https://stackoverflow.com/questions/28256923/import-cycle-not-allowed,273,358809.0,9.0,,,2015-01-31 21:50:08,2025-04-08 18:22:46,2021-06-08 13:03:22,,,go,softshipper,34429,1743843,registered,true,28258647,,CC BY-SA 4.0,2018-07-11 17:05:06,844,767,1,0,0,1,true,false,false,true,true,true,24,4,false,0.025,0.0008,4312,2015,1,21,Saturday,true,false,false,false,false,false,false
12655464,Can functions be passed as parameters?,"In Java I can do something like
derp(new Runnable { public void run () { /* run this sometime later */ } })
and ""run"" the code in the method later. It's a pain to handle (anonymous inner class), but it can be done.
Does Go have something that can facilitate a function/callback being passed in as a parameter?
",https://stackoverflow.com/questions/12655464/can-functions-be-passed-as-parameters,273,297572.0,8.0,,,2012-09-29 18:45:33,2021-02-06 04:58:11,2019-09-29 08:14:12,,,function;go,Saad,29236,353217,registered,true,12655719,,CC BY-SA 4.0,,360,315,1,0,0,2,true,false,false,true,true,true,38,6,true,0.027,0.0009,5166,2012,9,18,Saturday,true,false,false,false,false,false,false
6878590,The maximum value for an int type in Go,"How does one specify the maximum value representable for an unsigned integer type?
I would like to know how to initialize min in the loop below that iteratively computes min and max lengths from some structs.
var minLen uint = ???
var maxLen uint = 0
for _, thing := range sliceOfThings {
if minLen > thing.n { minLen = thing.n }
if maxLen < thing.n { maxLen = thing.n }
}
if minLen > maxLen {
// If there are no values, clamp min at 0 so that min <= max.
minLen = 0
}
so that the first time through the comparison, minLen >= n.
",https://stackoverflow.com/questions/6878590/the-maximum-value-for-an-int-type-in-go,270,481302.0,13.0,,,2011-07-29 20:21:51,2022-06-11 21:50:22,2018-07-11 16:45:30,,,numbers;go,Mike Samuel,121009,20394,registered,true,6878625,,CC BY-SA 4.0,,640,556,4,0,0,2,true,false,false,true,true,true,39,9,false,0.027,0.0006,5594,2011,7,20,Friday,false,false,false,false,false,false,false
28153203,"undefined" function declared in another file?,"I'm trying to write a basic go program that calls a function on a different file, but a part of the same package. However, it returns:
undefined: NewEmployee
Here is the source code:
main.go:
package main
func main() {
emp := NewEmployee()
}
employee.go:
package main
type Employee struct {
name string
age int
}
func NewEmployee() *Employee {
p := &Employee{}
return p
}
func PrintEmployee (p *Employee) {
return ""Hello world!""
}
",https://stackoverflow.com/questions/28153203/undefined-function-declared-in-another-file,269,231734.0,14.0,,,2015-01-26 15:27:12,2023-07-28 03:19:46,2021-02-23 09:12:30,,,go;undefined;func,Juan M,4573,2438413,registered,true,28153553,,CC BY-SA 4.0,,602,476,5,0,0,3,true,false,false,true,true,true,56,6,true,0.06,0.0012,4317,2015,1,15,Monday,false,false,false,false,false,false,false
45266784,Go test string contains substring,"How do I check if a string is a substring of another string in Go?
For example, I want to check someString.contains(""something"").
",https://stackoverflow.com/questions/45266784/go-test-string-contains-substring,267,305558.0,3.0,,,2017-07-23 15:27:38,2024-12-09 20:44:37,,,,go;substring,Elliott Beach,11882,5749914,registered,true,45266785,,CC BY-SA 3.0,,150,130,1,0,0,2,true,false,false,true,true,false,33,5,false,0.01,0.0009,3408,2017,7,15,Sunday,true,false,false,false,false,false,false
19200235,Golang tests in sub-directory,"I want to create a package in Go with tests and examples for the package as subdirectories to keep the workspace cleaner. Is this possible and if so how?
All the documentation always puts the testing code in the same place as the other code, is this better in some way or just convention?
",https://stackoverflow.com/questions/19200235/golang-tests-in-sub-directory,263,181168.0,4.0,,,2013-10-05 16:50:04,2024-06-07 12:44:40,2022-07-07 08:21:41,,,unit-testing;go;build,The Graceful Penguin,2744,1111356,registered,true,21725603,,CC BY-SA 4.0,,305,291,0,0,0,3,true,false,false,true,true,true,29,4,false,0.022,0.0015,4795,2013,10,16,Saturday,true,false,false,false,false,false,false
35480623,How to import local packages in go?,"I am new to go and working on an example code that I want to localize.
In the original main.go import statement it was:
import (
"log"
"net/http"
"github.com/foo/bar/myapp/common"
"github.com/foo/bar/myapp/routers"
)
Now I have common and routers package in /home/me/go/src/myapp
So I converted the import statement to:
import (
"log"
"net/http"
"./common"
"./routers"
)
But when I run go install myapp I get these errors:
can't load package: /home/me/go/src/myapp/main.go:7:3: local import "./common" in non-local package
Also, when I use common and routers instead of ./common and ./routers in the import statement, I get:
myapp/main.go:7:3: cannot find package "common" in any of:
/usr/local/go/src/common (from $GOROOT)
/home/me/go/src/common (from $GOPATH)
myapp/main.go:8:2: cannot find package "routers" in any of:
/usr/local/go/src/routers (from $GOROOT)
/home/me/go/src/routers (from $GOPATH)
How can I fix this?
",https://stackoverflow.com/questions/35480623/how-to-import-local-packages-in-go,263,467961.0,12.0,,,2016-02-18 11:47:32,2024-01-28 10:11:39,2020-07-29 10:24:07,,,go,Karlom,15174,5774375,registered,true,35511866,,CC BY-SA 4.0,,1347,1085,13,0,0,1,true,false,false,true,true,true,35,7,true,0.026,0.0006,3929,2016,2,11,Thursday,false,false,false,false,false,false,false
2976630,How does Go compile so quickly?,"I've Googled and poked around the Go website, but I can't find an explanation for Go's extraordinary build times. Are they products of the language features (or lack thereof), a highly optimized compiler, or something else? I'm not trying to promote Go; I'm just curious.
",https://stackoverflow.com/questions/2976630/how-does-go-compile-so-quickly,262,83573.0,12.0,,,2010-06-04 18:10:12,2024-01-21 10:35:29,2022-03-26 09:24:33,,,performance;go;build;compiler-construction,Evan Kroske,4604,156787,registered,true,2976675,,CC BY-SA 4.0,,279,272,0,0,0,4,true,false,false,true,true,true,31,6,true,0.144,0.0031,6014,2010,6,18,Friday,false,false,false,false,false,false,false
25845172,Parsing RFC-3339 / ISO-8601 date-time string in Go,"I tried parsing the date string "2014-09-12T11:45:26.371Z" in Go. This time format is defined as:
Code
layout := "2014-09-12T11:45:26.371Z"
str := "2014-11-12T11:45:26.371Z"
t, err := time.Parse(layout , str)
I got this error:
parsing time "2014-11-12T11:47:39.489Z": month out of range
How can I parse this date string?
",https://stackoverflow.com/questions/25845172/parsing-rfc-3339-iso-8601-date-time-string-in-go,261,413870.0,8.0,,,2014-09-15 09:47:47,2022-02-23 10:02:44,2022-02-23 10:02:44,,,date;go,kannanrbk,7202,1449101,registered,true,,,CC BY-SA 4.0,,704,404,2,2,0,2,false,false,false,true,true,true,50,8,false,0.019,0.0006,4450,2014,9,9,Monday,false,false,false,false,false,false,false
9985559,Organizing a multiple-file Go project,"Note: this question is related to this one, but two years is a very long time in Go history.
What is the standard way to organize a Go project during development ?
My project is a single package mypack, so I guess I put all the .go files in a mypack directory.
But then, I would like to test it during development so I need at least a file declaring the main package, so that I can do go run trypack.go
How should I organize this ? Do I need to do go install mypack each time I want to try it ?
",https://stackoverflow.com/questions/9985559/organizing-a-multiple-file-go-project,260,175699.0,7.0,,,2012-04-03 00:20:13,2019-04-28 03:03:15,2017-11-10 08:48:49,2019-10-31 19:11:09,Opinion-based,go,Blacksad,15586,820664,registered,true,9985600,,,,731,499,5,1,0,1,true,true,false,true,true,true,37,5,false,0.04,0.0015,5345,2012,4,0,Tuesday,false,false,false,false,false,false,false
19612449,Default value in Go's method,"Is there a way to specify default value in Go's function? I am trying to find this in the documentation but I can't find anything that specifies that this is even possible.
func SaySomething(i string = ""Hello"")(string){
...
}
",https://stackoverflow.com/questions/19612449/default-value-in-gos-method,259,327637.0,5.0,,,2013-10-26 22:10:17,2025-03-31 21:12:42,2022-02-10 04:24:35,,,go;default-value;function-call;default-arguments,denniss,17785,364253,registered,true,19612688,,CC BY-SA 4.0,,259,228,1,0,0,4,true,false,false,true,true,true,32,5,false,0.015,0.0008,4774,2013,10,22,Saturday,true,false,false,false,false,false,false
27775376,Value receiver vs. pointer receiver,"It is very unclear for me in which case I would want to use a value receiver instead of always using a pointer receiver.
To recap from the docs:
type T struct {
a int
}
func (tv T) Mv(a int) int { return 0 } // value receiver
func (tp *T) Mp(f float32) float32 { return 1 } // pointer receiver
The docs also say "For types such as basic types, slices, and small structs, a value receiver is very cheap so unless the semantics of the method requires a pointer, a value receiver is efficient and clear."
First point they docs say a value receiver is "very cheap", but the question is whether it is cheaper than a pointer receiver. So I made a small benchmark (code on gist) which showed me, that pointer receiver is faster even for a struct that has only one string field. These are the results:
// Struct one empty string property
BenchmarkChangePointerReceiver 2000000000 0.36 ns/op
BenchmarkChangeItValueReceiver 500000000 3.62 ns/op
// Struct one zero int property
BenchmarkChangePointerReceiver 2000000000 0.36 ns/op
BenchmarkChangeItValueReceiver 2000000000 0.36 ns/op
(Edit: Please note that second point became invalid in newer go versions, see comments.)
Second point the docs say that a value receiver it is "efficient and clear" which is more a matter of taste, isn't it? Personally I prefer consistency by using the same thing everywhere. Efficiency in what sense? Performance wise it seems pointer are almost always more efficient. Few test-runs with one int property showed minimal advantage of Value receiver (range of 0.01-0.1 ns/op)
Can someone tell me a case where a value receiver clearly makes more sense than a pointer receiver? Or am I doing something wrong in the benchmark? Did I overlook other factors?
",https://stackoverflow.com/questions/27775376/value-receiver-vs-pointer-receiver,259,87261.0,4.0,,,2015-01-05 07:54:11,2025-01-18 08:56:55,2021-03-26 14:15:59,,,function;pointers;go,Chrisport,3196,3210551,registered,true,27775558,,CC BY-SA 4.0,,2079,1836,2,1,0,3,true,false,false,true,true,true,35,5,false,0.046,0.003,4338,2015,1,7,Monday,false,false,false,false,false,false,false
10866195,"Stack vs heap allocation of structs in Go, and how they relate to garbage collection","I'm experiencing a bit of cognitive dissonance between C-style stack-based programming, where automatic variables live on the stack and allocated memory lives on the heap, and Python-style stack-based-programming, where the only thing that lives on the stack are references/pointers to objects on the heap.
As far as I can tell, the two following functions give the same output:
func myFunction() (*MyStructType, error) {
var chunk *MyStructType = new(HeaderChunk)
...
return chunk, nil
}
func myFunction() (*MyStructType, error) {
var chunk MyStructType
...
return &chunk, nil
}
i.e., allocate a new struct and return it.
If I'd written that in C, the first one would have put an object on the heap and the second would have put it on the stack. The first would return a pointer to the heap, the second would return a pointer to the stack, which would have evaporated by the time the function had returned, which would be a Bad Thing.
If I'd written it in Python (or many other modern languages except C#) example 2 would not have been possible.
I get that Go garbage collects both values, so both of the above forms are fine.
To quote:
Note that, unlike in C, it's perfectly OK to return the address of a
local variable; the storage associated with the variable survives
after the function returns. In fact, taking the address of a composite
literal allocates a fresh instance each time it is evaluated, so we
can combine these last two lines.
But it raises a couple of questions.
In example 1, the struct is declared on the heap. What about example 2? Is that declared on the stack in the same way it would be in C or does it go on the heap too?
If example 2 is declared on the stack, how does it stay available after the function returns?
If example 2 is actually declared on the heap, how is it that structs are passed by value rather than by reference? What's the point of pointers in this case?
",https://stackoverflow.com/questions/10866195/stack-vs-heap-allocation-of-structs-in-go-and-how-they-relate-to-garbage-collec,257,75849.0,6.0,,,2012-06-02 21:46:14,2022-12-29 01:14:00,2022-12-29 01:14:00,,,go;heap-memory;stack-memory,Joe,48047,148423,registered,true,10866871,,CC BY-SA 4.0,,2251,1994,1,1,0,3,true,false,false,true,true,true,84,15,false,0.079,0.0034,5285,2012,6,21,Saturday,true,false,false,false,false,false,false
12321133,How to properly seed random number generator,"I am trying to generate a random string in Go and here is the code I have written so far:
package main
import (
""bytes""
""fmt""
""math/rand""
""time""
)
func main() {
fmt.Println(randomString(10))
}
func randomString(l int) string {
var result bytes.Buffer
var temp string
for i := 0; i < l; {
if string(randInt(65, 90)) != temp {
temp = string(randInt(65, 90))
result.WriteString(temp)
i++
}
}
return result.String()
}
func randInt(min int, max int) int {
rand.Seed(time.Now().UTC().UnixNano())
return min + rand.Intn(max-min)
}
My implementation is very slow. Seeding using time brings the same random number for a certain time, so the loop iterates again and again. How can I improve my code?
",https://stackoverflow.com/questions/12321133/how-to-properly-seed-random-number-generator,249,236825.0,12.0,,,2012-09-07 15:29:44,2023-09-01 17:54:40,2019-11-21 08:48:32,,,random;go,copperMan,2515,1399105,registered,true,12321192,,CC BY-SA 4.0,,851,800,2,0,0,2,true,false,false,true,true,true,44,7,false,0.051,0.0011,5188,2012,9,15,Friday,false,false,false,false,false,false,false
22688010,How to trim leading and trailing white spaces of a string?,"Which is the effective way to trim the leading and trailing white spaces of string variable in Go?
",https://stackoverflow.com/questions/22688010/how-to-trim-leading-and-trailing-white-spaces-of-a-string,249,239159.0,8.0,,,2014-03-27 12:43:04,2021-07-07 17:41:57,2018-07-13 21:40:07,,,go,Alex Mathew,4324,2742702,registered,true,22688229,,CC BY-SA 4.0,2023-04-27 13:49:44,106,99,0,0,0,1,true,false,false,true,true,true,58,11,true,0.033,0.001,4622,2014,3,12,Thursday,false,false,false,false,false,false,false
30295146,How can I install a package with go get?,"I want to install packages from github to my $GOPATH, I have tried this:
go get github.com:capotej/groupcache-db-experiment.git
the repository is here.
",https://stackoverflow.com/questions/30295146/how-can-i-install-a-package-with-go-get,248,741494.0,3.0,,,2015-05-18 04:32:23,2024-07-21 09:03:13,2021-08-17 06:16:08,,,go;go-toolchain,roger,10133,2849157,registered,true,30296041,,CC BY-SA 4.0,,287,153,2,1,0,2,true,false,false,true,true,true,40,9,true,0.004,0.0003,4205,2015,5,4,Monday,false,false,false,false,false,false,false
28799110,How to join a slice of strings into a single string?,"package main
import (
""fmt""
""strings""
)
func main() {
reg := [...]string {""a"",""b"",""c""}
fmt.Println(strings.Join(reg,"",""))
}
gives me an error of:
prog.go:10: cannot use reg (type [3]string) as type []string in argument to strings.Join
Is there a more direct/better way than looping and adding to a var?
",https://stackoverflow.com/questions/28799110/how-to-join-a-slice-of-strings-into-a-single-string,246,346371.0,3.0,,,2015-03-01 21:09:47,2025-09-08 21:11:09,2019-06-27 02:03:07,,,go;slice,cycle4passion,3422,4618774,registered,true,28799151,,CC BY-SA 4.0,,383,313,1,0,0,2,true,false,false,true,true,true,52,11,true,0.009,0.0007,4283,2015,3,21,Sunday,true,false,false,false,false,false,false
38673673,Access HTTP response as string in Go,"I'd like to parse the response of a web request, but I'm getting trouble accessing it as string.
func main() {
resp, err := http.Get(""http://google.hu/"")
if err != nil {
// handle error
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
ioutil.WriteFile(""dump"", body, 0600)
for i:= 0; i < len(body); i++ {
fmt.Println( body[i] ) // This logs uint8 and prints numbers
}
fmt.Println( reflect.TypeOf(body) )
fmt.Println(""done"")
}
How can I access the response as string? ioutil.WriteFile writes correctly the response to a file.
I've already checked the package reference but it's not really helpful.
",https://stackoverflow.com/questions/38673673/access-http-response-as-string-in-go,243,392042.0,5.0,,,2016-07-30 11:58:18,2025-08-23 14:25:46,,,,network-programming;go,Tibor Szasz,3267,329869,registered,true,38673698,,CC BY-SA 3.0,,738,680,2,0,0,2,true,false,false,true,true,false,36,7,false,0.013,0.0006,3766,2016,7,11,Saturday,true,false,false,false,false,false,false
11354518,Application auto build versioning,"Is it possible to increment a minor version number automatically each time a Go app is compiled?
I would like to set a version number inside my program, with an autoincrementing section:
$ myapp -version
MyApp version 0.5.132
Being 0.5 the version number I set, and 132 a value that increments automatically each time the binary is compiled.
Is this possible in Go?
",https://stackoverflow.com/questions/11354518/application-auto-build-versioning,242,123131.0,8.0,,,2012-07-06 00:52:00,2024-12-26 03:10:17,2019-06-18 18:17:45,,,go,Sebastián Grignoli,33792,290221,registered,true,11355611,,CC BY-SA 4.0,,423,371,1,0,0,1,true,false,false,true,true,true,33,4,false,0.065,0.002,5251,2012,7,0,Friday,false,false,false,false,false,false,false
66894200,Error message "go: go.mod file not found in current directory or any parent directory; see 'go help modules'","I just updated to the new version of Go - Go version 1.16.2 Linux/amd64 and am getting an error when I build a Hello, World! example:
go: go.mod file not found in current directory or any parent directory; see 'go help modules'
Even when I follow the fix from this post it isn't working. I set these variables and then build again:
GO111MODULE=on
GOPROXY=https://proxy.golang.org,direct
And the same problem unfortunately.
",https://stackoverflow.com/questions/66894200/error-message-go-go-mod-file-not-found-in-current-directory-or-any-parent-dire,241,547889.0,16.0,,,2021-03-31 19:33:26,2025-02-28 04:49:50,2024-11-26 10:34:53,,,linux;go,asker152,5107,4159198,registered,true,66903554,,CC BY-SA 4.0,2022-05-25 20:22:16,715,426,1,2,0,2,true,false,false,true,true,true,127,18,false,0.029,0.0004,2061,2021,3,19,Wednesday,false,false,false,false,false,false,false
11104085,Does a break statement break from a switch/select?,"I know that switch/select statements break automatically after every case. I am wondering, in the following code:
for {
switch sometest() {
case 0:
dosomething()
case 1:
break
default:
dosomethingelse()
}
}
Does the break statement exit the for loop or just the switch block?
",https://stackoverflow.com/questions/11104085/does-a-break-statement-break-from-a-switch-select,238,214821.0,7.0,,,2012-06-19 15:16:10,2022-11-23 07:06:15,2020-08-06 17:18:20,,,select;switch-statement;go;break,Matt,22529,810671,registered,true,11105482,,CC BY-SA 4.0,,426,323,6,0,0,4,true,false,false,true,true,true,50,8,true,0.033,0.0011,5268,2012,6,15,Tuesday,false,false,false,false,false,false,false
10516662,How to measure test coverage in Go,"Has anyone succeeded in generating code coverage for Go unit tests? I can't find a tool for that on the web.
",https://stackoverflow.com/questions/10516662/how-to-measure-test-coverage-in-go,233,342101.0,16.0,,,2012-05-09 12:59:15,2026-10-08 11:23:55,2021-03-26 15:00:44,,,unit-testing;testing;go;code-coverage,Georgi Atsev,3105,1234200,registered,true,18911602,,CC BY-SA 4.0,,116,109,0,0,0,4,true,false,false,true,true,true,34,7,false,0.047,0.0007,5309,2012,5,12,Wednesday,false,false,false,false,false,false,false
24534072,"How to compare if two structs, slices or maps are equal?","I want to check if two structs, slices and maps are equal.
But I'm running into problems with the following code. See my comments at the relevant lines.
package main
import (
""fmt""
""reflect""
)
type T struct {
X int
Y string
Z []int
M map[string]int
}
func main() {
t1 := T{
X: 1,
Y: ""lei"",
Z: []int{1, 2, 3},
M: map[string]int{
""a"": 1,
""b"": 2,
},
}
t2 := T{
X: 1,
Y: ""lei"",
Z: []int{1, 2, 3},
M: map[string]int{
""a"": 1,
""b"": 2,
},
}
fmt.Println(t2 == t1)
//error - invalid operation: t2 == t1 (struct containing []int cannot be compared)
fmt.Println(reflect.ValueOf(t2) == reflect.ValueOf(t1))
//false
fmt.Println(reflect.TypeOf(t2) == reflect.TypeOf(t1))
//true
//Update: slice or map
a1 := []int{1, 2, 3, 4}
a2 := []int{1, 2, 3, 4}
fmt.Println(a1 == a2)
//invalid operation: a1 == a2 (slice can only be compared to nil)
m1 := map[string]int{
""a"": 1,
""b"": 2,
}
m2 := map[string]int{
""a"": 1,
""b"": 2,
}
fmt.Println(m1 == m2)
// m1 == m2 (map can only be compared to nil)
}
http://play.golang.org/p/AZIzW2WunI
",https://stackoverflow.com/questions/24534072/how-to-compare-if-two-structs-slices-or-maps-are-equal,233,297380.0,7.0,,,2014-07-02 14:41:07,2024-02-24 17:25:00,2019-11-08 14:33:16,,,go;go-reflect,leiyonglin,6926,1078503,registered,true,24534351,,CC BY-SA 4.0,,1401,1289,1,1,0,2,true,false,false,true,true,true,56,11,true,0.024,0.0008,4525,2014,7,14,Wednesday,false,false,false,false,false,false,false
25637440,How to pad a number with zeros when printing?,"How can I print a number or make a string with zero padding to make it fixed width?
For instance, if I have the number 12 and I want to make it 000012.
",https://stackoverflow.com/questions/25637440/how-to-pad-a-number-with-zeros-when-printing,232,212835.0,11.0,,,2014-09-03 06:13:58,2024-06-18 15:16:10,2023-11-23 11:28:20,,,go;format,Travis Reeder,41568,105562,registered,true,,,CC BY-SA 4.0,,194,154,2,0,0,2,false,false,false,true,true,true,45,9,true,0.052,0.0011,4462,2014,9,6,Wednesday,false,false,false,false,false,false,false
28081486,How can I "go run" a project with multiple files in the main package?,"I have a single file in the main package called main.go. Because the code isn't reusable I want to separate part of the code in a different file but in the same package.
How do I split the contents of main.go into multiple files without creating a separate package?
I want a directory structure like this:
ls foo
# output:
main.go
bar.go
File bar.go
// file bar.go
package main
import "fmt"
func Bar() {
fmt.Println("Bar")
}
File main.go
// file main.go
package main
func main() {
Bar()
}
In main.go i want to use func Bar() from bar.go. But when I run go run main.go it results in:
# command-line-arguments
./main.go:4:2: undefined: Bar
What can be done do run the code without an error?
",https://stackoverflow.com/questions/28081486/how-can-i-go-run-a-project-with-multiple-files-in-the-main-package,232,144665.0,9.0,,,2015-01-22 04:51:10,2024-01-27 12:15:54,2024-01-27 12:15:54,,,go;package,Neil,9543,288424,registered,true,28081554,,CC BY-SA 4.0,,1147,721,13,0,0,2,true,false,false,true,true,true,79,14,true,0.062,0.0016,4321,2015,1,4,Thursday,false,false,false,false,false,false,false
7059735,How to print boolean value in Go?,"As we have %d for int. What is the format specifier for boolean values?
",https://stackoverflow.com/questions/7059735/how-to-print-boolean-value-in-go,232,243559.0,5.0,,,2011-08-14 21:09:41,2024-03-25 15:49:30,2018-11-11 17:39:43,,,boolean;go,Anuj Verma,2977,894220,registered,true,,,CC BY-SA 4.0,,92,72,1,0,0,2,false,false,false,true,true,true,33,7,true,0.021,0.001,5578,2011,8,21,Sunday,true,false,false,false,false,false,false
11693865,Lowercase JSON key names with JSON Marshal in Go,"I wish to use the ""encoding/json"" package to marshal a struct declared in one of the imported packages of my application.
Eg.:
type T struct {
Foo int
}
Because it is imported, all available (exported) fields in the struct begins with an upper case letter. But I wish to have lower case key names:
out, err := json.Marshal(&T{Foo: 42})
will result in
{""Foo"":42}
but I wish to get
{""foo"":42}
Is it possible to get around the problem in some easy way?
",https://stackoverflow.com/questions/11693865/lowercase-json-key-names-with-json-marshal-in-go,232,72487.0,5.0,,,2012-07-27 18:46:19,2025-01-29 14:21:48,2020-10-29 19:47:08,,,json;go;serialization;tags;marshalling,ANisus,78828,694331,registered,true,11694255,,CC BY-SA 4.0,,644,477,3,0,0,5,true,false,false,true,true,true,48,9,false,0.069,0.0032,5230,2012,7,18,Friday,false,false,false,false,false,false,false
23229975,Is it safe to remove selected keys from map within a range loop?,"How can one remove selected keys from a map?
Is it safe to combine delete() with range, as in the code below?
package main
import ""fmt""
type Info struct {
value string
}
func main() {
table := make(map[string]*Info)
for i := 0; i < 10; i++ {
str := fmt.Sprintf(""%v"", i)
table[str] = &Info{str}
}
for key, value := range table {
fmt.Printf(""deleting %v=>%v\n"", key, value.value)
delete(table, key)
}
}
https://play.golang.org/p/u1vufvEjSw
",https://stackoverflow.com/questions/23229975/is-it-safe-to-remove-selected-keys-from-map-within-a-range-loop,231,93175.0,4.0,,,2014-04-22 20:52:58,2019-02-09 13:03:31,2018-07-13 21:49:14,,,dictionary;for-loop;go,Everton,14191,1011695,registered,true,23230406,,CC BY-SA 4.0,,631,512,2,1,0,3,true,false,false,true,true,true,64,13,true,0.043,0.0025,4596,2014,4,20,Tuesday,false,false,false,false,false,false,false
28800672,How to add new methods to an existing type in Go?,"I want to add a convenience util method on to gorilla/mux Route and Router types:
package util
import(
""net/http""
""github.com/0xor1/gorillaseed/src/server/lib/mux""
)
func (r *mux.Route) Subroute(tpl string, h http.Handler) *mux.Route{
return r.PathPrefix(""/"" + tpl).Subrouter().PathPrefix(""/"").Handler(h)
}
func (r *mux.Router) Subroute(tpl string, h http.Handler) *mux.Route{
return r.PathPrefix(""/"" + tpl).Subrouter().PathPrefix(""/"").Handler(h)
}
but the compiler informs me
Cannot define new methods on non-local type mux.Router
So how would I achieve this? Do I create a new struct type that has an anonymous mux.Route and mux.Router fields? Or something else?
",https://stackoverflow.com/questions/28800672/how-to-add-new-methods-to-an-existing-type-in-go,231,167564.0,3.0,,,2015-03-01 23:44:56,2024-06-21 22:14:20,2019-04-01 22:02:58,,,go;extension-methods,Daniel Robinson,15098,1259261,registered,true,28800807,,CC BY-SA 4.0,,783,693,2,0,0,2,true,false,false,true,true,true,49,11,true,0.018,0.0014,4283,2015,3,23,Sunday,true,false,false,false,false,false,false
24987131,How to parse unix timestamp to time.Time,"I'm trying to parse an Unix timestamp but I get out of range error. That doesn't really makes sense to me, because the layout is correct (as in the Go docs):
package main
import ""fmt""
import ""time""
func main() {
tm, err := time.Parse(""1136239445"", ""1405544146"")
if err != nil{
panic(err)
}
fmt.Println(tm)
}
",https://stackoverflow.com/questions/24987131/how-to-parse-unix-timestamp-to-time-time,231,397381.0,7.0,,,2014-07-28 00:45:58,2023-07-21 00:52:17,2018-07-13 21:44:11,,,go;time;unix-timestamp,hey,7979,3780579,registered,true,24987221,,CC BY-SA 4.0,,515,349,1,2,0,3,true,false,false,true,true,true,40,7,false,0.018,0.0006,4499,2014,7,0,Monday,false,false,false,false,false,false,false
8022389,Convert a float64 to an int in Go,"How does one convert a float64 to an int in Go? I know the strconv package can be used to convert anything to or from a string, but not between data types where one isn't a string. I know I can use fmt.Sprintf to convert anything to a string, and then strconv it to the data type I need, but this extra conversion seems a bit clumsy - is there a better way to do this?
",https://stackoverflow.com/questions/8022389/convert-a-float64-to-an-int-in-go,231,404481.0,6.0,,,2011-11-05 18:43:28,2025-04-01 12:25:12,2011-11-05 22:09:38,,,go,Chris Bunch,90739,422,registered,true,8022789,,CC BY-SA 3.0,,415,369,3,0,0,1,true,false,false,true,true,true,33,8,false,0.015,0.0006,5495,2011,11,18,Saturday,true,false,false,false,false,false,false
5801008,Go << and >> operators,"Could someone please explain to me the usage of << and >> in Go? I guess it is similar to some other languages.
",https://stackoverflow.com/questions/5801008/go-and-operators,230,136008.0,10.0,,,2011-04-27 07:54:57,2023-01-23 14:43:53,2013-04-01 03:44:40,,,go;bitwise-operators,brianoh,2319,726764,unregistered,true,,,CC BY-SA 3.0,,157,124,2,0,0,2,false,false,false,true,true,true,34,5,false,0.074,0.0017,5687,2011,4,7,Wednesday,false,false,false,false,false,false,false
12122159,How to do a https request with bad certificate?,"Say I want to get https://golang.org programatically. Currently golang.org (ssl) has a bad certificate which is issued to *.appspot.com So when I run this:
package main
import (
""log""
""net/http""
)
func main() {
_, err := http.Get(""https://golang.org/"")
if err != nil {
log.Fatal(err)
}
}
I get (as I expected)
Get https://golang.org/: certificate is valid for *.appspot.com, *.*.appspot.com, appspot.com, not golang.org
Now, I want to trust this certificate myself (imagine a self-issued certificate where I can validate fingerprint etc.): how can I make a request and validate/trust the certificate?
I probably need to use openssl to download the certificate, load it into my file and fill tls.Config struct !?
",https://stackoverflow.com/questions/12122159/how-to-do-a-https-request-with-bad-certificate,230,280141.0,6.0,,,2012-08-25 12:57:46,2020-12-07 12:45:52,2018-08-24 09:00:39,,,ssl;https;go,topskip,17775,317915,registered,true,12122718,,CC BY-SA 4.0,,864,749,5,0,0,3,true,false,false,true,true,true,47,9,true,0.021,0.0008,5201,2012,8,12,Saturday,true,false,false,false,false,false,false
20234104,How to format current time using a yyyyMMddHHmmss format?,"I'm trying to format the current time using this format yyyyMMddHHmmss.
t := time.Now()
fmt.Println(t.Format(""yyyyMMddHHmmss""))
That is outputting:
yyyyMMddHHmmss
Any suggestions?
",https://stackoverflow.com/questions/20234104/how-to-format-current-time-using-a-yyyymmddhhmmss-format,230,279975.0,7.0,,,2013-11-27 04:45:28,2024-10-29 21:41:27,,,,time;go;format;timestamp,sergserg,22413,1575153,registered,true,20234207,,CC BY-SA 3.0,,268,186,3,0,0,4,true,false,false,true,true,false,57,9,true,0.025,0.0008,4742,2013,11,4,Wednesday,false,false,false,false,false,false,false
16466320,Is there a way to do repetitive tasks at intervals?,"Is there a way to do repetitive background tasks in Go? I'm thinking of something like Timer.schedule(task, delay, period) in Java. I know I can do this with a goroutine and Time.sleep(), but I'd like something that easily stopped.
Here's what I got, but looks ugly to me. Is there a cleaner/better way?
func oneWay() {
var f func()
var t *time.Timer
f = func () {
fmt.Println(""doing stuff"")
t = time.AfterFunc(time.Duration(5) * time.Second, f)
}
t = time.AfterFunc(time.Duration(5) * time.Second, f)
defer t.Stop()
//simulate doing stuff
time.Sleep(time.Minute)
}
",https://stackoverflow.com/questions/16466320/is-there-a-way-to-do-repetitive-tasks-at-intervals,230,201078.0,10.0,,,2013-05-09 16:13:14,2025-01-19 16:36:49,2019-09-10 12:02:30,,,go,Steve Brisk,2793,814696,registered,true,16466581,,CC BY-SA 4.0,,688,624,3,0,0,1,true,false,false,true,true,true,51,10,true,0.05,0.0011,4944,2013,5,16,Thursday,false,false,false,false,false,false,false
18342195,How to declare a constant map in Golang?,"I am trying to declare to constant in Go, but it is throwing an error.
This is my code:
const myMap = map[int]string{
1: "one",
2: "two",
3: "three",
}
This is the error
map[int]string{…} (value of type map[int]string) is not constant
",https://stackoverflow.com/questions/18342195/how-to-declare-a-constant-map-in-golang,230,273178.0,7.0,,,2013-08-20 18:15:30,2024-11-27 05:56:29,2022-12-23 08:29:27,,,go,samol,21190,2521225,registered,true,18342312,,CC BY-SA 4.0,,389,279,2,0,0,1,true,false,false,true,true,true,40,8,true,0.026,0.0008,4841,2013,8,18,Tuesday,false,false,false,false,false,false,false
15130321,Is there a method to generate a UUID with Go language?,"I have code that looks like this:
u := make([]byte, 16)
_, err := rand.Read(u)
if err != nil {
return
}
u[8] = (u[8] | 0x80) & 0xBF // what does this do?
u[6] = (u[6] | 0x40) & 0x4F // what does this do?
return hex.EncodeToString(u)
It returns a string with a length of 32, but I don't think it is a valid UUID. If it is a real UUID, why is it a UUID, and what is the purpose of the code that modifies the value of u[8] and u[6]?
Is there a better way of generating UUIDs?
",https://stackoverflow.com/questions/15130321/is-there-a-method-to-generate-a-uuid-with-go-language,229,391055.0,15.0,,,2013-02-28 07:58:39,2024-07-20 19:06:04,2022-06-22 23:10:52,,,go;uuid,hardPass,21241,1316684,registered,true,15130941,,CC BY-SA 4.0,,559,488,3,0,0,2,true,false,false,true,true,true,54,11,true,0.038,0.0006,5014,2013,2,7,Thursday,false,false,false,false,false,false,false
17539407,How to import local packages without gopath,"I've used GOPATH but for this current issue I'm facing it does not help. I want to be able to create packages that are specific to a project:
myproject/
├── binary1.go
├── binary2.go
├── package1.go
└── package2.go
I tried multiple ways but how do I get package1.go to work in the binary1.go or the binary2.go and so on?
For example; I want to be able to import ""package1"" and then be able to run go build binary1.go and everything works fine without the error being thrown that the package cannot be found on GOROOT or GOPATH. The reason why I need this kind of functionality is for large scale projects; I do not want to have to reference multiple other packages or keep them in one large file.
",https://stackoverflow.com/questions/17539407/how-to-import-local-packages-without-gopath,226,342137.0,10.0,,,2013-07-09 03:28:54,2023-03-28 09:18:42,2019-09-18 15:48:17,,,go;package,user1529891,,,does_not_exist,true,17539525,,CC BY-SA 4.0,,850,701,9,0,0,2,true,false,false,true,false,true,43,7,false,0.029,0.0007,4883,2013,7,3,Tuesday,false,false,false,false,false,false,false
28447297,How to check for an empty struct?,"I define a struct ...
type Session struct {
playerId string
beehive string
timestamp time.Time
}
Sometimes I assign an empty session to it (because nil is not possible)
session = Session{};
Then I want to check, if it is empty:
if session == Session{} {
// do stuff...
}
Obviously this is not working. How do I write it?
",https://stackoverflow.com/questions/28447297/how-to-check-for-an-empty-struct,223,332507.0,9.0,,,2015-02-11 05:37:17,2024-08-26 14:36:16,,,,struct;go,Michael,7203,1903257,registered,true,28447372,,CC BY-SA 3.0,,447,347,3,0,0,2,true,false,false,true,true,false,33,7,true,0.027,0.0007,4301,2015,2,5,Wednesday,false,false,false,false,false,false,false
67201708,Go update all modules,"Using this module as an example (using a specific commit so others will see
what I see):
git clone git://github.com/walles/moar
Set-Location moar
git checkout d24acdbf
I would like a way to tell Go to "update everything". Assume that the module
will work with the newest version of everything. Below are five ways I found to
do this, assume each is run on a clean clone. This results in a go.mod of 19
lines:
go get -u
This results in a go.mod of 14 lines:
go get -u
go mod tidy
This results in a go.mod of 13 lines:
go mod tidy
If I just manually delete everything in require and run go mod tidy, I get
12 lines. If I just manually delete everything in require and run go get -u, I get 11 lines. My question is, why are these methods producing different
results, and what is the "right way" to do what I am trying to do?
",https://stackoverflow.com/questions/67201708/go-update-all-modules,221,360776.0,5.0,,,2021-04-21 18:39:28,2024-04-30 15:50:43,2022-01-24 21:31:12,,,go;module;package;go-modules,Zombo,1,1002260,registered,true,67202539,,CC BY-SA 4.0,,1068,846,11,0,0,4,true,false,false,true,true,true,21,4,false,0.014,0.0006,2040,2021,4,18,Wednesday,false,false,false,false,false,false,false
22688906,Go naming conventions for const,"I'm trying to determine whether there is a naming convention for the names of const in Golang.
I personally would tend to follow the C style and write them in upper case, but I haven't found anything on this page http://golang.org/doc/effective_go.html which seems to list some naming conventions for the language.
",https://stackoverflow.com/questions/22688906/go-naming-conventions-for-const,221,161637.0,3.0,,,2014-03-27 13:19:00,2017-08-08 09:48:20,2016-08-03 14:40:20,2024-02-07 16:52:13,Opinion-based,go;constants;naming-conventions,LtWorf,7738,1827457,registered,true,22688926,,,,414,316,1,1,0,3,true,true,false,true,true,true,31,5,false,0.019,0.0014,4622,2014,3,13,Thursday,false,false,false,false,false,false,false
20240179,nil detection in Go,"I see a lot of code in Go to detect nil, like this:
if err != nil {
// handle the error
}
however, I have a struct like this:
type Config struct {
host string
port float64
}
and config is an instance of Config, when I do:
if config == nil {
}
there is compile error, saying:
cannot convert nil to type Config
",https://stackoverflow.com/questions/20240179/nil-detection-in-go,221,337474.0,6.0,,,2013-11-27 10:41:20,2020-05-18 19:25:55,2016-04-05 22:22:32,,,go;null,user1663023,,,does_not_exist,true,20240309,,CC BY-SA 3.0,,441,341,3,0,0,2,true,false,false,true,false,true,19,4,false,0.018,0.0007,4742,2013,11,10,Wednesday,false,false,false,false,false,false,false
9644139,From io.Reader to string in Go,"I have an io.ReadCloser object (from an http.Response object).
What's the most efficient way to convert the entire stream to a string object?
",https://stackoverflow.com/questions/9644139/from-io-reader-to-string-in-go,220,197471.0,7.0,,,2012-03-10 05:19:32,2021-02-18 18:29:38,2016-08-02 18:38:50,,,go,djd,5288,457278,registered,true,9649061,,CC BY-SA 3.0,,196,143,3,0,0,1,true,false,false,true,true,true,30,6,false,0.035,0.0011,5369,2012,3,5,Saturday,true,false,false,false,false,false,false
14155122,How to call function from another file in Go,"I want to call function from another file in Go. Can any one help?
test1.go
package main
func main() {
demo()
}
test2.go
package main
import "fmt"
func main() {
}
func demo() {
fmt.Println("HI")
}
How to call demo in test2 from test1?
",https://stackoverflow.com/questions/14155122/how-to-call-function-from-another-file-in-go,220,233252.0,9.0,,,2013-01-04 10:15:44,2026-04-07 19:52:41,2021-12-23 11:17:13,,,go,user1788542,,,does_not_exist,true,14155156,,CC BY-SA 4.0,,410,269,7,0,0,1,true,false,false,true,false,true,44,9,false,0.039,0.0009,5069,2013,1,10,Friday,false,false,false,false,false,false,false
24809235,How to initialize a nested struct?,"I cannot figure out how to initialize a nested struct. Find an example here:
http://play.golang.org/p/NL6VXdHrjh
package main
type Configuration struct {
Val string
Proxy struct {
Address string
Port string
}
}
func main() {
c := &Configuration{
Val: "test",
Proxy: {
Address: "addr",
Port: "80",
}
}
}
",https://stackoverflow.com/questions/24809235/how-to-initialize-a-nested-struct,219,265918.0,11.0,,,2014-07-17 16:48:22,2024-10-23 09:05:15,2020-10-09 08:05:59,,,go,sontags,3261,1098584,registered,true,24809404,,CC BY-SA 4.0,,532,434,1,1,0,1,true,false,false,true,true,true,34,6,true,0.041,0.0008,4510,2014,7,16,Thursday,false,false,false,false,false,false,false
1713214,How to use C++ in Go,"In the new Go language, how do I call C++ code? In other words, how can I wrap my C++ classes and use them in Go?
",https://stackoverflow.com/questions/1713214/how-to-use-c-in-go,219,181028.0,13.0,,,2009-11-11 05:25:13,2024-11-12 19:37:39,2019-11-22 11:40:26,,,c++;wrapper;go,Frank,66794,60628,registered,true,1721230,,CC BY-SA 4.0,,171,114,0,1,0,3,true,false,false,true,true,true,20,6,false,0.072,0.0012,6219,2009,11,5,Wednesday,false,false,false,false,false,false,false
30681054,What is the usage of backtick in golang structs definition?,"type NetworkInterface struct {
Gateway string `json:""gateway""`
IPAddress string `json:""ip""`
IPPrefixLen int `json:""ip_prefix_len""`
MacAddress string `json:""mac""`
...
}
I'm quite confused what's the function of contents in backtick, like json:""gateway"".
Is it just comment, like //this is the gateway?
",https://stackoverflow.com/questions/30681054/what-is-the-usage-of-backtick-in-golang-structs-definition,217,81579.0,2.0,,,2015-06-06 09:15:57,2022-05-03 17:00:43,2015-06-06 10:47:58,2015-06-07 02:49:09,Duplicate,go,harryz,5430,1813875,registered,true,30681110,,,,434,370,3,0,0,1,true,true,false,true,true,true,59,10,true,0.025,0.0027,4186,2015,6,9,Saturday,true,false,false,false,false,false,false
30716354,How do I do a literal *int64 in Go?,"I have a struct type with a *int64 field.
type SomeType struct {
SomeField *int64
}
At some point in my code, I want to declare a literal of this (say, when I know said value should be 0, or pointing to a 0, you know what I mean)
instance := SomeType{
SomeField: &0,
}
...except this doesn't work
./main.go:xx: cannot use &0 (type *int) as type *int64 in field value
So I try this
instance := SomeType{
SomeField: &int64(0),
}
...but this also doesn't work
./main.go:xx: cannot take the address of int64(0)
How do I do this? The only solution I can come up with is using a placeholder variable
var placeholder int64
placeholder = 0
instance := SomeType{
SomeField: &placeholder,
}
Note: the &0 syntax works fine when it's a *int instead of an *int64. Edit: no it does not. Sorry about this.
Edit:
Aparently there was too much ambiguity to my question. I'm looking for a way to literally state a *int64. This could be used inside a constructor, or to state literal struct values, or even as arguments to other functions. But helper functions or using a different type are not solutions I'm looking for.
",https://stackoverflow.com/questions/30716354/how-do-i-do-a-literal-int64-in-go,216,168295.0,6.0,,,2015-06-08 18:21:38,2026-02-10 21:05:06,2016-10-05 07:05:33,,,pointers;go;struct;literals,ThisGuy,2933,1058820,registered,true,30716481,,CC BY-SA 3.0,,1443,1159,10,0,0,4,true,false,false,true,true,true,35,9,true,0.036,0.0013,4184,2015,6,18,Monday,false,false,false,false,false,false,false
39804861,What is a concise way to create a 2D slice in Go?,"I am learning Go by going through A Tour of Go. One of the exercises there asks me to create a 2D slice of dy rows and dx columns containing uint8. My current approach, which works, is this:
a:= make([][]uint8, dy) // initialize a slice of dy slices
for i:=0;i<dy;i++ {
a[i] = make([]uint8, dx) // initialize a slice of dx unit8 in each of dy slices
}
I think that iterating through each slice to initialize it is too verbose. And if the slice had more dimensions, the code would become unwieldy. Is there a concise way to initialize 2D (or n-dimensional) slices in Go?
",https://stackoverflow.com/questions/39804861/what-is-a-concise-way-to-create-a-2d-slice-in-go,216,243778.0,4.0,,,2016-10-01 09:11:00,2024-12-29 21:06:54,2024-12-29 21:06:54,,,go;matrix;multidimensional-array;slice;jagged-arrays,hazrmard,3811,4591810,registered,true,39806983,,CC BY-SA 4.0,,726,585,4,1,0,5,true,false,false,true,true,true,49,12,true,0.016,0.0009,3703,2016,10,9,Saturday,true,false,false,false,false,false,false
15945030,Change values while iterating,"Let's suppose I have these types:
type Attribute struct {
Key, Val string
}
type Node struct {
Attr []Attribute
}
and that I want to iterate on my node's attributes to change them.
I would have loved to be able to do:
for _, attr := range n.Attr {
if attr.Key == ""href"" {
attr.Val = ""something""
}
}
but as attr isn't a pointer, this wouldn't work and I have to do:
for i, attr := range n.Attr {
if attr.Key == ""href"" {
n.Attr[i].Val = ""something""
}
}
Is there a simpler or faster way? Is it possible to directly get pointers from range?
Obviously I don't want to change the structures just for the iteration and more verbose solutions are no solutions.
",https://stackoverflow.com/questions/15945030/change-values-while-iterating,215,135683.0,4.0,,,2013-04-11 09:19:03,2019-06-16 13:53:55,2019-06-16 13:53:55,,,arrays;for-loop;go,Denys Séguret,384576,263525,registered,true,15952415,,CC BY-SA 4.0,,844,704,5,0,0,3,true,false,false,true,true,true,29,4,false,0.029,0.0016,4972,2013,4,9,Thursday,false,false,false,false,false,false,false
17156371,How to get JSON response from http.Get,"I'm trying read JSON data from web, but that code returns empty result. I'm not sure what I'm doing wrong here.
package main
import ""os""
import ""fmt""
import ""net/http""
import ""io/ioutil""
import ""encoding/json""
type Tracks struct {
Toptracks []Toptracks_info
}
type Toptracks_info struct {
Track []Track_info
Attr []Attr_info
}
type Track_info struct {
Name string
Duration string
Listeners string
Mbid string
Url string
Streamable []Streamable_info
Artist []Artist_info
Attr []Track_attr_info
}
type Attr_info struct {
Country string
Page string
PerPage string
TotalPages string
Total string
}
type Streamable_info struct {
Text string
Fulltrack string
}
type Artist_info struct {
Name string
Mbid string
Url string
}
type Track_attr_info struct {
Rank string
}
func get_content() {
// json data
url := ""http://ws.audioscrobbler.com/2.0/?method=geo.gettoptracks&api_key=c1572082105bd40d247836b5c1819623&format=json&country=Netherlands""
res, err := http.Get(url)
if err != nil {
panic(err.Error())
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
panic(err.Error())
}
var data Tracks
json.Unmarshal(body, &data)
fmt.Printf(""Results: %v\n"", data)
os.Exit(0)
}
func main() {
get_content()
}
",https://stackoverflow.com/questions/17156371/how-to-get-json-response-from-http-get,214,363554.0,5.0,,,2013-06-17 20:35:40,2024-08-14 07:30:02,2019-08-11 14:36:31,,,json;go,Akshay Deep Giri,3310,740182,registered,true,31129967,,CC BY-SA 4.0,,1471,1440,1,0,0,2,true,false,false,true,true,true,38,7,false,0.014,0.0006,4905,2013,6,20,Monday,false,false,false,false,false,false,false
19167970,Mock functions in Go,"I'm puzzled with dependencies. I want to be able to replace some function calls with mock ones. Here's a snippet of my code:
func get_page(url string) string {
get_dl_slot(url)
defer free_dl_slot(url)
resp, err := http.Get(url)
if err != nil { return "" }
defer resp.Body.Close()
contents, err := ioutil.ReadAll(resp.Body)
if err != nil { return "" }
return string(contents)
}
func downloader() {
dl_slots = make(chan bool, DL_SLOT_AMOUNT) // Init the download slot semaphore
content := get_page(BASE_URL)
links_regexp := regexp.MustCompile(LIST_LINK_REGEXP)
matches := links_regexp.FindAllStringSubmatch(content, -1)
for _, match := range matches{
go serie_dl(match[1], match[2])
}
}
I'd like to be able to test downloader() without actually getting a page through http - i.e. by mocking either get_page (easier since it returns just the page content as a string) or http.Get().
I found this thread which seems to be about a similar problem. Julian Phillips presents his library, Withmock as a solution, but I'm unable to get it to work. Here's the relevant parts of my testing code, which is largely cargo cult code to me, to be honest:
import (
"testing"
"net/http" // mock
"code.google.com/p/gomock"
)
...
func TestDownloader (t *testing.T) {
ctrl := gomock.NewController()
defer ctrl.Finish()
http.MOCK().SetController(ctrl)
http.EXPECT().Get(BASE_URL)
downloader()
// The rest to be written
}
The test output is following:
ERROR: Failed to install '_et/http': exit status 1 output: can't load
package: package _et/http: found packages http (chunked.go) and main
(main_mock.go) in
/var/folders/z9/ql_yn5h550s6shtb9c5sggj40000gn/T/withmock570825607/path/src/_et/http
Is the Withmock a solution to my testing problem? What should I do to get it to work?
",https://stackoverflow.com/questions/19167970/mock-functions-in-go,214,224598.0,10.0,,,2013-10-03 19:47:40,2024-03-27 01:09:26,2020-09-22 12:41:31,,,unit-testing;mocking;go,GolDDranks,3650,1106456,registered,true,19168875,,CC BY-SA 4.0,,2239,1922,5,2,0,3,true,false,false,true,true,true,20,4,false,0.045,0.001,4797,2013,10,19,Thursday,false,false,false,false,false,false,false
44370277,""<type> is pointer to interface, not interface" confusion","I have this problem which seems a bit weird to me. Take a look at this snippet of code:
package coreinterfaces
type FilterInterface interface {
Filter(s *string) bool
}
type FieldFilter struct {
Key string
Val string
}
func (ff *FieldFilter) Filter(s *string) bool {
// Some code
}
type FilterMapInterface interface {
AddFilter(f *FilterInterface) uuid.UUID
RemoveFilter(i uuid.UUID)
GetFilterByID(i uuid.UUID) *FilterInterface
}
type FilterMap struct {
mutex sync.Mutex
Filters map[uuid.UUID]FilterInterface
}
func (fp *FilterMap) AddFilter(f *FilterInterface) uuid.UUID {
// Some code
}
func (fp *FilterMap) RemoveFilter(i uuid.UUID) {
// Some code
}
func (fp *FilterMap) GetFilterByID(i uuid.UUID) *FilterInterface {
// Some code
}
On some other package, I have the following code:
func DoFilter() {
fieldfilter := &coreinterfaces.FieldFilter{Key: "app", Val: "152511"}
filtermap := &coreinterfaces.FilterMap{}
_ = filtermap.AddFilter(fieldfilter) // <--- Exception is raised here
}
The run-time won't accept the line mentioned because
"cannot use fieldfilter (type *coreinterfaces.FieldFilter) as type
*coreinterfaces.FilterInterface in argument to fieldint.AddFilter:
*coreinterfaces.FilterInterface is pointer to interface, not interface"
However, when changing the code to:
func DoBid() error {
bs := string(b)
var ifilterfield coreinterfaces.FilterInterface
fieldfilter := &coreinterfaces.FieldFilter{Key: "app", Val: "152511"}
ifilterfield = fieldfilter
filtermap := &coreinterfaces.FilterMap{}
_ = filtermap.AddFilter(&ifilterfield)
}
Everything is alright and when debugging the application it really seems to include
I'm a bit confused on this topic. When looking at other blog posts and stack overflow threads discussing this exact same issue (for example - This, or
This) the first snippet which raises this exception should work, because both fieldfilter and fieldmap are initialized as pointers to interfaces, rather than value of interfaces. I haven't been able to wrap my head around what actually happens here that I need to change in order for me not to declare a FieldInterface and assign the implementation for that interface. There must be an elegant way to do this.
",https://stackoverflow.com/questions/44370277/type-is-pointer-to-interface-not-interface-confusion,214,140172.0,2.0,,,2017-06-05 13:37:52,2022-02-26 04:02:26,2020-12-05 10:03:29,,,pointers;go;interface,0rka,2436,6691722,registered,true,44372954,,CC BY-SA 4.0,,2753,2386,3,2,0,3,true,false,false,true,true,true,73,8,false,0.014,0.0015,3456,2017,6,13,Monday,false,false,false,false,false,false,false
25161774,What are conventions for filenames in Go?,"I could find the conventions for naming packages in Go: no underscore between words, everything lowercase.
Does this convention apply to the filenames too?
Do you also put one struct in one file as if you did for a java class and then name the file after the struct?
Currently, if I have a struct WebServer, I put it in a file web_server.go.
",https://stackoverflow.com/questions/25161774/what-are-conventions-for-filenames-in-go,214,181124.0,6.0,,,2014-08-06 13:32:54,2024-09-26 08:52:44,,,,go;naming-conventions,david,2767,3802013,registered,true,25162021,,CC BY-SA 3.0,,373,345,0,0,0,2,true,false,false,true,true,false,41,7,true,0.033,0.0012,4490,2014,8,13,Wednesday,false,false,false,false,false,false,false
1854302,Is assert evil?,"The Go language creators write:
Go doesn't provide assertions. They are undeniably convenient, but our experience has been that programmers use them as a crutch to avoid thinking about proper error handling and reporting. Proper error handling means that servers continue operation after non-fatal errors instead of crashing. Proper error reporting means that errors are direct and to the point, saving the programmer from interpreting a large crash trace. Precise errors are particularly important when the programmer seeing the errors is not familiar with the code.
How would these arguments apply to C or C++? What are some pros and cons of using assert()?
",https://stackoverflow.com/questions/1854302/is-assert-evil,213,33019.0,21.0,,,2009-12-06 04:04:19,2023-08-26 19:43:58,2023-03-30 21:00:59,2012-07-10 18:45:39,not constructive,c++;c;error-handling;go;assert,Frank,66794,60628,registered,true,1854338,,,,829,662,2,1,0,5,true,true,false,true,true,true,15,3,true,0.636,0.0065,6194,2009,12,4,Sunday,true,false,false,false,false,false,false
13737745,Split a string on whitespace in Go?,"Given an input string such as "" word1 word2 word3 word4 "", what would be the best approach to split this as an array of strings in Go? Note that there can be any number of spaces or unicode-spacing characters between each word.
In Java I would just use someString.trim().split(""\\s+"").
(Note: possible duplicate Split string using regular expression in Go doesn't give any good quality answer. Please provide an actual example, not just a link to the regexp or strings packages reference.)
",https://stackoverflow.com/questions/13737745/split-a-string-on-whitespace-in-go,212,171283.0,4.0,,,2012-12-06 05:53:12,2022-05-09 19:41:49,2017-05-23 12:26:09,,,regex;go,ralfoide,3103,218258,registered,true,13737890,,CC BY-SA 3.0,,682,498,4,1,0,2,true,false,false,true,true,true,35,7,true,0.023,0.0012,5098,2012,12,5,Thursday,false,false,false,false,false,false,false
18926303,Iterate through the fields of a struct in Go,"Basically, the only way (that I know of) to iterate through the values of the fields of a struct is like this:
type Example struct {
a_number uint32
a_string string
}
//...
r := &Example{(2 << 31) - 1, ""....""}:
for _, d:= range []interface{}{ r.a_number, r.a_string, } {
//do something with the d
}
I was wondering, if there's a better and more versatile way of achieving []interface{}{ r.a_number, r.a_string, }, so I don't need to list each parameter individually, or alternatively, is there a better way to loop through a struct?
I tried to look through the reflect package, but I hit a wall, because I'm not sure what to do once I retrieve reflect.ValueOf(*r).Field(0).
Thanks!
",https://stackoverflow.com/questions/18926303/iterate-through-the-fields-of-a-struct-in-go,211,319639.0,8.0,,,2013-09-20 21:39:55,2024-01-10 21:49:53,2017-09-25 08:00:29,,,go;go-reflect,omninonsense,7032,2133758,registered,true,18927729,,CC BY-SA 3.0,,875,709,5,1,0,2,true,false,false,true,true,true,44,9,false,0.025,0.0007,4810,2013,9,21,Friday,false,false,false,false,false,false,false
30182538,Why can't I duplicate a slice with `copy()`?,"I need to make a copy of a slice in Go and reading the docs there is a copy function at my disposal.
The copy built-in function copies elements from a source slice into a
destination slice. (As a special case, it also will copy bytes from a
string to a slice of bytes.) The source and destination may overlap.
Copy returns the number of elements copied, which will be the minimum
of len(src) and len(dst).
But when I do:
arr := []int{1, 2, 3}
tmp := []int{}
copy(tmp, arr)
fmt.Println(tmp)
fmt.Println(arr)
My tmp is empty as it was before (I even tried to use arr, tmp):
[]
[1 2 3]
You can check it on go playground. So why can not I copy a slice?
",https://stackoverflow.com/questions/30182538/why-cant-i-duplicate-a-slice-with-copy,210,208057.0,11.0,,,2015-05-12 05:33:26,2025-04-18 11:08:20,2019-08-31 12:06:30,,,go;slice,Salvador Dali,225001,1090562,registered,true,30182622,,CC BY-SA 4.0,,939,670,4,2,0,2,true,false,false,true,true,true,48,8,true,0.053,0.001,4211,2015,5,5,Tuesday,false,false,false,false,false,false,false
18635671,How to define multiple name tags in a struct,"I need to get an item from a mongo database, so I defined a struct like this
type Page struct {
PageId string `bson:""pageId""`
Meta map[string]interface{} `bson:""meta""`
}
Now I also need to encode it to JSON, but it encodes the fields as uppercase (i get PageId instead of pageId) so i also need to define field tags for JSON. I tried something like this but it didn't work:
type Page struct {
PageId string `bson:""pageId"",json:""pageId""`
Meta map[string]interface{} `bson:""meta"",json:""pageId""`
}
So how can this be done, define multiple name tags in a struct?
",https://stackoverflow.com/questions/18635671/how-to-define-multiple-name-tags-in-a-struct,210,102515.0,2.0,,,2013-09-05 11:56:28,2022-03-27 07:00:50,2015-06-04 10:36:03,,,json;struct;go,scc,10836,46183,registered,true,18635910,,CC BY-SA 3.0,,686,617,2,0,0,3,true,false,false,true,true,true,44,9,false,0.02,0.002,4825,2013,9,11,Thursday,false,false,false,false,false,false,false
15049903,How to use custom packages,"I'm trying to create and use a custom package in Go. It's probably something very obvious but I cannot find much information about this. Basically, I have these two files in the same folder:
mylib.go
package mylib
type SomeType struct {
}
main.go
package main
import (
""mylib""
)
func main() {
}
When I try to go run main.go, I get this error:
main.go:4:2: import ""mylib"": cannot find package
I've tried to run go build mylib.go first but it doesn't seem to be doing anything (no file generated, no error message). So any idea how I could do this?
",https://stackoverflow.com/questions/15049903/how-to-use-custom-packages,208,214788.0,10.0,,,2013-02-24 08:15:47,2025-03-27 15:59:05,2020-02-23 20:53:10,,,import;package;go,laurent,91357,561309,registered,true,15051192,,CC BY-SA 4.0,,733,566,5,0,0,3,true,false,false,true,true,true,26,5,false,0.047,0.001,5018,2013,2,8,Sunday,true,false,false,false,false,false,false
25218903,How are people managing authentication in Go?,"For those building RESTful APIs and JS front-end apps in Go, how are you managing authentication? Are you using any particular libraries or techniques?
I'm surprised to find so little discussion about this. I keep in mind answers like the following, and am trying to avoid developing my own implementation:
Authentication Form in ASP.Net
Is everybody coding their own solution, separately?
",https://stackoverflow.com/questions/25218903/how-are-people-managing-authentication-in-go,208,88517.0,7.0,,,2014-08-09 13:09:19,2020-05-27 17:08:18,2017-05-23 12:02:45,2020-05-30 00:50:24,Not suitable for this site,authentication;go,SexxLuthor,4576,3925041,registered,true,27470944,,,,516,393,0,1,0,2,true,true,false,true,true,true,45,7,true,0.079,0.0023,4487,2014,8,13,Saturday,true,false,false,false,false,false,false
6478962,What does the '.' (dot or period) in a Go import statement do?,"In the Go tutorial, and most of the Go code I've looked at, packages are imported like this:
import (
""fmt""
""os""
""launchpad.net/lpad""
...
)
But in http://bazaar.launchpad.net/~niemeyer/lpad/trunk/view/head:/session_test.go, the gocheck package is imported with a . (period):
import (
""http""
. ""launchpad.net/gocheck""
""launchpad.net/lpad""
""os""
)
What is the significance of the . (period)?
",https://stackoverflow.com/questions/6478962/what-does-the-dot-or-period-in-a-go-import-statement-do,207,45317.0,3.0,,,2011-06-25 16:16:36,2024-03-31 16:58:22,2016-08-03 14:33:34,,,import;go,Eric Seidel,2931,586750,registered,true,6478990,,CC BY-SA 3.0,,616,431,4,1,0,2,true,false,false,true,true,true,70,13,true,0.066,0.0046,5628,2011,6,16,Saturday,true,false,false,false,false,false,false
24069664,What does go install do?,"The docs say nothing about what build vs install does
My expectation was that it's like make install; i.e. it takes the compiled stuff and puts in its final location (/usr/local/bin/my_new_toy or whatever) but it seems that it puts things in GOROOT/bin
Can I tell go to do a make install - i.e. put things elsewhere? Or do I just write a makefile (please tell me no)?
",https://stackoverflow.com/questions/24069664/what-does-go-install-do,206,303335.0,2.0,,,2014-06-05 20:27:51,2024-04-12 16:03:39,2014-06-05 20:30:14,,,go,pm100,50712,173397,registered,true,24070046,,CC BY-SA 3.0,,469,370,6,0,0,1,true,false,false,true,true,true,24,5,true,0.007,0.0007,4552,2014,6,20,Thursday,false,false,false,false,false,false,false
40680981,Are maps passed by value or by reference in Go?,"Are maps passed by value or reference in Go ?
It is always possible to define a function as following, but is this an overkill ?
func foo(dat *map[string]interface{}) {...}
Same question for return value. Should I return a pointer to the map, or return the map as value ?
The intention is of course to avoid unnecessary data copy.
",https://stackoverflow.com/questions/40680981/are-maps-passed-by-value-or-by-reference-in-go,206,165834.0,3.0,,,2016-11-18 15:42:06,2020-11-08 18:58:05,,,,go,chmike,22514,75517,registered,true,40681058,,CC BY-SA 3.0,,390,338,1,0,0,1,true,false,false,true,true,false,47,10,true,0.018,0.0012,3655,2016,11,15,Friday,false,false,false,false,false,false,false
23729790,How can I do test setup using the testing package in Go,"How can I do overall test setup processing which sets the stage for all the tests when using the testing package?
As an example in Nunit there is a [SetUp] attribute.
[TestFixture]
public class SuccessTests
{
[SetUp] public void Init()
{ /* Load test data */ }
}
",https://stackoverflow.com/questions/23729790/how-can-i-do-test-setup-using-the-testing-package-in-go,205,228957.0,11.0,,,2014-05-19 04:36:40,2024-12-27 18:07:36,2015-12-05 08:06:42,,,unit-testing;go,miltonb,7491,302164,registered,true,34102842,,CC BY-SA 3.0,,383,270,2,1,0,2,true,false,false,true,true,true,55,12,false,0.048,0.0009,4569,2014,5,4,Monday,false,false,false,false,false,false,false
12311033,Extracting substrings in Go,"I'm trying to read an entire line from the console (including whitespace), then process it. Using bufio.ReadString, the newline character is read together with the input, so I came up with the following code to trim the newline character:
input,_:=src.ReadString('\n')
inputFmt:=input[0:len(input)-2]+"""" //Need to manually add end of string
Is there a more idiomatic way to do this? That is, is there already a library that takes care of the ending null byte when extracting substrings for you?
(Yes, I know there is already a way to read a line without the newline character in go readline -> string but I'm looking more for elegant string manipulation.)
",https://stackoverflow.com/questions/12311033/extracting-substrings-in-go,205,412064.0,9.0,,,2012-09-07 02:43:59,2024-08-27 12:11:06,2018-11-13 15:55:23,,,go;substring,mark2222,2167,1263980,registered,true,12313812,,CC BY-SA 4.0,,785,663,1,1,0,2,true,false,false,true,true,true,27,4,false,0.022,0.0005,5188,2012,9,2,Friday,false,false,false,false,false,false,false
28031603,What do three dots "./..." mean in Go command line invocations?,"If you run Golang tests on Travis CI, it will download all of your dependencies with three dots:
go get -d -v ./... && go build -v ./...
What does ./... indicate or expand to there? I've done some research but it doesn't seem to be a Unix convention.
",https://stackoverflow.com/questions/28031603/what-do-three-dots-mean-in-go-command-line-invocations,205,57613.0,2.0,,,2015-01-19 18:52:15,2016-10-21 08:19:17,,,,go,Kevin Burke,66063,329700,registered,true,28031651,,CC BY-SA 3.0,,372,262,2,1,0,1,true,false,false,true,true,false,73,11,true,0.035,0.0036,4324,2015,1,18,Monday,false,false,false,false,false,false,false
16280176,Go: panic: runtime error: invalid memory address or nil pointer dereference,"When running my Go program, it panics and returns the following:
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xb code=0x1 addr=0x38 pc=0x26df]
goroutine 1 [running]:
main.getBody(0x1cdcd4, 0xf800000004, 0x1f2b44, 0x23, 0xf84005c800, ...)
/Users/matt/Dropbox/code/go/scripts/cron/fido.go:65 +0x2bb
main.getToken(0xf84005c7e0, 0x10)
/Users/matt/Dropbox/code/go/scripts/cron/fido.go:140 +0x156
main.main()
/Users/matt/Dropbox/code/go/scripts/cron/fido.go:178 +0x61
goroutine 2 [syscall]:
created by runtime.main
/usr/local/Cellar/go/1.0.3/src/pkg/runtime/proc.c:221
goroutine 3 [syscall]:
syscall.Syscall6()
/usr/local/Cellar/go/1.0.3/src/pkg/syscall/asm_darwin_amd64.s:38 +0x5
syscall.kevent(0x6, 0x0, 0x0, 0xf840085188, 0xa, ...)
/usr/local/Cellar/go/1.0.3/src/pkg/syscall/zsyscall_darwin_amd64.go:199 +0x88
syscall.Kevent(0xf800000006, 0x0, 0x0, 0xf840085188, 0xa0000000a, ...)
/usr/local/Cellar/go/1.0.3/src/pkg/syscall/syscall_bsd.go:546 +0xa4
net.(*pollster).WaitFD(0xf840085180, 0xf840059040, 0x0, 0x0, 0x0, ...)
/usr/local/Cellar/go/1.0.3/src/pkg/net/fd_darwin.go:96 +0x185
net.(*pollServer).Run(0xf840059040, 0x0)
/usr/local/Cellar/go/1.0.3/src/pkg/net/fd.go:236 +0xe4
created by net.newPollServer
/usr/local/Cellar/go/1.0.3/src/pkg/net/newpollserver.go:35 +0x382
I've looked at the responses others have had to the same exception, but can't see anything simple (i.e. an unhandled error).
I am running it on a machine that does not have access to the API servers listed in the code, but I was hoping it'd return an appropriate error (as I've attempted to catch errors of that kind).
package main
/*
Fido fetches the list of public images from the Glance server, captures the IDs of images with 'status': 'active' and then queues the images for pre-fetching with the Glance CLI utility `glance-cache-manage`. Once the images are added to the queue, `glance-cache-prefetcher` is called to actively fetch the queued images into the local compute nodes' image cache.
See http://docs.openstack.org/developer/glance/cache.html for further details on the Glance image cache.
*/
import (
""bytes""
""encoding/json""
""fmt""
""io/ioutil""
/*
""log""
""log/syslog""
*/
""net/http""
""os""
""os/exec""
)
func prefetchImages() error {
cmd := exec.Command(""glance-cache-prefetcher"")
err := cmd.Run()
if err != nil {
return fmt.Errorf(""glance-cache-prefetcher failed to execute properly: %v"", err)
}
return nil
}
func queueImages(hostname string, imageList []string) error {
for _, image := range imageList {
cmd := exec.Command(""glance-cache-manage"", ""--host="", hostname, ""queue-image"", image)
err := cmd.Run()
if err != nil {
return fmt.Errorf(""glance-cache-manage failed to execute properly: %v"", err)
} else {
fmt.Printf(""Image %s queued"", image)
}
}
return nil
}
func getBody(method string, url string, headers map[string]string, body []byte) ([]byte, error) {
client := &http.Client{}
req, err := http.NewRequest(method, url, bytes.NewReader(body))
if err != nil {
return nil, err
}
for key, value := range headers {
req.Header.Add(key, value)
}
res, err := client.Do(req)
defer res.Body.Close()
if err != nil {
return nil, err
}
var bodyBytes []byte
if res.StatusCode == 200 {
bodyBytes, err = ioutil.ReadAll(res.Body)
} else if err != nil {
return nil, err
} else {
return nil, fmt.Errorf(""The remote end did not return a HTTP 200 (OK) response."")
}
return bodyBytes, nil
}
func getImages(authToken string) ([]string, error) {
type GlanceDetailResponse struct {
Images []struct {
Name string `json:""name""`
Status string `json:""status""`
ID string `json:""id""`
}
}
method := ""GET""
url := ""http://192.168.1.2:9292/v1.1/images/detail""
headers := map[string]string{""X-Auth-Token"": authToken}
bodyBytes, err := getBody(method, url, headers, nil)
if err != nil {
return nil, fmt.Errorf(""unable to retrieve the response body from the Glance API server: %v"", err)
}
var glance GlanceDetailResponse
err = json.Unmarshal(bodyBytes, &glance)
if err != nil {
return nil, fmt.Errorf(""unable to parse the JSON response:"", err)
}
imageList := make([]string, 10)
for _, image := range glance.Images {
if image.Status == ""active"" {
imageList = append(imageList, image.ID)
}
}
return imageList, nil
}
func getToken() (string, error) {
type TokenResponse struct {
Auth []struct {
Token struct {
Expires string `json:""expires""`
ID string `json:""id""`
}
}
}
method := ""POST""
url := ""http://192.168.1.2:5000/v2.0/tokens""
headers := map[string]string{""Content-type"": ""application/json""}
creds := []byte(`{""auth"":{""passwordCredentials"":{""username"": ""glance"", ""password"":""<password>""}, ""tenantId"":""<tenantkeygoeshere>""}}`)
bodyBytes, err := getBody(method, url, headers, creds)
if err != nil {
return """", err
}
var keystone TokenResponse
err = json.Unmarshal(bodyBytes, &keystone)
if err != nil {
return """", err
}
authToken := string((keystone.Auth[0].Token.ID))
return authToken, nil
}
func main() {
/*
slog, err := syslog.New(syslog.LOG_ERR, ""[fido]"")
if err != nil {
log.Fatalf(""unable to connect to syslog: %v"", err)
os.Exit(1)
} else {
defer slog.Close()
}
*/
hostname, err := os.Hostname()
if err != nil {
// slog.Err(""Hostname not captured"")
os.Exit(1)
}
authToken, err := getToken()
if err != nil {
// slog.Err(""The authentication token from the Glance API server was not retrieved"")
os.Exit(1)
}
imageList, err := getImages(authToken)
err = queueImages(hostname, imageList)
if err != nil {
// slog.Err(""Could not queue the images for pre-fetching"")
os.Exit(1)
}
err = prefetchImages()
if err != nil {
// slog.Err(""Could not queue the images for pre-fetching"")
os.Exit(1)
}
return
}
",https://stackoverflow.com/questions/16280176/go-panic-runtime-error-invalid-memory-address-or-nil-pointer-dereference,205,600175.0,7.0,,,2013-04-29 13:41:16,2024-05-16 07:24:53,,,,go,elithrar,24468,556573,registered,true,16280362,,CC BY-SA 3.0,,6600,6531,2,0,0,1,true,false,false,true,true,false,75,11,false,0.012,0.0003,4954,2013,4,13,Monday,false,false,false,false,false,false,false
55807322,Can I list all standard Go packages?,"Is there a way in Go to list all the standard/built-in packages (i.e., the packages which come installed with a Go installation)?
I have a list of packages and I want to figure out which packages are standard.
",https://stackoverflow.com/questions/55807322/can-i-list-all-standard-go-packages,205,17321.0,3.0,,,2019-04-23 08:41:20,2020-04-06 08:22:38,2020-04-06 08:22:38,,,go;go-packages,Alok Kumar Singh,2589,4106031,registered,true,,,CC BY-SA 4.0,,234,211,0,0,0,2,false,false,false,true,true,true,36,7,true,0.173,0.0118,2769,2019,4,8,Tuesday,false,false,false,false,false,false,false
6986944,Does the Go language have function/method overloading?,"I'm porting a C library to Go. A C function (with varargs) is defined like this:
curl_easy_setopt(CURL *curl, CURLoption option, ...);
So I created wrapper C functions:
curl_wrapper_easy_setopt_str(CURL *curl, CURLoption option, char* param);
curl_wrapper_easy_setopt_long(CURL *curl, CURLoption option, long param);
If I define function in Go like this:
func (e *Easy)SetOption(option Option, param string) {
e.code = Code(C.curl_wrapper_easy_setopt_str(e.curl, C.CURLoption(option), C.CString(param)))
}
func (e *Easy)SetOption(option Option, param long) {
e.code = Code(C.curl_wrapper_easy_setopt_long(e.curl, C.CURLoption(option), C.long(param)))
}
The Go compiler complains:
*Easy·SetOption redeclared in this block
So does Go support function (method) overloading, or does this error mean something else?
",https://stackoverflow.com/questions/6986944/does-the-go-language-have-function-method-overloading,204,174197.0,6.0,,,2011-08-08 18:42:48,2024-07-18 18:45:29,2024-03-04 02:16:16,,,go;overloading,Darius Kucinskas,10789,71910,registered,true,6987002,,CC BY-SA 4.0,,965,834,4,0,0,2,true,false,false,true,true,true,54,7,true,0.034,0.0012,5584,2011,8,18,Monday,false,false,false,false,false,false,false
31064688,Which is the nicer way to initialize a map?,"As map is a reference type. What is difference between:?
m := make(map[string]int32)
and
m := map[string]int32{}
",https://stackoverflow.com/questions/31064688/which-is-the-nicer-way-to-initialize-a-map,204,213461.0,1.0,,,2015-06-26 04:03:57,2021-02-17 13:23:09,2021-02-17 13:23:09,2015-06-26 06:12:13,Duplicate,go,iwat,3941,185371,registered,true,31064737,,,,193,118,3,0,0,1,true,true,false,true,true,true,43,9,true,0.005,0.001,4166,2015,6,4,Friday,false,false,false,false,false,false,false
61845013,"package XXX is not in GOROOT" when building a Go project,"I have a weird issue that arose when I took a break from this project. Upon starting up Golang, I'm riddled with errors when trying to run my project.
The specific error, when building one of my packages, is:
start.go: package project/game is not in GOROOT (C:\Go\src\project\game)
I have a folder structure as such under C:\Users\username
go
|-src
|-project
|-game
|-entity
|-whatever.go
|-game_stuff.go
|-server
and my env vars are as such:
GOROOT=C:\Go
GOPATH=C:\Users\ketchup\go
for each of the modules (project/game/entity, project/game, project/server), I did a git mod init.
When building, Goland will try to run this:
C:\Go\bin\go.exe build -o C:\Users\ketchup\AppData\Local\Temp\___go_build_project_server.exe project/server
and return the error.
Can anyone help me with this issue? Kind of lost since Goland was working fine the last time I opened it. Also not even sure what direction to look at - I'm pretty new to Go and I'm not really sure what documentation to look at :\ Thank you everyone!
",https://stackoverflow.com/questions/61845013/package-xxx-is-not-in-goroot-when-building-a-go-project,201,653459.0,30.0,,,2020-05-16 23:35:31,2025-10-21 21:14:07,2023-03-22 01:31:54,,,go,Michael Shum,2647,6724060,registered,true,61860666,,CC BY-SA 4.0,2025-10-21 21:13:06,1240,1073,6,0,0,1,true,false,false,true,true,true,67,11,false,0.046,0.0003,2380,2020,5,23,Saturday,true,false,false,false,false,false,false
13670818,Pair/tuple data type in Go,"I need a queue of (string, int) pairs. That's easy enough:
type job struct {
url string
depth int
}
queue := make(chan job)
queue <- job{url, depth}
are there built-in pair/tuple data types in Go? There is support for returning multiple values from a function, but as far as I can tell, the multiple value tuples produced are not first-class citizens in Go's type system. Is that the case?
As for the "what have you tried" part, the obvious syntax (from a Python programmer's POV)
queue := make(chan (string, int))
didn't work.
",https://stackoverflow.com/questions/13670818/pair-tuple-data-type-in-go,200,287721.0,6.0,,,2012-12-02 15:43:00,2023-12-16 04:37:22,2023-08-31 01:04:00,,,go;tuples,Fred Foo,366168,166749,registered,true,13686006,,CC BY-SA 4.0,,742,552,4,1,0,2,true,false,false,true,true,true,26,5,false,0.021,0.0007,5102,2012,12,15,Sunday,true,false,false,false,false,false,false
10408646,How to import and use different packages of the same name,"For example, I want to use both the text/template and html/template packages in one source file.
But the code below throw errors.
import (
"fmt"
"net/http"
"text/template" // template redeclared as imported package name
"html/template" // template redeclared as imported package name
)
func handler_html(w http.ResponseWriter, r *http.Request) {
t_html, err := html.template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)
t_text, err := text.template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)
}
",https://stackoverflow.com/questions/10408646/how-to-import-and-use-different-packages-of-the-same-name,199,99475.0,2.0,,,2012-05-02 06:18:42,2025-11-23 02:36:44,2025-11-23 02:36:44,,,go;package,hardPass,21241,1316684,registered,true,10408720,,CC BY-SA 4.0,,680,623,3,0,0,2,true,false,false,true,true,true,57,11,false,0.02,0.002,5316,2012,5,6,Wednesday,false,false,false,false,false,false,false
14680255,Difference between fmt.Println() and println() in Go,"As illustrated below, both fmt.Println() and println() give same output in Go: Hello world!
But: how do they differ from each other?
Snippet 1, using the fmt package;
package main
import (
""fmt""
)
func main() {
fmt.Println(""Hello world!"")
}
Snippet 2, without the fmt package;
package main
func main() {
println(""Hello world!"")
}
",https://stackoverflow.com/questions/14680255/difference-between-fmt-println-and-println-in-go,199,70703.0,5.0,,,2013-02-04 04:11:28,2024-08-03 15:50:28,2020-01-11 14:20:26,,,go;println,YulCheney,3135,1262447,registered,true,14680373,,CC BY-SA 4.0,,634,352,7,1,0,2,true,false,false,true,true,true,52,7,false,0.071,0.0028,5038,2013,2,4,Monday,false,false,false,false,false,false,false
12668681,How to get the number of characters in a string,"How can I get the number of characters of a string in Go?
For example, if I have a string ""hello"" the method should return 5. I saw that len(str) returns the number of bytes and not the number of characters so len(""£"") returns 2 instead of 1 because £ is encoded with two bytes in UTF-8.
",https://stackoverflow.com/questions/12668681/how-to-get-the-number-of-characters-in-a-string,198,170111.0,7.0,,,2012-10-01 06:52:15,2022-06-13 16:17:51,2021-01-27 17:45:51,,,string;go;character;string-length,Ammar,5770,92728,registered,true,12668840,,CC BY-SA 4.0,,372,289,4,0,0,4,true,false,false,true,true,true,47,10,false,0.041,0.0012,5164,2012,10,6,Monday,false,false,false,false,false,false,false
26285735,Subtracting time.Duration from time in Go,"I have a time.Time value obtained from time.Now() and I want to get another time which is exactly 1 month ago.
I know subtracting is possible with time.Sub() (which wants another time.Time), but that will result in a time.Duration and I need it the other way around.
",https://stackoverflow.com/questions/26285735/subtracting-time-duration-from-time-in-go,197,245276.0,4.0,,,2014-10-09 18:40:53,2022-04-29 03:04:34,2022-04-29 03:04:34,,,datetime;go,Martijn van Maasakkers,2837,1629858,registered,true,26285835,,CC BY-SA 4.0,,348,269,5,0,0,2,true,false,false,true,true,true,41,6,false,0.016,0.0008,4426,2014,10,18,Thursday,false,false,false,false,false,false,false
40632802,How to convert byte array to string in Go,"[]byte to string raises an error.
string([]byte[:n]) raises an error too.
By the way, for example, sha1 value to string for filename.
Does it need utf-8 or any other encoding set explicitly?
Thanks!
",https://stackoverflow.com/questions/40632802/how-to-convert-byte-array-to-string-in-go,197,512559.0,7.0,,,2016-11-16 12:59:17,2020-08-05 04:34:52,2019-04-02 08:01:17,2020-05-23 15:42:51,Duplicate,go;types;sha1,lindsay show,2099,7159949,registered,true,,,,,233,200,2,0,0,3,false,true,false,true,true,true,41,9,false,0.014,0.0004,3657,2016,11,12,Wednesday,false,false,false,false,false,false,false
9378021,How to get process details from its PID,"I have maintained a list of PIDs of processes currently running on my system (Linux). From this, now it would be great if I could get the process details from this PID. I have come over syscall.Getrusage() in Go, but I am not getting the desired results.
What should I do?
",https://stackoverflow.com/questions/9378021/how-to-get-process-details-from-its-pid,197,563703.0,7.0,,,2012-02-21 12:58:08,2026-06-01 14:46:09,2021-11-09 03:33:50,,,go,geek,2033,1169316,registered,true,,,CC BY-SA 4.0,,378,273,0,1,0,1,false,false,false,true,true,true,39,8,false,0.012,0.0003,5387,2012,2,12,Tuesday,false,false,false,false,false,false,false
12667327,Go StartsWith(str string),"Is there a StartsWith(str1, str2 string) function that can check if str1 is a prefix of str2 in Go language?
I want a function similar to the Java's startsWith().
",https://stackoverflow.com/questions/12667327/go-startswithstr-string,197,177051.0,2.0,,,2012-10-01 03:50:57,2023-07-16 11:03:25,2020-05-09 02:00:47,,,string;go;startswith,Ammar,5770,92728,registered,true,12667373,,CC BY-SA 4.0,,357,164,4,1,0,3,true,false,false,true,true,true,25,3,false,0.011,0.0011,5164,2012,10,3,Monday,false,false,false,false,false,false,false
13214029,Go build: "Cannot find package" (even though GOPATH is set),"Even though I have GOPATH properly set, I still can't get ""go build"" or ""go run"" to find my own packages. What am I doing wrong?
$ echo $GOROOT
/usr/local/go
$ echo $GOPATH
/home/mitchell/go
$ cat ~/main.go
package main
import ""foobar""
func main() { }
$ cat /home/mitchell/go/src/foobar.go
package foobar
$ go build main.go
main.go:3:8: import ""foobar"": cannot find package
",https://stackoverflow.com/questions/13214029/go-build-cannot-find-package-even-though-gopath-is-set,195,465869.0,16.0,,,2012-11-03 22:15:59,2023-06-09 12:37:50,2019-02-19 09:00:53,,,build;go;package,MitchellSalad,4281,1107253,registered,true,13223578,,CC BY-SA 4.0,,424,380,2,0,0,3,true,false,false,true,true,true,69,10,false,0.034,0.0004,5131,2012,11,22,Saturday,true,false,false,false,false,false,false
17555857,Go Unpacking Array As Arguments,"So in Python and Ruby there is the splat operator (*) for unpacking an array as arguments. In Javascript there is the .apply() function. Is there a way of unpacking an array/slice as function arguments in Go? Any resources for this would be great as well!
Something along the lines of this:
func my_func(a, b int) (int) {
return a + b
}
func main() {
arr := []int{2,4}
sum := my_func(arr)
}
",https://stackoverflow.com/questions/17555857/go-unpacking-array-as-arguments,195,183947.0,4.0,,,2013-07-09 18:45:45,2022-12-29 03:23:08,2022-12-29 03:23:08,,,go;argument-unpacking,eatonphil,13882,1507139,registered,true,17556146,,CC BY-SA 4.0,,443,405,1,0,0,2,true,false,false,true,true,true,31,5,false,0.022,0.0011,4883,2013,7,18,Tuesday,false,false,false,false,false,false,false
13244048,"No startswith,endswith functions in Go?","Just curious to findout: why aren't there standard functions like startswith, endswith, etc as part of the standard libraries in the Go programming language?
",https://stackoverflow.com/questions/13244048/no-startswith-endswith-functions-in-go,194,66590.0,2.0,,,2012-11-06 03:45:19,2020-12-17 21:21:14,,,,string;go,Sahas,11499,73249,registered,true,13244078,,CC BY-SA 3.0,,165,158,0,0,0,2,true,false,false,true,true,false,39,5,true,0.03,0.0029,5128,2012,11,3,Tuesday,false,false,false,false,false,false,false
16895294,How to set timeout for http.Get() requests in Golang?,"I'm making a URL fetcher in Go and have a list of URLs to fetch. I send http.Get() requests to each URL and obtain their response.
resp,fetch_err := http.Get(url)
How can I set a custom timeout for each Get request? (The default time is very long and that makes my fetcher really slow.) I want my fetcher to have a timeout of around 40-45 seconds after which it should return ""request timed out"" and move on to the next URL.
How can I achieve this?
",https://stackoverflow.com/questions/16895294/how-to-set-timeout-for-http-get-requests-in-golang,191,216990.0,7.0,,,2013-06-03 11:06:41,2025-02-07 05:20:46,2016-08-03 12:12:24,,,http;get;timeout;go,pymd,4521,1611112,registered,true,25344458,,CC BY-SA 3.0,,511,453,2,0,0,4,true,false,false,true,true,true,53,9,true,0.032,0.0009,4919,2013,6,11,Monday,false,false,false,false,false,false,false
19094704,Indentation in Go: tabs or spaces?,"Is there a standard Google Go coding conventions document somewhere that sets whether tabs or spaces are preferred for indentation in Go source code?
What is the official recommendation, if any?
",https://stackoverflow.com/questions/19094704/indentation-in-go-tabs-or-spaces,191,151297.0,2.0,,,2013-09-30 12:48:12,2024-06-26 13:43:15,2024-06-25 04:29:33,,,go;formatting;coding-style;indentation;gofmt,Erik Kaplun,38505,247623,registered,true,19094725,,CC BY-SA 4.0,,209,195,0,0,0,5,true,false,false,true,true,true,34,6,true,0.013,0.0013,4800,2013,9,12,Monday,false,false,false,false,false,false,false
24489384,How to print the values of slices,"I want to see the values which are in the slice. How can I print them?
projects []Project
",https://stackoverflow.com/questions/24489384/how-to-print-the-values-of-slices,190,324846.0,10.0,,,2014-06-30 11:44:21,2025-05-28 13:19:10,2019-12-06 13:27:44,,,arrays;go,fnr,9817,3771173,registered,true,24489454,,CC BY-SA 4.0,,125,94,1,0,0,2,true,false,false,true,true,true,33,7,false,0.031,0.0006,4527,2014,6,11,Monday,false,false,false,false,false,false,false
23148812,What's the meaning of interface{}?,"I'm new to interfaces and trying to do SOAP request by github
I don't understand the meaning of
Msg interface{}
in this code:
type Envelope struct {
Body `xml:""soap:""`
}
type Body struct {
Msg interface{}
}
I've observed the same syntax in
fmt.Println
but don't understand what's being achieved by
interface{}
",https://stackoverflow.com/questions/23148812/whats-the-meaning-of-interface,190,91509.0,8.0,,,2014-04-18 06:39:23,2023-12-04 19:28:44,2017-11-24 14:11:05,,,go,user,2912,2383973,registered,true,23148998,,CC BY-SA 3.0,,542,337,4,1,0,1,true,false,false,true,true,true,38,5,true,0.087,0.0021,4600,2014,4,6,Friday,false,false,false,false,false,false,false
12830095,Setting HTTP headers,"I'm trying to set a header in my Go web server. I'm using gorilla/mux and net/http packages.
I'd like to set Access-Control-Allow-Origin: * to allow cross domain AJAX.
Here's my Go code:
func saveHandler(w http.ResponseWriter, r *http.Request) {
// do some stuff with the request data
}
func main() {
r := mux.NewRouter()
r.HandleFunc(""/save"", saveHandler)
http.Handle(""/"", r)
http.ListenAndServe("":""+port, nil)
}
The net/http package has documentation describing sending http request headers as if it were a client - I'm not exactly sure how to set response headers?
",https://stackoverflow.com/questions/12830095/setting-http-headers,189,168556.0,9.0,,,2012-10-10 23:39:13,2024-03-08 01:03:41,2019-02-02 10:24:56,,,http;go;cors;http-headers,Zen,7385,464937,registered,true,12830156,,CC BY-SA 4.0,,694,590,5,0,0,4,true,false,false,true,true,true,20,3,false,0.053,0.0011,5155,2012,10,23,Wednesday,false,false,false,false,false,false,false
38552803,How to convert a bool to a string in Go?,"I am trying to convert a bool called isExist to a string (true or false) by using string(isExist) but it does not work. What is the idiomatic way to do this in Go?
",https://stackoverflow.com/questions/38552803/how-to-convert-a-bool-to-a-string-in-go,189,217411.0,4.0,,,2016-07-24 13:56:32,2021-07-19 11:48:30,,,,go;type-conversion,Casper LI,4853,2828227,registered,true,38552924,,CC BY-SA 3.0,,249,164,6,0,0,2,true,false,false,true,true,false,40,10,true,0.018,0.0009,3772,2016,7,13,Sunday,true,false,false,false,false,false,false
18207772,How to wait for all goroutines to finish without using time.Sleep?,"This code selects all xml files in the same folder, as the invoked executable and asynchronously applies processing to each result in the callback method (in the example below, just the name of the file is printed out).
How do I avoid using the sleep method to keep the main method from exiting? I have problems wrapping my head around channels (I assume that's what it takes, to synchronize the results) so any help is appreciated!
package main
import (
""fmt""
""io/ioutil""
""path""
""path/filepath""
""os""
""runtime""
""time""
)
func eachFile(extension string, callback func(file string)) {
exeDir := filepath.Dir(os.Args[0])
files, _ := ioutil.ReadDir(exeDir)
for _, f := range files {
fileName := f.Name()
if extension == path.Ext(fileName) {
go callback(fileName)
}
}
}
func main() {
maxProcs := runtime.NumCPU()
runtime.GOMAXPROCS(maxProcs)
eachFile("".xml"", func(fileName string) {
// Custom logic goes in here
fmt.Println(fileName)
})
// This is what i want to get rid of
time.Sleep(100 * time.Millisecond)
}
",https://stackoverflow.com/questions/18207772/how-to-wait-for-all-goroutines-to-finish-without-using-time-sleep,188,150598.0,6.0,,,2013-08-13 11:22:40,2024-04-02 01:57:24,2016-11-04 12:58:23,,,go;synchronization;goroutine,Dante,11474,1121143,registered,true,18207832,,CC BY-SA 3.0,,1212,1174,1,0,0,3,true,false,false,true,true,true,66,11,true,0.04,0.0012,4848,2013,8,11,Tuesday,false,false,false,false,false,false,false
33119748,Convert time.Time to string,"I'm trying to add some values from my database to a []string in Go. Some of these are timestamps.
I get the error:
cannot use U.Created_date (type time.Time) as type string in array element
Can I convert time.Time to string?
type UsersSession struct {
Userid int
Timestamp time.Time
Created_date time.Time
}
type Users struct {
Name string
Email string
Country string
Created_date time.Time
Id int
Hash string
IP string
}
var usersArray = [][]string{}
rows, err := db.Query("SELECT u.id, u.hash, u.name, u.email, u.country, u.IP, u.created_date, us.timestamp, us.created_date FROM usersSession AS us LEFT JOIN users AS u ON u.id = us.userid WHERE us.timestamp + interval 30 minute >= now()")
U := Users{}
US := UsersSession{}
for rows.Next() {
err = rows.Scan(&U.Id, &U.Hash, &U.Name, &U.Email, &U.Country, &U.IP, &U.Created_date, &US.Timestamp, &US.Created_date)
checkErr(err)
userid_string := strconv.Itoa(U.Id)
user := []string{userid_string, U.Hash, U.Name, U.Email, U.Country, U.IP, U.Created_date, US.Timestamp, US.Created_date}
// -------------
// ^ this is where the error occurs
// cannot use U.Created_date (type time.Time) as type string in array element (for US.Created_date and US.Timestamp aswell)
// -------------
usersArray = append(usersArray, user)
log.Print("usersArray: ", usersArray)
}
",https://stackoverflow.com/questions/33119748/convert-time-time-to-string,187,430714.0,6.0,,,2015-10-14 07:57:18,2023-11-13 13:31:55,2023-11-13 13:31:55,,,string;go;datetime;time,A.D,2290,4273851,registered,true,33119937,,CC BY-SA 4.0,,1596,1456,5,0,0,4,true,false,false,true,true,true,27,4,false,0.014,0.0004,4056,2015,10,7,Wednesday,false,false,false,false,false,false,false
13422578,In Go how to get a slice of values from a map?,"If I have a map m is there a better way of getting a slice of the values v than this?
package main
import (
"fmt"
)
func main() {
m := make(map[int]string)
m[1] = "a"
m[2] = "b"
m[3] = "c"
m[4] = "d"
// Can this be done better?
v := make([]string, len(m), len(m))
idx := 0
for _, value := range m {
v[idx] = value
idx++
}
fmt.Println(v)
}
Is there a built-in feature of a map? Is there a function in a Go package, or is this the only way to do this?
",https://stackoverflow.com/questions/13422578/in-go-how-to-get-a-slice-of-values-from-a-map,186,238885.0,6.0,,,2012-11-16 18:47:53,2024-09-05 06:59:24,2022-03-27 11:45:05,,,dictionary;go;slice,masebase,5295,828622,registered,true,13422647,,CC BY-SA 4.0,,644,567,4,0,0,3,true,false,false,true,true,true,46,12,true,0.025,0.0008,5118,2012,11,18,Friday,false,false,false,false,false,false,false
26327391,json.Marshal(struct) returns "{}","type TestObject struct {
kind string `json:""kind""`
id string `json:""id, omitempty""`
name string `json:""name""`
email string `json:""email""`
}
func TestCreateSingleItemResponse(t *testing.T) {
testObject := new(TestObject)
testObject.kind = ""TestObject""
testObject.id = ""f73h5jf8""
testObject.name = ""Yuri Gagarin""
testObject.email = ""Yuri.Gagarin@Vostok.com""
fmt.Println(testObject)
b, err := json.Marshal(testObject)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(b[:]))
}
Here is the output:
[ `go test -test.run=""^TestCreateSingleItemResponse$""` | done: 2.195666095s ]
{TestObject f73h5jf8 Yuri Gagarin Yuri.Gagarin@Vostok.com}
{}
PASS
Why is the JSON essentially empty?
",https://stackoverflow.com/questions/26327391/json-marshalstruct-returns,184,56173.0,1.0,,,2014-10-12 16:34:12,2024-10-14 10:38:42,2018-05-17 16:55:22,,,json;go;marshalling,Doug Knesek,6717,210153,registered,true,26327436,,CC BY-SA 4.0,,829,767,2,0,0,3,true,false,false,true,true,true,43,3,false,0.018,0.0033,4423,2014,10,16,Sunday,true,false,false,false,false,false,false
21959148,SSL is not enabled on the server,"Trying to communicate with a postgres database with go, preparing the statement like this:
var stmt *sql.Stmt
var err error
stmt, err = db.Prepare(selectStatement)
if err != nil {
fmt.Printf(""db.Prepare error: %v\n"",err)
return err
}
Throws the following error:
db.Prepare error: pq: SSL is not enabled on the server
Any solution ?
I can add more information, if needed.
",https://stackoverflow.com/questions/21959148/ssl-is-not-enabled-on-the-server,182,151928.0,8.0,,,2014-02-22 19:13:35,2025-05-26 15:42:11,2015-06-11 17:19:14,,,go,Gustavo Semião-Lobo,2718,1217298,registered,true,21959214,,CC BY-SA 3.0,,463,387,2,0,0,1,true,false,false,true,true,true,32,7,false,0.053,0.0012,4655,2014,2,19,Saturday,true,false,false,false,false,false,false
16971741,How do you clear a slice in Go?,"What is the appropriate way to clear a slice in Go?
Here's what I've found in the go forums:
// test.go
package main
import (
""fmt""
)
func main() {
letters := []string{""a"", ""b"", ""c"", ""d""}
fmt.Println(cap(letters))
fmt.Println(len(letters))
// clear the slice
letters = letters[:0]
fmt.Println(cap(letters))
fmt.Println(len(letters))
}
Is this correct?
To clarify, the buffer is cleared so it can be reused.
An example is Buffer.Truncate function in the bytes package.
Notice that Reset just calls Truncate(0). So it appears that in this case line 70 would evaluate:
b.buf = b.buf[0 : 0]
http://golang.org/src/pkg/bytes/buffer.go
// Truncate discards all but the first n unread bytes from the buffer.
60 // It panics if n is negative or greater than the length of the buffer.
61 func (b *Buffer) Truncate(n int) {
62 b.lastRead = opInvalid
63 switch {
64 case n < 0 || n > b.Len():
65 panic(""bytes.Buffer: truncation out of range"")
66 case n == 0:
67 // Reuse buffer space.
68 b.off = 0
69 }
70 b.buf = b.buf[0 : b.off+n]
71 }
72
73 // Reset resets the buffer so it has no content.
74 // b.Reset() is the same as b.Truncate(0).
75 func (b *Buffer) Reset() { b.Truncate(0) }
",https://stackoverflow.com/questions/16971741/how-do-you-clear-a-slice-in-go,182,187361.0,3.0,,,2013-06-06 20:38:30,2023-09-21 10:26:28,2018-02-05 08:16:40,,,arrays;go;slice,Chris Weber,5936,194653,registered,true,16972044,,CC BY-SA 3.0,,1644,1292,2,3,0,3,true,false,false,true,true,true,31,8,true,0.016,0.001,4916,2013,6,20,Thursday,false,false,false,false,false,false,false
27137521,How to convert interface{} to string?,"I'm using docopt to parse command-line arguments. This works, and it results in a map, such as
map[<host>:www.google.de <port>:80 --help:false --version:false]
Now I would like to concatenate the host and the port value to a string with a colon in-between the two values. Basically, something such as:
host := arguments[""<host>""] + "":"" + arguments[""<port>""]
Unfortunately, this doesn't work, as I get the error message:
invalid operation: arguments[""""] + "":"" (mismatched types interface {} and string)
So obviously I need to convert the value that I get from the map (which is just interface{}, so it can be anything) to a string. Now my question is, how do I do that?
",https://stackoverflow.com/questions/27137521/how-to-convert-interface-to-string,182,311236.0,4.0,,,2014-11-25 21:58:24,2021-07-14 20:21:28,,,,go,Golo Roden,153081,1333873,registered,true,27137607,,CC BY-SA 3.0,,885,705,5,1,0,1,true,false,false,true,true,false,37,6,true,0.013,0.0006,4379,2014,11,21,Tuesday,false,false,false,false,false,false,false
31622052,How to serve up a JSON response using Go?,"Question: Currently I'm printing out my response in the func Index
like this fmt.Fprintf(w, string(response)) however, how can I send JSON properly in the request so that it maybe consumed by a view?
package main
import (
""fmt""
""github.com/julienschmidt/httprouter""
""net/http""
""log""
""encoding/json""
)
type Payload struct {
Stuff Data
}
type Data struct {
Fruit Fruits
Veggies Vegetables
}
type Fruits map[string]int
type Vegetables map[string]int
func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
response, err := getJsonResponse();
if err != nil {
panic(err)
}
fmt.Fprintf(w, string(response))
}
func main() {
router := httprouter.New()
router.GET(""/"", Index)
log.Fatal(http.ListenAndServe("":8080"", router))
}
func getJsonResponse()([]byte, error) {
fruits := make(map[string]int)
fruits[""Apples""] = 25
fruits[""Oranges""] = 10
vegetables := make(map[string]int)
vegetables[""Carrats""] = 10
vegetables[""Beets""] = 0
d := Data{fruits, vegetables}
p := Payload{d}
return json.MarshalIndent(p, """", "" "")
}
",https://stackoverflow.com/questions/31622052/how-to-serve-up-a-json-response-using-go,182,289333.0,6.0,,,2015-07-25 01:52:11,2022-05-13 03:04:44,2017-05-06 15:59:22,,,json;go,John Abraham,18889,1191635,registered,true,31622112,,CC BY-SA 3.0,,1232,1141,3,0,0,2,true,false,false,true,true,true,41,9,true,0.021,0.0006,4137,2015,7,1,Saturday,true,false,false,false,false,false,false
15407719,"In Go's http package, how do I get the query string on a POST request?","I'm using the httppackage from Go to deal with POST request. How can I access and parse the content of the query string from the Requestobject ? I can't find the answer from the official documentation.
",https://stackoverflow.com/questions/15407719/in-gos-http-package-how-do-i-get-the-query-string-on-a-post-request,181,332428.0,6.0,,,2013-03-14 11:17:00,2025-07-07 02:53:38,2016-08-03 15:14:19,,,go;query-string,Fabien,13716,87584,registered,true,15408779,,CC BY-SA 3.0,,235,202,2,0,0,2,true,false,false,true,true,true,74,15,true,0.018,0.0005,5000,2013,3,11,Thursday,false,false,false,false,false,false,false
26027350,Go Interface Fields,"I'm familiar with the fact that, in Go, interfaces define functionality, rather than data. You put a set of methods into an interface, but you are unable to specify any fields that would be required on anything that implements that interface.
For example:
// Interface
type Giver interface {
Give() int64
}
// One implementation
type FiveGiver struct {}
func (fg *FiveGiver) Give() int64 {
return 5
}
// Another implementation
type VarGiver struct {
number int64
}
func (vg *VarGiver) Give() int64 {
return vg.number
}
Now we can use the interface and its implementations:
// A function that uses the interface
func GetSomething(aGiver Giver) {
fmt.Println(""The Giver gives: "", aGiver.Give())
}
// Bring it all together
func main() {
fg := &FiveGiver{}
vg := &VarGiver{3}
GetSomething(fg)
GetSomething(vg)
}
/*
Resulting output:
5
3
*/
Now, what you can't do is something like this:
type Person interface {
Name string
Age int64
}
type Bob struct implements Person { // Not Go syntax!
...
}
func PrintName(aPerson Person) {
fmt.Println(""Person's name is: "", aPerson.Name)
}
func main() {
b := &Bob{""Bob"", 23}
PrintName(b)
}
However, after playing around with interfaces and embedded structs, I've discovered a way to do this, after a fashion:
type PersonProvider interface {
GetPerson() *Person
}
type Person struct {
Name string
Age int64
}
func (p *Person) GetPerson() *Person {
return p
}
type Bob struct {
FavoriteNumber int64
Person
}
Because of the embedded struct, Bob has everything Person has. It also implements the PersonProvider interface, so we can pass Bob into functions that are designed to use that interface.
func DoBirthday(pp PersonProvider) {
pers := pp.GetPerson()
pers.Age += 1
}
func SayHi(pp PersonProvider) {
fmt.Printf(""Hello, %v!\r"", pp.GetPerson().Name)
}
func main() {
b := &Bob{
5,
Person{""Bob"", 23},
}
DoBirthday(b)
SayHi(b)
fmt.Printf(""You're %v years old now!"", b.Age)
}
Here is a Go Playground that demonstrates the above code.
Using this method, I can make an interface that defines data rather than behavior, and which can be implemented by any struct just by embedding that data. You can define functions that explicitly interact with that embedded data and are unaware of the nature of the outer struct. And everything is checked at compile time! (The only way you could mess up, that I can see, would be embedding the interface PersonProvider in Bob, rather than a concrete Person. It would compile and fail at runtime.)
Now, here's my question: is this a neat trick, or should I be doing it differently?
",https://stackoverflow.com/questions/26027350/go-interface-fields,180,133921.0,2.0,,,2014-09-24 22:07:41,2024-01-10 03:38:55,2014-09-24 22:31:19,,,struct;interface;go,Matt Mc,9347,700471,registered,true,26027902,,CC BY-SA 3.0,,3014,2733,8,1,0,3,true,false,false,true,true,true,19,3,false,0.015,0.0013,4441,2014,9,22,Wednesday,false,false,false,false,false,false,false
10510691,How to check whether a file or directory exists?,"I want to check the existence of file ./conf/app.ini in my Go code,
but I can't find a good way to do that.
I know there is a method of File in Java: public boolean exists(), which returns true if the file or directory exists.
But how can this be done in Go?
",https://stackoverflow.com/questions/10510691/how-to-check-whether-a-file-or-directory-exists,179,164850.0,6.0,,,2012-05-09 06:12:59,2024-12-25 09:30:50,2018-07-13 21:50:40,2021-01-30 11:36:47,Duplicate,file;go,hardPass,21241,1316684,registered,true,10510783,,,,311,264,2,0,0,2,true,true,false,true,true,true,48,9,true,0.036,0.0011,5309,2012,5,6,Wednesday,false,false,false,false,false,false,false
67203641,missing go.sum entry for module providing package <package_name>,"Using the buffalo framework,
after bootstraping it via buffalo new <project_name>
I am trying to run buffalo dev
Expecting to see:
project running on port 3000
But I am getting those error messages instead
actions/app.go:4:2: missing go.sum entry for module providing package github.com/gobuffalo/buffalo (imported by sc_api/actions); to add:go get sc_api/actions
actions/app.go:13:2: missing go.sum entry for module providing package github.com/gobuffalo/mw-csrf (imported by sc_api/actions); to add: go get sc_api/actions
actions/app.go has been generated by buffalo, but in case you are wondering the error does match the import statement in this file.
// app.go
package actions
import (
"github.com/gobuffalo/buffalo" // 1rst line
"github.com/gobuffalo/envy"
forcessl "github.com/gobuffalo/mw-forcessl"
paramlogger "github.com/gobuffalo/mw-paramlogger"
"github.com/unrolled/secure"
"sc_api/models"
"github.com/gobuffalo/buffalo-pop/v2/pop/popmw"
csrf "github.com/gobuffalo/mw-csrf" // 2nd line
i18n "github.com/gobuffalo/mw-i18n"
"github.com/gobuffalo/packr/v2"
)
What does it mean ? How do I fix it ?
",https://stackoverflow.com/questions/67203641/missing-go-sum-entry-for-module-providing-package-package-name,179,194852.0,4.0,,,2021-04-21 21:20:37,2023-11-08 22:52:44,2021-09-16 09:38:52,,,go;go-modules;buffalo,Paulo,11112,4534923,registered,true,67203642,,CC BY-SA 4.0,,1416,1262,5,0,0,3,true,false,false,true,true,true,70,8,false,0.021,0.0009,2040,2021,4,21,Wednesday,false,false,false,false,false,false,false
15018545,How to index characters in a Golang string?,"How to get an ""E"" output rather than 69?
package main
import ""fmt""
func main() {
fmt.Print(""HELLO""[1])
}
Does Golang have function to convert a char to byte and vice versa?
",https://stackoverflow.com/questions/15018545/how-to-index-characters-in-a-golang-string,179,274154.0,12.0,,,2013-02-22 06:56:04,2024-07-11 13:18:22,2015-11-10 14:55:22,,,string;go;character,user977828,7767,977828,registered,true,15020162,,CC BY-SA 3.0,2024-07-08 15:50:48,220,182,1,0,0,3,true,false,false,true,true,true,43,8,true,0.044,0.0007,5020,2013,2,6,Friday,false,false,false,false,false,false,false
19998250,Proper package naming for testing with the Go language,"I have seen several different test package naming strategies within Go and wanted to know what pros and cons of each are and which one I should use.
Strategy 1:
File name: github.com/user/myfunc.go
package myfunc
Test file name: github.com/user/myfunc_test.go
package myfunc
See bzip2 for an example.
Strategy 2:
File name: github.com/user/myfunc.go
package myfunc
Test file name: github.com/user/myfunc_test.go
package myfunc_test
import (
"github.com/user/myfunc"
)
See wire for an example.
Strategy 3:
File name: github.com/user/myfunc.go
package myfunc
Test file name: github.com/user/myfunc_test.go
package myfunc_test
import (
. "myfunc"
)
See strings for an example.
The Go standard library seems to use a mixture of strategy 1 and 2. Which of all three should I use? It's a pain appending package *_test to my testing packages as it means I can't test my package private methods but maybe there is a hidden advantage I am not aware of?
",https://stackoverflow.com/questions/19998250/proper-package-naming-for-testing-with-the-go-language,179,65426.0,4.0,,,2013-11-15 09:56:53,2022-03-29 08:33:37,2022-03-29 08:33:37,,,unit-testing;go,Dan,5373,736070,registered,true,31443271,,CC BY-SA 4.0,,1625,980,13,3,0,2,true,false,false,true,true,true,54,9,false,0.061,0.0027,4754,2013,11,9,Friday,false,false,false,false,false,false,false
21268000,Unmarshaling nested JSON objects,"There are a few questions on the topic but none of them seem to cover my case, thus I'm creating a new one.
I have JSON like the following:
{""foo"":{ ""bar"": ""1"", ""baz"": ""2"" }, ""more"": ""text""}
Is there a way to unmarshal the nested bar property and assign it directly to a struct property without creating a nested struct?
The solution I'm adopting right now is the following:
type Foo struct {
More String `json:""more""`
Foo struct {
Bar string `json:""bar""`
Baz string `json:""baz""`
} `json:""foo""`
// FooBar string `json:""foo.bar""`
}
This is a simplified version, please ignore the verbosity. As you can see, I'd like to be able to parse and assign the value to
// FooBar string `json:""foo.bar""`
I've seen people using a map, but that's not my case. I basically don't care about the content of foo (which is a large object), except for a few specific elements.
What is the correct approach in this case? I'm not looking for weird hacks, thus if this is the way to go, I'm fine with that.
",https://stackoverflow.com/questions/21268000/unmarshaling-nested-json-objects,179,214982.0,9.0,,,2014-01-21 20:05:58,2023-03-20 14:22:50,2020-02-23 20:56:54,,,json;go,Simone Carletti,177685,123527,registered,true,21268855,,CC BY-SA 4.0,2018-04-01 03:56:14,1638,1034,4,4,0,2,true,false,false,true,true,true,32,4,false,0.042,0.0008,4687,2014,1,20,Tuesday,false,false,false,false,false,false,false
30612611,What does go build build? (go build vs. go install),"New Go programmers often don't know or get confused what the fundamental go build command does.
What do exactly the go build and go install commands build and where do they put the result/output?
",https://stackoverflow.com/questions/30612611/what-does-go-build-build-go-build-vs-go-install,177,134446.0,2.0,,,2015-06-03 06:39:22,2019-12-29 02:57:31,2019-12-29 02:57:31,,,go;build;compilation,icza,424367,1705598,registered,true,30612612,,CC BY-SA 4.0,,237,197,2,0,0,3,true,false,false,true,true,true,51,10,false,0.015,0.0013,4189,2015,6,6,Wednesday,false,false,false,false,false,false,false
53837919,Should go.sum file be checked in to the git repository?,"I have a program with source code hosted on GitHub that uses Go Modules introduced in go 1.11.
go.mod file describes my dependencies, but go.sum file seems to be a lockfile. Should I be adding go.sum to my repository or should I gitignore it?
",https://stackoverflow.com/questions/53837919/should-go-sum-file-be-checked-in-to-the-git-repository,176,81097.0,2.0,,,2018-12-18 17:06:17,2024-05-30 21:42:56,,,,go,ahmet alp balkan,46180,54929,registered,true,53852916,,CC BY-SA 4.0,,297,244,3,0,0,1,true,false,false,true,true,false,55,10,true,0.025,0.0022,2895,2018,12,17,Tuesday,false,false,false,false,false,false,false
5885486,Get current time as formatted string in Go?,"What's the best way to get the current timestamp in Go and convert to string? I need both date and time in eg. YYYYMMDDhhmmss format.
",https://stackoverflow.com/questions/5885486/get-current-time-as-formatted-string-in-go,175,269112.0,9.0,,,2011-05-04 15:00:04,2023-01-11 16:58:57,2019-11-27 13:07:10,,,timestamp;go,brianoh,3597,727302,registered,true,5885753,,CC BY-SA 4.0,,141,134,0,0,0,2,true,false,false,true,true,true,43,8,true,0.033,0.0007,5680,2011,5,15,Wednesday,false,false,false,false,false,false,false
37932551,mkdir if not exists using golang,"I am learning golang(beginner) and I have been searching on both google and stackoverflow but I could not find an answer so excuse me if already asked, but how can I mkdir if not exists in golang.
For example in node I would use fs-extra with the function ensureDirSync (if blocking is of no concern of course)
fs.ensureDir(""./public"");
",https://stackoverflow.com/questions/37932551/mkdir-if-not-exists-using-golang,173,166567.0,7.0,,,2016-06-20 22:03:35,2023-08-14 13:36:02,2020-04-23 23:44:58,,,go;directory;path;filepath;mkdir,Alfred,62093,11926,registered,true,37932674,,CC BY-SA 4.0,,477,340,1,1,0,5,true,false,false,true,true,true,32,6,false,0.042,0.001,3806,2016,6,22,Monday,false,false,false,false,false,false,false
1752414,How to reverse a string in Go?,"How can we reverse a simple string in Go?
",https://stackoverflow.com/questions/1752414/how-to-reverse-a-string-in-go,173,181723.0,39.0,,,2009-11-17 22:44:47,2025-02-12 10:03:17,2015-12-30 00:22:54,,,string;go;reverse,user211499,1757,211499,registered,true,,,CC BY-SA 3.0,2018-08-31 05:34:54,49,42,0,0,0,3,false,false,false,true,true,true,30,7,true,0.215,0.001,6213,2009,11,22,Tuesday,false,false,false,false,false,false,false
26545883,How to do one-liner if else statement?,"Please see https://golangdocs.com/ternary-operator-in-golang as pointed by @accdias (see comments)
Can I write a simple if-else statement with variable assignment in go (golang) as I would do in php? For example:
$var = ( $a > $b )? $a: $b;
Currently I have to use the following:
var c int
if a > b {
c = a
} else {
c = b
}
Sorry I cannot remember the name if this control statement and I couldn't find the info in-site or through google search. :/
",https://stackoverflow.com/questions/26545883/how-to-do-one-liner-if-else-statement,173,347937.0,12.0,,,2014-10-24 10:09:15,2022-09-26 07:26:04,2022-09-26 07:26:04,2021-06-30 22:46:57,Duplicate,go;if-statement;conditional-operator,thoroc,3697,2120421,registered,true,26546039,,,,622,465,2,1,0,3,true,true,false,true,true,true,38,7,true,0.034,0.0005,4411,2014,10,10,Friday,false,false,false,false,false,false,false
12168873,Cross compile Go on OSX?,"I am trying to cross-compile a go app on OSX to build binaries for windows and linux. I have read everything what I could find on the net. Closest example that I have found has been published on (apart from many unfinished discussions on go-nuts mailing list):
http://solovyov.net/en/2012/03/09/cross-compiling-go/
yet it does not work on my installation. I have go 1.0.2. As 1.0.2 is quite recent it looks to me that all above examples do not apply to this version.
Tried to do ./make.bash --no-clean with ENV vars set to 386/windows, it does build go, however it builds go for my installation which is darwin/amd64 and completely ignores what is set in ENV that suppose to build different compiler.
Any advises how it can be done (if it can be done at all)?
",https://stackoverflow.com/questions/12168873/cross-compile-go-on-osx,172,189437.0,9.0,,,2012-08-28 23:16:30,2024-04-29 17:56:42,2017-02-09 09:03:53,,,go;compilation;cross-compiling,ljgww,3558,1454391,registered,true,35878611,,CC BY-SA 3.0,,893,764,2,1,0,3,true,false,false,true,true,true,24,5,true,0.048,0.0009,5198,2012,8,23,Tuesday,false,false,false,false,false,false,false
17480044,How to install the current version of Go in Ubuntu Precise,"Running sudo apt-get install golang-stable, I get Go version go1.0.3. Is there any way to install go1.1.1?
",https://stackoverflow.com/questions/17480044/how-to-install-the-current-version-of-go-in-ubuntu-precise,172,243312.0,20.0,,,2013-07-05 01:50:32,2023-10-28 08:00:51,2015-06-15 00:43:08,,,ubuntu;go,scc,10836,46183,registered,true,17566846,,CC BY-SA 3.0,,153,107,3,0,0,2,true,false,false,true,true,true,58,11,false,0.082,0.0007,4887,2013,7,1,Friday,false,false,false,false,false,false,false
19992334,how to listen to N channels? (dynamic select statement),"to start an endless loop of executing two goroutines, I can use the code below:
after receiving the msg it will start a new goroutine and go on for ever.
c1 := make(chan string)
c2 := make(chan string)
go DoStuff(c1, 5)
go DoStuff(c2, 2)
for ; true; {
select {
case msg1 := <-c1:
fmt.Println(""received "", msg1)
go DoStuff(c1, 1)
case msg2 := <-c2:
fmt.Println(""received "", msg2)
go DoStuff(c2, 9)
}
}
I would now like to have the same behavior for N goroutines, but how will the select statement look in that case?
This is the code bit I have started with, but I am confused how to code the select statement
numChans := 2
//I keep the channels in this slice, and want to ""loop"" over them in the select statemnt
var chans = [] chan string{}
for i:=0;i<numChans;i++{
tmp := make(chan string);
chans = append(chans, tmp);
go DoStuff(tmp, i + 1)
//How shall the select statment be coded for this case?
for ; true; {
select {
case msg1 := <-c1:
fmt.Println(""received "", msg1)
go DoStuff(c1, 1)
case msg2 := <-c2:
fmt.Println(""received "", msg2)
go DoStuff(c2, 9)
}
}
",https://stackoverflow.com/questions/19992334/how-to-listen-to-n-channels-dynamic-select-statement,172,70789.0,7.0,,,2013-11-15 02:18:00,2022-09-01 15:30:05,2019-01-24 18:43:17,,,go,JohnSmith,4688,304969,registered,true,19992525,,CC BY-SA 4.0,,1277,1201,2,0,0,1,true,false,false,true,true,true,55,9,false,0.099,0.0024,4754,2013,11,2,Friday,false,false,false,false,false,false,false
11353679,What's the recommended way to connect to MySQL from Go?,"I am looking for a reliable solution to connect to a MySQL database from Go. I've seen some libraries around, but it is difficult to determine the different states of completeness and current maintenance. I don't have complex needs, but I'd like to know what people are relying on or the most standard solution to connect to MySQL.
",https://stackoverflow.com/questions/11353679/whats-the-recommended-way-to-connect-to-mysql-from-go,172,78600.0,3.0,,,2012-07-05 23:00:36,2022-03-29 08:01:49,2022-03-29 08:00:24,2022-03-29 10:35:16,Not suitable for this site,mysql;database;go,Sergi Mansilla,12841,78640,registered,true,11357116,,,2019-05-17 06:02:22,339,332,0,0,0,3,true,true,false,true,true,true,59,10,true,0.038,0.0022,5252,2012,7,23,Thursday,false,false,false,false,false,false,false
46917331,What is the difference between backticks (``) & double quotes ("") in golang?,"What is the difference between backticks (``) & double quotes ("") in golang?
",https://stackoverflow.com/questions/46917331/what-is-the-difference-between-backticks-double-quotes-in-golang,172,85843.0,6.0,,,2017-10-24 18:12:19,2025-10-28 16:24:13,2024-03-12 03:11:19,,,string;go;quotes;string-literals;backticks,samadadi,3530,3858203,registered,true,46917369,,CC BY-SA 4.0,,125,92,2,0,0,5,true,false,false,true,true,true,91,13,true,0.07,0.002,3315,2017,10,18,Tuesday,false,false,false,false,false,false,false
24878737,What is the difference between go get and go install?,"After playing with the go tool for a while, it looks like go get:
- (optionally) downloads,
- compiles,
- and installs
a piece of software, while go install simply
- compiles
- and installs
it. In this case, why does the go install command exist, since go get supersedes it?
",https://stackoverflow.com/questions/24878737/what-is-the-difference-between-go-get-and-go-install,172,141200.0,6.0,,,2014-07-22 04:06:42,2024-08-12 15:50:24,2018-07-03 06:20:25,,,go,thiagowfx,6107,1745064,registered,true,24878851,,CC BY-SA 4.0,,422,273,5,0,0,1,true,false,false,true,true,true,53,10,true,0.042,0.0012,4505,2014,7,4,Tuesday,false,false,false,false,false,false,false
13190836,Is there a way to iterate over a slice in reverse in Go?,"It would be convenient to be able to say something like:
for _, element := reverse range mySlice {
...
}
Edit: I asked this question a long time ago, it is 2022 now and the generic solution by @Ivan below seems like the way to go!
",https://stackoverflow.com/questions/13190836/is-there-a-way-to-iterate-over-a-slice-in-reverse-in-go,170,131230.0,9.0,,,2012-11-02 07:07:43,2024-08-20 20:31:16,2023-01-06 19:48:16,,,go,agam,5524,387527,registered,true,13191474,,CC BY-SA 4.0,,296,240,1,0,0,1,true,false,false,true,true,true,56,13,true,0.069,0.0013,5132,2012,11,7,Friday,false,false,false,false,false,false,false
33238518,What could happen if I don't close response.Body?,"In Go, I have some http responses and I sometimes forget to call:
resp.Body.Close()
What happens in this case? will there be a memory leak? Also is it safe to put in defer resp.Body.Close() immediately after getting the response object?
client := http.DefaultClient
resp, err := client.Do(req)
defer resp.Body.Close()
if err != nil {
return nil, err
}
What if there is an error, could resp or resp.Body be nil?
",https://stackoverflow.com/questions/33238518/what-could-happen-if-i-dont-close-response-body,170,112564.0,5.0,,,2015-10-20 13:49:41,2021-05-21 21:27:07,2020-03-30 14:18:35,,,go,Daniel Robinson,15098,1259261,registered,true,33238755,,CC BY-SA 4.0,,531,423,5,0,0,1,true,false,false,true,true,true,53,8,true,0.044,0.0015,4050,2015,10,13,Tuesday,false,false,false,false,false,false,false
30652577,Go doing a GET request and building the Querystring,"I am pretty new to Go and don't quite understand everything as yet. In many of the modern languages Node.js, Angular, jQuery, PHP you can do a GET request with additional query string parameters.
Doing this in Go isn't quite a simple as it seems, and I can't really figure it out as yet. I really don't want to have to concatenate a string for each of the requests I want to do.
Here is the sample script:
package main
import (
""fmt""
""io/ioutil""
""net/http""
)
func main() {
client := &http.Client{}
req, _ := http.NewRequest(""GET"", ""http://api.themoviedb.org/3/tv/popular"", nil)
req.Header.Add(""Accept"", ""application/json"")
resp, err := client.Do(req)
if err != nil {
fmt.Println(""Errored when sending request to the server"")
return
}
defer resp.Body.Close()
resp_body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(resp.Status)
fmt.Println(string(resp_body))
}
In this example you can see there is a URL, which requires a GET variable of api_key with your api key as the value. The problem being that this becomes hard coded in the form of:
req, _ := http.NewRequest(""GET"", ""http://api.themoviedb.org/3/tv/popular?api_key=mySuperAwesomeApiKey"", nil)
Is there a way to build this query string dynamically?? At the moment I will need to assemble the URL prior to this step in order to get a valid response.
",https://stackoverflow.com/questions/30652577/go-doing-a-get-request-and-building-the-querystring,169,307357.0,4.0,,,2015-06-04 19:32:14,2024-03-27 18:19:27,2015-06-04 19:35:06,,,http;go,Rudi Strydom,4667,2080324,registered,true,,,CC BY-SA 3.0,,1473,1390,2,0,0,2,false,false,false,true,true,true,51,9,false,0.013,0.0005,4188,2015,6,19,Thursday,false,false,false,false,false,false,false
24855081,How do I import a specific version of a package using go get?,"coming from a Node environment I used to install a specific version of a vendor lib into the project folder (node_modules) by telling npm to install that version of that lib from the package.json or even directly from the console, like so:
$ npm install express@4.0.0
Then I used to import that version of that package in my project just with:
var express = require('express');
Now, I want to do the same thing with go. How can I do that?
Is it possible to install a specific version of a package? If so, using a centralized $GOPATH, how can I import one version instead of another?
I would do something like this:
$ go get github.com/wilk/uuid@0.0.1
$ go get github.com/wilk/uuid@0.0.2
But then, how can I make a difference during the import?
",https://stackoverflow.com/questions/24855081/how-do-i-import-a-specific-version-of-a-package-using-go-get,169,331318.0,15.0,,,2014-07-20 21:28:02,2021-11-17 20:15:10,2016-06-23 05:03:39,,,go;package;package-managers,Wilk,8193,916784,registered,true,51979879,,CC BY-SA 3.0,,939,754,9,0,0,3,true,false,false,true,true,true,61,13,true,0.045,0.0005,4507,2014,7,21,Sunday,true,false,false,false,false,false,false
19230191,Convert an integer to a float number,"How do I convert an integer value to float64 type?
I tried
float(integer_value)
But this does not work. And can't find any package that does this on Golang.org
How do I get float64 values from integer values?
",https://stackoverflow.com/questions/19230191/convert-an-integer-to-a-float-number,169,216101.0,3.0,,,2013-10-07 16:41:25,2022-11-08 00:23:44,2020-02-23 20:52:56,,,go,user2671513,,,does_not_exist,true,19230240,,CC BY-SA 4.0,,343,214,3,1,0,1,true,false,false,true,false,true,36,7,false,0.014,0.0008,4793,2013,10,16,Monday,false,false,false,false,false,false,false
11064981,Why does Go have a "goto" statement?,"I was surprised to find that Go has a 'goto' statement. I've always been taught that 'goto' statements are a thing of the past and evil for it occludes the actual flow of a program, and that functions or methods are always a better way of controlling flow.
I must be missing something. Why did Google include it?
",https://stackoverflow.com/questions/11064981/why-does-go-have-a-goto-statement,169,96598.0,3.0,,,2012-06-16 15:58:41,2022-01-07 23:43:21,2022-01-07 23:41:26,2022-01-07 12:57:24,Opinion-based,go;goto,harm,10481,71444,registered,true,11065563,,,,401,313,0,1,0,2,true,true,false,true,true,true,46,7,true,0.031,0.0017,5271,2012,6,15,Saturday,true,false,false,false,false,false,false
19094099,How to dump goroutine stacktraces?,"I have Java background, and I love to use signal QUIT to inspect Java thread dump.
How to let Golang print out all goroutines stack trace?
",https://stackoverflow.com/questions/19094099/how-to-dump-goroutine-stacktraces,168,187804.0,11.0,,,2013-09-30 12:17:48,2024-12-01 12:42:33,2014-07-11 20:20:22,,,go,user972946,,,does_not_exist,true,19094539,,CC BY-SA 3.0,,154,140,0,0,0,1,true,false,false,true,false,true,34,5,true,0.059,0.0009,4800,2013,9,12,Monday,false,false,false,false,false,false,false
6807590,How to stop a goroutine,"I have a goroutine that calls a method, and passes returned value on a channel:
ch := make(chan int, 100)
go func(){
for {
ch <- do_stuff()
}
}()
How do I stop such a goroutine?
",https://stackoverflow.com/questions/6807590/how-to-stop-a-goroutine,168,262923.0,8.0,,,2011-07-24 15:05:03,2025-08-11 07:21:22,2019-10-20 15:40:17,,,go;goroutine;channel,Łukasz Gruner,3259,459706,registered,true,8098837,,CC BY-SA 4.0,2019-10-20 15:40:10,238,200,1,0,0,3,true,false,false,true,true,true,23,5,false,0.03,0.0006,5599,2011,7,15,Sunday,true,false,false,false,false,false,false
16551354,How to split a string and assign it to variables,"In Python it is possible to split a string and assign it to variables:
ip, port = '127.0.0.1:5432'.split(':')
but in Go it does not seem to work:
ip, port := strings.Split(""127.0.0.1:5432"", "":"")
// assignment count mismatch: 2 = 1
Question: How to split a string and assign values in one step?
",https://stackoverflow.com/questions/16551354/how-to-split-a-string-and-assign-it-to-variables,168,167528.0,9.0,,,2013-05-14 19:31:42,2020-07-26 17:53:33,2020-02-23 21:06:31,,,string;go;split,Pyt,1935,2383156,registered,true,16551613,,CC BY-SA 4.0,,386,300,2,0,0,3,true,false,false,true,true,true,48,10,false,0.054,0.001,4939,2013,5,19,Tuesday,false,false,false,false,false,false,false
13247644,ToString() function in Go,"The strings.Join function takes slices of strings only:
s := []string{""foo"", ""bar"", ""baz""}
fmt.Println(strings.Join(s, "", ""))
But it would be nice to be able to pass arbitrary objects which implement a ToString() function.
type ToStringConverter interface {
ToString() string
}
Is there something like this in Go or do I have to decorate existing types like int with ToString methods and write a wrapper around strings.Join?
func Join(a []ToStringConverter, sep string) string
",https://stackoverflow.com/questions/13247644/tostring-function-in-go,167,207390.0,7.0,,,2012-11-06 09:02:41,2022-08-14 10:10:18,2012-11-06 09:32:56,,,go;tostring,deamon,93452,238134,registered,true,13247979,,CC BY-SA 3.0,,634,489,7,0,0,2,true,false,false,true,true,true,25,4,false,0.034,0.0008,5128,2012,11,9,Tuesday,false,false,false,false,false,false,false
34846848,How to break a long line of code in Golang?,"Coming from Python, I'm not used to see code lines longer than 80 columns.
So when I encounter this:
err := database.QueryRow(""select * from users where user_id=?"", id).Scan(&ReadUser.ID, &ReadUser.Name, &ReadUser.First, &ReadUser.Last, &ReadUser.Email)
I tried to break it to
err := database.QueryRow(""select * from users where user_id=?"", id) \
.Scan(&ReadUser.ID, &ReadUser.Name, &ReadUser.First, &ReadUser.Last, &ReadUser.Email)
But I get
syntax error: unexpected \
I also tried just breaking the line with hitting enter and put a semicolon at the end:
err := database.QueryRow(""select * from users where user_id=?"", id)
.Scan(&ReadUser.ID, &ReadUser.Name, &ReadUser.First, &ReadUser.Last, &ReadUser.Email);
But the I again get:
syntax error: unexpected .
So I'm wondering what's the golangic way to do so?
",https://stackoverflow.com/questions/34846848/how-to-break-a-long-line-of-code-in-golang,167,125591.0,7.0,,,2016-01-18 03:29:35,2023-05-24 07:43:15,2019-10-01 07:03:06,,,go;syntax,Karlom,15174,5774375,registered,true,34848928,,CC BY-SA 4.0,,1056,894,5,0,0,2,true,false,false,true,true,true,43,10,true,0.056,0.0013,3960,2016,1,3,Monday,false,false,false,false,false,false,false
18149601,Go install fails with error: no install location for directory xxx outside GOPATH,"~/src/go-statsd-client> echo $GOPATH
/Users/me/gopath
~/src/go-statsd-client> echo $GOROOT
/usr/local/Cellar/go/1.1.1\
~/src/go-statsd-client> go install
go install: no install location for directory /Users/me/src/go-statsd-client outside GOPATH
No matter what structure the project is in this always fails with the same message. Go build works perfectly.
Here is my go env
GOARCH=""amd64""
GOBIN=""""
GOCHAR=""6""
GOEXE=""""
GOHOSTARCH=""amd64""
GOHOSTOS=""darwin""
GOOS=""darwin""
GOPATH=""/Users/me/gopath""
GORACE=""""
GOROOT=""/usr/local/Cellar/go/1.1.1""
GOTOOLDIR=""/usr/local/Cellar/go/1.1.1/pkg/tool/darwin_amd64""
CC=""gcc""
GOGCCFLAGS=""-g -O2 -fPIC -m64 -pthread -fno-common""
CGO_ENABLED=""1""
This is on Mac OSX Mountain Lion and go was installed with homebrew.
",https://stackoverflow.com/questions/18149601/go-install-fails-with-error-no-install-location-for-directory-xxx-outside-gopat,166,134502.0,12.0,,,2013-08-09 14:52:32,2019-07-01 00:12:09,2019-03-03 16:47:28,,,macos;go,tgandrews,12688,41709,registered,true,18164310,,CC BY-SA 4.0,,845,763,3,0,0,2,true,false,false,true,true,true,81,13,false,0.089,0.0012,4852,2013,8,14,Friday,false,false,false,false,false,false,false
27267900,Runtime error: assignment to entry in nil map,"I am trying to generate a map and then convert that to a yaml file like this:
uid :
kasi:
cn: Chaithra
street: fkmp
nandan:
cn: Chaithra
street: fkmp
remya:
cn: Chaithra
street: fkmp
I think I am missing something important while creating the map. My code is below.
package main
import (
""fmt""
""gopkg.in/yaml.v2""
)
type T struct {
cn string
street string
}
func main() {
names := []string{""kasi"", ""remya"", ""nandan""}
m := make(map[string]map[string]T, len(names))
for _, name := range names {
//t := T{cn: ""Chaithra"", street: ""fkmp""}
m[""uid""][name] = T{cn: ""Chaithra"", street: ""fkmp""}
}
fmt.Println(m)
y, _ := yaml.Marshal(&m)
fmt.Println(string(y))
//fmt.Println(m, names)
}
It is giving the following error:
panic: runtime error: assignment to entry in nil map
",https://stackoverflow.com/questions/27267900/runtime-error-assignment-to-entry-in-nil-map,166,204217.0,6.0,,,2014-12-03 09:26:26,2023-11-12 00:52:33,2014-12-05 21:26:20,,,dictionary;go;yaml,Kasinath Kottukkal,2649,2321866,registered,true,27268063,,CC BY-SA 3.0,,1010,917,3,0,0,3,true,false,false,true,true,true,45,8,false,0.029,0.0008,4371,2014,12,9,Wednesday,false,false,false,false,false,false,false
13511203,Why can't I assign a *Struct to an *Interface?,"I'm just working through the Go tour, and I'm confused about pointers and interfaces. Why doesn't this Go code compile?
package main
type Interface interface {}
type Struct struct {}
func main() {
var ps *Struct
var pi *Interface
pi = ps
_, _ = pi, ps
}
i.e. if Struct is an Interface, why wouldn't a *Struct be a *Interface?
The error message I get is:
prog.go:10: cannot use ps (type *Struct) as type *Interface in assignment:
*Interface is pointer to interface, not interface
",https://stackoverflow.com/questions/13511203/why-cant-i-assign-a-struct-to-an-interface,166,82942.0,4.0,,,2012-11-22 10:55:50,2020-01-11 10:38:59,,,,go,Simon Nickerson,43477,4728,registered,true,13511853,,CC BY-SA 3.0,,672,513,6,1,0,1,true,false,false,true,true,false,50,9,true,0.048,0.002,5112,2012,11,10,Thursday,false,false,false,false,false,false,false
38654383,How to search for an element in a golang slice,"I have a slice of structs.
type Config struct {
Key string
Value string
}
// I form a slice of the above struct
var myconfig []Config
// unmarshal a response body into the above slice
if err := json.Unmarshal(respbody, &myconfig); err != nil {
panic(err)
}
fmt.Println(config)
Here is the output of this:
[{key1 test} {web/key1 test2}]
How can I search this array to get the element where key=""key1""?
",https://stackoverflow.com/questions/38654383/how-to-search-for-an-element-in-a-golang-slice,165,373253.0,10.0,,,2016-07-29 08:46:01,2025-07-22 21:14:06,2018-12-07 09:48:21,,,go;struct;slice,codec,8974,5996587,registered,true,38654444,,CC BY-SA 4.0,,509,427,3,0,0,3,true,false,false,true,true,true,46,10,false,0.027,0.0004,3767,2016,7,8,Friday,false,false,false,false,false,false,false
6125683,Call Go functions from C,"I am trying to create a static object written in Go to interface with a C program (say, a kernel module or something).
I have found documentation on calling C functions from Go, but I haven't found much on how to go the other way. What I've found is that it's possible, but complicated.
Here is what I found:
Blog post about callbacks between C and Go
Does anyone have experience with this? In short, I'm trying to create a PAM module written entirely in Go.
",https://stackoverflow.com/questions/6125683/call-go-functions-from-c,165,64852.0,4.0,,,2011-05-25 14:02:12,2022-03-28 18:06:33,2016-12-14 18:19:59,,,c;shared-libraries;go;dynamic-linking,beatgammit,20311,538551,registered,true,6147097,,CC BY-SA 3.0,,838,509,0,3,0,4,true,false,false,true,true,true,24,5,false,0.062,0.0025,5659,2011,5,14,Wednesday,false,false,false,false,false,false,false
20628918,"cannot download, $GOPATH not set","I want to install json2csv using go get github.com/jehiah/json2csv but I receive this error:
package github.com/jehiah/json2csv: cannot download, $GOPATH not set. For more details see: go help go path
Any help on how to fix this on MacOS?
",https://stackoverflow.com/questions/20628918/cannot-download-gopath-not-set,163,173163.0,15.0,,,2013-12-17 08:06:03,2020-08-20 13:48:01,,,,macos;installation;go,Mona Jalal,39075,2414957,registered,true,20629533,,CC BY-SA 3.0,,293,242,2,0,0,3,true,false,false,true,true,false,32,5,false,0.087,0.0009,4722,2013,12,8,Tuesday,false,false,false,false,false,false,false
6372474,How to determine an interface{} value's "real" type?,"I have not found a good resource for using interface{} types. For example
package main
import ""fmt""
func weirdFunc(i int) interface{} {
if i == 0 {
return ""zero""
}
return i
}
func main() {
var i = 5
var w = weirdFunc(5)
// this example works!
if tmp, ok := w.(int); ok {
i += tmp
}
fmt.Println(""i ="", i)
}
Do you know of a good introduction to using Go's interface{}?
specific questions:
- how do I get the ""real"" Type of w?
- is there any way to get the string representation of a type?
- is there any way to use the string representation of a type to
convert a value?
",https://stackoverflow.com/questions/6372474/how-to-determine-an-interface-values-real-type,162,194693.0,8.0,,,2011-06-16 13:13:41,2022-07-07 05:44:46,2013-03-31 21:28:34,,,types;type-conversion;go,cc young,20569,662063,registered,true,6373426,,CC BY-SA 3.0,,734,627,3,0,0,3,true,false,false,true,true,true,66,8,true,0.041,0.0008,5637,2011,6,13,Thursday,false,false,false,false,false,false,false
11692860,How can I efficiently download a large file using Go?,"Is there a way to download a large file using Go that will store the content directly into a file instead of storing it all in memory before writing it to a file? Because the file is so big, storing it all in memory before writing it to a file is going to use up all the memory.
",https://stackoverflow.com/questions/11692860/how-can-i-efficiently-download-a-large-file-using-go,162,142028.0,5.0,,,2012-07-27 17:38:52,2024-09-29 12:21:24,2022-04-16 15:39:44,,,go;download,Cory,15725,155857,registered,true,11693049,,CC BY-SA 4.0,,286,279,0,0,0,2,true,false,false,true,true,true,53,10,true,0.035,0.0011,5230,2012,7,17,Friday,false,false,false,false,false,false,false
31595791,How to test panics?,"I'm currently pondering how to write tests that check if a given piece of code panicked? I know that Go uses recover to catch panics, but unlike say, Java code, you can't really specify what code should be skipped in case of a panic or what have you. So if I have a function:
func f(t *testing.T) {
defer func() {
if r := recover(); r != nil {
fmt.Println(""Recovered in f"", r)
}
}()
OtherFunctionThatPanics()
t.Errorf(""The code did not panic"")
}
I can't really tell whether OtherFunctionThatPanics panicked and we recovered, or if the function did not panic at all. How do I specify which code to skip over if there is no panic and which code to execute if there is a panic? How can I check whether there was some panic we recovered from?
",https://stackoverflow.com/questions/31595791/how-to-test-panics,162,90899.0,11.0,,,2015-07-23 18:51:37,2023-05-26 01:22:37,2015-11-11 10:11:23,,,testing;go,ThePiachu,9283,953732,registered,true,31596110,,CC BY-SA 3.0,,930,786,3,1,0,2,true,false,false,true,true,true,19,4,true,0.121,0.0018,4139,2015,7,18,Thursday,false,false,false,false,false,false,false
21532113,Golang converting string to int64,"I want to convert a string to an int64. What I find from the strconv package is the Atoi function. It seems to cast a string to an int and return it:
// Atoi is shorthand for ParseInt(s, 10, 0).
func Atoi(s string) (i int, err error) {
i64, err := ParseInt(s, 10, 0)
return int(i64), err
}
The ParseInt actually returns an int64:
func ParseInt(s string, base int, bitSize int) (i int64, err error){
//...
}
So if I want to get an int64 from a string, should I avoid using Atoi, instead use ParseInt? Or is there an Atio64 hidden somewhere?
",https://stackoverflow.com/questions/21532113/golang-converting-string-to-int64,161,257262.0,3.0,,,2014-02-03 16:08:00,2023-07-31 15:10:58,2017-09-27 08:04:40,,,string;go;int64,user1663023,,,does_not_exist,true,21532180,,CC BY-SA 3.0,,658,563,4,0,0,3,true,false,false,true,false,true,33,5,false,0.012,0.0006,4674,2014,2,16,Monday,false,false,false,false,false,false,false
25965584,Separating unit tests and integration tests in Go,"Is there an established best practice for separating unit tests and integration tests in GoLang (testify)? I have a mix of unit tests (which do not rely on any external resources and thus run really fast) and integration tests (which do rely on any external resources and thus run slower). So, I want to be able to control whether or not to include the integration tests when I say go test.
The most straight-forward technique would seem to be to define a -integrate flag in main:
var runIntegrationTests = flag.Bool(""integration"", false
, ""Run the integration tests (in addition to the unit tests)"")
And then to add an if-statement to the top of every integration test:
if !*runIntegrationTests {
this.T().Skip(""To run this test, use: go test -integration"")
}
Is this the best I can do? I searched the testify documentation to see if there is perhaps a naming convention or something that accomplishes this for me, but didn't find anything. Am I missing something?
",https://stackoverflow.com/questions/25965584/separating-unit-tests-and-integration-tests-in-go,161,102722.0,7.0,,,2014-09-22 01:30:05,2023-11-21 13:05:08,2016-11-08 15:28:57,,,unit-testing;go;integration-testing;testify,Craig Jones,2707,191906,registered,true,,,CC BY-SA 3.0,,1071,982,3,0,0,4,false,false,false,true,true,true,49,8,false,0.068,0.0016,4443,2014,9,1,Monday,false,false,false,false,false,false,false
25543520,Declare slice or make slice?,"In Go, what is the difference between var s []int and s := make([]int, 0)?
I find that both works, but which one is better?
",https://stackoverflow.com/questions/25543520/declare-slice-or-make-slice,161,108079.0,5.0,,,2014-08-28 07:51:54,2024-11-27 08:08:40,2020-08-19 18:25:37,,,go;allocation;slice,Wang Yi,1887,3985766,registered,true,25544086,,CC BY-SA 4.0,,164,124,2,0,0,3,true,false,false,true,true,true,28,5,true,0.046,0.0015,4468,2014,8,7,Thursday,false,false,false,false,false,false,false
42186003,How to uninstall Go?,"I tried the answer here Removed golang but go command still works?, but it didn't work (I can still run go)
Currently, when I run which go I see this output
/usr/local/go/bin/go
I think I had two installations of go as my GOPATH was pointing to another folder named gocode. I've now removed that folder, and the usr/local/go/bin/go folder.
I've also removed my GOPATH. However, I can still run go.
How do I uninstall go?
",https://stackoverflow.com/questions/42186003/how-to-uninstall-go,160,425250.0,15.0,,,2017-02-12 09:29:30,2022-09-19 09:23:28,2021-08-14 10:50:47,,,go,praks5432,7872,915672,registered,true,42186042,,CC BY-SA 4.0,2020-12-11 17:54:05,660,422,7,1,0,1,true,false,false,true,true,true,20,4,true,0.035,0.0004,3569,2017,2,9,Sunday,true,false,false,false,false,false,false
43580131,exec: "gcc": executable file not found in %PATH% when trying go build,"I am using Windows 10. When I tried to build Chaincode it reported this error
# github.com/hyperledger/fabric/vendor/github.com/miekg/pkcs11
exec: ""gcc"": executable file not found in %PATH%
My chaincode imports:
import (
""fmt""
""strconv""
""github.com/hyperledger/fabric/core/chaincode/shim""
pb ""github.com/hyperledger/fabric/protos/peer""
)
It's running fine in Docker.
",https://stackoverflow.com/questions/43580131/exec-gcc-executable-file-not-found-in-path-when-trying-go-build,160,280632.0,24.0,,,2017-04-24 05:03:25,2023-05-22 13:42:42,2017-07-11 10:48:40,,,windows;go;build;hyperledger-fabric;cgo,jaswanth,1837,6925001,registered,true,43588236,,CC BY-SA 3.0,,612,391,2,2,0,5,true,false,false,true,true,true,79,12,false,0.086,0.0006,3498,2017,4,5,Monday,false,false,false,false,false,false,false
26744873,Converting map to struct,"I am trying to create a generic method in Go that will fill a struct using data from a map[string]interface{}. For example, the method signature and usage might look like:
func FillStruct(data map[string]interface{}, result interface{}) {
...
}
type MyStruct struct {
Name string
Age int64
}
myData := make(map[string]interface{})
myData[""Name""] = ""Tony""
myData[""Age""] = 23
result := &MyStruct{}
FillStruct(myData, result)
// result now has Name set to ""Tony"" and Age set to 23
I know this can be done using JSON as an intermediary; is there another more efficient way of doing this?
",https://stackoverflow.com/questions/26744873/converting-map-to-struct,160,241126.0,9.0,,,2014-11-04 20:56:40,2023-01-05 03:53:17,2014-11-04 22:20:47,,,go,tgrosinger,2629,623949,registered,true,26746461,,CC BY-SA 3.0,,673,609,3,0,0,1,true,false,false,true,true,true,24,4,false,0.037,0.0007,4400,2014,11,20,Tuesday,false,false,false,false,false,false,false
22621754,How can I merge two maps in go?,"I have a recursive function that creates objects representing file paths (the keys are paths and the values are info about the file). It's recursive as it's only meant to handle files, so if a directory is encountered, the function is recursively called on the directory.
All that being said, I'd like to do the equivalent of a set union on two maps (i.e. the ""main"" map updated with the values from the recursive call). Is there an idiomatic way to do this aside from iterating over one map and assigning each key, value in it to the same thing in the other map?
That is: given a,b are of type map [string] *SomeObject, and a and b are eventually populated, is there any way to update a with all the values in b?
",https://stackoverflow.com/questions/22621754/how-can-i-merge-two-maps-in-go,160,198023.0,7.0,,,2014-03-24 22:17:51,2024-06-06 08:11:22,2022-05-17 12:55:17,,,dictionary;go;union,jeffknupp,6384,301749,registered,true,22621838,,CC BY-SA 4.0,,815,716,6,0,0,3,true,false,false,true,true,true,31,8,true,0.035,0.0008,4625,2014,3,22,Monday,false,false,false,false,false,false,false
52026284,Accessing local packages within a go module (go 1.11),"I'm trying out Go's new modules system and am having trouble accessing local packages. The following project is in a folder on my desktop outside my gopath.
My project structure looks like:
/
- /platform
- platform.go
- main.go
- go.mod
// platform.go
package platform
import ""fmt""
func Print() {
fmt.Println(""Hi"")
}
// main.go
package main
import ""platform""
func main() {
platform.Print()
}
go build main.go tells me
cannot find module for path platform
",https://stackoverflow.com/questions/52026284/accessing-local-packages-within-a-go-module-go-1-11,160,183107.0,4.0,,,2018-08-26 12:32:04,2025-05-07 22:06:40,,,,go;vgo,David Alsh,8137,4040931,registered,true,52026558,,CC BY-SA 4.0,,631,493,5,0,0,2,true,false,false,true,true,false,53,9,false,0.022,0.0009,3009,2018,8,12,Sunday,true,false,false,false,false,false,false
24652775,Convert Go map to json,"I tried to convert my Go map to a json string with encoding/json Marshal, but it resulted in a empty string.
Here's my code :
package main
import (
""encoding/json""
""fmt""
)
type Foo struct {
Number int `json:""number""`
Title string `json:""title""`
}
func main() {
datas := make(map[int]Foo)
for i := 0; i < 10; i++ {
datas[i] = Foo{Number: 1, Title: ""test""}
}
jsonString, _ := json.Marshal(datas)
fmt.Println(datas)
fmt.Println(jsonString)
}
My output is :
map[9:{1 test} 2:{1 test} 7:{1 test} 3:{1 test} 4:{1 test} 5:{1 test} 6:{1 test} 8:{1 test} 0:{1 test} 1:{1 test}]
[]
I really don't know where I'm wrong. Thank you for your help.
",https://stackoverflow.com/questions/24652775/convert-go-map-to-json,159,235065.0,5.0,,,2014-07-09 11:42:53,2021-06-26 14:40:39,2015-02-21 13:27:28,,,json;go,Cronos87,1976,3752379,registered,true,24652881,,CC BY-SA 3.0,,792,703,3,0,0,2,true,false,false,true,true,true,22,5,false,0.021,0.0007,4518,2014,7,11,Wednesday,false,false,false,false,false,false,false
18361750,Correct approach to global logging,"What's the pattern for application logging in Go? If I've got, say, 5 goroutines I need to log from, should I...
- Create a single
log.Logger and pass it around?
- Pass around a pointer to that
log.Logger?
- Should each goroutine or function create a logger?
- Should I create the logger as a global variable?
",https://stackoverflow.com/questions/18361750/correct-approach-to-global-logging,159,93331.0,8.0,,,2013-08-21 15:35:44,2024-04-25 09:38:03,2021-07-26 14:30:59,,,logging;go,Carson,17981,200619,registered,true,18362952,,CC BY-SA 4.0,,384,306,2,0,0,2,true,false,false,true,true,true,34,5,false,0.086,0.0017,4840,2013,8,15,Wednesday,false,false,false,false,false,false,false
28472922,When to use os.Exit() and panic()?,"Could someone explain the key differences between os.Exit() and panic() and how they are used in practice in Go?
",https://stackoverflow.com/questions/28472922/when-to-use-os-exit-and-panic,158,114814.0,3.0,,,2015-02-12 08:45:35,2024-09-16 08:01:45,2018-07-13 21:51:21,,,go;exit,Timur Fayzrakhmanov,20117,1349754,registered,true,28473339,,CC BY-SA 4.0,,146,113,2,0,0,2,true,false,false,true,true,true,34,6,true,0.026,0.0014,4300,2015,2,8,Thursday,false,false,false,false,false,false,false
71040681,qemu-x86_64: Could not open '/lib64/ld-linux-x86-64.so.2': No such file or directory,"I have a Rancher Deskop(dockerd) on M1 MacOS and when I am trying to build below dockerfile I am getting an error such as below. Here is the command how I am trying to build the image docker build -t te-grafana-dashboards-toolchain --no-cache .
I tried to change the platforms but nonae of them worked for me. I am a bit lost about this platform issue for M1 but any help will be appreciated, What I am doing wrong? What might the root cause of this?
Removing intermediate container 70af516d5d6b
---> a69229847153
Step 5/6 : RUN GO111MODULE="on" go get github.com/jsonnet-bundler/jsonnet-bundler/cmd/jb; ln -s $(go env GOPATH)/bin/jb /usr/bin/jb
---> Running in 13545862fffe
qemu-x86_64: Could not open '/lib64/ld-linux-x86-64.so.2': No such file or directory
qemu-x86_64: Could not open '/lib64/ld-linux-x86-64.so.2': No such file or directory
Removing intermediate container 13545862fffe
Dockerfile
FROM --platform=linux/amd64 ubuntu:focal
RUN apt update; apt install -y curl jq build-essential python3.8 python3-pip docker-compose jsonnet bison mercurial
RUN ln -s /usr/bin/python3.8 /usr/bin/python
RUN curl -OL https://golang.org/dl/go1.17.linux-amd64.tar.gz; mkdir /etc/golang; tar -xvzf go1.17.linux-amd64.tar.gz -C /etc/golang; ln -s /etc/golang/go/bin/go /usr/bin/go; rm -f go1.17.linux-amd64.tar.gz
RUN GO111MODULE="on" go get github.com/jsonnet-bundler/jsonnet-bundler/cmd/jb; ln -s $(go env GOPATH)/bin/jb /usr/bin/jb
WORKDIR /workspace
",https://stackoverflow.com/questions/71040681/qemu-x86-64-could-not-open-lib64-ld-linux-x86-64-so-2-no-such-file-or-direc,157,187654.0,8.0,,,2022-02-08 20:47:16,2025-03-05 23:14:28,2022-02-08 20:57:45,,,docker;go;apple-m1;rancher,semural,4731,12530530,registered,true,,,CC BY-SA 4.0,,1561,1479,3,0,0,4,false,false,false,true,true,true,92,10,false,0.043,0.0008,1747,2022,2,20,Tuesday,false,false,false,false,false,false,false
7052693,How to get the name of a function in Go?,"Given a function, is it possible to get its name? Say:
func foo() {
}
func GetFunctionName(i interface{}) string {
// ...
}
func main() {
// Will print ""name: foo""
fmt.Println(""name:"", GetFunctionName(foo))
}
I was told that runtime.FuncForPC would help, but I failed to understand how to use it.
",https://stackoverflow.com/questions/7052693/how-to-get-the-name-of-a-function-in-go,157,114855.0,4.0,,,2011-08-13 19:12:20,2022-10-10 15:10:15,2016-08-22 05:19:34,,,go;reflection;go-reflect,moraes,13719,125967,registered,true,7053871,,CC BY-SA 3.0,,429,314,1,1,0,3,true,false,false,true,true,true,40,10,true,0.035,0.0014,5579,2011,8,19,Saturday,true,false,false,false,false,false,false
20945069,Catching return values from goroutines,"The below code gives compilation error saying 'unexpected go':
x := go doSomething(arg)
func doSomething(arg int) int{
...
return my_int_value
}
I know, I can fetch the return value if I call the function normally i.e. without using goroutine or I can use channels etc.
My question is why is it not possible to fetch a return value like this from a goroutine.
",https://stackoverflow.com/questions/20945069/catching-return-values-from-goroutines,157,159105.0,6.0,,,2014-01-06 07:28:09,2024-11-16 08:40:03,2021-08-04 10:49:21,,,go;concurrency;goroutine,Nerve,6951,1541507,registered,true,20945350,,CC BY-SA 4.0,,415,370,1,0,0,3,true,false,false,true,true,true,38,5,false,0.038,0.001,4702,2014,1,7,Monday,false,false,false,false,false,false,false
13137365,How to change int into int64?,"Im trying to convert an integer into an integer64 in go but im having no luck. Anyone know an easy way to do this?
",https://stackoverflow.com/questions/13137365/how-to-change-int-into-int64,157,158528.0,3.0,,,2012-10-30 10:47:28,2020-07-30 07:08:52,,,,go,AC3112,1641,1367664,registered,true,13137429,,CC BY-SA 3.0,,122,115,0,0,0,1,true,false,false,true,true,false,29,6,true,0.019,0.001,5135,2012,10,10,Tuesday,false,false,false,false,false,false,false
20185511,Range references instead values,"I saw that range returns the key and the "copy" of the value. Is there a way for that range to return the address of the item? Example
package main
import "fmt"
type MyType struct {
field string
}
func main() {
var array [10]MyType
for _, e := range array {
e.field = "foo"
}
for _, e := range array {
fmt.Println(e.field)
fmt.Println("--")
}
}
http://play.golang.org/p/AFOGG9NGpx
Here "field" is not modified because range sends the copy of field.
Do I have to use index or is there any other way to modify the value?
",https://stackoverflow.com/questions/20185511/range-references-instead-values,157,84700.0,9.0,,,2013-11-25 05:39:34,2024-09-11 10:56:11,2022-04-06 16:42:47,,,pointers;reference;go,ttncrch,7343,2190535,registered,true,29498133,,CC BY-SA 4.0,,735,623,1,1,0,3,true,false,false,true,true,true,31,4,false,0.106,0.0019,4744,2013,11,5,Monday,false,false,false,false,false,false,false
40096750,How to set HTTP status code on http.ResponseWriter,"How do I set the HTTP status code on an http.ResponseWriter (e.g. to 500 or 403)?
I can see that requests normally have a status code of 200 attached to them.
",https://stackoverflow.com/questions/40096750/how-to-set-http-status-code-on-http-responsewriter,156,180365.0,3.0,,,2016-10-17 22:37:35,2019-12-13 17:41:59,2019-01-22 15:38:02,,,go,Nick H,2055,4678144,registered,true,40096757,,CC BY-SA 4.0,,187,160,1,0,0,1,true,false,false,true,true,true,50,8,false,0.017,0.0009,3687,2016,10,22,Monday,false,false,false,false,false,false,false
39993688,Are slices passed by value?,"In Go, I am trying to make a scramble slice function for my traveling salesman problem. While doing this I noticed when I started editing the slice I gave the scramble function was different every time I passed it in.
After some debugging I found out it was due to me editing the slice inside the function. But since Go is supposed to be a "pass by value" language, how is this possible?
https://play.golang.org/p/mMivoH0TuV
I have provided a playground link to show what I mean.
By removing line 27 you get a different output than leaving it in, this should not make a difference since the function is supposed to make its own copy of the slice when passed in as an argument.
Can someone explain the phenomenon?
",https://stackoverflow.com/questions/39993688/are-slices-passed-by-value,155,110539.0,5.0,,,2016-10-12 08:15:06,2022-10-18 06:36:32,2021-03-04 12:24:39,,,go;slice;pass-by-value,duck,1964,4901806,registered,true,39993797,,CC BY-SA 4.0,,825,723,0,1,0,3,true,false,false,true,true,true,27,5,true,0.045,0.0014,3692,2016,10,8,Wednesday,false,false,false,false,false,false,false
18088294,How to not marshal an empty struct into JSON with Go?,"I have a struct like this:
type Result struct {
Data MyStruct `json:""data,omitempty""`
Status string `json:""status,omitempty""`
Reason string `json:""reason,omitempty""`
}
But even if the instance of MyStruct is entirely empty (meaning, all values are default), it's being serialized as:
""data"":{}
I know that the encoding/json docs specify that ""empty"" fields are:
false, 0, any nil pointer or interface value, and any array,
slice, map, or string of length zero
but with no consideration for a struct with all empty/default values. All of its fields are also tagged with omitempty, but this has no effect.
How can I get the JSON package to not marshal my field that is an empty struct?
",https://stackoverflow.com/questions/18088294/how-to-not-marshal-an-empty-struct-into-json-with-go,155,161495.0,6.0,,,2013-08-06 18:56:06,2025-03-13 22:47:09,2013-08-08 23:23:03,,,json;go,Matt,23947,1048862,registered,true,18088527,,CC BY-SA 3.0,,945,732,3,1,0,2,true,false,false,true,true,true,53,11,true,0.037,0.001,4855,2013,8,18,Tuesday,false,false,false,false,false,false,false
11066946,Partly JSON unmarshal into a map in Go,"My websocket server will receive and unmarshal JSON data. This data will always be wrapped in an object with key/value pairs. The key-string will act as value identifier, telling the Go server what kind of value it is. By knowing what type of value, I can then proceed to JSON unmarshal the value into the correct type of struct.
Each json-object might contain multiple key/value pairs.
Example JSON:
{
""sendMsg"":{""user"":""ANisus"",""msg"":""Trying to send a message""},
""say"":""Hello""
}
Is there any easy way using the ""encoding/json"" package to do this?
package main
import (
""encoding/json""
""fmt""
)
// the struct for the value of a ""sendMsg""-command
type sendMsg struct {
user string
msg string
}
// The type for the value of a ""say""-command
type say string
func main(){
data := []byte(`{""sendMsg"":{""user"":""ANisus"",""msg"":""Trying to send a message""},""say"":""Hello""}`)
// This won't work because json.MapObject([]byte) doesn't exist
objmap, err := json.MapObject(data)
// This is what I wish the objmap to contain
//var objmap = map[string][]byte {
// ""sendMsg"": []byte(`{""user"":""ANisus"",""msg"":""Trying to send a message""}`),
// ""say"": []byte(`""hello""`),
//}
fmt.Printf(""%v"", objmap)
}
Thanks for any kind of suggestion/help!
",https://stackoverflow.com/questions/11066946/partly-json-unmarshal-into-a-map-in-go,155,192958.0,4.0,,,2012-06-16 20:51:50,2023-05-18 15:15:55,2012-06-17 08:25:21,,,json;dictionary;go,ANisus,78828,694331,registered,true,11067084,,CC BY-SA 3.0,,1390,1294,3,0,0,3,true,false,false,true,true,true,38,8,false,0.021,0.0008,5271,2012,6,20,Saturday,true,false,false,false,false,false,false
8307478,How to find out element position in slice?,"How does one determine the position of an element present in slice?
I need something like the following:
type intSlice []int
func (slice intSlice) pos(value int) int {
for p, v := range slice {
if (v == value) {
return p
}
}
return -1
}
",https://stackoverflow.com/questions/8307478/how-to-find-out-element-position-in-slice,154,184478.0,11.0,,,2011-11-29 07:57:11,2023-06-25 04:22:05,2017-11-09 16:15:04,,,position;go;slice,OCyril,3205,892936,registered,true,8307594,,CC BY-SA 3.0,,319,281,1,0,0,3,true,false,false,true,true,true,42,8,true,0.06,0.0008,5471,2011,11,7,Tuesday,false,false,false,false,false,false,false
13904441,How can I bundle static resources in a Go program?,"I'm working on a small web application in Go that's meant to be used as a tool on a developer's machine to help debug their applications/web services. The interface to the program is a web page that includes not only the HTML but some JavaScript (for functionality), images, and CSS (for styling). I'm planning on open-sourcing this application, so users should be able to run a Makefile, and all the resources will go where they need to go. However, I'd also like to be able to simply distribute an executable with as few files/dependencies as possible. Is there a good way to bundle the HTML/CSS/JS with the executable, so users only have to download and worry about one file?
Right now, in my app, serving a static file looks a little like this:
// called via http.ListenAndServe
func switchboard(w http.ResponseWriter, r *http.Request) {
// snipped dynamic routing...
// look for static resource
uri := r.URL.RequestURI()
if fp, err := os.Open("static" + uri); err == nil {
defer fp.Close()
staticHandler(w, r, fp)
return
}
// snipped blackhole route
}
So it's pretty simple: if the requested file exists in my static directory, invoke the handler, which simply opens the file and tries to set a good Content-Type before serving. My thought was that there's no reason this needs to be based on the real filesystem: if there were compiled resources, I could simply index them by request URI and serve them as such.
Let me know if there's not a good way to do this or I'm barking up the wrong tree by trying to do this. I just figured the end-user would appreciate as few files as possible to manage.
",https://stackoverflow.com/questions/13904441/how-can-i-bundle-static-resources-in-a-go-program,154,74390.0,5.0,,,2012-12-16 18:52:32,2024-03-05 17:26:34,2024-03-05 17:26:34,,,go;bundle,Jimmy Sawczuk,13674,350278,registered,true,13904528,,CC BY-SA 4.0,,1759,1671,2,0,0,2,true,false,false,true,true,true,50,10,true,0.067,0.0021,5088,2012,12,18,Sunday,true,false,false,false,false,false,false
31379404,Is this casting in golang?,"paxPayment, ok = dataObject.(*entities.PassengerPayment)
What are the brackets used for? I'm not sure what is going on in this assignment operation.
Do you need any more details to answer this question?
",https://stackoverflow.com/questions/31379404/is-this-casting-in-golang,154,125635.0,1.0,,,2015-07-13 09:10:03,2019-07-23 18:59:06,2019-02-20 16:21:00,,,go;types;type-conversion,Varun Patro,2229,4160987,registered,true,31379484,,CC BY-SA 4.0,,239,205,1,0,0,3,true,false,false,true,true,true,26,5,true,0.008,0.0012,4149,2015,7,9,Monday,false,false,false,false,false,false,false
14323872,Using forked package import in Go,"Suppose you have a repository at github.com/someone/repo and you fork it to github.com/you/repo. You want to use your fork instead of the main repo, so you do a
go get github.com/you/repo
Now all the import paths in this repo will be ""broken"", meaning, if there are multiple packages in the repository that reference each other via absolute URLs, they will reference the source, not the fork.
Is there a better way as cloning it manually into the right path?
git clone git@github.com:you/repo.git $GOPATH/src/github.com/someone/repo
",https://stackoverflow.com/questions/14323872/using-forked-package-import-in-go,152,49151.0,14.0,,,2013-01-14 17:53:51,2026-05-20 15:11:12,2013-01-14 21:44:02,,,go,user187676,,,does_not_exist,true,56792766,,CC BY-SA 3.0,,634,539,4,0,0,1,true,false,false,true,false,true,33,6,false,0.285,0.0031,5059,2013,1,17,Monday,false,false,false,false,false,false,false
12561162,"used as value" in function call,"What's the proper way of calling functions when evaluating their values in conditional statements?
package main
import ""fmt""
func main(){
if sumThis(1,2) > sumThis(3,4){
fmt.Println(""test"")
} else {
fmt.Println(""derp"")
}
}
func sumThis(a, b int){
return a+b
}
this returns error:
./test4.go:4: sumThis(1, 2) used as value
./test4.go:4: sumThis(3, 4) used as value
./test4.go:11: too many arguments to return
How would you write this in Go?
",https://stackoverflow.com/questions/12561162/used-as-value-in-function-call,152,96560.0,1.0,,,2012-09-24 08:13:19,2018-11-28 07:21:03,2018-11-28 07:20:44,,,go,Saad,29236,353217,registered,true,12561304,,CC BY-SA 4.0,,582,513,2,0,0,1,true,false,false,true,true,true,42,6,false,0.01,0.0016,5171,2012,9,8,Monday,false,false,false,false,false,false,false
18041334,Convert interface{} to int,"I'm trying to get a value from a JSON and cast it to int but it doesn't work, and I don't know how to do it properly.
Here is the error message:
...cannot convert val (type interface {}) to type int: need type assertion
And the code:
var f interface{}
err = json.Unmarshal([]byte(jsonStr), &f)
if err != nil {
utility.CreateErrorResponse(w, ""Error: failed to parse JSON data."")
return
}
m := f.(map[string]interface{})
val, ok := m[""area_id""]
if !ok {
utility.CreateErrorResponse(w, ""Error: Area ID is missing from submitted data."")
return
}
fmt.Fprintf(w, ""Type = %v"", val) // <--- Type = float64
iAreaId := int(val) // <--- Error on this line.
testName := ""Area_"" + iAreaId // not reaching here
",https://stackoverflow.com/questions/18041334/convert-interface-to-int,151,277508.0,12.0,,,2013-08-04 09:00:19,2023-01-13 10:36:58,2018-07-13 21:41:57,,,go,Nick,4592,1941790,registered,true,18041561,,CC BY-SA 4.0,,883,814,2,0,0,1,true,false,false,true,true,true,26,4,false,0.043,0.0005,4857,2013,8,9,Sunday,true,false,false,false,false,false,false
15326421,How do I do a case insensitive regular expression in Go?,"I could write my regular expression to handle both cases, such as regexp.Compile("[a-zA-Z]"), but my regular expression is constructed from a string given by the user:
reg, err := regexp.Compile(strings.Replace(s.Name, " ", "[ \\._-]", -1))
Where s.Name is the name. Which could be something like 'North by Northwest'. Now, the most apparent solution to me would be to walk through each character of s.Name and write '[nN]' for each letter:
for i := 0; i < len(s.Name); i++ {
if s.Name[i] == " " {
fmt.Fprintf(str, "%s[ \\._-]", str);
} else {
fmt.Fprintf(str, "%s[%s%s]", str, strings.ToLower(s.Name[i]), strings.ToUpper(s.Name[i]))
}
}
But I feel this is a rather non-elegant solution. Speed is not really a concern, but I need to know if there is another way.
",https://stackoverflow.com/questions/15326421/how-do-i-do-a-case-insensitive-regular-expression-in-go,150,118468.0,4.0,,,2013-03-10 19:19:46,2022-09-22 21:42:32,2022-09-22 21:42:32,,,regex;go,Svip,3250,2099873,registered,true,15326471,,CC BY-SA 4.0,,1022,873,5,0,0,2,true,false,false,true,true,true,56,11,true,0.034,0.0013,5004,2013,3,19,Sunday,true,false,false,false,false,false,false
19253469,Make a URL-encoded POST request using `http.NewRequest(...)`,"I want to make a POST request to an API sending my data as a application/x-www-form-urlencoded content type. Due to the fact that I need to manage the request headers, I'm using the http.NewRequest(method, urlStr string, body io.Reader) method to create a request. For this POST request I append my data query to the URL and leave the body empty, something like this:
package main
import (
""bytes""
""fmt""
""net/http""
""net/url""
""strconv""
)
func main() {
apiUrl := ""https://api.com""
resource := ""/user/""
data := url.Values{}
data.Set(""name"", ""foo"")
data.Add(""surname"", ""bar"")
u, _ := url.ParseRequestURI(apiUrl)
u.Path = resource
u.RawQuery = data.Encode()
urlStr := fmt.Sprintf(""%v"", u) // ""https://api.com/user/?name=foo&surname=bar""
client := &http.Client{}
r, _ := http.NewRequest(""POST"", urlStr, nil)
r.Header.Add(""Authorization"", ""auth_token=\""XXXXXXX\"""")
r.Header.Add(""Content-Type"", ""application/x-www-form-urlencoded"")
r.Header.Add(""Content-Length"", strconv.Itoa(len(data.Encode())))
resp, _ := client.Do(r)
fmt.Println(resp.Status)
}
As I response, I get always a 400 BAD REQUEST. I believe the problem relies on my request and the API does not understand which payload I am posting. I'm aware of methods like Request.ParseForm, not really sure how to use it in this context though. Maybe am I missing some further Header, maybe is there a better way to send payload as a application/json type using the body parameter?
",https://stackoverflow.com/questions/19253469/make-a-url-encoded-post-request-using-http-newrequest,150,223740.0,1.0,,,2013-10-08 16:38:54,2021-12-17 08:48:21,2016-01-18 16:13:23,,,http;go,Fernando Á.,7835,1187471,registered,true,19253970,,CC BY-SA 3.0,,1763,1526,7,2,0,2,true,false,false,true,true,true,60,7,false,0.004,0.0007,4792,2013,10,16,Tuesday,false,false,false,false,false,false,false
6395076,"Using reflect, how do you set the value of a struct field?","having a rough time working with struct fields using reflect package. in particular, have not figured out how to set the field value.
type t struct { fi int; fs string }
var r t = t{ 123, ""jblow"" }
var i64 int64 = 456
getting Name of field i - this seems to work
var field = reflect.TypeOf(r).Field(i).Name
getting value of field i as a) interface{}, b) int - this seems to work
var iface interface{} = reflect.ValueOf(r).Field(i).Interface()
var i int = int(reflect.ValueOf(r).Field(i).Int())
setting value of field i - try one - panic
reflect.ValueOf(r).Field(i).SetInt( i64 )
panic: reflect.Value·SetInt using value obtained using unexported field
assuming it did not like field names ""id"" and ""name"", so renamed to ""Id"" and ""Name""
a) is this assumption correct?
b) if correct, thought not necessary since in same file / package
setting value of field i - try two (with field names capitalized ) - panic
reflect.ValueOf(r).Field(i).SetInt( 465 )
reflect.ValueOf(r).Field(i).SetInt( i64 )
panic: reflect.Value·SetInt using unaddressable value
Instructions below by @peterSO are thorough and high quality
Four. this works:
reflect.ValueOf(&r).Elem().Field(i).SetInt( i64 )
he documents as well that the field names must be exportable (begin with capital letter)
",https://stackoverflow.com/questions/6395076/using-reflect-how-do-you-set-the-value-of-a-struct-field,150,164462.0,3.0,,,2011-06-18 09:24:05,2023-05-13 18:15:12,2017-07-12 12:03:41,,,go;reflection;go-reflect,cc young,20569,662063,registered,true,6396678,,CC BY-SA 3.0,,1615,1291,8,0,0,3,true,false,false,true,true,true,58,12,true,0.018,0.0009,5635,2011,6,9,Saturday,true,false,false,false,false,false,false
40589353,"Adding hours, minutes, seconds to current time","How do I add hours, minutes, and seconds (defined as ints) to the current time, similar to AddDate?
timein := time.Now().Local().AddDate(Hours, Mins, Sec)
but with hours, minutes, and seconds.
",https://stackoverflow.com/questions/40589353/adding-hours-minutes-seconds-to-current-time,150,168434.0,2.0,,,2016-11-14 12:58:17,2022-04-14 17:11:47,2017-12-07 15:42:15,,,go;time,joshii_h,1711,5003199,registered,true,40589596,,CC BY-SA 3.0,,247,196,2,0,0,2,true,false,false,true,true,true,46,7,false,0.012,0.0009,3659,2016,11,12,Monday,false,false,false,false,false,false,false
1877045,How do you get the output of a system command in Go?,"Let's say I want to run 'ls' in a go program, and store the results in a string. There seems to be a few commands to fork processes in the exec and os packages, but they require file arguments for stdout, etc. Is there a way to get the output as a string?
",https://stackoverflow.com/questions/1877045/how-do-you-get-the-output-of-a-system-command-in-go,149,206266.0,8.0,,,2009-12-09 21:33:19,2021-04-04 21:29:02,2010-03-19 16:14:31,,,go,marketer,44157,61008,registered,true,1886140,,CC BY-SA 2.5,,263,256,0,0,0,1,true,false,false,true,true,true,52,12,true,0.039,0.0007,6191,2009,12,21,Wednesday,false,false,false,false,false,false,false
25025409,Delete element in a slice,"func main() {
a := []string{""Hello1"", ""Hello2"", ""Hello3""}
fmt.Println(a)
// [Hello1 Hello2 Hello3]
a = append(a[:0], a[1:]...)
fmt.Println(a)
// [Hello2 Hello3]
}
How does this delete trick with the append function work?
It would seem that it's grabbing everything before the first element (empty array)
Then appending everything after the first element (position zero)
What does the ... (dot dot dot) do?
",https://stackoverflow.com/questions/25025409/delete-element-in-a-slice,149,190605.0,8.0,,,2014-07-29 21:36:36,2023-05-25 11:13:12,2015-05-09 04:35:46,,,go,Jorge Olivero,3863,2441725,registered,true,25025536,,CC BY-SA 3.0,,487,435,1,0,0,1,true,false,false,true,true,true,25,5,false,0.042,0.0008,4498,2014,7,21,Tuesday,false,false,false,false,false,false,false
60675415,How to upgrade the go version in a go mod,"What is the proper way to upgrade the go version in a go mod, specifically 1.13 to 1.14?
Do you simply edit the go.mod file and change go 1.13 to go 1.14?
I'm not asking about how to edit the go.mod file, I'm asking if it is proper to simply change the go version in the go.mod file, and everything else (all the dependencies) is still ok for the project?
",https://stackoverflow.com/questions/60675415/how-to-upgrade-the-go-version-in-a-go-mod,149,165308.0,6.0,,,2020-03-13 18:15:59,2024-08-27 16:53:44,2020-03-13 18:27:35,,,go;go-modules,James Haskell,2115,1778335,registered,true,,,CC BY-SA 4.0,,412,359,2,0,0,2,false,false,false,true,true,true,41,10,false,0.036,0.0009,2444,2020,3,18,Friday,false,false,false,false,false,false,false
39320025,How to stop http.ListenAndServe(),"I am using the Mux library from Gorilla Web Toolkit along with the bundled Go http server.
The problem is that in my application the HTTP server is only one component and it is required to stop and start at my discretion.
When I call http.ListenAndServe(fmt.Sprintf("":%d"", service.Port()), service.router) it blocks and I cannot seem to stop the server from running.
I am aware this has been a problem in the past, is that still the case? Are there any new solutions?
",https://stackoverflow.com/questions/39320025/how-to-stop-http-listenandserve,148,144218.0,10.0,,,2016-09-04 18:12:02,2024-06-05 06:51:52,2019-07-26 17:23:37,,,go,jim,9178,225885,registered,true,,,CC BY-SA 4.0,,512,471,1,0,0,1,false,false,false,true,true,true,33,4,false,0.069,0.001,3730,2016,9,18,Sunday,true,false,false,false,false,false,false
18208394,How to test the equivalence of maps in Golang?,"I have a table-driven test case like this one:
func CountWords(s string) map[string]int
func TestCountWords(t *testing.T) {
var tests = []struct {
input string
want map[string]int
}{
{""foo"", map[string]int{""foo"":1}},
{""foo bar foo"", map[string]int{""foo"":2,""bar"":1}},
}
for i, c := range tests {
got := CountWords(c.input)
// TODO test whether c.want == got
}
}
I could check whether the lengths are the same and write a loop that checks if every key-value pair is the same. But then I have to write this check again when I want to use it for another type of map (say map[string]string).
What I ended up doing is, I converted the maps to strings and compared the strings:
func checkAsStrings(a,b interface{}) bool {
return fmt.Sprintf(""%v"", a) != fmt.Sprintf(""%v"", b)
}
//...
if checkAsStrings(got, c.want) {
t.Errorf(""Case #%v: Wanted: %v, got: %v"", i, c.want, got)
}
This assumes that the string representations of equivalent maps are the same, which seems to be true in this case (if the keys are the same then they hash to the same value, so their orders will be the same). Is there a better way to do this? What is the idiomatic way to compare two maps in table-driven tests?
",https://stackoverflow.com/questions/18208394/how-to-test-the-equivalence-of-maps-in-golang,147,151821.0,8.0,,,2013-08-13 11:52:19,2024-06-10 16:56:09,2019-04-28 10:40:57,,,testing;maps;go;equivalence;table-driven,andras,6769,212013,registered,true,18211675,,CC BY-SA 4.0,,1317,1228,3,0,0,5,true,false,false,true,true,true,46,9,true,0.053,0.001,4848,2013,8,11,Tuesday,false,false,false,false,false,false,false
19560334,How to disable Golang unused import error,"By default, Go treats unused import as error, forcing you to delete the import.
I want to know if there exists some hope to change to this behavior, e.g. reducing it to warning.
I find this problem extremely annoying, preventing me from enjoying coding in Go.
For example, I was testing some code, disabling a segment/function. Some functions from a lib is no longer used (e.g. fmt, errors, whatever), but I will need to re-enable the function after a little testing. Now the program won't compile unless I remove those imports, and a few minutes later I need to re-import the lib.
I was doing this process again and again when developing a GAE program.
",https://stackoverflow.com/questions/19560334/how-to-disable-golang-unused-import-error,147,53501.0,9.0,,,2013-10-24 08:05:17,2023-05-03 05:19:06,2020-06-24 03:59:40,,,go,Nick,4592,1941790,registered,true,,,CC BY-SA 4.0,,682,654,0,0,0,1,false,false,false,true,true,true,41,7,false,0.168,0.0027,4776,2013,10,8,Thursday,false,false,false,false,false,false,false
19965795,How to write log to file,"I'm trying to write to a log file with Go.
I have tried several approaches, all of which have failed. This is what I have tried:
func TestLogging(t *testing.T) {
if !FileExists(""logfile"") {
CreateFile(""logfile"")
}
f, err := os.Open(""logfile"")
if err != nil {
t.Fatalf(""error: %v"", err)
}
// attempt #1
log.SetOutput(io.MultiWriter(os.Stderr, f))
log.Println(""hello, logfile"")
// attempt #2
log.SetOutput(io.Writer(f))
log.Println(""hello, logfile"")
// attempt #3
log.SetOutput(f)
log.Println(""hello, logfile"")
}
func FileExists(name string) bool {
if _, err := os.Stat(name); err != nil {
if os.IsNotExist(err) {
return false
}
}
return true
}
func CreateFile(name string) error {
fo, err := os.Create(name)
if err != nil {
return err
}
defer func() {
fo.Close()
}()
return nil
}
The log file gets created, but nothing ever gets printed or appended to it. Why?
",https://stackoverflow.com/questions/19965795/how-to-write-log-to-file,146,223931.0,11.0,,,2013-11-13 22:30:45,2020-08-12 13:27:02,2020-01-06 18:50:57,,,go;logging,Allison A,5913,1655418,registered,true,19966217,,CC BY-SA 4.0,,1065,1020,1,0,0,2,true,false,false,true,true,true,24,6,false,0.049,0.0007,4756,2013,11,22,Wednesday,false,false,false,false,false,false,false
26159416,Init array of structs in Go,"I'm newbie in Go. This issue is driving me nuts. How do you init array of structs in Go?
type opt struct {
shortnm char
longnm, help string
needArg bool
}
const basename_opts []opt {
opt {
shortnm: 'a',
longnm: "multiple",
needArg: false,
help: "Usage for a"}
},
opt {
shortnm: 'b',
longnm: "b-option",
needArg: false,
help: "Usage for b"}
}
The compiler said it expecting ; after []opt.
Where should I put the braces { to init my array of struct?
",https://stackoverflow.com/questions/26159416/init-array-of-structs-in-go,146,293603.0,5.0,,,2014-10-02 10:59:43,2024-09-17 17:19:07,2020-11-27 22:38:07,,,arrays;struct;go,daniel.widyanto,1739,4102075,registered,true,,,CC BY-SA 4.0,,727,643,4,0,0,3,false,false,false,true,true,true,27,6,false,0.017,0.0005,4433,2014,10,10,Thursday,false,false,false,false,false,false,false
28240489,Golang testing: "no test files","I'm creating a simple test within my package directory called reverseTest.go
package main
import ""testing""
func TestReverse(t *testing.T) {
cases := []struct {
in, want string
}{
{""Hello, world"", ""dlrow ,olleH""},
{""Hello, 世界"", ""界世 ,olleH""},
{"""", """"},
}
for _, c := range cases {
got := Reverse(c.in)
if got != c.want {
t.Errorf(""Reverse(%q) == %q, want %q"", c.in, got, c.want)
}
}
}
whenever i try to run it the output is
exampleFolder[no test files]
this is my go env
GOARCH=""amd64""
GOBIN=""""
GOCHAR=""6""
GOEXE=""""
GOHOSTARCH=""amd64""
GOHOSTOS=""linux""
GOOS=""linux""
GOPATH=""/home/juan/go""
GORACE=""""
GOROOT=""/usr/lib/go""
GOTOOLDIR=""/usr/lib/go/pkg/tool/linux_amd64""
TERM=""dumb""
CC=""gcc""
GOGCCFLAGS=""-g -O2 -fPIC -m64 -pthread""
CXX=""g++""
CGO_ENABLED=""1""
Any help will be greatly appreciated. Thanks!!
",https://stackoverflow.com/questions/28240489/golang-testing-no-test-files,145,132083.0,9.0,,,2015-01-30 16:37:55,2024-05-03 08:47:32,2018-02-27 23:57:56,,,testing;go;terminal,Juan M,4573,2438413,registered,true,28240537,,CC BY-SA 3.0,,996,896,3,0,0,3,true,false,false,true,true,true,41,5,false,0.068,0.0011,4313,2015,1,16,Friday,false,false,false,false,false,false,false
35479041,How to convert ISO 8601 time in golang?,"What is the equivalent code in golang for the following shell command ?
date -u +%Y-%m-%dT%T%z
",https://stackoverflow.com/questions/35479041/how-to-convert-iso-8601-time-in-golang,145,167340.0,6.0,,,2016-02-18 10:36:09,2025-04-21 00:51:42,2016-02-18 14:51:18,,,go,codefx,10722,244009,registered,true,42217963,,CC BY-SA 3.0,,115,95,1,0,0,1,true,false,false,true,true,true,39,8,true,0.036,0.0009,3929,2016,2,10,Thursday,false,false,false,false,false,false,false
10411538,How do I convert a string to a lower case representation?,"How do I convert a string to a lower case representation?
I feel that there must be built-in function for it, but I just can't find it.
I did find a ToLower in ""unicode/letter"", but it only works for one rune at a time.
",https://stackoverflow.com/questions/10411538/how-do-i-convert-a-string-to-a-lower-case-representation,145,101383.0,2.0,,,2012-05-02 10:01:13,2019-10-21 11:40:40,2019-10-21 11:40:40,,,go,oers,18784,644450,registered,true,10411579,,CC BY-SA 4.0,,269,222,2,0,0,1,true,false,false,true,true,true,57,11,true,0.02,0.0014,5316,2012,5,10,Wednesday,false,false,false,false,false,false,false
28448543,How to create nested directories using Mkdir in Golang?,"I am trying to create a set of nested directories from a Go executable such as 'dir1/dir2/dir3'. I have succeeded in creating a single directory with this line:
os.Mkdir(""."" + string(filepath.Separator) + c.Args().First(),0777);
However, I have no idea how to approach creating a predetermined nested set of directories inside of that directory.
",https://stackoverflow.com/questions/28448543/how-to-create-nested-directories-using-mkdir-in-golang,144,180983.0,6.0,,,2015-02-11 07:15:16,2025-03-19 13:00:41,2018-12-11 11:55:44,,,go;mkdir,tommymcdonald,1602,1992958,registered,true,28448702,,CC BY-SA 4.0,,387,349,1,0,0,2,true,false,false,true,true,true,55,9,true,0.033,0.0008,4301,2015,2,7,Wednesday,false,false,false,false,false,false,false
16105325,How to check a channel is closed or not without reading it?,"This is a good example of workers & controller mode in Go written by @Jimt, in answer to
""Is there some elegant way to pause & resume any other goroutine in golang?""
package main
import (
""fmt""
""runtime""
""sync""
""time""
)
// Possible worker states.
const (
Stopped = 0
Paused = 1
Running = 2
)
// Maximum number of workers.
const WorkerCount = 1000
func main() {
// Launch workers.
var wg sync.WaitGroup
wg.Add(WorkerCount + 1)
workers := make([]chan int, WorkerCount)
for i := range workers {
workers[i] = make(chan int)
go func(i int) {
worker(i, workers[i])
wg.Done()
}(i)
}
// Launch controller routine.
go func() {
controller(workers)
wg.Done()
}()
// Wait for all goroutines to finish.
wg.Wait()
}
func worker(id int, ws <-chan int) {
state := Paused // Begin in the paused state.
for {
select {
case state = <-ws:
switch state {
case Stopped:
fmt.Printf(""Worker %d: Stopped\n"", id)
return
case Running:
fmt.Printf(""Worker %d: Running\n"", id)
case Paused:
fmt.Printf(""Worker %d: Paused\n"", id)
}
default:
// We use runtime.Gosched() to prevent a deadlock in this case.
// It will not be needed of work is performed here which yields
// to the scheduler.
runtime.Gosched()
if state == Paused {
break
}
// Do actual work here.
}
}
}
// controller handles the current state of all workers. They can be
// instructed to be either running, paused or stopped entirely.
func controller(workers []chan int) {
// Start workers
for i := range workers {
workers[i] <- Running
}
// Pause workers.
<-time.After(1e9)
for i := range workers {
workers[i] <- Paused
}
// Unpause workers.
<-time.After(1e9)
for i := range workers {
workers[i] <- Running
}
// Shutdown workers.
<-time.After(1e9)
for i := range workers {
close(workers[i])
}
}
But this code also has an issue: If you want to remove a worker channel in workers when worker() exits, dead lock happens.
If you close(workers[i]), next time controller writes into it will cause a panic since go can't write into a closed channel. If you use some mutex to protect it, then it will be stuck on workers[i] <- Running since the worker is not reading anything from the channel and write will be blocked, and mutex will cause a dead lock. You can also give a bigger buffer to channel as a work-around, but it's not good enough.
So I think the best way to solve this is worker() close channel when exits, if the controller finds a channel closed, it will jump over it and do nothing. But I can't find how to check a channel is already closed or not in this situation. If I try to read the channel in controller, the controller might be blocked. So I'm very confused for now.
PS: Recovering the raised panic is what I have tried, but it will close goroutine which raised panic. In this case it will be controller so it's no use.
Still, I think it's useful for Go team to implement this function in next version of Go.
",https://stackoverflow.com/questions/16105325/how-to-check-a-channel-is-closed-or-not-without-reading-it,144,274881.0,11.0,,,2013-04-19 13:05:24,2024-10-27 15:04:51,2017-05-23 12:09:58,,,go;channel,Shane Hou,5078,1153066,registered,true,16105721,,CC BY-SA 3.0,,3613,3412,7,1,0,2,true,false,false,true,true,true,59,12,true,0.04,0.0005,4964,2013,4,13,Friday,false,false,false,false,false,false,false
24122821,Go time.Now().UnixNano() convert to milliseconds?,"How can I get Unix time in Go in milliseconds?
I have the following function:
func makeTimestamp() int64 {
return time.Now().UnixNano() % 1e6 / 1e3
}
I need less precision and only want milliseconds.
",https://stackoverflow.com/questions/24122821/go-time-now-unixnano-convert-to-milliseconds,143,236571.0,7.0,,,2014-06-09 14:49:08,2023-06-08 19:14:33,2021-07-16 16:24:07,,,time;go;unix-timestamp;date-conversion,mconlin,8843,1176631,registered,true,24122933,,CC BY-SA 4.0,,250,205,1,0,0,4,true,false,false,true,true,true,49,5,true,0.03,0.0006,4548,2014,6,14,Monday,false,false,false,false,false,false,false
7922270,Obtain user's home directory,"Is the following the best way of obtaining the running user's home directory? Or is there a specific function that I've ovelooked?
os.Getenv(""HOME"")
If the above is correct, does anyone happen to know whether this approach is guaranteed to work on non-Linux platforms, e.g. Windows?
",https://stackoverflow.com/questions/7922270/obtain-users-home-directory,143,103912.0,7.0,,,2011-10-27 20:54:35,2021-04-09 22:27:21,2018-10-03 13:14:10,,,go;home-directory,Paul Ruane,38738,83264,registered,true,13004756,,CC BY-SA 4.0,,324,286,1,0,0,2,true,false,false,true,true,true,32,4,false,0.067,0.0014,5504,2011,10,20,Thursday,false,false,false,false,false,false,false
38144050,How do I check for an empty slice?,"I am calling a function that returns an empty array if there are no values.
When I do this it doesn't work:
if r == [] {
fmt.Println(""No return value"")
}
The work around I'm using is:
var a [0]int
if r == a {
fmt.Println(""No return value"")
}
But declaring a variable just to check the return value doesn't seem right. What's the better way to do this?
",https://stackoverflow.com/questions/38144050/how-do-i-check-for-an-empty-slice,143,215079.0,3.0,,,2016-07-01 11:16:42,2018-09-28 12:09:34,2016-07-01 12:59:59,,,go;slice,Kshitiz Sharma,18767,1345655,registered,true,38144180,,CC BY-SA 3.0,,467,391,2,0,0,2,true,false,false,true,true,true,34,8,true,0.014,0.0007,3795,2016,7,11,Friday,false,false,false,false,false,false,false
28576173,Reason for huge size of compiled executable of Go,"I complied a hello world Go program which generated native executable on my linux machine. But I was surprised to see the size of the simple Hello world Go program, it was 1.9MB !
Why is it that the executable of such a simple program in Go is so huge?
",https://stackoverflow.com/questions/28576173/reason-for-huge-size-of-compiled-executable-of-go,143,58806.0,3.0,,,2015-02-18 04:47:10,2019-04-02 07:12:21,2016-08-02 16:12:31,,,go;executable,Karthic Rao,3824,2067919,registered,true,28579099,,CC BY-SA 3.0,,269,255,0,0,0,2,true,false,false,true,true,true,49,9,false,0.051,0.0024,4294,2015,2,4,Wednesday,false,false,false,false,false,false,false
23723955,How can I pass a slice as a variadic input?,"I have a function func more(... t). I'm wondering if it's possible to use a slice to populate a list of arguments ... .
I'm trying to solve the following program. Basically to mimic a normal shell which receives the command as a string.
Command function requires a "list" of arguments and I don't see how I can convert a string into a such list
import "os/exec"
import "strings"
func main(){
plainCommand := "echo hello world"
sliceA := strings.Fields(plainCommand)
cmd := exec.Command(sliceA)
}
",https://stackoverflow.com/questions/23723955/how-can-i-pass-a-slice-as-a-variadic-input,143,88115.0,3.0,,,2014-05-18 16:02:28,2024-08-02 07:37:17,2024-08-02 07:37:17,,,go;parameter-passing;slice;variadic-functions,The user with no hat,11026,3257971,registered,true,23724092,,CC BY-SA 4.0,,693,550,3,1,0,4,true,false,false,true,true,true,43,10,true,0.034,0.0016,4570,2014,5,16,Sunday,true,false,false,false,false,false,false
6182369,Exec a shell command in Go,"I'm looking to execute a shell command in Go and get the resulting output as a string in my program. I saw the Rosetta Code version:
package main
import ""fmt""
import ""exec""
func main() {
cmd, err := exec.Run(""/bin/ls"", []string{""/bin/ls""}, []string{}, """", exec.DevNull, exec.PassThrough, exec.PassThrough)
if (err != nil) {
fmt.Println(err)
return
}
cmd.Close()
But this doesn't capture the actual standard out or err in a way that I can programatically access - those still print out to the regular stdout / stderr. I saw that using Pipe as the out or err could help elsewhere, but no example of how to do so. Any ideas?
",https://stackoverflow.com/questions/6182369/exec-a-shell-command-in-go,142,273540.0,11.0,,,2011-05-31 02:18:08,2024-11-07 14:13:36,,,,go;shellexecute,Chris Bunch,90739,422,registered,true,6182595,,CC BY-SA 3.0,,767,642,1,1,0,2,true,false,false,true,true,false,26,6,false,0.04,0.0005,5653,2011,5,2,Tuesday,false,false,false,false,false,false,false
20924303,How to do date/time comparison,"Is there any options in doing date comparison in Go? I have to sort data based on date and time - independently. So I might allow an object that occurs within a range of dates so long as it also occurs within a range of times. In this model, I could not simply just select the oldest date, youngest time/latest date, latest time and Unix() seconds compare them. I'd really appreciate any suggestions.
Ultimately, I wrote a time parsing string compare module to check if a time is within a range. However, this is not faring to well; I've got some gaping issues. I'll post that here just for fun, but I'm hoping there's a better way to time compare.
package main
import (
""strconv""
""strings""
)
func tryIndex(arr []string, index int, def string) string {
if index <= len(arr)-1 {
return arr[index]
}
return def
}
/*
* Takes two strings of format ""hh:mm:ss"" and compares them.
* Takes a function to compare individual sections (split by "":"").
* Note: strings can actually be formatted like ""h"", ""hh"", ""hh:m"",
* ""hh:mm"", etc. Any missing parts will be added lazily.
*/
func timeCompare(a, b string, compare func(int, int) (bool, bool)) bool {
aArr := strings.Split(a, "":"")
bArr := strings.Split(b, "":"")
// Catches margins.
if (b == a) {
return true
}
for i := range aArr {
aI, _ := strconv.Atoi(tryIndex(aArr, i, ""00""))
bI, _ := strconv.Atoi(tryIndex(bArr, i, ""00""))
res, flag := compare(aI, bI)
if res {
return true
} else if flag { // Needed to catch case where a > b and a is the lower limit
return false
}
}
return false
}
func timeGreaterEqual(a, b int) (bool, bool) {return a > b, a < b}
func timeLesserEqual(a, b int) (bool, bool) {return a < b, a > b}
/*
* Returns true for two strings formmated ""hh:mm:ss"".
* Note: strings can actually be formatted like ""h"", ""hh"", ""hh:m"",
* ""hh:mm"", etc. Any missing parts will be added lazily.
*/
func withinTime(timeRange, time string) bool {
rArr := strings.Split(timeRange, ""-"")
if timeCompare(rArr[0], rArr[1], timeLesserEqual) {
afterStart := timeCompare(rArr[0], time, timeLesserEqual)
beforeEnd := timeCompare(rArr[1], time, timeGreaterEqual)
return afterStart && beforeEnd
}
// Catch things like `timeRange := ""22:00:00-04:59:59""` which will happen
// with UTC conversions from local time.
// THIS IS THE BROKEN PART I BELIEVE
afterStart := timeCompare(rArr[0], time, timeLesserEqual)
beforeEnd := timeCompare(rArr[1], time, timeGreaterEqual)
return afterStart || beforeEnd
}
So TLDR, I wrote a withinTimeRange(range, time) function but it's not working totally correctly. (In fact, mostly just the second case, where a time range crosses over days is broken. The original part worked, I just realized I'd need to account for that when making conversions to UTC from local.)
If there's a better (preferably built in) way, I'd love to hear about it!
NOTE:
Just as an example, I solved this issue in Javascript with this function:
function withinTime(start, end, time) {
var s = Date.parse(""01/01/2011 ""+start);
var e = Date.parse(""01/0""+(end==""24:00:00""?""2"":""1"")+""/2011 ""+(end==""24:00:00""?""00:00:00"":end));
var t = Date.parse(""01/01/2011 ""+time);
return s <= t && e >= t;
}
However I really want to do this filter server-side.
",https://stackoverflow.com/questions/20924303/how-to-do-date-time-comparison,142,256320.0,9.0,,,2014-01-04 17:35:17,2022-11-08 09:35:19,2019-11-07 17:31:55,,,datetime;go;datetime-comparison,eatonphil,13882,1507139,registered,true,20924491,,CC BY-SA 4.0,,3543,3453,2,0,0,3,true,false,false,true,true,true,30,5,false,0.035,0.0006,4704,2014,1,17,Saturday,true,false,false,false,false,false,false
7151261,Append to a file in Go,"So I can read from a local file like so:
data, error := ioutil.ReadFile(name)
And I can write to a local file
ioutil.WriteFile(filename, content, permission)
But how can I append to a file? Is there a built in method?
",https://stackoverflow.com/questions/7151261/append-to-a-file-in-go,141,177204.0,8.0,,,2011-08-22 17:37:07,2024-09-20 18:58:26,2013-03-05 22:30:23,,,file-io;go,seveibar,5053,559475,registered,true,12876022,,CC BY-SA 3.0,,293,224,2,0,0,2,true,false,false,true,true,true,22,6,false,0.045,0.0008,5570,2011,8,17,Monday,false,false,false,false,false,false,false
14025833,range over interface{} which stores a slice,"Given the scenario where you have a function which accepts t interface{}. If it is determined that the t is a slice, how do I range over that slice?
func main() {
data := []string{""one"",""two"",""three""}
test(data)
moredata := []int{1,2,3}
test(data)
}
func test(t interface{}) {
switch reflect.TypeOf(t).Kind() {
case reflect.Slice:
// how do I iterate here?
for _,value := range t {
fmt.Println(value)
}
}
}
Go Playground Example: http://play.golang.org/p/DNldAlNShB
",https://stackoverflow.com/questions/14025833/range-over-interface-which-stores-a-slice,141,129940.0,4.0,,,2012-12-24 21:28:44,2021-12-02 11:27:14,2020-06-15 09:14:36,,,go;reflection;slice;go-reflect,Owen Allen,12108,435223,registered,true,14026030,,CC BY-SA 4.0,,678,534,4,1,0,4,true,false,false,true,true,true,43,7,false,0.031,0.0011,5080,2012,12,21,Monday,false,false,false,false,false,false,false
42605337,Cannot assign to struct field in a map,"I have the data structure like this:
type Snapshot struct {
Key string
Users []Users
}
snapshots := make(map[string] Snapshot, 1)
// then did the initialization
snapshots[""test""] = Snapshot {
Key: ""testVal"",
Users: make([]Users, 0),
}
Users is another struct.
Then when I tried to append some new Users values in the Users slice like this:
snapshots[""test""].Users = append(snapshots[""test""].Users, user)
I kept getting this error:
cannot assign to struct field snapshots[""test""].Users in map
Also tried the workaround here https://github.com/golang/go/issues/3117 so like this:
tmp := snapshots[""test""].Users
tmp = append(tmp, user)
snapshots[""test""].Users = tmp
But no luck, still exactly same error.
And also tried to declare the map with pointer, so: snapshots := make(map[string] *Snapshot, 1), still no luck.
",https://stackoverflow.com/questions/42605337/cannot-assign-to-struct-field-in-a-map,141,134725.0,5.0,,,2017-03-05 06:42:19,2022-03-16 17:36:13,2019-03-29 00:53:32,,,go,lnshi,2998,7658313,registered,true,42606051,,CC BY-SA 4.0,,1135,840,7,1,0,1,true,false,false,true,true,true,38,8,false,0.037,0.001,3548,2017,3,6,Sunday,true,false,false,false,false,false,false
32758235,How to get all dependency files for a program,"I make a program in Go and after completing the code, if I want to run this code on other pc or VM, then it does not get all the dependency package files. How can I get all dependency files?
",https://stackoverflow.com/questions/32758235/how-to-get-all-dependency-files-for-a-program,140,199374.0,7.0,,,2015-09-24 09:45:43,2024-07-02 16:29:09,2021-02-11 07:56:23,,,go,user5370520,,,does_not_exist,true,32758318,,CC BY-SA 4.0,,198,191,0,0,0,1,true,false,false,true,false,true,45,9,false,0.035,0.0007,4076,2015,9,9,Thursday,false,false,false,false,false,false,false
16331063,How can I get the string representation of a struct?,"For my application, it does not matter if the string is human readable or not.
",https://stackoverflow.com/questions/16331063/how-can-i-get-the-string-representation-of-a-struct,140,241084.0,6.0,,,2013-05-02 05:39:42,2024-07-25 15:01:17,2020-07-18 12:08:31,,,string;struct;go,abw333,6011,807089,registered,true,16331470,,CC BY-SA 4.0,,86,79,0,0,0,3,true,false,false,true,true,true,52,10,true,0.025,0.0006,4951,2013,5,5,Thursday,false,false,false,false,false,false,false
26942150,importing go files in same folder,"I am having difficulty in importing a local go file into another go file.
My project structure is like something below
-samplego
--pkg
--src
---github.com
----xxxx
-----a.go
-----b.go
--bin
I am trying to import a.go inside b.go. I tried the following,
import ""a""
import ""github.com/xxxx/a""
None of these worked..I understand I have to meddle up with GOPATH but I couldn't get it right. Presently my GOPATH is pointing to samplego(/workspace/samplego).I get the below error
cannot find package ""a"" in any of:
/usr/local/go/src/pkg/a (from $GOROOT)
/workspace/samplego/src/a (from $GOPATH)
Also, how does GOPATH work when these source files are imported into another project/module? Would the local imports be an issue then? What is the best practice in this case - is it to have just one go file in module(with associated tests)?
",https://stackoverflow.com/questions/26942150/importing-go-files-in-same-folder,140,220653.0,7.0,,,2014-11-15 03:19:29,2022-12-13 14:36:45,2014-11-15 03:40:03,,,import;path;go,g0c00l.g33k,2648,1965994,registered,true,26942393,,CC BY-SA 3.0,,948,841,3,0,0,3,true,false,false,true,true,true,33,6,false,0.032,0.0006,4389,2014,11,3,Saturday,true,false,false,false,false,false,false
21961615,What are the problems that are mitigated by not allowing nested function declarations in Go?,"Lambdas work as expected:
func main() {
inc := func(x int) int { return x+1; }
}
However, the following declaration inside a declaration is not allowed:
func main() {
func inc(x int) int { return x+1; }
}
For what reason are nested functions not allowed?
",https://stackoverflow.com/questions/21961615/what-are-the-problems-that-are-mitigated-by-not-allowing-nested-function-declara,140,78010.0,5.0,,,2014-02-22 22:41:55,2022-01-19 17:39:21,2020-11-30 15:09:24,,,function;go;declaration,corazza,32650,924313,registered,true,21967381,,CC BY-SA 4.0,,334,265,2,0,0,3,true,false,false,true,true,true,92,15,true,0.064,0.0018,4655,2014,2,22,Saturday,true,false,false,false,false,false,false
28227095,Multiple values in single-value context,"Due to error handling in Go, I often end up with multiple values functions. So far, the way I have managed this has been very messy and I am looking for best practices to write cleaner code.
Let's say I have the following function:
type Item struct {
Value int
Name string
}
func Get(value int) (Item, error) {
// some code
return item, nil
}
How can I assign a new variable to item.Value elegantly. Before introducing the error handling, my function just returned item and I could simply do this:
val := Get(1).Value
Now I do this:
item, _ := Get(1)
val := item.Value
Isn't there a way to access directly the first returned variable?
",https://stackoverflow.com/questions/28227095/multiple-values-in-single-value-context,140,135023.0,7.0,,,2015-01-30 00:10:16,2025-04-22 17:15:03,2018-03-28 15:06:19,,,go;error-handling;return-value;multiple-return-values,Spearfisher,8875,2641547,registered,true,28233172,,CC BY-SA 3.0,,790,657,5,0,0,4,true,false,false,true,true,true,39,5,false,0.052,0.001,4313,2015,1,0,Friday,false,false,false,false,false,false,false
18130859,How can I iterate over a string by runes in Go?,"I wanted to this:
for i := 0; i < len(str); i++ {
dosomethingwithrune(str[i]) // takes a rune
}
But it turns out that str[i] has type byte (uint8) rather than rune.
How can I iterate over the string by runes rather than bytes?
",https://stackoverflow.com/questions/18130859/how-can-i-iterate-over-a-string-by-runes-in-go,139,204278.0,5.0,,,2013-08-08 16:08:12,2024-09-17 05:25:12,,,,string;loops;go;rune,Matt,22529,810671,registered,true,18130880,,CC BY-SA 3.0,,335,238,5,0,0,4,true,false,false,true,true,false,47,11,true,0.024,0.0007,4853,2013,8,16,Thursday,false,false,false,false,false,false,false
12703243,What is the zero for string?,"func NewKey(c appengine.Context, kind, stringID string, intID int64, parent *Key) *Key
The documentation says :
NewKey creates a new key. kind cannot be empty. Either one or both of
stringID and intID must be zero. If both are zero, the key
returned is incomplete. parent must either be a complete key or nil.
What is the zero for string?
I tried 0 and nil, and I got errors like:
cannot use nil as type string in function argument
",https://stackoverflow.com/questions/12703243/what-is-the-zero-for-string,139,102520.0,2.0,,,2012-10-03 06:48:58,2017-07-19 23:16:42,2017-07-19 23:16:42,,,string;go,DeanSinaean,2367,1412350,registered,true,12703280,,CC BY-SA 3.0,,591,447,4,0,0,2,true,false,false,true,true,true,28,6,true,0.02,0.0014,5162,2012,10,6,Wednesday,false,false,false,false,false,false,false
13812121,How to clear a map in Go?,"I'm looking for something like the c++ function .clear() for the primitive type map.
Or should I just create a new map instead?
Update: Thank you for your answers. By looking at the answers I just realized that sometimes creating a new map may lead to some inconsistency that we don't want. Consider the following example:
var a map[string]string
var b map[string]string
func main() {
a = make(map[string]string)
b=a
a[""hello""]=""world""
a = nil
fmt.Println(b[""hello""])
}
I mean, this is still different from the .clear() function in c++, which will clear the content in the object.
",https://stackoverflow.com/questions/13812121/how-to-clear-a-map-in-go,138,157898.0,8.0,,,2012-12-11 01:16:46,2024-03-09 19:28:17,2012-12-11 01:56:23,,,go,lavin,2476,1567953,registered,true,13812401,,CC BY-SA 3.0,,699,608,4,0,0,1,true,false,false,true,true,true,25,7,true,0.051,0.0009,5093,2012,12,1,Tuesday,false,false,false,false,false,false,false
21302520,Iterating through map in template,"I am trying to display a list gym classes (Yoga, Pilates etc). For each class type there are several classes, so I want to group all the Yoga classes, and all the Pilates classes and so on.
I made this function to take a slice and make a map of it
func groupClasses(classes []entities.Class) map[string][]entities.Class {
classMap := make(map[string][]entities.Class)
for _, class := range classes {
classMap[class.ClassType.Name] = append(classMap[class.ClassType.Name], class)
}
return classMap
}
The problem is now how can I iterate through it, according to http://golang.org/pkg/text/template/, you need to access it in .Key format, I don't know the keys (unless I also passed a slice of keys into the template). How do I unpack this map in my view.
All I have currently is
{{ . }}
which displays something like:
map[Pilates:[{102 PILATES ~/mobifit/video/ocen.mpg 169 40 2014-05-03 23:12:12 +0000 UTC 2014-05-03 23:12:12 +0000 UTC 1899-12-30 00:00:00 +0000 UTC {PILATES Pilates 1 2014-01-22 21:46:16 +0000 UTC} {1 leebrooks0@gmail.com password SUPERADMIN Lee Brooks {Male true} {1990-07-11 00:00:00 +0000 UTC true} {1.85 true} {88 true} 2014-01-22 21:46:16 +0000 UTC {0001-01-01 00:00:00 +0000 UTC false} {0001-01-01 00:00:00 +0000 UTC false} {0001-01-01 00:00:00 +0000 UTC false}} [{1 Mat 2014-01-22 21:46:16 +0000 UTC}]} {70 PILATES ~/mobifit/video/ocen.mpg 119 66 2014-03-31 15:12:12 +0000 UTC 2014-03-31 15:12:12 +0000 UTC 1899-12-30 00:00:00 +0000 UTC
",https://stackoverflow.com/questions/21302520/iterating-through-map-in-template,137,165752.0,2.0,,,2014-01-23 08:01:01,2017-07-16 11:08:29,2017-07-16 11:08:29,,,go;go-templates,Lee,8834,818951,registered,true,21302864,,CC BY-SA 3.0,,1669,1498,4,1,0,2,true,false,false,true,true,true,33,5,false,0.012,0.0008,4685,2014,1,8,Thursday,false,false,false,false,false,false,false
19847594,How to reliably detect os/platform in Go,"Here's what I'm currently using, which I think gets the job done, but there's got to be a better way:
func isWindows() bool {
return os.PathSeparator == '\\' && os.PathListSeparator == ';'
}
As you can see, in my case all I need to know is how to detect windows but I'd like to know the way to detect any platform/os.
Play:
http://play.golang.org/p/r4lYWDJDxL
",https://stackoverflow.com/questions/19847594/how-to-reliably-detect-os-platform-in-go,137,138334.0,10.0,,,2013-11-07 22:02:08,2025-01-21 21:17:34,2013-11-07 22:10:31,,,operating-system;go,Michael Whatcott,6105,605022,registered,true,19847868,,CC BY-SA 3.0,,496,377,1,1,0,2,true,false,false,true,true,true,40,7,false,0.072,0.001,4762,2013,11,22,Thursday,false,false,false,false,false,false,false
2707434,How to access command-line arguments passed to a Go program?,"How do I access command-line arguments in Go? They're not passed as arguments to main.
A complete program, possibly created by linking multiple packages, must have one package called main, with a function
func main() { ... }
defined. The function main.main() takes no arguments and returns no value.
",https://stackoverflow.com/questions/2707434/how-to-access-command-line-arguments-passed-to-a-go-program,137,120401.0,5.0,,,2010-04-25 06:55:27,2023-12-13 21:58:39,2013-11-21 09:44:29,,,go,Oleg Razgulyaev,5975,2153550,registered,true,2707480,,CC BY-SA 3.0,2018-07-02 12:48:06,396,313,2,0,0,1,true,false,false,true,true,true,60,10,true,0.042,0.0011,6054,2010,4,6,Sunday,true,false,false,false,false,false,false
38081807,For loop of two variables in Go,"The following for loop in Go isn't allowed,
for i := 0, j := 1; i < 10; i++, j++ {...}
What's the correct equivalent of the for-loop of two variables below?
for (int i = 0, j = 1; i < 10; i ++ , j ++) {...}
",https://stackoverflow.com/questions/38081807/for-loop-of-two-variables-in-go,136,91330.0,4.0,,,2016-06-28 16:39:19,2023-05-05 00:09:37,,,,go,sof,9803,363663,registered,true,38081920,,CC BY-SA 3.0,,281,219,2,0,0,1,true,false,false,true,true,false,31,7,false,0.044,0.0015,3798,2016,6,16,Tuesday,false,false,false,false,false,false,false
27516387,What is the correct way to find the min between two integers in Go?,"I imported the math library in my program, and I was trying to find the minimum of three numbers in the following way:
v1[j+1] = math.Min(v1[j]+1, math.Min(v0[j+1]+1, v0[j]+cost))
where v1 is declared as:
t := ""stackoverflow""
v1 := make([]int, len(t)+1)
However, when I run my program I get the following error:
./levenshtein_distance.go:36: cannot use int(v0[j + 1] + 1) (type int) as type float64 in argument to math.Min
I thought it was weird because I have another program where I write
fmt.Println(math.Min(2,3))
and that program outputs 2 without complaining.
so I ended up casting the values as float64, so that math.Min could work:
v1[j+1] = math.Min(float64(v1[j]+1), math.Min(float64(v0[j+1]+1), float64(v0[j]+cost)))
With this approach, I got the following error:
./levenshtein_distance.go:36: cannot use math.Min(int(v1[j] + 1), math.Min(int(v0[j + 1] + 1), int(v0[j] + cost))) (type float64) as type int in assignment
so to get rid of the problem, I just casted the result back to int
I thought this was extremely inefficient and hard to read:
v1[j+1] = int(math.Min(float64(v1[j]+1), math.Min(float64(v0[j+1]+1), float64(v0[j]+cost))))
I also wrote a small minInt function, but I think this should be unnecessary because the other programs that make use of math.Min work just fine when taking integers, so I concluded this has to be a problem of my program and not the library per se.
Is there anything that I'm doing terrible wrong?
Here's a program that you can use to reproduce the issues above, line 36 specifically:
package main
import (
""math""
)
func main() {
LevenshteinDistance(""stackoverflow"", ""stackexchange"")
}
func LevenshteinDistance(s string, t string) int {
if s == t {
return 0
}
if len(s) == 0 {
return len(t)
}
if len(t) == 0 {
return len(s)
}
v0 := make([]int, len(t)+1)
v1 := make([]int, len(t)+1)
for i := 0; i < len(v0); i++ {
v0[i] = i
}
for i := 0; i < len(s); i++ {
v1[0] = i + 1
for j := 0; j < len(t); j++ {
cost := 0
if s[i] != t[j] {
cost = 1
}
v1[j+1] = int(math.Min(float64(v1[j]+1), math.Min(float64(v0[j+1]+1), float64(v0[j]+cost))))
}
for j := 0; j < len(v0); j++ {
v0[j] = v1[j]
}
}
return v1[len(t)]
}
",https://stackoverflow.com/questions/27516387/what-is-the-correct-way-to-find-the-min-between-two-integers-in-go,136,199407.0,9.0,,,2014-12-17 00:22:02,2025-04-06 21:45:20,,,,go,ILikeTacos,18944,1315565,registered,true,27516559,,CC BY-SA 3.0,,2737,2404,13,0,0,1,true,false,false,true,true,false,67,14,true,0.045,0.0007,4357,2014,12,0,Wednesday,false,false,false,false,false,false,false
32751537,Why do I get a "cannot assign" error when setting value to a struct as a value in a map?,"New to Go. Encountered this error and have had no luck finding the cause or the rationale for it:
If I create a struct, I can obviously assign and re-assign the values no problem:
type Person struct {
name string
age int
}
func main() {
x := Person{""Andy Capp"", 98}
x.age = 99
fmt.Printf(""age: %d\n"", x.age)
}
but if the struct is one value in a map:
type Person struct {
name string
age int
}
type People map[string]Person
func main() {
p := make(People)
p[""HM""] = Person{""Hank McNamara"", 39}
p[""HM""].age = p[""HM""].age + 1
fmt.Printf(""age: %d\n"", p[""HM""].age)
}
I get cannot assign to p[""HM""].age. That's it, no other info. http://play.golang.org/p/VRlSItd4eP
I found a way around this - creating an incrementAge func on Person, which can be called and the result assigned to the map key, eg p[""HM""] = p[""HM""].incrementAge().
But, my question is, what is the reason for this ""cannot assign"" error, and why shouldn't I be allowed to assign the struct value directly?
",https://stackoverflow.com/questions/32751537/why-do-i-get-a-cannot-assign-error-when-setting-value-to-a-struct-as-a-value-i,136,96971.0,2.0,,,2015-09-24 00:29:52,2020-08-02 03:43:50,2015-09-24 00:41:56,2015-09-24 01:45:12,Duplicate,go,sbeam,4922,125875,registered,true,32751792,,,,1202,1006,5,1,0,1,true,true,false,true,true,true,98,20,true,0.021,0.0014,4076,2015,9,0,Thursday,false,false,false,false,false,false,false
3912089,Why are there no generics in Go?,"Does anybody know why there is no real support for generics/templates/whatsInAName in Go? So there is a generic map, but that's supplied by the compiler, while a Go programmer can't write her own implementation. With all the talk about making Go as orthogonal as possible, why can I USE a generic type but not CREATE a new one?
Especially when it comes to functional programming, there are lambdas, even closures, but with a static type system lacking generics, how do I write, well, generic higher order functions like filter(predicate, list)? OK, Linked lists and the like can be done with interface{} sacrificing type safety.
It looks like generics will only be added to Go as an afterthought, if at all,. I do trust Ken Thompson to do way better than the Java implementers, but why keep generics out? Or are they planned and just not implemented yet?
",https://stackoverflow.com/questions/3912089/why-are-there-no-generics-in-go,136,37078.0,5.0,,,2010-10-12 06:10:07,2022-10-18 14:25:54,2022-10-18 14:01:40,2022-11-01 17:34:55,Duplicate,generics;functional-programming;go,user434817,,,does_not_exist,true,3912095,,,,915,855,3,0,0,3,true,true,false,true,false,true,32,7,true,0.135,0.0037,5884,2010,10,6,Tuesday,false,false,false,false,false,false,false
26092155,Just run single test instead of the whole suite?,"I have a test suite for a Go package that implements a dozen tests. Sometimes, one of the tests in the suite fails and I'd like to re-run that test individually to save time in debugging process. Is this possible or do I have to write a separate file for this every time?
",https://stackoverflow.com/questions/26092155/just-run-single-test-instead-of-the-whole-suite,135,175233.0,6.0,,,2014-09-29 03:35:03,2022-06-20 13:03:28,2014-09-29 19:34:07,2022-04-25 15:59:47,Duplicate,go,lang2,12166,172265,registered,true,26092203,,,,279,272,0,0,0,1,true,true,false,true,true,true,48,9,true,0.034,0.0008,4436,2014,9,3,Monday,false,false,false,false,false,false,false
25677235,Create a io.Reader from a local file,"I would like to open a local file, and return a io.Reader. The reason is that I need to feed a io.Reader to a library I am using, like:
func read(r io.Reader) (results []string) {
}
",https://stackoverflow.com/questions/25677235/create-a-io-reader-from-a-local-file,135,163645.0,6.0,,,2014-09-05 01:05:30,2023-10-03 02:46:15,2019-08-19 13:44:42,,,go,Xi 张熹,11194,277368,registered,true,25677274,,CC BY-SA 4.0,,242,185,3,0,0,1,true,false,false,true,true,true,36,7,false,0.037,0.0008,4460,2014,9,1,Friday,false,false,false,false,false,false,false
13329154,no new variables on left side of :=,"What's happening here?
package main
import ""fmt""
func main() {
myArray :=[...]int{12,14,26} ;
fmt.Println(myArray)
myArray :=[...]int{11,12,14} //error pointing on this line
fmt.Println(myArray) ;
}
It throws an error that says
no new variables on left side of :=
What I was doing was re-assigning values to an already declared variable.
",https://stackoverflow.com/questions/13329154/no-new-variables-on-left-side-of,135,97329.0,4.0,,,2012-11-11 06:42:08,2020-05-11 04:23:53,2018-11-13 13:14:33,,,variables;go;colon-equals,Runes,1461,1815675,registered,true,13329186,,CC BY-SA 4.0,,446,377,2,0,0,3,true,false,false,true,true,true,35,8,false,0.041,0.0014,5123,2012,11,6,Sunday,true,false,false,false,false,false,false
11766320,Does Go have lambda expressions or anything similar?,"Does Go support lambda expressions or anything similar?
I want to port a library from another language that uses lambda expressions (Ruby).
",https://stackoverflow.com/questions/11766320/does-go-have-lambda-expressions-or-anything-similar,135,146748.0,7.0,,,2012-08-01 19:37:20,2024-09-17 14:57:17,2019-05-10 18:39:58,,,go;lambda,loyalflow,15159,1361315,registered,true,11766428,,CC BY-SA 4.0,,155,141,0,0,0,2,true,false,false,true,true,true,52,8,true,0.048,0.0009,5225,2012,8,19,Wednesday,false,false,false,false,false,false,false
53298478,Has been blocked by CORS policy: Response to preflight request doesn’t pass access control check,"I have created trip server. It works fine and we are able to make POST request by Insomnia but when we make POST request by axios on our front-end, it sends an error:
has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: It does not have HTTP ok status.
Our request on axios:
let config = {
headers: {
""Content-Type"": ""application/json"",
'Access-Control-Allow-Origin': '*',
}
}
let data = {
""id"": 4
}
axios.post('http://196.121.147.69:9777/twirp/route.FRoute/GetLists', data, config)
.then((res) => {
console.log(res)
})
.catch((err) => {
console.log(err)
});
}
My go file:
func setupResponse(w *http.ResponseWriter, req *http.Request) {
(*w).Header().Set(""Access-Control-Allow-Origin"", ""*"")
(*w).Header().Set(""Access-Control-Allow-Methods"", ""POST,GET,OPTIONS, PUT, DELETE"")
(*w).Header().Set(""Access-Control-Allow-Headers"", ""Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization"")
}
func WithUserAgent(base http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
ua := r.Header.Get(""Jwt"")
ctx = context.WithValue(ctx, ""jwt"", ua)
r = r.WithContext(ctx)
setupResponse(&w, r)
base.ServeHTTP(w, r)
})
}
const (
host = ""localhost""
port = 5432
user = ""postgres""
password = ""postgres""
dbname = ""postgres""
)
func main() {
psqlInfo := fmt.Sprintf(""host=%s port=%d user=%s ""+
""password=%s dbname=%s sslmode=disable"",
host, port, user, password, dbname)
server := &s.Server{psqlInfo}
twirpHandler := p.NewFinanceServiceServer(server, nil)
wrap := WithUserAgent(twirpHandler)
log.Fatalln(http.ListenAndServe("":9707"", wrap))
}
As I said before on Insomnia it works great, but when we make an axios POST request, on browser's console following appears:
has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: It does not have HTTP ok status.
",https://stackoverflow.com/questions/53298478/has-been-blocked-by-cors-policy-response-to-preflight-request-doesn-t-pass-acce,135,764135.0,12.0,,,2018-11-14 10:52:30,2023-12-25 05:02:35,2021-07-05 10:46:29,,,rest;google-chrome;go;axios;cors,GGG,1457,10596363,registered,true,53304135,,CC BY-SA 4.0,,2284,2113,6,0,0,5,true,false,false,true,true,true,96,15,false,0.016,0.0002,2929,2018,11,10,Wednesday,false,false,false,false,false,false,false
19646889,Why should I use log.Println instead of fmt.Println?,"From log.go (the implementation of the log package) :
167 // Println calls l.Output to print to the logger.
168 // Arguments are handled in the manner of fmt.Println.
169 func (l *Logger) Println(v ...interface{}) { l.Output(2, fmt.Sprintln(v...)) }
log.Println is just a function wrapper for fmt.Sprintln , why should I use it instead of fmt.Println or fmt.Sprintln ?
Any practical reasons ?
",https://stackoverflow.com/questions/19646889/why-should-i-use-log-println-instead-of-fmt-println,135,46430.0,1.0,,,2013-10-28 23:22:04,2019-03-27 12:17:50,2013-10-29 08:11:41,,,logging;go,Salah Eddine Taouririt,26873,1120221,registered,true,19646964,,CC BY-SA 3.0,,829,398,5,5,0,2,true,false,false,true,true,true,52,8,true,0.022,0.0029,4772,2013,10,23,Monday,false,false,false,false,false,false,false
33436730,"Unmarshal JSON with some known, and some unknown field names","I have the following JSON
{""a"":1, ""b"":2, ""?"":1, ""??"":1}
I know that it has the ""a"" and ""b"" fields, but I don't know the names of other fields. So I want to unmarshal it in the following type:
type Foo struct {
// Known fields
A int `json:""a""`
B int `json:""b""`
// Unknown fields
X map[string]interface{} `json:???` // Rest of the fields should go here.
}
How do I do that?
",https://stackoverflow.com/questions/33436730/unmarshal-json-with-some-known-and-some-unknown-field-names,135,122204.0,9.0,,,2015-10-30 13:06:06,2025-05-08 21:26:59,2019-10-14 14:02:39,,,json;go,Abyx,13059,343443,registered,true,79613195,,CC BY-SA 4.0,,457,388,2,0,0,2,true,false,false,true,true,true,60,10,false,0.074,0.0011,4040,2015,10,13,Friday,false,false,false,false,false,false,false
59556394,GoLand (JetBrains) shows error message "Unresolved Reference". But Code compiles and runs,"I am writing a project using the Go language with GoLand IDE by Jetbrains.
While writing the code, GoLand shows me an error message such as "unresolved reference" when the reference do exist and that the program compiles and runs correctly.
Here is a similar (but simpler) example of some code that I have found here on stackoverflow (Go - append to slice in struct) to reproduce this issue.
The same error message appears even though I have implemented the methods just a few lines above.
package main
import (
"fmt"
)
type MyBoxItem struct {
Name string
}
type MyBox struct {
Items []MyBoxItem
}
func (box *MyBox) AddItem(item MyBoxItem) {
box.Items = append(box.Items, item)
}
func main() {
item1 := MyBoxItem{Name: "Test Item 1"}
item2 := MyBoxItem{Name: "Test Item 2"}
box := MyBox{}
box.AddItem(item1)
box.AddItem(item2)
// checking the output
fmt.Println(len(box.Items))
fmt.Println(box.Items)
}
box.AddItem(item1) and box.AddItem(item2) are marked red as an error. If I move my cursor above it, it says unresolved reference "AddItem". Yet the code compiles and runs. And as this was the solution to an other stackoverflow question, I do not think that the code is wrong. Furthermore I cannot find any mistakes in it.
[EDIT: I load the code from a remote server and edit it locally on my private pc. After finishing my changes, I upload it to the remote server (using GoLands tools like "Browse remote host") and build and compile it there. After trying it out locally with the very same code, the error message sometimes is there and sometimes not. I am totally confused]
",https://stackoverflow.com/questions/59556394/goland-jetbrains-shows-error-message-unresolved-reference-but-code-compiles,134,93607.0,29.0,,,2020-01-01 21:53:14,2024-10-10 12:02:49,2021-09-05 14:37:42,,,go;jetbrains-ide;goland,David,1351,12637942,registered,true,,,CC BY-SA 4.0,,2055,1699,5,2,1,3,false,false,false,true,true,true,99,12,false,0.31,0.0014,2516,2020,1,21,Wednesday,false,false,false,false,false,false,false
9539108,Obtaining a Unix Timestamp in Go Language (current time in seconds since epoch),"I have some code written in Go which I am trying to update to work with the latest weekly builds. (It was last built under r60). Everything is now working except for the following bit:
if t, _, err := os.Time(); err == nil {
port[5] = int32(t)
}
Any advice on how to update this to work with the current Go implementation?
",https://stackoverflow.com/questions/9539108/obtaining-a-unix-timestamp-in-go-language-current-time-in-seconds-since-epoch,134,203616.0,4.0,,,2012-03-02 19:21:07,2021-03-26 18:04:23,2013-11-04 09:30:54,,,unix;timestamp;go,crc,1515,517883,registered,true,9539644,,CC BY-SA 3.0,,369,331,1,0,0,3,true,false,false,true,true,true,79,13,false,0.02,0.0007,5377,2012,3,19,Friday,false,false,false,false,false,false,false
40326540,How to assign default value if env var is empty?,"How do you assign a default value if an environment variable isn't set in Go?
In Python I could do mongo_password = os.getenv('MONGO_PASS', 'pass') where pass is the default value if MONGO_PASS env var isn't set.
I tried an if statement based on os.Getenv being empty, but that doesn't seem to work due to the scope of variable assignment within an if statement. And I'm checking for multiple env var's, so I can't act on this information within the if statement.
",https://stackoverflow.com/questions/40326540/how-to-assign-default-value-if-env-var-is-empty,134,156075.0,10.0,,,2016-10-30 06:21:43,2026-02-26 12:56:57,2019-09-20 02:56:40,,,go;environment-variables,Ryan Clair,1451,5233657,registered,true,40326580,,CC BY-SA 4.0,,539,466,4,0,0,2,true,false,false,true,true,true,48,10,true,0.064,0.0009,3674,2016,10,6,Sunday,true,false,false,false,false,false,false
24809287,How do you get a Golang program to print the line number of the error it just called?,"I was trying to throw errors in my Golang program with log.Fatal but, log.Fatal does not also print the line where the log.Fatal was ran. Is there no way of getting access to the line number that called log.Fatal? i.e. is there a way to get the line number when throwing an error?
I was trying to google this but was unsure how. The best thing I could get was printing the stack trace, which I guess is good but might be a little too much. I also don't want to write debug.PrintStack() every time I need the line number, I am just surprised there isn't any built in function for this like log.FatalStackTrace() or something that isn't costume.
Also, the reason I do not want to make my own debugging/error handling stuff is because I don't want people to have to learn how to use my special costume handling code. I just want something standard where people can read my code later and be like
""ah ok, so its throwing an error and doing X...""
The less people have to learn about my code the better :)
",https://stackoverflow.com/questions/24809287/how-do-you-get-a-golang-program-to-print-the-line-number-of-the-error-it-just-ca,134,106096.0,3.0,,,2014-07-17 16:50:40,2023-08-04 09:28:01,2016-08-03 14:43:37,,,error-handling;go,Charlie Parker,6492,1601580,registered,true,24809859,,CC BY-SA 3.0,,1196,1009,5,1,0,2,true,false,false,true,true,true,85,18,true,0.028,0.0013,4510,2014,7,16,Thursday,false,false,false,false,false,false,false
27234861,Correct way of getting Client's IP Addresses from http.Request,"What's the correct way to get all client's IP Addresses from http.Request? In PHP there are a lot of variables that I should check. Is it the same on Go?
One that I found is:
req.RemoteAddr
And is the request case sensitive? for example x-forwarded-for is the same as X-Forwarded-For and X-FORWARDED-FOR? (from req.Header.Get(""X-FORWARDED-FOR""))
",https://stackoverflow.com/questions/27234861/correct-way-of-getting-clients-ip-addresses-from-http-request,134,363982.0,8.0,,,2014-12-01 18:31:57,2022-04-19 04:02:18,2019-05-27 19:41:12,,,http;go;ip,Kokizzu,27267,1620210,registered,true,27235620,,CC BY-SA 4.0,,569,351,7,1,0,3,true,false,false,true,true,true,66,9,false,0.022,0.0004,4373,2014,12,18,Monday,false,false,false,false,false,false,false
21326109,Why are lists used infrequently in Go?,"Is there a way to create an array/slice in Go without a hard-coded array size? Why is List ignored?
In all the languages I've worked with extensively: Delphi, C#, C++, Python - Lists are very important because they can be dynamically resized, as opposed to arrays.
In Golang, there is indeed a list.Liststruct, but I see very little documentation about it - whether in Go By Example or the three Go books that I have - Summerfield, Chisnal and Balbaert - they all spend a lot of time on arrays and slices and then skip to maps. In souce code examples I also find little or no use of list.List.
It also appears that, unlike Python, Range is not supported for List - big drawback IMO. Am I missing something?
Slices are lovely, but they still need to be based on an array with a hard-coded size. That's where List comes in.
",https://stackoverflow.com/questions/21326109/why-are-lists-used-infrequently-in-go,134,143234.0,7.0,,,2014-01-24 06:41:55,2022-03-29 08:10:11,2022-03-29 08:10:11,,,arrays;list;go,Vector,11943,712579,registered,true,22701892,,CC BY-SA 4.0,,970,823,3,1,0,3,true,false,false,true,true,true,38,7,true,0.049,0.0009,4684,2014,1,6,Friday,false,false,false,false,false,false,false
30483652,How to get capturing group functionality in Go regular expressions,"I'm porting a library from Ruby to Go, and have just discovered that regular expressions in Ruby are not compatible with Go (google RE2). It's come to my attention that Ruby & Java (plus other languages use PCRE regular expressions (perl compatible, which supports capturing groups)), so I need to re-write my expressions so that they compile ok in Go.
For example, I have the following regex:
`(?<Year>\d{4})-(?<Month>\d{2})-(?<Day>\d{2})`
This should accept input such as:
2001-01-20
The capturing groups allow the year, month and day to be captured into variables. To get the value of each group, it's very easy; you just index into the returned matched data with the group name and you get the value back. So, for example to get the year, something like this pseudo code:
m=expression.Match(""2001-01-20"")
year = m[""Year""]
This is a pattern I use a lot in my expressions, so I have a lot of re-writing to do.
So, is there a way to get this kind of functionality in Go regexp; how should I re-write these expressions?
",https://stackoverflow.com/questions/30483652/how-to-get-capturing-group-functionality-in-go-regular-expressions,133,192302.0,8.0,,,2015-05-27 13:17:06,2022-12-16 12:59:02,2019-08-16 06:32:24,,,regex;go;capture-group,Plastikfan,4112,223936,registered,true,30483899,,CC BY-SA 4.0,,1167,1053,3,0,0,3,true,false,false,true,true,true,66,10,false,0.042,0.0007,4196,2015,5,13,Wednesday,false,false,false,false,false,false,false
42706246,How to build executable with name other than Golang package,"Is it possible to build (install, go get, etc) an executable with the name foobar if my Golang package name is one of the following:
github.com/username/go-foobar
github.com/username/foobar-tools
and has main.go in the package root?
",https://stackoverflow.com/questions/42706246/how-to-build-executable-with-name-other-than-golang-package,133,152483.0,2.0,,,2017-03-09 21:57:57,2023-11-13 17:19:01,,,,go;build;package;naming-conventions,Petr Razumov,2222,3656424,registered,true,42706464,,CC BY-SA 3.0,,330,237,4,0,0,4,true,false,false,true,true,false,59,10,false,0.013,0.0009,3544,2017,3,21,Thursday,false,false,false,false,false,false,false
34383705,How do I compare strings in GoLang?,"I am unable to produce a 'true' result when it comes to Go string comparison. I wrote the following to explain the issue and attached a screenshot of the output
// string comparison in Go
package main
import ""fmt""
import ""bufio""
import ""os""
func main() {
var isLetterA bool
fmt.Println(""Enter the letter a"")
reader := bufio.NewReader(os.Stdin)
input, _ := reader.ReadString('\n')
if(input == ""a"") {
isLetterA = true
} else {
isLetterA = false
}
fmt.Println(""You entered"",input)
fmt.Println(""Is it the letter a?"",isLetterA)
}
",https://stackoverflow.com/questions/34383705/how-do-i-compare-strings-in-golang,133,252934.0,4.0,,,2015-12-20 17:23:00,2022-03-08 16:18:31,2015-12-20 17:25:19,,,go,user2202911,3054,2202911,registered,true,34383753,,CC BY-SA 3.0,,746,588,1,1,1,1,true,false,false,true,true,true,35,7,true,0.016,0.0005,3989,2015,12,17,Sunday,true,false,false,false,false,false,false
1863460,What's the point of having pointers in Go?,"I know that pointers in Go allow mutation of a function's arguments, but wouldn't it have been simpler if they adopted just references (with appropriate const or mutable qualifiers). Now we have pointers and for some built-in types like maps and channels implicit pass by reference.
Am I missing something or are pointers in Go just an unnecessary complication?
",https://stackoverflow.com/questions/1863460/whats-the-point-of-having-pointers-in-go,133,35508.0,6.0,,,2009-12-07 22:47:26,2023-09-14 02:56:05,2010-03-19 16:14:52,,,pointers;go,anon,1357,226740,unregistered,true,,,CC BY-SA 2.5,,377,363,0,0,0,2,false,false,false,true,true,true,46,8,true,0.169,0.0037,6193,2009,12,22,Monday,false,false,false,false,false,false,false
27764421,"What is "_," (underscore comma) in a Go declaration?","And I can't seem to understand this kind of variable declaration:
_, prs := m[""example""]
What exactly is ""_,"" doing and why have they declared a variable like this instead of
prs := m[""example""]
(I found it as part of Go by Example: Maps)
",https://stackoverflow.com/questions/27764421/what-is-underscore-comma-in-a-go-declaration,132,91593.0,9.0,,,2015-01-04 10:07:31,2022-10-24 03:53:19,2018-07-13 21:45:53,,,variables;go,Kansuler,1589,3656968,registered,true,27764432,,CC BY-SA 4.0,,387,245,3,1,0,2,true,false,false,true,true,true,62,9,true,0.098,0.0014,4339,2015,1,10,Sunday,true,false,false,false,false,false,false
11184336,How to convert from []byte to int in Go Programming,"I need to create a client-server example over TCP. In the client side I read 2 numbers and I send them to the server. The problem I faced is that I can't convert from []byte to int, because the communication accept only data of type []byte.
Is there any way to convert []byte to int or I can send int to the server?
Some sample code will be really appreciated.
Thanks.
",https://stackoverflow.com/questions/11184336/how-to-convert-from-byte-to-int-in-go-programming,131,250580.0,10.0,,,2012-06-25 06:24:39,2024-05-25 20:55:51,2012-06-25 07:37:32,,,tcp;client-server;byte;type-conversion;go,Emanuel,6992,193921,registered,true,26561931,,CC BY-SA 3.0,,478,372,6,0,0,5,true,false,false,true,true,true,51,10,false,0.04,0.0005,5262,2012,6,6,Monday,false,false,false,false,false,false,false
17133590,How to get file length in Go?,"I looked up golang.org/pkg/os/#File , but still have no idea.
Seems there is no way to get file length, did I miss something?
How to get file length in Go?
",https://stackoverflow.com/questions/17133590/how-to-get-file-length-in-go,130,118781.0,4.0,,,2013-06-16 12:58:24,2020-05-08 11:54:50,2013-06-16 13:03:19,,,file;go,hardPass,21241,1316684,registered,true,17133613,,CC BY-SA 3.0,,217,158,0,1,0,2,true,false,false,true,true,true,29,7,true,0.034,0.0011,4906,2013,6,12,Sunday,true,false,false,false,false,false,false
24158114,What are the differences between Rust's `String` and `str`?,"Why does Rust have both String and str? What are the differences between them, and when should one be used over the other? Is one of them getting deprecated?
",https://stackoverflow.com/questions/24158114/what-are-the-differences-between-rusts-string-and-str,1095,241548.0,16.0,,,2014-06-11 08:29:34,2025-01-03 06:32:56,2023-09-05 08:03:15,,,string;rust,Daniel Fath,18433,220485,registered,true,24159933,,CC BY-SA 4.0,2019-04-28 12:49:05,358,158,2,2,0,2,true,false,false,true,true,true,63,9,true,0.066,0.0045,4546,2014,6,8,Wednesday,false,false,false,false,false,false,false
25106554,Why doesn't println! work in Rust unit tests?,"I've implemented the following method and unit test:
use std::fs::File;
use std::path::Path;
use std::io::prelude::*;
fn read_file(path: &Path) {
let mut file = File::open(path).unwrap();
let mut contents = String::new();
file.read_to_string(&mut contents).unwrap();
println!("{contents}");
}
#[test]
fn test_read_file() {
let path = &Path::new("/etc/hosts");
println!("{path:?}");
read_file(path);
}
I run the unit test this way:
rustc --test app.rs; ./app
I could also run this with
cargo test
I get a message back saying the test passed but the println! is never displayed on screen. Why not?
",https://stackoverflow.com/questions/25106554/why-doesnt-println-work-in-rust-unit-tests,685,253794.0,8.0,,,2014-08-03 16:10:50,2024-04-13 19:11:42,2024-04-13 19:11:42,,,testing;rust;println,ruipacheco,16862,70600,registered,true,25107081,,CC BY-SA 4.0,,909,679,4,0,0,3,true,false,false,true,true,true,49,8,true,0.032,0.0027,4493,2014,8,16,Sunday,true,false,false,false,false,false,false
30154541,How do I concatenate strings?,"How do I concatenate the following combinations of types:
str and str
String and str
String and String
",https://stackoverflow.com/questions/30154541/how-do-i-concatenate-strings,653,613779.0,10.0,,,2015-05-10 17:40:20,2025-05-21 19:16:02,2016-05-26 00:00:54,,,string;rust;string-concatenation,jsalter,6778,770829,registered,true,30154791,,CC BY-SA 3.0,2022-02-27 13:26:34,227,106,6,0,0,3,true,false,false,true,true,true,29,5,true,0.016,0.0011,4213,2015,5,17,Sunday,true,false,false,false,false,false,false
25877285,How do you disable dead code warnings at the crate level in Rust?,"While tinkering in Rust, I repeatedly encountered a lot of dead code warnings that made it difficult to focus. I tried using the outer attribute #[allow(dead_code)], but it only silences one warning at a time.
struct SemanticDirection;
fn main() {}
warning: struct `SemanticDirection` is never constructed
--> src\main.rs:1:8
|
1 | struct SemanticDirection;
| ^^^^^^^^^^^^^^^^^
|
= note: `#[warn(dead_code)]` on by default
How do I disable these warnings at the crate level?
",https://stackoverflow.com/questions/25877285/how-do-you-disable-dead-code-warnings-at-the-crate-level-in-rust,569,334706.0,14.0,,,2014-09-16 19:51:46,2024-12-11 08:59:55,2024-11-13 12:27:36,,,rust;compiler-warnings;dead-code,Andrew Wagner,25123,139802,registered,true,25877389,,CC BY-SA 4.0,,655,497,3,0,0,3,true,false,false,true,true,true,65,13,true,0.042,0.0017,4449,2014,9,19,Tuesday,false,false,false,false,false,false,false
27043268,Convert a String to int?,"Note: this question contains deprecated pre-1.0 code! The answer is correct, though.
To convert a str to an int in Rust, I can do this:
let my_int = from_str::<int>(my_str);
The only way I know how to convert a String to an int is to get a slice of it and then use from_str on it like so:
let my_int = from_str::<int>(my_string.as_slice());
Is there a way to directly convert a String to an int?
",https://stackoverflow.com/questions/27043268/convert-a-string-to-int,540,604941.0,8.0,,,2014-11-20 15:27:09,2023-12-20 17:34:49,2021-01-07 15:17:35,,,rust,mmtauqir,9649,814849,registered,true,27683271,,CC BY-SA 4.0,,599,415,9,0,0,1,true,false,false,true,true,true,24,5,true,0.013,0.0009,4384,2014,11,15,Thursday,false,false,false,false,false,false,false
34733811,What is the difference between iter and into_iter?,"I am doing the Rust by Example tutorial, which has this code snippet:
// Vec example
let vec1 = vec![1, 2, 3];
let vec2 = vec![4, 5, 6];
// `iter()` for vecs yields `&i32`. Destructure to `i32`.
println!("2 in vec1: {}", vec1.iter() .any(|&x| x == 2));
// `into_iter()` for vecs yields `i32`. No destructuring required.
println!("2 in vec2: {}", vec2.into_iter().any(| x| x == 2));
// Array example
let array1 = [1, 2, 3];
let array2 = [4, 5, 6];
// `iter()` for arrays yields `&i32`.
println!("2 in array1: {}", array1.iter() .any(|&x| x == 2));
// `into_iter()` for arrays unusually yields `&i32`.
println!("2 in array2: {}", array2.into_iter().any(|&x| x == 2));
I am quite confused — for a Vec, the iterator returned from .iter yields references and the iterator returned from .into_iter yields values, but for an array these iterators are identical?
What is the use case/API for these two methods?
",https://stackoverflow.com/questions/34733811/what-is-the-difference-between-iter-and-into-iter,535,182080.0,6.0,,,2016-01-12 00:48:51,2025-04-17 07:11:34,2023-09-09 22:29:12,,,rust;iterator,vitiral,9456,1036670,registered,true,34745885,,CC BY-SA 4.0,,1545,979,4,5,0,2,true,false,false,true,true,true,50,8,true,0.033,0.0029,3966,2016,1,0,Tuesday,false,false,false,false,false,false,false
21747136,How do I print the type of a variable in Rust?,"I have the following:
let mut my_number = 32.90;
How do I print the type of my_number?
Using type and type_of did not work. Is there another way I can print the number's type?
",https://stackoverflow.com/questions/21747136/how-do-i-print-the-type-of-a-variable-in-rust,515,258776.0,18.0,,,2014-02-13 06:49:09,2024-08-12 16:58:24,2024-08-12 16:58:24,,,types;rust,user2431012,5257,2431012,registered,true,,,CC BY-SA 4.0,,300,177,4,0,0,2,false,false,false,true,true,true,46,11,true,0.07,0.002,4664,2014,2,6,Thursday,false,false,false,false,false,false,false
25383488,How to match a String against string literals?,"I'm trying to figure out how to match a String in Rust.
I initially tried matching like this, but I figured out Rust cannot implicitly cast from std::string::String to &str.
fn main() {
let stringthing = String::from(""c"");
match stringthing {
""a"" => println!(""0""),
""b"" => println!(""1""),
""c"" => println!(""2""),
}
}
This has the error:
error[E0308]: mismatched types
--> src/main.rs:4:9
|
4 | ""a"" => println!(""0""),
| ^^^ expected struct `std::string::String`, found reference
|
= note: expected type `std::string::String`
found type `&'static str`
I then tried to construct new String objects, as I could not find a function to cast a String to a &str.
fn main() {
let stringthing = String::from(""c"");
match stringthing {
String::from(""a"") => println!(""0""),
String::from(""b"") => println!(""1""),
String::from(""c"") => println!(""2""),
}
}
This gave me the following error 3 times:
error[E0164]: `String::from` does not name a tuple variant or a tuple struct
--> src/main.rs:4:9
|
4 | String::from(""a"") => return 0,
| ^^^^^^^^^^^^^^^^^ not a tuple variant or struct
How to actually match Strings in Rust?
",https://stackoverflow.com/questions/25383488/how-to-match-a-string-against-string-literals,467,237338.0,9.0,,,2014-08-19 12:30:02,2024-03-07 14:01:50,2021-01-07 15:17:25,,,string;match;rust,Jeroen,17304,2558778,registered,true,32790546,,CC BY-SA 4.0,,1592,1285,11,0,0,3,true,false,false,true,true,true,46,8,true,0.038,0.002,4477,2014,8,12,Tuesday,false,false,false,false,false,false,false
32300132,Why can't I store a value and a reference to that value in the same struct?,"I have a value and I want to store that value and a reference to
something inside that value in my own type:
struct Thing {
count: u32,
}
struct Combined<'a>(Thing, &'a u32);
fn make_combined<'a>() -> Combined<'a> {
let thing = Thing { count: 42 };
Combined(thing, &thing.count)
}
Sometimes, I have a value and I want to store that value and a reference to
that value in the same structure:
struct Combined<'a>(Thing, &'a Thing);
fn make_combined<'a>() -> Combined<'a> {
let thing = Thing::new();
Combined(thing, &thing)
}
Sometimes, I'm not even taking a reference of the value and I get the
same error:
struct Combined<'a>(Parent, Child<'a>);
fn make_combined<'a>() -> Combined<'a> {
let parent = Parent::new();
let child = parent.child();
Combined(parent, child)
}
In each of these cases, I get an error that one of the values ""does
not live long enough"". What does this error mean?
",https://stackoverflow.com/questions/32300132/why-cant-i-store-a-value-and-a-reference-to-that-value-in-the-same-struct,462,73762.0,5.0,,,2015-08-30 19:06:11,2024-08-04 10:28:18,2021-03-07 01:01:02,,,rust;reference;lifetime;borrow-checker,Shepmaster,442509,155423,registered,true,32300133,,CC BY-SA 4.0,,1119,1019,3,0,0,4,true,false,false,true,true,true,79,16,true,0.068,0.0063,4101,2015,8,19,Sunday,true,false,false,false,false,false,false
26946646,Package with both a library and a binary?,"I would like to make a Rust package that contains both a reusable library (where most of the program is implemented), and also an executable that uses it.
Assuming I have not confused any semantics in the Rust module system, what should my Cargo.toml file look like?
",https://stackoverflow.com/questions/26946646/package-with-both-a-library-and-a-binary,441,184712.0,5.0,,,2014-11-15 14:04:29,2025-02-16 20:22:48,2022-05-02 15:52:58,,,rust;rust-cargo,Andrew Wagner,25123,139802,registered,true,26946705,,CC BY-SA 4.0,,296,269,1,0,0,2,true,false,false,true,true,true,41,8,true,0.027,0.0024,4389,2014,11,14,Saturday,true,false,false,false,false,false,false
29483365,What is the syntax for a multiline string literal?,"I'm having a hard time figuring out how string syntax works in Rust. Specifically, I'm trying to figure out how to make a multiple line string.
",https://stackoverflow.com/questions/29483365/what-is-the-syntax-for-a-multiline-string-literal,432,279202.0,8.0,,,2015-04-07 03:43:11,2026-05-19 18:56:15,2022-10-01 16:01:32,,,string;rust;syntax,Dumbapples,4949,4643182,registered,true,29483453,,CC BY-SA 4.0,,151,144,0,0,0,3,true,false,false,true,true,true,50,9,true,0.029,0.0015,4246,2015,4,3,Tuesday,false,false,false,false,false,false,false
57259126,Why does the Rust compiler not optimize code assuming that two mutable references cannot alias?,"As far as I know, reference/pointer aliasing can hinder the compiler's ability to generate optimized code, since they must ensure the generated binary behaves correctly in the case where the two references/pointers indeed alias. For instance, in the following C code,
void adds(int *a, int *b) {
*a += *b;
*a += *b;
}
when compiled by clang version 6.0.0-1ubuntu2 (tags/RELEASE_600/final) with the -O3 flag, it emits
0000000000000000 <adds>:
0: 8b 07 mov (%rdi),%eax # load a into EAX
2: 03 06 add (%rsi),%eax # load-and-add b
4: 89 07 mov %eax,(%rdi) # store into a
6: 03 06 add (%rsi),%eax # load-and-add b again
8: 89 07 mov %eax,(%rdi) # store into a again
a: c3 retq
Here the code stores back to (%rdi) twice in case int *a and int *b alias.
When we explicitly tell the compiler that these two pointers cannot alias with the restrict keyword:
void adds(int *restrict a, int *restrict b) {
*a += *b;
*a += *b;
}
Then Clang will emit a more optimized version that effectively does *a += 2 * (*b), which is equivalent if (as promised by restrict) *b isn't modified by assigning to *a:
0000000000000000 <adds>:
0: 8b 06 mov (%rsi),%eax # load b once
2: 01 c0 add %eax,%eax # double it
4: 01 07 add %eax,(%rdi) # *a += 2 * (*b)
6: c3 retq
Since Rust makes sure (except in unsafe code) that two mutable references cannot alias, I would think that the compiler should be able to emit the more optimized version of the code.
When I test with the code below and compile it with rustc 1.35.0 with -C opt-level=3 --emit obj,
#![crate_type = "staticlib"]
#[no_mangle]
fn adds(a: &mut i32, b: &mut i32) {
*a += *b;
*a += *b;
}
it generates:
0000000000000000 <adds>:
0: 8b 07 mov (%rdi),%eax
2: 03 06 add (%rsi),%eax
4: 89 07 mov %eax,(%rdi)
6: 03 06 add (%rsi),%eax
8: 89 07 mov %eax,(%rdi)
a: c3 retq
This does not take advantage of the guarantee that a and b cannot alias.
Is this because the current Rust compiler is still in development and has not yet incorporated alias analysis to do the optimization?
Is this because there is still a chance that a and b could alias, even in safe Rust?
",https://stackoverflow.com/questions/57259126/why-does-the-rust-compiler-not-optimize-code-assuming-that-two-mutable-reference,422,54889.0,1.0,,,2019-07-29 17:57:44,2022-08-27 17:14:40,2022-08-27 17:14:40,,,rust;reference;compiler-optimization;llvm-codegen,Zhiyao,4514,8626243,registered,true,57259339,,CC BY-SA 4.0,2022-03-19 07:43:00,3270,2613,22,0,0,4,true,false,false,true,true,true,95,15,true,0.018,0.0077,2672,2019,7,17,Monday,false,false,false,false,false,false,false
26643688,How do I split a string in Rust?,"From the documentation, it's not clear. In Java you could use the split method like so:
""some string 123 ffd"".split(""123"");
",https://stackoverflow.com/questions/26643688/how-do-i-split-a-string-in-rust,409,504030.0,7.0,,,2014-10-30 01:45:31,2023-08-01 23:07:53,2018-05-12 17:25:33,,,rust,Incerteza,35684,2813589,registered,true,47152394,,CC BY-SA 4.0,,289,126,2,1,0,1,true,false,false,true,true,true,32,8,true,0.014,0.0008,4405,2014,10,1,Thursday,false,false,false,false,false,false,false
29008127,Why are Rust executables so huge?,"I find the approach and the way they define the language in the first two chapters of the documentation particularly interesting. So I decided to get my fingers wet and started out with "Hello, world!".
I did so on Windows 7 x64, btw.
fn main() {
println!("Hello, world!");
}
Issuing cargo build and looking at the result in targets\debug I found the resulting .exe being 3MB. After some searching (documentation of cargo command line flags is hard to find...) I found the --release option and created the release build. To my surprise, the .exe size has only become smaller by an insignificant amount: 2.99MB instead of 3MB.
My expectation would have been that a systems programming language would produce something compact.
Can anyone elaborate on what Rust is compiling to, how it can be possible it produces such huge images from a 3-line program? Is it compiling to a virtual machine? Is there a strip command I missed (debug info inside the release build?)? Anything else which might allow to understand what is going on?
",https://stackoverflow.com/questions/29008127/why-are-rust-executables-so-huge,398,125210.0,6.0,,,2015-03-12 11:07:45,2023-01-29 13:25:50,2023-01-10 18:42:52,,,rust;rust-cargo,BitTickler,12250,2225104,registered,true,29008355,,CC BY-SA 4.0,2018-02-15 14:39:00,1203,1053,5,0,0,2,true,false,false,true,true,true,33,6,true,0.048,0.0032,4272,2015,3,11,Thursday,false,false,false,false,false,false,false
27791532,"How do I create a global, mutable singleton?","What is the best way to create and use a struct with only one instantiation in the system? Yes, this is necessary, it is the OpenGL subsystem, and making multiple copies of this and passing it around everywhere would add confusion, rather than relieve it.
The singleton needs to be as efficient as possible. It doesn't seem possible to store an arbitrary object on the static area, as it contains a Vec with a destructor. The second option is to store an (unsafe) pointer on the static area, pointing to a heap allocated singleton. What is the most convenient and safest way to do this, while keeping syntax terse?
",https://stackoverflow.com/questions/27791532/how-do-i-create-a-global-mutable-singleton,381,241052.0,9.0,,,2015-01-06 03:11:29,2025-07-02 19:59:15,2022-09-07 21:22:08,,,rust,stevenkucera,4723,1099089,registered,true,,,CC BY-SA 4.0,,642,615,1,0,0,1,false,false,false,true,true,true,44,8,true,0.037,0.0016,4337,2015,1,3,Tuesday,false,false,false,false,false,false,false
28519997,What are Rust's exact auto-dereferencing rules?,"I'm learning/experimenting with Rust, and in all the elegance that I find in this language, there is one peculiarity that baffles me and seems totally out of place.
Rust automatically dereferences pointers when making method calls. I made some tests to determine the exact behaviour:
struct X { val: i32 }
impl std::ops::Deref for X {
type Target = i32;
fn deref(&self) -> &i32 { &self.val }
}
trait M { fn m(self); }
impl M for i32 { fn m(self) { println!(""i32::m()""); } }
impl M for X { fn m(self) { println!(""X::m()""); } }
impl M for &X { fn m(self) { println!(""&X::m()""); } }
impl M for &&X { fn m(self) { println!(""&&X::m()""); } }
impl M for &&&X { fn m(self) { println!(""&&&X::m()""); } }
trait RefM { fn refm(&self); }
impl RefM for i32 { fn refm(&self) { println!(""i32::refm()""); } }
impl RefM for X { fn refm(&self) { println!(""X::refm()""); } }
impl RefM for &X { fn refm(&self) { println!(""&X::refm()""); } }
impl RefM for &&X { fn refm(&self) { println!(""&&X::refm()""); } }
impl RefM for &&&X { fn refm(&self) { println!(""&&&X::refm()""); } }
struct Y { val: i32 }
impl std::ops::Deref for Y {
type Target = i32;
fn deref(&self) -> &i32 { &self.val }
}
struct Z { val: Y }
impl std::ops::Deref for Z {
type Target = Y;
fn deref(&self) -> &Y { &self.val }
}
#[derive(Clone, Copy)]
struct A;
impl M for A { fn m(self) { println!(""A::m()""); } }
impl M for &&&A { fn m(self) { println!(""&&&A::m()""); } }
impl RefM for A { fn refm(&self) { println!(""A::refm()""); } }
impl RefM for &&&A { fn refm(&self) { println!(""&&&A::refm()""); } }
fn main() {
// I'll use @ to denote left side of the dot operator
(*X{val:42}).m(); // i32::m() , Self == @
X{val:42}.m(); // X::m() , Self == @
(&X{val:42}).m(); // &X::m() , Self == @
(&&X{val:42}).m(); // &&X::m() , Self == @
(&&&X{val:42}).m(); // &&&X:m() , Self == @
(&&&&X{val:42}).m(); // &&&X::m() , Self == *@
(&&&&&X{val:42}).m(); // &&&X::m() , Self == **@
println!(""-------------------------"");
(*X{val:42}).refm(); // i32::refm() , Self == @
X{val:42}.refm(); // X::refm() , Self == @
(&X{val:42}).refm(); // X::refm() , Self == *@
(&&X{val:42}).refm(); // &X::refm() , Self == *@
(&&&X{val:42}).refm(); // &&X::refm() , Self == *@
(&&&&X{val:42}).refm(); // &&&X::refm(), Self == *@
(&&&&&X{val:42}).refm(); // &&&X::refm(), Self == **@
println!(""-------------------------"");
Y{val:42}.refm(); // i32::refm() , Self == *@
Z{val:Y{val:42}}.refm(); // i32::refm() , Self == **@
println!(""-------------------------"");
A.m(); // A::m() , Self == @
// without the Copy trait, (&A).m() would be a compilation error:
// cannot move out of borrowed content
(&A).m(); // A::m() , Self == *@
(&&A).m(); // &&&A::m() , Self == &@
(&&&A).m(); // &&&A::m() , Self == @
A.refm(); // A::refm() , Self == @
(&A).refm(); // A::refm() , Self == *@
(&&A).refm(); // A::refm() , Self == **@
(&&&A).refm(); // &&&A::refm(), Self == @
}
So, it seems that, more or less:
- The compiler will insert as many dereference operators as necessary to invoke a method.
- The compiler, when resolving methods declared using
&self (call-by-reference):
- First tries calling for a single dereference of
self
- Then tries calling for the exact type of
self
- Then, tries inserting as many dereference operators as necessary for a match
- Methods declared using
self (call-by-value) for type T behave as if they were declared using &self (call-by-reference) for type &T and called on the reference to whatever is on the left side of the dot operator.
- The above rules are first tried with raw built-in dereferencing, and if there's no match, the overload with
Deref trait is used.
What are the exact auto-dereferencing rules? Can anyone give any formal rationale for such a design decision?
",https://stackoverflow.com/questions/28519997/what-are-rusts-exact-auto-dereferencing-rules,359,64894.0,4.0,,,2015-02-14 20:31:55,2023-01-06 17:24:43,2021-02-22 19:50:58,,,rust;reference;language-lawyer,kFYatek,5983,403742,registered,true,28552082,,CC BY-SA 4.0,,5108,4677,9,1,0,3,true,false,false,true,true,true,51,6,true,0.062,0.0055,4298,2015,2,20,Saturday,true,false,false,false,false,false,false
31192956,What's the de-facto way of reading and writing files in Rust 1.x?,"With Rust being comparatively new, I've seen far too many ways of reading and writing files. Many are extremely messy snippets someone came up with for their blog, and 99% of the examples I've found (even on Stack Overflow) are from unstable builds that no longer work. Now that Rust is stable, what is a simple, readable, non-panicking snippet for reading or writing files?
This is the closest I've gotten to something that works in terms of reading a text file, but it's still not compiling even though I'm fairly certain I've included everything I should have. This is based off of a snippet I found on Google+ of all places, and the only thing I've changed is that the old BufferedReader is now just BufReader:
use std::fs::File;
use std::io::BufReader;
use std::path::Path;
fn main() {
let path = Path::new(""./textfile"");
let mut file = BufReader::new(File::open(&path));
for line in file.lines() {
println!(""{}"", line);
}
}
The compiler complains:
error: the trait bound `std::result::Result<std::fs::File, std::io::Error>: std::io::Read` is not satisfied [--explain E0277]
--> src/main.rs:7:20
|>
7 |> let mut file = BufReader::new(File::open(&path));
|> ^^^^^^^^^^^^^^
note: required by `std::io::BufReader::new`
error: no method named `lines` found for type `std::io::BufReader<std::result::Result<std::fs::File, std::io::Error>>` in the current scope
--> src/main.rs:8:22
|>
8 |> for line in file.lines() {
|> ^^^^^
To sum it up, what I'm looking for is:
- brevity
- readability
- covers all possible errors
- doesn't panic
",https://stackoverflow.com/questions/31192956/whats-the-de-facto-way-of-reading-and-writing-files-in-rust-1-x,355,242002.0,3.0,,,2015-07-02 19:23:46,2025-06-23 18:24:09,2016-09-11 02:03:50,,,file-io;rust,Jared,4960,709010,registered,true,31193386,,CC BY-SA 3.0,,1856,1670,4,0,0,2,true,false,false,true,true,true,69,12,true,0.012,0.0015,4160,2015,7,19,Thursday,false,false,false,false,false,false,false
37928591,Is there a command to update Cargo to the latest official release?,"I seem to have diverging versions of rustc and cargo (I think),
$ rustc -V
rustc 1.9.0 (e4e8b6668 2016-05-18)
$ cargo -V
cargo 0.10.0-nightly (10ddd7d 2016-04-08)
Is there a command akin to
pip install --upgrade pip
for upgrading cargo? I.e. something like
cargo install --upgrade cargo
",https://stackoverflow.com/questions/37928591/is-there-a-command-to-update-cargo-to-the-latest-official-release,352,317213.0,7.0,,,2016-06-20 17:38:13,2024-08-01 06:05:11,2018-08-04 16:26:53,,,rust;package-managers;rust-cargo,Filip Allberg,5751,5045375,registered,true,37928782,,CC BY-SA 4.0,2024-05-15 19:21:58,547,298,6,0,0,3,true,false,false,true,true,true,66,12,true,0.022,0.0011,3806,2016,6,17,Monday,false,false,false,false,false,false,false
26388861,How can I include a module from another file from the same project?,"By following this guide I created a Cargo project.
src/main.rs
fn main() {
hello::print_hello();
}
mod hello {
pub fn print_hello() {
println!("Hello, world!");
}
}
which I run using
cargo build && cargo run
and it compiles without errors. Now I'm trying to split the main module in two but cannot figure out how to include a module from another file.
My project tree looks like this
├── src
├── hello.rs
└── main.rs
and the content of the files:
src/main.rs
use hello;
fn main() {
hello::print_hello();
}
src/hello.rs
mod hello {
pub fn print_hello() {
println!("Hello, world!");
}
}
When I compile it with cargo build I get
error[E0432]: unresolved import `hello`
--> src/main.rs:1:5
|
1 | use hello;
| ^^^^^ no `hello` external crate
I tried to follow the compiler's suggestions and modified main.rs to:
#![feature(globs)]
extern crate hello;
use hello::*;
fn main() {
hello::print_hello();
}
But this still doesn't help much, now I get this:
error[E0463]: can't find crate for `hello`
--> src/main.rs:3:1
|
3 | extern crate hello;
| ^^^^^^^^^^^^^^^^^^^ can't find crate
Is there a trivial example of how to include one module from the current project into the project's main file?
",https://stackoverflow.com/questions/26388861/how-can-i-include-a-module-from-another-file-from-the-same-project,346,326339.0,6.0,,,2014-10-15 17:47:50,2025-07-08 18:58:15,2025-07-08 18:58:15,,,rust;module;program-entry-point;rust-cargo,ave,19803,1509733,registered,true,26390046,,CC BY-SA 4.0,,1940,1298,13,1,0,4,true,false,false,true,true,true,67,13,true,0.018,0.0011,4420,2014,10,17,Wednesday,false,false,false,false,false,false,false
52445961,How do I fix the Rust error "linker 'cc' not found" for Debian on Windows 10?,"I'm running Debian on Windows 10 (Windows Subsystem for Linux) and installed Rust using the command:
curl https://sh.rustup.rs -sSf | sh
There were no errors in the install, but when I tried to compile with rustc I got the error linker 'cc' not found.
",https://stackoverflow.com/questions/52445961/how-do-i-fix-the-rust-error-linker-cc-not-found-for-debian-on-windows-10,326,250964.0,12.0,,,2018-09-21 14:33:23,2025-06-06 00:47:04,2025-06-06 00:47:04,,,linux;windows;rust,Thane Plummer,11158,2391063,registered,true,,,CC BY-SA 4.0,,356,255,3,0,0,3,false,false,false,true,true,true,95,16,true,0.048,0.0013,2983,2018,9,14,Friday,false,false,false,false,false,false,false
42917566,What is this question mark operator about?,"I'm reading the documentation for File:
//..
let mut file = File::create(""foo.txt"")?;
//..
What is the ? in this line? I do not recall seeing it in the Rust Book before.
",https://stackoverflow.com/questions/42917566/what-is-this-question-mark-operator-about,322,140078.0,4.0,,,2017-03-21 02:50:31,2025-04-07 01:05:37,2022-10-01 15:23:23,,,rust;syntax,Angel Angel,22432,4140572,registered,true,42921174,,CC BY-SA 4.0,,318,173,3,1,0,2,true,false,false,true,true,true,42,7,true,0.029,0.0023,3532,2017,3,2,Tuesday,false,false,false,false,false,false,false
30340815,Managing the lifetimes of garbage-collected objects,"I am making a simplistic mark-and-compact garbage collector. Without going too much into details, the API it exposes is like this:
/// Describes the internal structure of a managed object.
pub struct Tag { ... }
/// An unmanaged pointer to a managed object.
pub type Pointer = *mut usize;
/// Mapping from old to new locations.
pub type Adjust = BTreeMap<usize, Pointer>;
/// Mark this object and anything it points to as non-garbage.
pub unsafe fn survive(ptr: Pointer);
pub struct Heap { ... }
impl Heap {
pub fn new() -> Heap;
// Allocate an object with the specified structure.
pub fn allocate(&mut self, tag: Tag) -> Pointer;
/// Move all live objects from `heap` into `self`.
pub unsafe fn reallocate(&mut self, heap: Heap) -> Adjust;
}
This API is obviously fundamentally unsafe. I would like to rework the API (without changing the internals, which are just fine!) to account for the following facts:
All Pointers to (objects allocated in) a Heap become invalid when the heap is merged into another heap.
merge returns an Adjust whose values are valid Pointers to (objects allocated in) self.
I have the following tentative solution:
// Replaces Pointer.
#[derive(Copy, Clone)]
pub struct Object<'a> {
ptr: *mut AtomicUsize,
mark: PhantomData<&'a usize>
}
impl<'a> Object<'a> {
pub fn survive(self); // Now supposed to be perfectly safe!
}
pub type Adjust<'a> = BTreeMap<usize, Object<'a>>;
pub struct Heap { ... }
pub struct Allocator<'a> { ... }
impl Heap {
fn allocator(&'a self) -> Allocator<'a>;
// The following doesn't work:
//
// fn allocate(&'a mut self) -> Object<'a>;
// fn reallocate(&'a mut self, heap: Heap) -> Adjust<'a>;
//
// Because it doesn't allow the user to allocate more
// than one `Object` at a time (!) in a `Heap`.
}
impl<'a> Allocator<'a> {
// Note that the resulting `Object`s are tied to the `Heap`,
// but not to the allocator itself.
fn allocate(&mut self, tag: Tag) -> Object<'a>;
fn reallocate(&mut self, heap: Heap) -> Adjust<'a>;
}
Is this design correct? If not, what needs to be changed?
",https://stackoverflow.com/questions/30340815/managing-the-lifetimes-of-garbage-collected-objects,321,9175.0,0.0,,,2015-05-20 05:18:14,2022-03-09 16:38:38,2021-07-09 02:58:49,2022-03-15 06:40:46,Needs more focus,garbage-collection;rust;allocation;lifetime,isekaijin,19917,46571,registered,false,,,,2021-12-28 13:40:42,2668,2296,9,1,0,4,false,true,false,true,true,true,51,6,false,0.0,0.035,4203,2015,5,5,Wednesday,false,false,false,false,false,false,false
47565203,Cargo build hangs with " Blocking waiting for file lock on the registry index" after building parity from source,"I followed the readme instructions for building Parity from source and then executed:
cargo build --release
~/.cargo/bin/cargo build --release
as instructed, both of which returned the following message while the prompt hung:
Blocking waiting for file lock on the registry index
I'm on a Mac.
",https://stackoverflow.com/questions/47565203/cargo-build-hangs-with-blocking-waiting-for-file-lock-on-the-registry-index-a,313,190445.0,25.0,,,2017-11-30 02:58:27,2024-11-12 13:07:20,2022-06-07 22:25:39,,,rust;rust-cargo,Naruto Sempai,7481,1008162,registered,true,47855850,,CC BY-SA 4.0,2023-04-03 17:19:03,544,296,2,2,0,2,true,false,false,true,true,true,122,19,false,0.131,0.0016,3278,2017,11,2,Thursday,false,false,false,false,false,false,false
28311868,What is the equivalent of the join operator over a vector of Strings?,"I wasn't able to find the Rust equivalent for the ""join"" operator over a vector of Strings. I have a Vec<String> and I'd like to join them as a single String:
let string_list = vec![""Foo"".to_string(),""Bar"".to_string()];
let joined = something::join(string_list,""-"");
assert_eq!(""Foo-Bar"", joined);
Related:
",https://stackoverflow.com/questions/28311868/what-is-the-equivalent-of-the-join-operator-over-a-vector-of-strings,311,269750.0,3.0,,,2015-02-04 01:19:59,2024-01-06 19:45:53,2019-05-29 11:55:00,,,string;rust,Davide Aversa,6146,173787,registered,true,28312049,,CC BY-SA 4.0,,623,397,4,1,0,2,true,false,false,true,true,true,69,13,true,0.011,0.0012,4308,2015,2,1,Wednesday,false,false,false,false,false,false,false
27840394,How can a Rust program access metadata from its Cargo package?,"How do you access a Cargo package's metadata (e.g. version) from the Rust code in the package? In my case, I am building a command line tool that I'd like to have a standard --version flag, and I'd like the implementation to read the version of the package from Cargo.toml so I don't have to maintain it in two places. I can imagine there are other reasons someone might want to access Cargo metadata from the program as well.
",https://stackoverflow.com/questions/27840394/how-can-a-rust-program-access-metadata-from-its-cargo-package,306,72613.0,4.0,,,2015-01-08 12:41:59,2025-06-27 19:02:17,,,,rust;rust-cargo,Jimmy,37681,242493,registered,true,27841363,,CC BY-SA 3.0,2025-04-03 12:48:41,460,427,2,0,0,2,true,false,false,true,true,false,62,11,true,0.055,0.0042,4335,2015,1,12,Thursday,false,false,false,false,false,false,false
19076719,How do I convert a Vector of bytes (u8) to a string?,"I am trying to write simple TCP/IP client in Rust and I need to print out the buffer I got from the server.
How do I convert a Vec<u8> (or a &[u8]) to a String?
",https://stackoverflow.com/questions/19076719/how-do-i-convert-a-vector-of-bytes-u8-to-a-string,302,343416.0,6.0,,,2013-09-29 10:03:36,2023-07-17 21:54:01,2021-04-10 18:19:29,,,rust,Athabaska Dick,4371,677701,registered,true,19076878,,CC BY-SA 4.0,,224,171,3,0,0,1,true,false,false,true,true,true,52,12,true,0.017,0.0009,4801,2013,9,10,Sunday,true,false,false,false,false,false,false
31012923,What is the difference between Copy and Clone?,"This issue seems to imply it's just an implementation detail (memcpy vs ???), but I can't find any explicit description of the differences.
",https://stackoverflow.com/questions/31012923/what-is-the-difference-between-copy-and-clone,301,122027.0,6.0,,,2015-06-23 20:31:09,2024-02-10 01:07:21,2015-06-24 03:23:08,,,rust,user12341234,7323,3277393,registered,true,31013156,,CC BY-SA 3.0,,238,140,1,1,0,1,true,false,false,true,true,true,46,8,true,0.049,0.0025,4169,2015,6,20,Tuesday,false,false,false,false,false,false,false
24047686,Default function arguments in Rust,"Is it possible to create a function with a default argument?
fn add(a: int = 1, b: int = 2) { a + b }
",https://stackoverflow.com/questions/24047686/default-function-arguments-in-rust,289,194619.0,10.0,,,2014-06-04 21:13:42,2024-10-30 01:20:38,2021-01-07 15:20:21,,,function;parameters;arguments;rust,Jeroen,17304,2558778,registered,true,24049607,,CC BY-SA 4.0,,134,103,1,0,0,4,true,false,false,true,true,true,34,5,false,0.051,0.0015,4553,2014,6,21,Wednesday,false,false,false,false,false,false,false
36604010,How can I build multiple binaries with Cargo?,"I'd like to make a project with a daemon and a client, connecting through a unix socket.
A client and a daemon requires two binaries, so how do I tell Cargo to build two targets from two different sources?
To add a bit of fantasy, I'd like to have a library for the main part of the daemon, and just have a binary to wrap around it and communicate through sockets.
So, we have this kind of tree architecture:
├── Cargo.toml
├── target
| └── debug
| ├── daemon
│ └── client
└── src
├── daemon
│ ├── bin
│ │ └── main.rs
│ └── lib
│ └── lib.rs
└── client
└── bin
└── main.rs
I could make one executable which manages both concerns, but that's not what I want to do, unless it's very good practice.
",https://stackoverflow.com/questions/36604010/how-can-i-build-multiple-binaries-with-cargo,283,148341.0,3.0,,,2016-04-13 16:10:01,2023-07-01 13:23:45,2016-04-13 17:17:17,,,rust;rust-cargo,RallionRl,3023,5630582,registered,true,36604610,,CC BY-SA 3.0,,924,774,8,0,0,2,true,false,false,true,true,true,45,8,true,0.02,0.0019,3874,2016,4,16,Wednesday,false,false,false,false,false,false,false
31609137,Why are explicit lifetimes needed in Rust?,"I was reading the lifetimes chapter of the Rust book, and I came across this example for a named/explicit lifetime:
struct Foo<'a> {
x: &'a i32,
}
fn main() {
let x; // -+ x goes into scope
// |
{ // |
let y = &5; // ---+ y goes into scope
let f = Foo { x: y }; // ---+ f goes into scope
x = &f.x; // | | error here
} // ---+ f and y go out of scope
// |
println!(""{}"", x); // |
} // -+ x goes out of scope
It's quite clear to me that the error being prevented by the compiler is the use-after-free of the reference assigned to x: after the inner scope is done, f and therefore &f.x become invalid, and should not have been assigned to x.
My issue is that the problem could have easily been analyzed away without using the explicit 'a lifetime, for instance by inferring an illegal assignment of a reference to a wider scope (x = &f.x;).
In which cases are explicit lifetimes actually needed to prevent use-after-free (or some other class?) errors?
",https://stackoverflow.com/questions/31609137/why-are-explicit-lifetimes-needed-in-rust,283,38257.0,12.0,,,2015-07-24 11:15:06,2026-01-03 03:57:32,2018-06-19 18:23:35,,,reference;rust;static-analysis;lifetime,corazza,32650,924313,registered,true,31612025,,CC BY-SA 4.0,,1462,1214,7,1,0,4,true,false,false,true,true,true,42,7,true,0.314,0.0074,4138,2015,7,11,Friday,false,false,false,false,false,false,false
40006219,"Why is it discouraged to accept a reference &String, &Vec, or &Box as a function argument?","I wrote some Rust code that takes a &String as an argument:
fn awesome_greeting(name: &String) {
println!(""Wow, you are awesome, {}!"", name);
}
I've also written code that takes in a reference to a Vec or Box:
fn total_price(prices: &Vec<i32>) -> i32 {
prices.iter().sum()
}
fn is_even(value: &Box<i32>) -> bool {
**value % 2 == 0
}
However, I received some feedback that doing it like this isn't a good idea. Why not?
",https://stackoverflow.com/questions/40006219/why-is-it-discouraged-to-accept-a-reference-string-vec-or-box-as-a-function,267,30512.0,4.0,,,2016-10-12 18:50:50,2023-04-26 20:44:45,2023-02-17 20:08:07,,,rust,Shepmaster,442509,155423,registered,true,40006220,,CC BY-SA 4.0,,581,473,5,0,0,1,true,false,false,true,true,true,102,16,true,0.131,0.0088,3692,2016,10,18,Wednesday,false,false,false,false,false,false,false
40792801,What is the best way to concatenate vectors in Rust?,"Is it even possible to concatenate vectors in Rust? If so, is there an elegant way to do so? I have something like this:
let mut a = vec![1, 2, 3];
let b = vec![4, 5, 6];
for val in &b {
a.push(val);
}
Does anyone know of a better way?
",https://stackoverflow.com/questions/40792801/what-is-the-best-way-to-concatenate-vectors-in-rust,262,246145.0,4.0,,,2016-11-24 18:34:56,2025-02-14 14:08:46,2023-01-01 10:40:35,,,vector;rust;concatenation,Joe Thomas,6557,3072896,registered,true,40795247,,CC BY-SA 4.0,,286,248,1,0,0,3,true,false,false,true,true,true,52,10,true,0.016,0.0011,3649,2016,11,18,Thursday,false,false,false,false,false,false,false
26368288,How do I stop iteration and return an error when Iterator::map returns a Result::Err?,"I have a function that returns a Result:
fn find(id: &Id) -> Result<Item, ItemError> {
// ...
}
Then another using it like this:
let parent_items: Vec<Item> = parent_ids.iter()
.map(|id| find(id).unwrap())
.collect();
How do I handle the case of failure inside any of the map iterations?
I know I could use flat_map and in this case the error results would be ignored:
let parent_items: Vec<Item> = parent_ids.iter()
.flat_map(|id| find(id).into_iter())
.collect();
Result's iterator has either 0 or 1 items depending on the success state, and flat_map will filter it out if it's 0.
However, I don't want to ignore errors, I want to instead make the whole code block just stop and return a new error (based on the error that came up within the map, or just forward the existing error).
How do I best handle this in Rust?
",https://stackoverflow.com/questions/26368288/how-do-i-stop-iteration-and-return-an-error-when-iteratormap-returns-a-result,262,86716.0,6.0,,,2014-10-14 18:58:12,2025-11-09 16:25:50,2019-05-01 23:19:31,,,rust;rust-result,Kai Sellgren,30812,1364206,registered,true,26370894,,CC BY-SA 4.0,,1082,878,8,0,0,2,true,false,false,true,true,true,85,14,true,0.069,0.003,4421,2014,10,18,Tuesday,false,false,false,false,false,false,false
57458460,Why is there a large performance impact when looping over an array with 240 or more elements?,"When running a sum loop over an array in Rust, I noticed a huge performance drop when CAPACITY >= 240. CAPACITY = 239 is about 80 times faster.
Is there special compilation optimization Rust is doing for ""short"" arrays?
Compiled with rustc -C opt-level=3.
use std::time::Instant;
const CAPACITY: usize = 240;
const IN_LOOPS: usize = 500000;
fn main() {
let mut arr = [0; CAPACITY];
for i in 0..CAPACITY {
arr[i] = i;
}
let mut sum = 0;
let now = Instant::now();
for _ in 0..IN_LOOPS {
let mut s = 0;
for i in 0..arr.len() {
s += arr[i];
}
sum += s;
}
println!(""sum:{} time:{:?}"", sum, now.elapsed());
}
",https://stackoverflow.com/questions/57458460/why-is-there-a-large-performance-impact-when-looping-over-an-array-with-240-or-m,261,24066.0,2.0,,,2019-08-12 09:16:34,2019-08-16 10:05:03,2019-08-15 02:35:39,,,arrays;performance;rust;llvm-codegen,Guy Korland,9058,593425,registered,true,57462362,,CC BY-SA 4.0,,818,695,4,0,0,4,true,false,false,true,true,true,93,17,true,0.083,0.0108,2658,2019,8,9,Monday,false,false,false,false,false,false,false
33025887,How to use a local unpublished crate?,"I've made a library:
cargo new my_lib
and I want to use that library in a different program:
cargo new my_program --bin
extern crate my_lib;
fn main {
println!(""Hello, World!"");
}
what do I need to do to get this to work?
They aren't in the same project folder.
.
├── my_lib
└── my_program
Hopefully this makes sense.
I thought I'd be able to override the path as per the Cargo guide, but it states
You cannot use this feature to tell Cargo how to find local unpublished crates.
This is when using the latest stable version of Rust (1.3).
",https://stackoverflow.com/questions/33025887/how-to-use-a-local-unpublished-crate,255,119691.0,3.0,,,2015-10-08 21:01:22,2024-09-11 23:10:17,2021-11-29 17:58:02,,,rust;rust-crates,Andre S.,2762,2734279,registered,true,33025972,,CC BY-SA 4.0,,788,565,4,1,0,2,true,false,false,true,true,true,37,7,true,0.025,0.0021,4062,2015,10,21,Thursday,false,false,false,false,false,false,false
30177395,"When does a closure implement Fn, FnMut and FnOnce?","What are the specific conditions for a closure to implement the Fn, FnMut and FnOnce traits?
That is:
- When does a closure not implement the
FnOnce trait?
- When does a closure not implement the
FnMut trait?
- When does a closure not implement the
Fn trait?
For instance, mutating the state of the closure on it's body makes the compiler not implement Fn on it.
",https://stackoverflow.com/questions/30177395/when-does-a-closure-implement-fn-fnmut-and-fnonce,245,79320.0,3.0,,,2015-05-11 20:49:36,2025-07-14 20:16:29,2016-09-08 14:20:20,,,rust;closures,Denilson Amorim,10450,2679626,registered,true,30232500,,CC BY-SA 3.0,,554,362,7,0,0,2,true,false,false,true,true,true,51,9,true,0.038,0.0031,4212,2015,5,20,Monday,false,false,false,false,false,false,false
27893223,How do I iterate over a range with a custom step?,"How can I iterate over a range in Rust with a step other than 1? I'm coming from a C++ background so I'd like to do something like
for(auto i = 0; i <= n; i+=2) {
//...
}
In Rust I need to use the range function, and it doesn't seem like there is a third argument available for having a custom step. How can I accomplish this?
",https://stackoverflow.com/questions/27893223/how-do-i-iterate-over-a-range-with-a-custom-step,243,170428.0,6.0,,,2015-01-11 23:14:58,2024-08-22 17:29:56,2022-06-26 00:27:24,,,rust;iterator,Syntactic Fructose,20374,1409312,registered,true,32841532,,CC BY-SA 4.0,,399,335,3,0,0,2,true,false,false,true,true,true,49,11,true,0.035,0.0014,4332,2015,1,23,Sunday,true,false,false,false,false,false,false
26731243,How do I use a macro across module files?,"I have two modules in separate files within the same crate, where the crate has macro_rules enabled. I want to use the macros defined in one module in another module.
// macros.rs
#[macro_export] // or not? is ineffectual for this, afaik
macro_rules! my_macro(...)
// something.rs
use macros;
// use macros::my_macro; <-- unresolved import (for obvious reasons)
my_macro!() // <-- how?
I currently hit the compiler error ""macro undefined: 'my_macro'""... which makes sense; the macro system runs before the module system. How do I work around that?
",https://stackoverflow.com/questions/26731243/how-do-i-use-a-macro-across-module-files,242,156618.0,5.0,,,2014-11-04 09:07:24,2021-11-23 13:37:00,2019-02-25 20:48:27,,,module;rust;rust-macros,user,5590,1467466,registered,true,31749071,,CC BY-SA 4.0,,622,558,3,0,0,3,true,false,false,true,true,true,41,9,true,0.032,0.0015,4400,2014,11,9,Tuesday,false,false,false,false,false,false,false
19605132,Is it possible to use global variables in Rust?,"I know that in general, global-variables are to be avoided. Nevertheless, I think in a practical sense, it is sometimes desirable (in situations where the variable is integral to the program) to use them.
In order to learn Rust, I'm currently writing a database test program using sqlite3 and the Rust/sqlite3 package on GitHub. Consequently, that necessitates (in my test-program) (as an alternative to a global variable), to pass the database variable between functions of which there are about a dozen. An example is below.
Is it possible and feasible and desirable to use global variables in Rust?
Given the example below, can I declare and use a global variable?
extern crate sqlite;
fn main() {
let db: sqlite::Connection = open_database();
if !insert_data(&db, insert_max) {
return;
}
}
I tried the following, but it doesn't appear to be quite right and resulted in the errors below (I tried also with an unsafe block):
extern crate sqlite;
static mut DB: Option<sqlite::Connection> = None;
fn main() {
DB = sqlite::open("test.db").expect("'test.db' should be readable");
println!("Database Opened OK");
create_table();
println!("Completed");
}
// Create Table
fn create_table() {
let sql = "CREATE TABLE IF NOT EXISTS TEMP2 (ikey INTEGER PRIMARY KEY NOT NULL)";
match DB.exec(sql) {
Ok(_) => println!("Table created"),
Err(err) => println!("Exec of Sql failed : {}\nSql={}", err, sql),
}
}
Errors that resulted from compile:
error[E0308]: mismatched types
--> src/main.rs:6:10
|
6 | DB = sqlite::open("test.db").expect("'test.db' should be readable");
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected enum `std::option::Option`, found struct `sqlite::Connection`
|
= note: expected type `std::option::Option<sqlite::Connection>`
found type `sqlite::Connection`
error: no method named `exec` found for type `std::option::Option<sqlite::Connection>` in the current scope
--> src/main.rs:16:14
|
16 | match DB.exec(sql) {
| ^^^^
",https://stackoverflow.com/questions/19605132/is-it-possible-to-use-global-variables-in-rust,236,256282.0,10.0,,,2013-10-26 09:39:45,2025-06-29 02:12:45,2025-06-23 19:10:30,,,global-variables;rust,Brian Oh,10970,1949390,registered,true,,,CC BY-SA 4.0,,2415,2222,4,0,0,2,false,false,false,true,true,true,47,9,true,0.039,0.0009,4774,2013,10,9,Saturday,true,false,false,false,false,false,false
19650265,Is there a faster/shorter way to initialize variables in a Rust struct?,"In the following example, I would much prefer to assign a value to each field in the struct in the declaration of the fields. Alternatively, it effectively takes one additional statement for each field to assign a value to the fields. All I want to be able to do is to assign default values when the struct is instantiated.
Is there a more succinct way of doing this?
struct cParams {
iInsertMax: i64,
iUpdateMax: i64,
iDeleteMax: i64,
iInstanceMax: i64,
tFirstInstance: bool,
tCreateTables: bool,
tContinue: bool,
}
impl cParams {
fn new() -> cParams {
cParams {
iInsertMax: -1,
iUpdateMax: -1,
iDeleteMax: -1,
iInstanceMax: -1,
tFirstInstance: false,
tCreateTables: false,
tContinue: false,
}
}
}
",https://stackoverflow.com/questions/19650265/is-there-a-faster-shorter-way-to-initialize-variables-in-a-rust-struct,234,184230.0,2.0,,,2013-10-29 05:21:31,2025-02-03 02:55:24,2025-02-03 02:55:24,,,rust;default-value,Brian Oh,10970,1949390,registered,true,19653453,,CC BY-SA 4.0,,880,842,1,0,0,2,true,false,false,true,true,true,71,12,true,0.011,0.0013,4771,2013,10,5,Tuesday,false,false,false,false,false,false,false
27535289,What is the correct way to return an Iterator (or any other trait)?,"The following Rust code compiles and runs without any issues.
fn main() {
let text = ""abc"";
println!(""{}"", text.split(' ').take(2).count());
}
After that, I tried something like this .... but it didn't compile
fn main() {
let text = ""word1 word2 word3"";
println!(""{}"", to_words(text).take(2).count());
}
fn to_words(text: &str) -> &Iterator<Item = &str> {
&(text.split(' '))
}
The main problem is that I'm not sure what return type the function to_words() should have. The compiler says:
error[E0599]: no method named `count` found for type `std::iter::Take<std::iter::Iterator<Item=&str>>` in the current scope
--> src/main.rs:3:43
|
3 | println!(""{}"", to_words(text).take(2).count());
| ^^^^^
|
= note: the method `count` exists but the following trait bounds were not satisfied:
`std::iter::Iterator<Item=&str> : std::marker::Sized`
`std::iter::Take<std::iter::Iterator<Item=&str>> : std::iter::Iterator`
What would be the correct code to make this run? .... and where is my knowledge gap?
",https://stackoverflow.com/questions/27535289/what-is-the-correct-way-to-return-an-iterator-or-any-other-trait,234,94098.0,2.0,,,2014-12-17 21:39:10,2021-09-12 12:53:30,2017-10-29 17:14:55,,,rust,forgemo,4924,541794,registered,true,27535594,,CC BY-SA 3.0,,1320,1168,4,0,0,1,true,false,false,true,true,true,67,13,true,0.021,0.0025,4357,2014,12,21,Wednesday,false,false,false,false,false,false,false
55603111,Unable to compile Rust hello world on Windows: linker link.exe not found,"I have installed Rust on windows from Rust installation page. After installation I tried running the ""hello world"" program but got the following error.
>cargo run
Error
Compiling helloworld v0.1.0 (C:\Users\DELL\helloworld)
error: linker `link.exe` not found
note: The system cannot find the file specified. (os error 2)
note: the msvc targets depend on the msvc linker but `link.exe` was not found
note: please ensure that VS 2013, VS 2015 or VS 2017 was installed with the Visual C++ option
error: aborting due to previous error
error: Could not compile `helloworld`.
To learn more, run the command again with --verbose.
Code:
fn main() {
println!(""Hello, world!"");
}
",https://stackoverflow.com/questions/55603111/unable-to-compile-rust-hello-world-on-windows-linker-link-exe-not-found,230,274403.0,20.0,,,2019-04-10 00:34:45,2026-01-05 09:14:56,2019-04-14 01:55:35,,,compiler-errors;installation;rust;linker-errors;build-tools,Zobia Kanwal,5143,10736243,registered,true,55603112,,CC BY-SA 4.0,2024-05-22 23:01:38,1002,687,3,1,0,5,true,false,false,true,true,true,72,12,false,0.073,0.0008,2782,2019,4,0,Wednesday,false,false,false,false,false,false,false
29403920,What's the difference between use and extern crate?,"I think that use is used to import identifiers into the current scope and extern crate is used to declare an external module. But this understanding (maybe wrong) doesn't make any sense to me. Can someone explain why Rust has these two concepts and what are the suitable cases to use them?
",https://stackoverflow.com/questions/29403920/whats-the-difference-between-use-and-extern-crate,221,61361.0,2.0,,,2015-04-02 02:13:48,2023-01-03 10:28:39,2023-01-01 11:11:07,,,rust,maralla,2851,4389183,registered,true,29404692,,CC BY-SA 4.0,,323,290,2,0,0,1,true,false,false,true,true,true,55,8,true,0.033,0.0036,4251,2015,4,2,Thursday,false,false,false,false,false,false,false
32059370,When is it appropriate to use an associated type versus a generic type?,"In this question, an issue arose that could be solved by changing an attempt at using a generic type parameter into an associated type. That prompted the question "Why is an associated type more appropriate here?", which made me want to know more.
The RFC that introduced associated types says:
This RFC clarifies trait matching by:
- Treating all trait type parameters as input types, and
- Providing associated types, which are output types.
The RFC uses a graph structure as a motivating example, and this is also used in the documentation, but I'll admit to not fully appreciating the benefits of the associated type version over the type-parameterized version. The primary thing is that the distance method doesn't need to care about the Edge type. This is nice but seems a bit shallow of a reason for having associated types at all.
I've found associated types to be pretty intuitive to use in practice, but I find myself struggling when deciding where and when I should use them in my own API.
When writing code, when should I choose an associated type over a generic type parameter, and when should I do the opposite?
",https://stackoverflow.com/questions/32059370/when-is-it-appropriate-to-use-an-associated-type-versus-a-generic-type,219,37391.0,3.0,,,2015-08-17 20:44:31,2024-09-06 13:45:16,2022-09-17 13:26:27,,,types;rust;idioms,Shepmaster,442509,155423,registered,true,32065644,,CC BY-SA 4.0,,1602,1136,2,3,0,3,true,false,false,true,true,true,71,13,true,0.08,0.0059,4114,2015,8,20,Monday,false,false,false,false,false,false,false
28123453,What is the difference between traits in Rust and typeclasses in Haskell?,"Traits in Rust seem at least superficially similar to typeclasses in Haskell, however I've seen people write that there are some differences between them. I was wondering exactly what these differences are.
",https://stackoverflow.com/questions/28123453/what-is-the-difference-between-traits-in-rust-and-typeclasses-in-haskell,213,30382.0,3.0,,,2015-01-24 07:50:44,2022-12-21 18:03:44,2021-08-31 12:02:13,,,haskell;rust;traits,LogicChains,4452,2553416,registered,true,32659986,,CC BY-SA 4.0,,369,207,0,2,0,3,true,false,false,true,true,true,73,12,true,0.099,0.007,4319,2015,1,7,Saturday,true,false,false,false,false,false,false
34484361,Does cargo install have an equivalent update command?,"I used cargo install to globally install a package, such as rustfmt or racer.
How can I update the installed package without first deleting it (cargo uninstall) and then running cargo install again.
Is there an update command?
",https://stackoverflow.com/questions/34484361/does-cargo-install-have-an-equivalent-update-command,210,82866.0,6.0,,,2015-12-27 20:09:55,2025-11-28 14:07:17,2025-11-28 14:07:17,,,rust;rust-cargo,w.brian,17767,547365,registered,true,56857644,,CC BY-SA 4.0,,305,227,3,0,0,2,true,false,false,true,true,true,53,8,true,0.072,0.0025,3982,2015,12,20,Sunday,true,false,false,false,false,false,false
28512394,How to lookup from and insert into a HashMap efficiently?,"I'd like to do the following:
- Lookup a
Vec for a certain key, and store it for later use.
- If it doesn't exist, create an empty
Vec for the key, but still keep it in the variable.
How to do this efficiently? Naturally I thought I could use match:
use std::collections::HashMap;
// This code doesn't compile.
let mut map = HashMap::new();
let key = ""foo"";
let values: &Vec<isize> = match map.get(key) {
Some(v) => v,
None => {
let default: Vec<isize> = Vec::new();
map.insert(key, default);
&default
}
};
When I tried it, it gave me errors like:
error[E0502]: cannot borrow `map` as mutable because it is also borrowed as immutable
--> src/main.rs:11:13
|
7 | let values: &Vec<isize> = match map.get(key) {
| --- immutable borrow occurs here
...
11 | map.insert(key, default);
| ^^^ mutable borrow occurs here
...
15 | }
| - immutable borrow ends here
I ended up with doing something like this, but I don't like the fact that it performs the lookup twice (map.contains_key and map.get):
// This code does compile.
let mut map = HashMap::new();
let key = ""foo"";
if !map.contains_key(key) {
let default: Vec<isize> = Vec::new();
map.insert(key, default);
}
let values: &Vec<isize> = match map.get(key) {
Some(v) => v,
None => {
panic!(""impossiburu!"");
}
};
Is there a safe way to do this with just one match?
",https://stackoverflow.com/questions/28512394/how-to-lookup-from-and-insert-into-a-hashmap-efficiently,210,82534.0,3.0,,,2015-02-14 04:23:30,2024-01-02 19:30:40,2017-11-21 20:28:56,,,hashmap;rust;lookup,Yusuke Shinyama,2103,4416558,registered,true,28512504,,CC BY-SA 3.0,,1774,1523,9,0,0,3,true,false,false,true,true,true,57,10,true,0.036,0.0025,4298,2015,2,4,Saturday,true,false,false,false,false,false,false
23975391,How to convert a String into a &'static str,"How do I convert a String into a &str? More specifically, I would like to convert it into a str with the static lifetime (&'static str).
",https://stackoverflow.com/questions/23975391/how-to-convert-a-string-into-a-static-str,209,215638.0,4.0,,,2014-05-31 23:30:45,2024-02-16 17:01:52,2018-02-09 21:52:29,,,rust,Christoph,28643,288703,registered,true,23977218,,CC BY-SA 3.0,,217,145,5,0,0,1,true,false,false,true,true,true,51,9,false,0.019,0.001,4557,2014,5,23,Saturday,true,false,false,false,false,false,false
15619320,How can I access command line parameters in Rust?,"The Rust tutorial does not explain how to take parameters from the command line. fn main() is only shown with an empty parameter list in all examples.
What is the correct way of accessing command line parameters from main?
",https://stackoverflow.com/questions/15619320/how-can-i-access-command-line-parameters-in-rust,209,81331.0,13.0,,,2013-03-25 15:59:30,2023-07-03 01:18:25,2022-02-24 23:20:29,,,command-line;rust,shutefan,7086,871423,registered,true,15621897,,CC BY-SA 4.0,,344,223,2,1,0,2,true,false,false,true,true,true,49,9,true,0.16,0.0026,4989,2013,3,15,Monday,false,false,false,false,false,false,false
57756927,Rust modules confusion when there is main.rs and lib.rs,"I have 4 files:
main.rs
mod bar;
fn main() {
let v = vec![1, 2, 3];
println!(""Hello, world!"");
}
lib.rs
pub mod foo;
pub mod bar;
foo.rs
pub fn say_foo() {
}
bar.rs
use crate::foo;
fn bar() {
foo::say_foo();
}
When I run cargo run I get an error saying:
error[E0432]: unresolved import `crate::foo`
--> src/bar.rs:1:5
|
1 | use crate::foo;
| ^^^^^^^^^^ no `foo` in the root
Could someone explain to me how to fix this? A bit more broadly: how does module lookup work when there's a main.rs and a lib.rs?
Edit: Adding mod foo to main.rs fixes the issue. But I don't understand this -- I was under the impression the lib.rs was the place that ""exposed"" all of my modules? Why do I have to declare the module in main.rs as well?
My Cargo.toml:
[package]
name = ""hello-world""
version = ""0.1.0""
authors = [""me@mgail.com>""]
edition = ""2018""
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
",https://stackoverflow.com/questions/57756927/rust-modules-confusion-when-there-is-main-rs-and-lib-rs,208,154822.0,8.0,,,2019-09-02 12:27:00,2026-08-10 14:51:19,2020-03-22 15:06:50,,,module;rust,nz_21,7849,7212809,registered,true,,,CC BY-SA 4.0,,1513,1004,18,0,0,2,false,false,false,true,true,true,55,9,false,0.052,0.0013,2637,2019,9,12,Monday,false,false,false,false,false,false,false
13322479,How to benchmark programs in Rust?,"Is it possible to benchmark programs in Rust? If yes, how? For example, how would I get execution time of program in seconds?
",https://stackoverflow.com/questions/13322479/how-to-benchmark-programs-in-rust,206,133095.0,9.0,,,2012-11-10 13:31:24,2023-01-01 11:00:31,2023-01-01 11:00:31,,,time;benchmarking;rust,php--,3347,946299,registered,true,13326510,,CC BY-SA 4.0,,133,126,0,0,0,3,true,false,false,true,true,true,34,6,true,0.068,0.0015,5124,2012,11,13,Saturday,true,false,false,false,false,false,false
28273169,How do I convert between numeric types safely and idiomatically?,"
Editor's note: This question is from a version of Rust prior to 1.0 and references some items that are not present in Rust 1.0. The answers still contain valuable information.
What's the idiomatic way to convert from (say) a usize to a u32?
For example, casting using 4294967295us as u32 works and the Rust 0.12 reference docs on type casting say
A numeric value can be cast to any numeric type. A raw pointer value can be cast to or from any integral type or raw pointer type. Any other cast is unsupported and will fail to compile.
but 4294967296us as u32 will silently overflow and give a result of 0.
I found ToPrimitive and FromPrimitive which provide nice functions like to_u32() -> Option<u32>, but they're marked as unstable:
#[unstable(feature = "core", reason = "trait is likely to be removed")]
What's the idiomatic (and safe) way to convert between numeric (and pointer) types?
The platform-dependent size of isize / usize is one reason why I'm asking this question - the original scenario was I wanted to convert from u32 to usize so I could represent a tree in a Vec<u32> (e.g. let t = Vec![0u32, 0u32, 1u32], then to get the grand-parent of node 2 would be t[t[2us] as usize]), and I wondered how it would fail if usize was less than 32 bits.
",https://stackoverflow.com/questions/28273169/how-do-i-convert-between-numeric-types-safely-and-idiomatically,204,255764.0,2.0,,,2015-02-02 07:50:33,2026-02-06 18:13:37,2020-06-20 09:12:55,,,casting;rust;numbers,Caspar,7939,775982,registered,true,28280042,,CC BY-SA 4.0,,1938,1299,16,3,0,3,true,false,false,true,true,true,64,10,true,0.008,0.0008,4310,2015,2,7,Monday,false,false,false,false,false,false,false
21011330,How do I invoke a system command and capture its output?,"Is there a way to invoke a system command, like ls or fuser in Rust? How about capturing its output?
",https://stackoverflow.com/questions/21011330/how-do-i-invoke-a-system-command-and-capture-its-output,203,116941.0,4.0,,,2014-01-09 03:55:46,2025-09-25 08:56:02,2021-01-07 15:22:38,,,rust,quux00,14844,871012,registered,true,25574952,,CC BY-SA 4.0,,134,101,2,0,0,1,true,false,false,true,true,true,56,11,true,0.034,0.0017,4699,2014,1,3,Thursday,false,false,false,false,false,false,false
36362020,"What is unwrap in Rust, and what is it used for?","I have this code that uses .unwrap():
fn main() {
let paths = std::fs::read_dir(""/home/user"").unwrap();
for path in paths {
println!(""Name: {}"", path.unwrap().path().display());
}
}
After looking at the definition of unwrap,
pub fn unwrap(self) -> T {
match self {
Ok(t) => t,
Err(e) => unwrap_failed(""called `Result::unwrap()` on an `Err` value"", e),
}
}
And the signature of read_dir
pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir>
Am I correct in understanding that unwrap returns the T type that is passed in Result?
",https://stackoverflow.com/questions/36362020/what-is-unwrap-in-rust-and-what-is-it-used-for,202,156873.0,2.0,,,2016-04-01 17:07:26,2025-11-19 15:53:04,2023-07-01 23:01:10,,,rust;error-handling,Angel Angel,22432,4140572,registered,true,36362163,,CC BY-SA 4.0,,1081,620,9,2,0,2,true,false,false,true,true,true,48,11,true,0.013,0.0013,3886,2016,4,17,Friday,false,false,false,false,false,false,false
41081240,Idiomatic callbacks in Rust,"In C/C++ I'd normally do callbacks with a plain function pointer, maybe passing a void* userdata parameter too. Something like this:
typedef void (*Callback)();
class Processor
{
public:
void setCallback(Callback c)
{
mCallback = c;
}
void processEvents()
{
//...
mCallback();
}
private:
Callback mCallback;
};
What is the idiomatic way of doing this in Rust? Specifically, what types should my setCallback() function take, and what type should mCallback be? Should it take an Fn? Maybe FnMut? Do I save it Boxed? An example would be amazing.
",https://stackoverflow.com/questions/41081240/idiomatic-callbacks-in-rust,201,76951.0,4.0,,,2016-12-10 23:02:50,2023-03-14 12:48:36,2022-09-28 17:09:49,,,callback;rust,Timmmm,100381,265521,registered,true,41081702,,CC BY-SA 4.0,,756,602,7,0,0,2,true,false,false,true,true,true,27,4,false,0.052,0.0026,3633,2016,12,23,Saturday,true,false,false,false,false,false,false
28158738,Cannot move out of borrowed content / cannot move out of behind a shared reference,"I don't understand the error cannot move out of borrowed content. I have received it many times and I have always solved it, but I've never understood why.
For example:
for line in self.xslg_file.iter() {
self.buffer.clear();
for current_char in line.into_bytes().iter() {
self.buffer.push(*current_char as char);
}
println!(""{}"", line);
}
produces the error:
error[E0507]: cannot move out of borrowed content
--> src/main.rs:31:33
|
31 | for current_char in line.into_bytes().iter() {
| ^^^^ cannot move out of borrowed content
In newer versions of Rust, the error is
error[E0507]: cannot move out of `*line` which is behind a shared reference
--> src/main.rs:31:33
|
31 | for current_char in line.into_bytes().iter() {
| ^^^^ move occurs because `*line` has type `std::string::String`, which does not implement the `Copy` trait
I solved it by cloning line:
for current_char in line.clone().into_bytes().iter() {
I don't understand the error even after reading other posts like:
- Can't borrow File from &mut self (error msg: cannot move out of borrowed content)
- Changing a node in a tree in Rust
What is the origin of this kind of error?
",https://stackoverflow.com/questions/28158738/cannot-move-out-of-borrowed-content-cannot-move-out-of-behind-a-shared-referen,201,119653.0,2.0,,,2015-01-26 21:04:41,2025-08-01 21:21:29,2019-08-27 12:42:58,,,reference;rust;move-semantics;borrow-checker,Peekmo,2913,2592187,registered,true,28159407,,CC BY-SA 4.0,,1804,1299,6,2,0,4,true,false,false,true,true,true,82,15,false,0.017,0.0017,4317,2015,1,21,Monday,false,false,false,false,false,false,false
57340308,How does Rust's 128-bit integer `i128` work on a 64-bit system?,"Rust has 128-bit integers, these are denoted with the data type i128 (and u128 for unsigned ints):
let a: i128 = 170141183460469231731687303715884105727;
How does Rust make these i128 values work on a 64-bit system; e.g. how does it do arithmetic on these?
Since, as far as I know, the value cannot fit in one register of a x86-64 CPU, does the compiler somehow use two registers for one i128 value? Or are they instead using some kind of big integer struct to represent them?
",https://stackoverflow.com/questions/57340308/how-does-rusts-128-bit-integer-i128-work-on-a-64-bit-system,200,42105.0,4.0,,,2019-08-03 16:44:06,2021-11-30 08:28:03,2021-11-30 08:28:03,,,rust;x86-64;bigint;int128;llvm-codegen,ruohola,25061,9835872,registered,true,57340670,,CC BY-SA 4.0,2021-02-18 09:47:01,575,478,5,0,0,5,true,false,false,true,true,true,67,11,true,0.095,0.0048,2667,2019,8,16,Saturday,true,false,false,false,false,false,false
24990520,How do I convert from an integer to a string?,"I am unable to compile code that converts a type from an integer to a string. I'm running an example from the Rust for Rubyists tutorial which has various type conversions such as:
"Fizz".to_str() and num.to_str() (where num is an integer).
I think the majority (if not all) of these to_str() function calls have been deprecated. What is the current way to convert an integer to a string?
The errors I'm getting are:
error: type `&'static str` does not implement any method in scope named `to_str`
error: type `int` does not implement any method in scope named `to_str`
",https://stackoverflow.com/questions/24990520/how-do-i-convert-from-an-integer-to-a-string,200,241960.0,1.0,,,2014-07-28 07:37:28,2026-03-27 11:51:24,2026-03-27 11:51:24,,,string;rust;type-conversion;integer,user3358302,2191,3358302,registered,true,24990987,,CC BY-SA 4.0,,864,586,5,1,0,4,true,false,false,true,true,true,45,10,true,0.004,0.0008,4499,2014,7,7,Monday,false,false,false,false,false,false,false
22048673,What are the identifiers denoted with a single apostrophe (')?,"I've encountered a number of types in Rust denoted with a single apostrophe:
'static
'r
'a
What is the significance of that apostrophe (')? Maybe it's a modifier of references (&)? Generic typing specific to references? I've no idea where the documentation for this is hiding.
",https://stackoverflow.com/questions/22048673/what-are-the-identifiers-denoted-with-a-single-apostrophe,198,37999.0,2.0,,,2014-02-26 17:22:40,2022-08-21 18:04:09,2022-08-21 18:04:09,,,rust,Greg Malcolm,3477,80050,registered,true,22049510,,CC BY-SA 4.0,,333,282,2,0,0,1,true,false,false,true,true,true,66,10,true,0.053,0.0052,4651,2014,2,17,Wednesday,false,false,false,false,false,false,false
21371534,"In Rust, is there a way to iterate through the values of an enum?","I come from a Java background and I might have something like enum Direction { NORTH, SOUTH, EAST, WEST} and I could do something with each of the values in turn with the enhanced for loop like:
for(Direction dir : Direction.values()) {
//do something with dir
}
I would like to do a similar thing with Rust enums.
",https://stackoverflow.com/questions/21371534/in-rust-is-there-a-way-to-iterate-through-the-values-of-an-enum,196,137458.0,11.0,,,2014-01-27 01:19:00,2024-10-02 11:48:23,2016-12-02 16:25:26,,,enums;iteration;rust,dougli1sqrd,2083,3238828,registered,true,21373995,,CC BY-SA 3.0,,413,323,2,0,0,3,true,false,false,true,true,true,65,14,true,0.08,0.0014,4681,2014,1,1,Monday,false,false,false,false,false,false,false
52045966,How to uninstall Rust that was installed via rustup?,"I installed Rust on my Ubuntu 16.04 machine through
curl https://sh.rustup.rs -sSf | sh
as can be seen on the Installation Page.
How do I now uninstall Rust?
",https://stackoverflow.com/questions/52045966/how-to-uninstall-rust-that-was-installed-via-rustup,194,185645.0,5.0,,,2018-08-27 19:38:13,2025-05-22 19:02:18,2018-08-27 20:37:17,,,rust;rustup,vvvvv,33244,5446749,registered,true,52045967,,CC BY-SA 4.0,,323,163,1,1,0,2,true,false,false,true,true,true,52,9,true,0.027,0.001,3008,2018,8,19,Monday,false,false,false,false,false,false,false
57754901,What is a "fat pointer"?,"I've read the term ""fat pointer"" in several contexts already, but I'm not sure what exactly it means and when it is used in Rust. The pointer seems to be twice as large as a normal pointer, but I don't understand why. It also seems to have something to do with trait objects.
",https://stackoverflow.com/questions/57754901/what-is-a-fat-pointer,190,43895.0,2.0,,,2019-09-02 09:56:59,2023-10-03 08:33:25,2021-01-07 15:22:15,,,pointers;rust,Lukas Kalbertodt,91680,2408867,registered,true,57754902,,CC BY-SA 4.0,,283,276,0,0,0,2,true,false,false,true,true,true,34,5,true,0.046,0.0043,2637,2019,9,9,Monday,false,false,false,false,false,false,false
26593387,How can I get the current time in milliseconds?,"How can I get the current time in milliseconds like I can in Java?
System.currentTimeMillis()
",https://stackoverflow.com/questions/26593387/how-can-i-get-the-current-time-in-milliseconds,189,200970.0,9.0,,,2014-10-27 17:34:14,2025-08-30 06:45:36,2018-01-11 01:08:46,,,rust,Incerteza,35684,2813589,registered,true,,,CC BY-SA 3.0,,166,96,1,0,0,1,false,false,false,true,true,true,47,9,true,0.045,0.0009,4408,2014,10,17,Monday,false,false,false,false,false,false,false
27582739,How do I create a HashMap literal?,"How I can create a HashMap literal in Rust? In Python I can do it so:
hashmap = {
'element0': {
'name': 'My New Element',
'childs': {
'child0': {
'name': 'Child For Element 0',
'childs': {
...
}
}
}
},
...
}
And in Go like this:
type Node struct {
name string
childs map[string]Node
}
hashmap := map[string]Node {
"element0": Node{
"My New Element",
map[string]Node {
'child0': Node{
"Child For Element 0",
map[string]Node {}
}
}
}
}
",https://stackoverflow.com/questions/27582739/how-do-i-create-a-hashmap-literal,188,87311.0,9.0,,,2014-12-20 17:45:54,2023-02-23 22:00:45,2020-12-10 21:11:57,,,hashmap;rust,Maxim Samburskiy,2071,4381158,registered,true,27582993,,CC BY-SA 4.0,,819,679,2,0,0,2,true,false,false,true,true,true,34,7,true,0.103,0.0022,4354,2014,12,17,Saturday,true,false,false,false,false,false,false
26469715,How do I write a Rust unit test that ensures that a panic has occurred?,"I have a Rust function that panics under some condition and I wish to write a test case to validate whether the function is panicking or not. I couldn't find anything except the assert! and assert_eq! macros. Is there some mechanism for testing this?
I could spawn a new task and checking whether that task panics or not. Does it make sense?
Returning a Result<T, E> is not suitable in my case.
I wish to add support for the Add trait to a Matrix type I am implementing. The ideal syntax for such addition would look like:
let m = m1 + m2 + m3;
where m1, m2, m3 are all matrices. Hence, the result type of add should be Matrix. Something like the following would be too cryptic:
let m = ((m1 + m2).unwrap() + m3).unwrap()
At the same time, the add() function needs to validate that the two matrices being added have same dimension. Thus, add() needs to panic if the dimensions don't match. The available option is panic!().
",https://stackoverflow.com/questions/26469715/how-do-i-write-a-rust-unit-test-that-ensures-that-a-panic-has-occurred,187,74760.0,8.0,,,2014-10-20 15:46:32,2023-06-25 15:25:10,2017-03-07 14:03:56,,,unit-testing;rust,Shailesh Kumar,7067,208890,registered,true,26470361,,CC BY-SA 3.0,,1221,945,16,0,0,2,true,false,false,true,true,true,71,15,true,0.107,0.0025,4415,2014,10,15,Monday,false,false,false,false,false,false,false
29530011,Creating a vector of zeros for a specific size,"I'd like to initialize a vector of zeros with a specific size that is determined at runtime.
In C, it would be like:
int main(void)
{
uint size = get_uchar();
int A[size][size];
memset(A, 0, size*size*sizeof(int));
}
Here's the helper function that I tried writing in Rust, but I think the slicing syntax 0..size is offending the compiler. Besides, it looks more verbose than the C version. Is there a more idiomatic way to do this?
fn zeros(size: u32) -> Vec<i32> {
let mut zero_vec: Vec<i32> = Vec::with_capacity(size);
for i in 0..size {
zero_vec.push(0);
}
return zero_vec;
}
I swear that the old docs used to explain a from_elem() method here and none of the permutations of the [0 ; size] notation seem to work
I'd like to stick this into a substring search algorithm ultimately:
pub fn kmp(text: &str, pattern: &str) -> i64 {
let mut shifts = zeros(pattern.len()+1);
}
",https://stackoverflow.com/questions/29530011/creating-a-vector-of-zeros-for-a-specific-size,187,190512.0,4.0,,,2015-04-09 04:50:34,2018-03-13 16:05:05,2015-04-10 02:24:35,,,rust,elleciel,2667,1744274,registered,true,29530932,,CC BY-SA 3.0,,1337,952,6,2,0,1,true,false,false,true,true,true,46,9,false,0.021,0.001,4244,2015,4,4,Thursday,false,false,false,false,false,false,false
36390665,How do you pass a Rust function as a parameter?,"Can I pass a function as a parameter? If not, what is a good alternative?
I tried some different syntaxes but I have not found the right one. I know I can do this:
fn example() {
let fun: fn(value: i32) -> i32;
fun = fun_test;
fun(5i32);
}
fn fun_test(value: i32) -> i32 {
println!(""{}"", value);
value
}
but that's not passing the function as a parameter to another function:
fn fun_test(value: i32, (some_function_prototype)) -> i32 {
println!(""{}"", value);
value
}
",https://stackoverflow.com/questions/36390665/how-do-you-pass-a-rust-function-as-a-parameter,186,152905.0,2.0,,,2016-04-03 20:18:16,2019-11-07 19:37:34,2019-11-07 19:34:31,,,rust,Angel Angel,22432,4140572,registered,true,36390748,,CC BY-SA 4.0,,580,511,2,0,0,1,true,false,false,true,true,true,47,10,true,0.013,0.0012,3884,2016,4,20,Sunday,true,false,false,false,false,false,false
39204908,How to check release / debug builds using cfg in Rust?,"With the C pre-processor it's common to do,
#if defined(NDEBUG)
// release build
#endif
#if defined(DEBUG)
// debug build
#endif
Cargo's rough equivalents are:
cargo build --release for release.
cargo build for debug.
How would Rust's #[cfg(...)] attribute or cfg!(...) macro be used to do something similar?
I understand that Rust's pre-processor doesn't work like C's. I checked the documentation and this page lists some attributes. (assuming this list is comprehensive)
debug_assertions could be checked, but it may be misleading when used to check for the more general debugging case.
I'm not sure if this question should be related to Cargo or not.
",https://stackoverflow.com/questions/39204908/how-to-check-release-debug-builds-using-cfg-in-rust,184,102050.0,1.0,,,2016-08-29 11:14:24,2024-08-25 14:15:58,2024-08-25 14:15:58,,,debugging;rust;rust-cargo;preprocessor;conditional-compilation,ideasman42,49986,432509,registered,true,39205417,,CC BY-SA 4.0,2023-08-18 20:05:18,937,667,6,1,0,5,true,false,false,true,true,true,54,11,true,0.01,0.0018,3736,2016,8,11,Monday,false,false,false,false,false,false,false
30558246,"How do I find the index of an element in an array, vector or slice?","I need to find an index of an element in a vector of strings. This is what I got so far:
fn main() {
let test: Vec<String> = vec![
""one"".to_string(),
""two"".to_string(),
""three"".to_string(),
""four"".to_string(),
];
let index: i32 = test
.iter()
.enumerate()
.find(|&r| r.1.to_string() == ""two"".to_string())
.unwrap()
.0;
}
It produces an error:
error[E0308]: mismatched types
--> src/main.rs:9:22
|
9 | let index: i32 = test
| ______________________^
10 | | .iter()
11 | | .enumerate()
12 | | .find(|&r| r.1.to_string() == ""two"".to_string())
13 | | .unwrap()
14 | | .0;
| |__________^ expected i32, found usize
I assume that's because enumerate() returns a tuple of (usize, _) (correct me if I'm wrong), but how do I convert usize to i32 here? If there is a better approach, I'm open to suggestions.
",https://stackoverflow.com/questions/30558246/how-do-i-find-the-index-of-an-element-in-an-array-vector-or-slice,182,220747.0,2.0,,,2015-05-31 13:54:16,2024-05-07 22:53:09,2024-05-07 22:53:09,,,rust;iterator,Caballero,12243,717839,registered,true,30558370,,CC BY-SA 4.0,,1125,965,6,0,0,2,true,false,false,true,true,true,67,15,true,0.009,0.0008,4192,2015,5,13,Sunday,true,false,false,false,false,false,false
30414424,How can I update a value in a mutable HashMap?,"Here is what I am trying to do:
use std::collections::HashMap;
fn main() {
let mut my_map = HashMap::new();
my_map.insert(""a"", 1);
my_map.insert(""b"", 3);
my_map[""a""] += 10;
// I expect my_map becomes {""b"": 3, ""a"": 11}
}
But this raises an error:
Rust 2015
error[E0594]: cannot assign to immutable indexed content
--> src/main.rs:8:5
|
8 | my_map[""a""] += 10;
| ^^^^^^^^^^^^^^^^^ cannot borrow as mutable
|
= help: trait `IndexMut` is required to modify indexed content, but it is not implemented for `std::collections::HashMap<&str, i32>`
Rust 2018
error[E0594]: cannot assign to data in a `&` reference
--> src/main.rs:8:5
|
8 | my_map[""a""] += 10;
| ^^^^^^^^^^^^^^^^^ cannot assign
I don't really understand what that means, since I made the HashMap mutable. When I try to update an element in a vector, I get the expected result:
let mut my_vec = vec![1, 2, 3];
my_vec[0] += 10;
println! {""{:?}"", my_vec};
// [11, 2, 3]
What is different about HashMap that I am getting the above error? Is there a way to update a value?
",https://stackoverflow.com/questions/30414424/how-can-i-update-a-value-in-a-mutable-hashmap,182,132624.0,6.0,,,2015-05-23 15:26:29,2024-08-14 13:06:41,2019-03-20 18:31:25,,,hashmap;rust,Akavall,87022,1078084,registered,true,30414450,,CC BY-SA 4.0,,1397,1108,7,0,0,2,true,false,false,true,true,true,46,10,true,0.045,0.0014,4200,2015,5,15,Saturday,true,false,false,false,false,false,false
44303915,No default toolchain configured after installing rustup,"I installed Rust using rustup, but when I try to enter a Rust command like cargo or rustc in my console, the following error appears:
error: no default toolchain configured
Is this a known issue?
",https://stackoverflow.com/questions/44303915/no-default-toolchain-configured-after-installing-rustup,172,93025.0,4.0,,,2017-06-01 09:38:01,2022-09-24 16:08:44,2022-09-24 16:08:44,,,rust;rustup,Darkaird,2960,7546477,registered,true,46864309,,CC BY-SA 4.0,,391,197,3,1,0,2,true,false,false,true,true,true,55,7,false,0.043,0.0018,3460,2017,6,9,Thursday,false,false,false,false,false,false,false
26836488,How to sort a vector in Rust?,"What is the currently recommended method for sorting values in a vector?
",https://stackoverflow.com/questions/26836488/how-to-sort-a-vector-in-rust,172,124020.0,3.0,,,2014-11-10 03:54:56,2022-12-18 15:52:42,2022-12-18 15:52:42,,,sorting;rust,Maxim Sloyko,16046,141906,registered,true,26836633,,CC BY-SA 4.0,,80,73,0,0,0,2,true,false,false,true,true,true,29,7,true,0.024,0.0014,4394,2014,11,3,Monday,false,false,false,false,false,false,false
24542115,How to index a String in Rust,"I am attempting to index a string in Rust, but the compiler throws an error. My code (Project Euler problem 4, playground):
fn is_palindrome(num: u64) -> bool {
let num_string = num.to_string();
let num_length = num_string.len();
for i in 0 .. num_length / 2 {
if num_string[i] != num_string[(num_length - 1) - i] {
return false;
}
}
true
}
The error:
error[E0277]: the trait bound `std::string::String: std::ops::Index<usize>` is not satisfied
--> <anon>:7:12
|
7 | if num_string[i] != num_string[(num_length - 1) - i] {
| ^^^^^^^^^^^^^
|
= note: the type `std::string::String` cannot be indexed by `usize`
Is there a reason why String can not be indexed? How can I access the data then?
",https://stackoverflow.com/questions/24542115/how-to-index-a-string-in-rust,170,196968.0,10.0,,,2014-07-02 22:29:10,2025-11-14 10:54:09,2022-04-11 01:25:42,,,string;indexing;rust,Sam Myers,2502,3799502,registered,true,24542502,,CC BY-SA 4.0,,1044,791,3,1,0,3,true,false,false,true,true,true,29,7,false,0.051,0.0009,4525,2014,7,22,Wednesday,false,false,false,false,false,false,false
39785597,How do I get a slice of a Vec<T> in Rust?,"I can not find within the documentation of Vec<T> how to retrieve a slice from a specified range.
Is there something like this in the standard library:
let a = vec![1, 2, 3, 4];
let suba = a.subvector(0, 2); // Contains [1, 2];
",https://stackoverflow.com/questions/39785597/how-do-i-get-a-slice-of-a-vect-in-rust,170,208498.0,2.0,,,2016-09-30 07:03:51,2020-05-22 20:38:20,2018-03-16 14:13:43,,,vector;rust,yageek,4530,856142,registered,true,39785759,,CC BY-SA 3.0,,289,238,2,0,0,2,true,false,false,true,true,true,47,11,true,0.01,0.0008,3704,2016,9,7,Friday,false,false,false,false,false,false,false
26611664,What is the r#""# operator in Rust?,"I saw the operator r#"""" in Rust but I can't find what it does. It came in handy for creating JSON:
let var1 = ""test1"";
let json = r#""{""type"": ""type1"", ""type2"": var1}""#;
println!(""{}"", json) // => {""type2"": ""type1"", ""type2"": var1}
What's the name of the operator r#""""? How do I make var1 evaluate?
",https://stackoverflow.com/questions/26611664/what-is-the-r-operator-in-rust,168,94352.0,3.0,,,2014-10-28 15:04:35,2022-09-04 09:39:08,2021-01-20 15:00:14,,,string;rust;syntax;string-literals,Incerteza,35684,2813589,registered,true,26611854,,CC BY-SA 4.0,,380,303,4,0,0,4,true,false,false,true,true,true,45,7,true,0.032,0.0018,4407,2014,10,15,Tuesday,false,false,false,false,false,false,false
22118221,How do you iterate over a string by character,"I have a string and I need to scan for every occurrence of ""foo"" and read all the text following it until a second "". Since Rust does not have a contains function for strings, I need to iterate by characters scanning for it. How would I do this?
Edit: Rust's &str has a contains() and find() method.
",https://stackoverflow.com/questions/22118221/how-do-you-iterate-over-a-string-by-character,168,215970.0,3.0,,,2014-03-01 18:08:04,2022-09-26 09:59:54,2016-10-20 20:19:02,,,string;iterator;rust,user2171584,1703,2171584,registered,true,,,CC BY-SA 3.0,,596,305,5,2,0,3,false,false,false,true,true,true,45,9,false,0.014,0.0008,4648,2014,3,18,Saturday,true,false,false,false,false,false,false
30320083,How to print a Vec?,"I tried the following code:
fn main() {
let v2 = vec![1; 10];
println!(""{}"", v2);
}
But the compiler complains:
error[E0277]: `std::vec::Vec<{integer}>` doesn't implement `std::fmt::Display`
--> src/main.rs:3:20
|
3 | println!(""{}"", v2);
| ^^ `std::vec::Vec<{integer}>` cannot be formatted with the default formatter
|
= help: the trait `std::fmt::Display` is not implemented for `std::vec::Vec<{integer}>`
= note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
= note: required by `std::fmt::Display::fmt`
Does anyone implement this trait for Vec<T>?
",https://stackoverflow.com/questions/30320083/how-to-print-a-vec,167,155501.0,8.0,,,2015-05-19 08:09:52,2024-04-28 20:29:08,2019-04-02 20:22:01,,,rust;println,highfly22,1891,1846758,registered,true,30320140,,CC BY-SA 4.0,,788,667,3,0,0,2,true,false,false,true,true,true,19,5,true,0.051,0.0011,4204,2015,5,8,Tuesday,false,false,false,false,false,false,false
26076005,How can I list files of a directory in Rust?,"How can I list all the files of a directory in Rust? I am looking for the equivalent of the following Python code.
files = os.listdir('./')
",https://stackoverflow.com/questions/26076005/how-can-i-list-files-of-a-directory-in-rust,167,182016.0,4.0,,,2014-09-27 15:04:07,2025-04-15 18:53:32,2015-08-10 09:17:50,,,rust,Graham Lee,3170,3551338,registered,true,,,CC BY-SA 3.0,,174,143,1,0,0,1,false,false,false,true,true,true,44,10,true,0.022,0.0009,4438,2014,9,15,Saturday,true,false,false,false,false,false,false
32677420,What does Rust have instead of a garbage collector?,"I understand Rust doesn't have a garbage collector and am wondering how memory is freed up when a binding goes out of scope.
So in this example, I understand that Rust reclaims the memory allocated to a when it goes out of scope.
{
let a = 4
}
The problem I am having with this, is firstly how this happens, and secondly isn't this a sort of garbage collection? How does it differ from typical garbage collection?
",https://stackoverflow.com/questions/32677420/what-does-rust-have-instead-of-a-garbage-collector,167,109072.0,5.0,,,2015-09-20 08:37:31,2026-07-29 22:17:14,2024-07-08 07:19:12,,,memory;rust;memory-management;garbage-collection,rix,10796,1004781,registered,true,32677591,,CC BY-SA 4.0,,487,420,2,0,0,4,true,false,false,true,true,true,51,9,true,0.046,0.0015,4080,2015,9,8,Sunday,true,false,false,false,false,false,false
32384594,How to check whether a path exists?,"The choice seems to be between std::fs::PathExt and std::fs::metadata, but the latter is suggested for the time being as it is more stable. Below is the code I have been working with as it is based off the docs:
use std::fs;
pub fn path_exists(path: &str) -> bool {
let metadata = try!(fs::metadata(path));
assert!(metadata.is_file());
}
However, for some odd reason let metadata = try!(fs::metadata(path)) still requires the function to return a Result<T,E> even though I simply want to return a boolean as shown from assert!(metadata.is_file()).
Even though there will probably be a lot of changes to this soon enough, how would I bypass the try!() issue?
Below is the relevant compiler error:
error[E0308]: mismatched types
--> src/main.rs:4:20
|
4 | let metadata = try!(fs::metadata(path));
| ^^^^^^^^^^^^^^^^^^^^^^^^ expected bool, found enum `std::result::Result`
|
= note: expected type `bool`
found type `std::result::Result<_, _>`
= note: this error originates in a macro outside of the current crate
error[E0308]: mismatched types
--> src/main.rs:3:40
|
3 | pub fn path_exists(path: &str) -> bool {
| ________________________________________^
4 | | let metadata = try!(fs::metadata(path));
5 | | assert!(metadata.is_file());
6 | | }
| |_^ expected (), found bool
|
= note: expected type `()`
found type `bool`
",https://stackoverflow.com/questions/32384594/how-to-check-whether-a-path-exists,164,142201.0,3.0,,,2015-09-03 20:09:57,2024-10-24 13:37:24,2017-06-26 00:44:32,,,rust,Juxhin,5730,3364618,registered,true,32384768,,CC BY-SA 3.0,,1645,1452,8,0,0,1,true,false,false,true,true,true,35,7,true,0.021,0.0012,4097,2015,9,20,Thursday,false,false,false,false,false,false,false
50251487,What are non-lexical lifetimes?,"Rust has an RFC related to non-lexical lifetimes which has been approved to be implemented in the language for a long time. Recently, Rust's support of this feature has improved a lot and is considered complete.
My question is: what exactly is a non-lexical lifetime?
",https://stackoverflow.com/questions/50251487/what-are-non-lexical-lifetimes,164,31074.0,1.0,,,2018-05-09 10:45:06,2021-04-18 03:25:17,2021-04-18 03:25:17,,,rust;terminology;lifetime;lifetime-scoping,Stargateur,27266,7076153,registered,true,,,CC BY-SA 4.0,,545,269,0,3,0,4,false,false,false,true,true,true,31,4,true,0.032,0.0053,3118,2018,5,10,Wednesday,false,false,false,false,false,false,false
31233938,Converting from Option<String> to Option<&str>,"Very often I have obtained an Option<String> from a calculation, and I would like to either use this value or a default hardcoded value.
This would be trivial with an integer:
let opt: Option<i32> = Some(3);
let value = opt.unwrap_or(0); // 0 being the default
But with a String and a &str, the compiler complains about mismatched types:
let opt: Option<String> = Some("some value".to_owned());
let value = opt.unwrap_or("default string");
The exact error here is:
error[E0308]: mismatched types
--> src/main.rs:4:31
|
4 | let value = opt.unwrap_or("default string");
| ^^^^^^^^^^^^^^^^
| |
| expected struct `std::string::String`, found reference
| help: try using a conversion method: `"default string".to_string()`
|
= note: expected type `std::string::String`
found type `&'static str`
One option is to convert the string slice into an owned String, as suggested by rustc:
let value = opt.unwrap_or("default string".to_string());
But this causes an allocation, which is undesirable when I want to immediately convert the result back to a string slice, as in this call to Regex::new():
let rx: Regex = Regex::new(&opt.unwrap_or("default string".to_string()));
I would rather convert the Option<String> to an Option<&str> to avoid this allocation.
What is the idiomatic way to write this?
",https://stackoverflow.com/questions/31233938/converting-from-optionstring-to-optionstr,162,61500.0,5.0,,,2015-07-05 19:02:37,2023-12-06 01:35:14,2022-09-08 00:33:38,,,rust,George Hilliard,16163,1830736,registered,true,53485793,,CC BY-SA 4.0,,1850,1557,11,0,0,1,true,false,false,true,true,true,62,5,false,0.081,0.0026,4157,2015,7,19,Sunday,true,false,false,false,false,false,false
51208703,How to raise a number to a power?,"I was trying to raise an integer to a power using the caret operator (^), but I am getting surprising results, e.g.:
assert_eq!(2^10, 8);
How can I perform exponentiation in Rust?
",https://stackoverflow.com/questions/51208703/how-to-raise-a-number-to-a-power,160,195697.0,6.0,,,2018-07-06 10:46:41,2023-06-05 14:58:13,2021-02-28 15:03:01,,,rust;operators;exponentiation,Matthias Braun,35032,775954,registered,true,51208704,,CC BY-SA 4.0,,232,181,2,0,0,3,true,false,false,true,true,true,33,8,true,0.031,0.0008,3060,2018,7,10,Friday,false,false,false,false,false,false,false
25428920,How to get a slice as an array in Rust?,"I have an array of an unknown size, and I would like to get a slice of that array and convert it to a statically sized array:
fn pop(barry: &[u8]) -> [u8; 3] {
barry[0..3] // expected array `[u8; 3]`, found slice `[u8]`
}
How would I do this?
",https://stackoverflow.com/questions/25428920/how-to-get-a-slice-as-an-array-in-rust,159,150043.0,9.0,,,2014-08-21 14:25:38,2025-06-23 19:17:52,2020-08-30 16:49:13,,,arrays;rust,Jeroen,17304,2558778,registered,true,50080940,,CC BY-SA 4.0,,293,255,1,0,0,2,true,false,false,true,true,true,39,10,true,0.06,0.0011,4475,2014,8,14,Thursday,false,false,false,false,false,false,false
25170091,How to make a reverse ordered for loop?,"
Editor's note: This question was asked before Rust 1.0 was released and the .. ""range"" operator was introduced. The question's code no longer represents the current style, but some answers below uses code that will work in Rust 1.0 and onwards.
I was playing on the Rust by Example website and wanted to print out fizzbuzz in reverse. Here is what I tried:
fn main() {
// `n` will take the values: 1, 2, ..., 100 in each iteration
for n in std::iter::range_step(100u, 0, -1) {
if n % 15 == 0 {
println!(""fizzbuzz"");
} else if n % 3 == 0 {
println!(""fizz"");
} else if n % 5 == 0 {
println!(""buzz"");
} else {
println!(""{}"", n);
}
}
}
There were no compilation errors, but it did not print out anything. How do I iterate from 100 to 1?
",https://stackoverflow.com/questions/25170091/how-to-make-a-reverse-ordered-for-loop,158,154589.0,2.0,,,2014-08-06 21:00:37,2022-03-06 02:57:21,2022-03-06 02:57:21,,,for-loop;rust,Tybalt,1771,1452670,registered,true,25170192,,CC BY-SA 4.0,,1003,841,2,1,0,2,true,false,false,true,true,true,39,8,true,0.013,0.001,4490,2014,8,21,Wednesday,false,false,false,false,false,false,false
28587698,What's the difference between placing "mut" before a variable name and after the ":"?,"Here are two function signatures I saw in the Rust documentation:
fn modify_foo(mut foo: Box<i32>) { *foo += 1; *foo }
fn modify_foo(foo: &mut i32) { *foo += 1; *foo }
Why the different placement of mut?
It seems that the first function could also be declared as
fn modify_foo(foo: mut Box<i32>) { /* ... */ }
",https://stackoverflow.com/questions/28587698/whats-the-difference-between-placing-mut-before-a-variable-name-and-after-the,157,29174.0,4.0,,,2015-02-18 15:46:54,2022-12-12 05:41:24,2019-03-18 11:01:36,,,variables;syntax;reference;rust;mutable,Jimmy Lu,5170,690061,registered,true,28587902,,CC BY-SA 4.0,,414,332,3,0,0,5,true,false,false,true,true,true,109,14,true,0.137,0.0054,4294,2015,2,15,Wednesday,false,false,false,false,false,false,false
23430735,How to convert Vec<char> to a string,"How to convert Vec<char> to string form so that I can print it?
",https://stackoverflow.com/questions/23430735/how-to-convert-vecchar-to-a-string,156,114442.0,3.0,,,2014-05-02 14:37:01,2026-09-11 12:53:33,2017-07-11 10:24:53,,,string;rust,user3596561,1575,3596561,registered,true,,,CC BY-SA 3.0,,90,70,1,0,0,2,false,false,false,true,true,true,42,7,false,0.026,0.0014,4586,2014,5,14,Friday,false,false,false,false,false,false,false
30811107,How do I get the first character out of a string?,"I want to get the first character of a std::str. The method char_at() is currently unstable, as is String::slice_chars.
I have come up with the following, but it seems excessive to get a single character and not use the rest of the vector:
let text = "hello world!";
let char_vec: Vec<char> = text.chars().collect();
let ch = char_vec[0];
",https://stackoverflow.com/questions/30811107/how-do-i-get-the-first-character-out-of-a-string,156,162375.0,7.0,,,2015-06-12 19:49:13,2023-01-02 12:33:35,2020-06-25 00:09:20,,,string;rust,XAMPPRocky,3739,4465497,registered,true,30811312,,CC BY-SA 4.0,,726,356,4,3,0,2,true,false,false,true,true,true,49,11,true,0.043,0.001,4180,2015,6,19,Friday,false,false,false,false,false,false,false
32304595,What's the difference between self and Self?,"I haven't come across Self in the documentation, only in the source code. The documentation only uses self.
",https://stackoverflow.com/questions/32304595/whats-the-difference-between-self-and-self,155,53739.0,4.0,,,2015-08-31 05:39:24,2024-09-06 08:36:29,2018-02-11 13:39:12,,,rust,user266003,,,does_not_exist,true,32306132,,CC BY-SA 3.0,,142,109,2,0,0,1,true,false,false,true,false,true,48,7,true,0.074,0.0029,4100,2015,8,5,Monday,false,false,false,false,false,false,false
31210357,Is there a modulus (not remainder) function / operation?,"In Rust (like most programming languages), the % operator performs the remainder operation, not the modulus operation. These operations have different results for negative numbers:
-21 modulus 4 => 3
-21 remainder 4 => -1
println!(""{}"", -21 % 4); // -1
However, I want the modulus.
I found a workaround ((a % b) + b) % b, but I don't want to reinvent the wheel if there's already a function for that!
",https://stackoverflow.com/questions/31210357/is-there-a-modulus-not-remainder-function-operation,155,101628.0,4.0,,,2015-07-03 15:39:32,2020-08-25 23:27:38,2018-11-21 02:37:29,,,rust;modulo,M. Brandt,3816,2979958,registered,true,,,CC BY-SA 4.0,,642,415,4,1,0,2,false,false,false,true,true,true,56,9,true,0.039,0.0015,4159,2015,7,15,Friday,false,false,false,false,false,false,false
38406793,Why is capitalizing the first letter of a string so convoluted in Rust?,"I'd like to capitalize the first letter of a &str. It's a simple problem and I hope for a simple solution. Intuition tells me to do something like this:
let mut s = ""foobar"";
s[0] = s[0].to_uppercase();
But &strs can't be indexed like this. The only way I've been able to do it seems overly convoluted. I convert the &str to an iterator, convert the iterator to a vector, upper case the first item in the vector, which creates an iterator, which I index into, creating an Option, which I unwrap to give me the upper-cased first letter. Then I convert the vector into an iterator, which I convert into a String, which I convert to a &str.
let s1 = ""foobar"";
let mut v: Vec<char> = s1.chars().collect();
v[0] = v[0].to_uppercase().nth(0).unwrap();
let s2: String = v.into_iter().collect();
let s3 = &s2;
Is there an easier way than this, and if so, what? If not, why is Rust designed this way?
",https://stackoverflow.com/questions/38406793/why-is-capitalizing-the-first-letter-of-a-string-so-convoluted-in-rust,154,52678.0,11.0,,,2016-07-16 01:07:22,2023-10-25 18:55:33,2017-05-23 12:02:05,,,string;rust;uppercase,marshallm,1825,1602188,registered,true,38406885,,CC BY-SA 3.0,,1202,942,8,1,0,3,true,false,false,true,true,true,71,13,true,0.209,0.0029,3780,2016,7,1,Saturday,true,false,false,false,false,false,false
29592256,What's the difference between `usize` and `u32`?,"The documentation says usize is
Operations and constants for pointer-sized unsigned integers.
In most cases, I can replace usize with u32 and nothing happens. So I don't understand why we need two types which are so alike.
",https://stackoverflow.com/questions/29592256/whats-the-difference-between-usize-and-u32,154,77684.0,1.0,,,2015-04-12 17:20:15,2023-07-19 16:16:05,,,,rust,Vayn,2757,419206,registered,true,29592369,,CC BY-SA 3.0,,314,229,3,0,0,1,true,false,false,true,true,false,52,7,true,0.013,0.002,4241,2015,4,17,Sunday,true,false,false,false,false,false,false
22596920,Split a module across several files,"I want to have a module with multiple structs in it, each in its own file. Using a Math module as an example:
Math/
Vector.rs
Matrix.rs
Complex.rs
I want each struct to be in the same module, which I would use from my main file, like so:
use Math::Vector;
fn main() {
// ...
}
However Rust's module system (which is a bit confusing to begin with) does not provide an obvious way to do this. It seems to only allow you to have your entire module in one file. Is this un-rustic? If not, how do I do this?
",https://stackoverflow.com/questions/22596920/split-a-module-across-several-files,153,81996.0,8.0,,,2014-03-23 20:53:07,2024-06-06 00:32:38,2019-08-25 14:44:24,,,module;rust,starscape,3063,1938727,registered,true,22597760,,CC BY-SA 4.0,,648,518,3,0,0,2,true,false,false,true,true,true,35,6,false,0.098,0.0019,4626,2014,3,20,Sunday,true,false,false,false,false,false,false
37877381,What is the difference between immutable and const variables in Rust?,"I learned that if a variable is not explicitly declared mutable using mut, it becomes immutable (it cannot be changed after declaration). Then why do we have the const keyword in Rust? Aren't they the same? If not, how do they differ?
",https://stackoverflow.com/questions/37877381/what-is-the-difference-between-immutable-and-const-variables-in-rust,152,34301.0,8.0,,,2016-06-17 09:03:07,2024-06-02 10:30:33,2022-09-08 00:45:03,,,rust;constants;immutability,7_R3X,4492,5460216,registered,true,37881340,,CC BY-SA 4.0,,268,235,2,0,0,3,true,false,false,true,true,true,69,11,true,0.233,0.0044,3809,2016,6,9,Friday,false,false,false,false,false,false,false
25569865,How to escape curly braces in a format string in Rust,"I want to write this
write!(f, ""{ hash:{}, subject: {} }"", self.hash, self.subject)
But since curly braces have special meaning for formatting it's clear that I can't place the outer curly braces like that without escaping. So I tried to escape them.
write!(f, ""\{ hash:{}, subject: {} \}"", self.hash, self.subject)
Rust doesn't like that either. Then I read this:
The literal characters {, }, or # may be included in a string by preceding them with the \ character. Since \ is already an escape character in Rust strings, a string literal using this escape will look like ""\{"".
So I tried
write!(f, ""\\{ hash:{}, subject: {} \\}"", self.hash, self.subject)
But that's also not working. :-(
",https://stackoverflow.com/questions/25569865/how-to-escape-curly-braces-in-a-format-string-in-rust,151,58930.0,1.0,,,2014-08-29 13:59:02,2018-10-08 12:41:34,,,,string-formatting;rust,Christoph,28643,288703,registered,true,25570140,,CC BY-SA 3.0,,844,705,3,0,0,2,true,false,false,true,true,false,53,11,false,0.017,0.0026,4467,2014,8,13,Friday,false,false,false,false,false,false,false
37890405,Is there a way to simplify converting an Option into a Result without a macro?,"I have something like this (the real function is Ini::Section::get from rust-ini):
impl Foo {
pub fn get<K>(&'a mut self, key: &K) -> Option<&'a str>
where
K: Hash + Eq,
{
// ...
}
}
I have to call it several times:
fn new() -> Result<Boo, String> {
let item1 = match section.get("item1") {
None => return Result::Err("no item1".to_string()),
Some(v) => v,
};
let item2 = match section.get("item2") {
None => return Result::Err("no item2".to_string()),
Some(v) => v,
};
}
To remove code bloat, I can write a macro like this:
macro_rules! try_ini_get {
($e:expr) => {
match $e {
Some(s) => Ok(s),
None => Err("no ini item".to_string()),
}
}
}
Is there any way to remove the code duplication without this macro implementation?
",https://stackoverflow.com/questions/37890405/is-there-a-way-to-simplify-converting-an-option-into-a-result-without-a-macro,150,123721.0,2.0,,,2016-06-17 21:09:54,2022-09-30 17:05:43,2022-09-30 17:05:43,,,rust,fghj,9524,1034749,registered,true,37890739,,CC BY-SA 4.0,,1144,963,4,1,0,1,true,false,false,true,true,true,78,15,true,0.016,0.0012,3809,2016,6,21,Friday,false,false,false,false,false,false,false
28991050,How to iterate a Vec<T> with the indexed position?,"I need to iterate a Vec including the position for each iterated element. I'm sure this is already in the API but I cannot see it.
I need something like this:
fn main() {
let v = vec![1; 10];
for (pos, e) in v.iter() {
// do something here
}
}
",https://stackoverflow.com/questions/28991050/how-to-iterate-a-vect-with-the-indexed-position,150,88701.0,2.0,,,2015-03-11 15:40:27,2026-01-12 12:46:43,2019-11-06 19:14:58,,,for-loop;rust;iterator,bitloner,2171,4651500,registered,true,28991157,,CC BY-SA 4.0,,319,268,2,0,0,3,true,false,false,true,true,true,56,9,true,0.023,0.0017,4273,2015,3,15,Wednesday,false,false,false,false,false,false,false
37586216,Step by step interactive debugger for Rust?,"How can I debug Rust application step by step interactively like I'm able to do with ""pry"" in Ruby?
I want to be able to see and preferably change the variables in real time when I reach a break point. Is there any production ready finished project?
",https://stackoverflow.com/questions/37586216/step-by-step-interactive-debugger-for-rust,150,92786.0,6.0,,,2016-06-02 08:13:41,2025-01-16 22:26:00,2016-06-02 09:42:40,2025-01-16 23:51:56,Not suitable for this site,debugging;rust,user6324692,,,does_not_exist,true,,,,,283,252,0,0,0,2,false,true,false,true,false,true,43,7,true,0.065,0.0016,3824,2016,6,8,Thursday,false,false,false,false,false,false,false
28800121,What do I have to do to solve a "use of moved value" error?,"I'm trying to compute the 10,001st prime in Rust (Project Euler 7), and as a part of this, my method to check whether or not an integer is prime references a vector:
fn main() {
let mut count: u32 = 1;
let mut num: u64 = 1;
let mut primes: Vec<u64> = Vec::new();
primes.push(2);
while count < 10001 {
num += 2;
if vectorIsPrime(num, primes) {
count += 1;
primes.push(num);
}
}
}
fn vectorIsPrime(num: u64, p: Vec<u64>) -> bool {
for i in p {
if num > i && num % i != 0 {
return false;
}
}
true
}
When I try to reference the vector, I get the following error:
error[E0382]: use of moved value: `primes`
--> src/main.rs:9:31
|
9 | if vectorIsPrime(num, primes) {
| ^^^^^^ value moved here, in previous iteration of loop
|
= note: move occurs because `primes` has type `std::vec::Vec<u64>`, which does not implement the `Copy` trait
What do I have to do to primes in order to be able to access it within the vectorIsPrime function?
",https://stackoverflow.com/questions/28800121/what-do-i-have-to-do-to-solve-a-use-of-moved-value-error,148,164033.0,3.0,,,2015-03-01 22:43:48,2019-04-07 15:44:03,2019-04-07 15:41:51,,,rust,mjkaufer,4274,2009336,registered,true,28800493,,CC BY-SA 4.0,,1269,1135,4,0,0,1,true,false,false,true,true,true,69,14,true,0.018,0.0009,4283,2015,3,22,Sunday,true,false,false,false,false,false,false
41034635,"How do I convert between String, &str, Vec<u8> and &[u8]?","A new Rustacean like me struggles with juggling these types: String, &str, Vec<u8>, &[u8].
In time, I hope to have an epiphany and suddenly get why some library calls use one or the other. Until then, I need help to map out each idiomatic transition.
Given these types:
let st: &str = ...;
let s: String = ...;
let u: &[u8] = ...;
let v: Vec<u8> = ...;
I think I have figured these out, but are they idiomatic?
&str -> String String::from(st)
&str -> &[u8] st.as_bytes()
String -> &str s.as_str()
&[u8] -> &str str::from_utf8(u)
Vec<u8> -> String String::from_utf8(v)
Ultimately I want a complete table of transitions for these types:
&str -> String
&str -> &[u8]
&str -> Vec<u8>
String -> &str
String -> &[u8]
String -> Vec<u8>
&[u8] -> &str
&[u8] -> String
&[u8] -> Vec<u8>
Vec<u8> -> &str
Vec<u8> -> String
Vec<u8> -> &[u8]
",https://stackoverflow.com/questions/41034635/how-do-i-convert-between-string-str-vecu8-and-u8,148,67211.0,1.0,,,2016-12-08 08:09:01,2021-04-08 18:43:29,2021-04-08 18:43:29,,,string;rust;type-conversion,Martin Algesten,13820,437679,registered,true,41034751,,CC BY-SA 4.0,,1310,1073,7,0,0,3,true,false,false,true,true,true,71,10,true,0.015,0.0022,3635,2016,12,8,Thursday,false,false,false,false,false,false,false
32552593,"Is it possible for one struct to extend an existing struct, keeping all the fields?","Using rust 1.2.0
Problem
I'm still in the process of learning Rust (coming from a Javascript background) and am trying to figure out if it is possible for one struct StructB to extend an existing struct StructA such that StructB has all the fields defined on StructA.
In Javascript (ES6 syntax) I could essentially do something like this...
class Person {
constructor (gender, age) {
this.gender = gender;
this.age = age;
}
}
class Child extends Person {
constructor (name, gender, age) {
super(gender, age);
this.name = name;
}
}
Constraints
StructA is from an external cargo package that I have no control over.
Current Progress
I found this blog post on single-inheritance which sounds like exactly what I need.
But trying to implement it resulted in this error message error: virtual structs have been removed from the language. Some searching later and I found out that it had been implemented and then removed per RFC-341 rather quickly.
Also found this thread about using traits, but since StructA is from an external cargo package I don't think it is possible for me to turn it into a trait.
So what would be the correct way to accomplish this in Rust?
",https://stackoverflow.com/questions/32552593/is-it-possible-for-one-struct-to-extend-an-existing-struct-keeping-all-the-fiel,147,121683.0,5.0,,,2015-09-13 17:36:17,2023-05-24 01:54:06,2015-09-13 19:16:26,,,inheritance;struct;rust,drebabels,2250,268567,registered,true,32552698,,CC BY-SA 3.0,,1809,1223,10,3,0,3,true,false,false,true,true,true,83,15,true,0.041,0.0012,4087,2015,9,17,Sunday,true,false,false,false,false,false,false
36928569,How can I create enums with constant values in Rust?,"I can do this:
enum MyEnum {
A(i32),
B(i32),
}
but not this:
enum MyEnum {
A(123), // 123 is a constant
B(456), // 456 is a constant
}
I can create the structures for A and B with a single field and then implement that field, but I think there might be an easier way. Is there any?
",https://stackoverflow.com/questions/36928569/how-can-i-create-enums-with-constant-values-in-rust,146,111137.0,7.0,,,2016-04-29 02:30:04,2024-02-28 11:57:19,2020-07-06 15:31:40,,,rust,Incerteza,35684,2813589,registered,true,36928678,,CC BY-SA 4.0,,399,304,4,0,0,1,true,false,false,true,true,true,52,10,true,0.063,0.0013,3858,2016,4,2,Friday,false,false,false,false,false,false,false
32682876,Is there any way to return a reference to a variable created in a function?,"I want to write a program that will write a file in 2 steps.
It is likely that the file may not exist before the program is run. The filename is fixed.
The problem is that OpenOptions.new().write() can fail. In that case, I want to call a custom function trycreate(). The idea is to create the file instead of opening it and return a handle. Since the filename is fixed, trycreate() has no arguments and I cannot set a lifetime of the returned value.
How can I resolve this problem?
use std::io::Write;
use std::fs::OpenOptions;
use std::path::Path;
fn trycreate() -> &OpenOptions {
let f = OpenOptions::new().write(true).open(""foo.txt"");
let mut f = match f {
Ok(file) => file,
Err(_) => panic!(""ERR""),
};
f
}
fn main() {
{
let f = OpenOptions::new().write(true).open(b""foo.txt"");
let mut f = match f {
Ok(file) => file,
Err(_) => trycreate(""foo.txt""),
};
let buf = b""test1\n"";
let _ret = f.write(buf).unwrap();
}
println!(""50%"");
{
let f = OpenOptions::new().append(true).open(""foo.txt"");
let mut f = match f {
Ok(file) => file,
Err(_) => panic!(""append""),
};
let buf = b""test2\n"";
let _ret = f.write(buf).unwrap();
}
println!(""Ok"");
}
",https://stackoverflow.com/questions/32682876/is-there-any-way-to-return-a-reference-to-a-variable-created-in-a-function,146,108901.0,5.0,,,2015-09-20 18:34:56,2025-07-02 23:04:49,2016-09-29 19:09:04,,,reference;rust;lifetime,Nex,1643,5356755,registered,true,,,CC BY-SA 3.0,,1443,1359,4,0,0,3,false,false,false,true,true,true,75,15,true,0.046,0.0013,4080,2015,9,18,Sunday,true,false,false,false,false,false,false
46290655,Does Rust's String have a method that returns the number of characters rather than the number of bytes?,"Based on the Rust book, the String::len method returns the number of bytes composing the string, which may not correspond to the length in characters.
For example if we consider the following string in Japanese, len() would return 30, which is the number of bytes and not the number of characters, which would be 10:
let s = String::from(""ラウトは難しいです!"");
s.len() // returns 30.
The only way I have found to get the number of characters is using the following function:
s.chars().count()
which returns 10, and is the correct number of characters.
Is there any method on String that returns the characters count, aside from the one I am using above?
",https://stackoverflow.com/questions/46290655/does-rusts-string-have-a-method-that-returns-the-number-of-characters-rather-th,145,104143.0,1.0,,,2017-09-19 01:58:56,2023-09-23 20:36:40,2023-01-01 11:14:56,,,string;rust,Salvatore Cosentino,7438,4384381,registered,true,,,CC BY-SA 4.0,,849,654,5,1,0,2,false,false,false,true,true,true,107,18,true,0.01,0.0014,3350,2017,9,1,Tuesday,false,false,false,false,false,false,false
28655362,How does one round a floating point number to a specified number of digits?,"How does one round a f64 floating point number in Rust to a specified number of digits?
",https://stackoverflow.com/questions/28655362/how-does-one-round-a-floating-point-number-to-a-specified-number-of-digits,144,128703.0,8.0,,,2015-02-22 06:55:55,2026-05-26 12:10:50,2015-02-22 13:25:01,,,rust,user1056805,2983,1056805,registered,true,28656825,,CC BY-SA 3.0,,95,88,0,0,0,1,true,false,false,true,true,true,75,14,true,0.062,0.0011,4290,2015,2,6,Sunday,true,false,false,false,false,false,false
37639276,When should inline be used in Rust?,"Rust has an "inline" attribute that can be used in one of those three flavors:
#[inline]
#[inline(always)]
#[inline(never)]
When should they be used?
In the Rust reference, we see an inline attributes section saying
The compiler automatically inlines functions based on internal heuristics. Incorrectly inlining functions can actually make the program slower, so it should be used with care.
In the Rust internals forum, huon was also conservative about specifying inline.
But we see considerable usage in the Rust source, including the standard library. A lot of inline attributes are added to one-line-functions, which should be easy for the compilers to spot and optimize through heuristics according to the reference. Are those in fact not needed?
",https://stackoverflow.com/questions/37639276/when-should-inline-be-used-in-rust,143,36930.0,1.0,,,2016-06-05 06:58:18,2022-09-30 11:41:14,2022-09-30 11:41:14,,,rust;inline;llvm-codegen,WiSaGaN,48437,866732,registered,true,37639889,,CC BY-SA 4.0,,1247,764,3,3,0,3,true,false,false,true,true,true,35,7,true,0.027,0.0039,3821,2016,6,6,Sunday,true,false,false,false,false,false,false
31492799,Cross-compile a Rust application from Linux to Windows,"Basically I'm trying to compile the simplest code to Windows while I am developing on Linux.
fn main() {
println!(""Hello, and bye."")
}
I found these commands by searching the internet:
rustc --target=i686-w64-mingw32-gcc main.rs
rustc --target=i686_pc_windows_gnu -C linker=i686-w64-mingw32-gcc main.rs
Sadly, none of them work. It gives me an error about the std crate missing
$ rustc --target=i686_pc_windows_gnu -C linker=i686-w64-mingw32-gcc main.rs
main.rs:1:1: 1:1 error: can't find crate for `std`
main.rs:1 fn main() {
^
error: aborting due to previous error
Is there a way to compile code on Linux that will run on Windows?
",https://stackoverflow.com/questions/31492799/cross-compile-a-rust-application-from-linux-to-windows,142,157798.0,6.0,,,2015-07-18 15:40:43,2026-03-31 14:55:48,2015-07-19 16:28:04,,,linux;windows;rust;cross-compiling,Fedcomp,2595,656669,registered,true,62853319,,CC BY-SA 3.0,,761,661,3,0,0,4,true,false,false,true,true,true,54,8,false,0.038,0.0009,4144,2015,7,15,Saturday,true,false,false,false,false,false,false
29570607,Is there a good way to convert a Vec<T> to an array?,"Is there a good way to convert a Vec<T> with size S to an array of type [T; S]? Specifically, I'm using a function that returns a 128-bit hash as a Vec<u8>, which will always have length 16, and I would like to deal with the hash as a [u8, 16].
Is there something built-in akin to the as_slice method which gives me what I want, or should I write my own function which allocates a fixed-size array, iterates through the vector copying each element, and returns the array?
",https://stackoverflow.com/questions/29570607/is-there-a-good-way-to-convert-a-vect-to-an-array,142,148435.0,1.0,,,2015-04-10 20:59:46,2021-03-29 14:55:16,2015-04-10 21:01:26,,,rust,jgray,1433,1517980,registered,true,29570662,,CC BY-SA 3.0,,578,486,6,0,0,1,true,false,false,true,true,true,58,12,true,0.007,0.001,4243,2015,4,20,Friday,false,false,false,false,false,false,false
22264502,"In Rust, what is the difference between clone() and to_owned()?","In Rust, Clone is a trait that specifies the clone method (and clone_from). Some traits, like StrSlice and CloneableVector specify a to_owned fn. Why would an implementation need both? What is the difference?
I did an experiment with Rust strings, which have both methods, and it demonstrates that there is a difference, but I don't understand it:
fn main() {
test_clone();
test_to_owned();
}
// compiles and runs fine
fn test_clone() {
let s1: &'static str = ""I am static"";
let s2 = ""I am boxed and owned"".to_string();
let c1 = s1.clone();
let c2 = s2.clone();
println!(""{:?}"", c1);
println!(""{:?}"", c2);
println!(""{:?}"", c1 == s1); // prints true
println!(""{:?}"", c2 == s2); // prints true
}
fn test_to_owned() {
let s1: &'static str = ""I am static"";
let s2 = ""I am boxed and owned"".to_string();
let c1 = s1.to_owned();
let c2 = s2.to_owned();
println!(""{:?}"", c1);
println!(""{:?}"", c2);
println!(""{:?}"", c1 == s1); // compile-time error here (see below)
println!(""{:?}"", c2 == s2);
}
The compile time error for the to_owned example is:
error: mismatched types: expected `~str` but found `&'static str`
(str storage differs: expected `~` but found `&'static `)
clone.rs:30 println!(""{:?}"", c1 == s1);
Why would the first example work but not the second?
",https://stackoverflow.com/questions/22264502/in-rust-what-is-the-difference-between-clone-and-to-owned,141,61880.0,1.0,,,2014-03-08 03:09:52,2022-08-05 18:40:48,2016-09-24 15:32:31,,,rust,quux00,14844,871012,registered,true,22265792,,CC BY-SA 3.0,,1583,1377,9,0,0,1,true,false,false,true,true,true,63,10,true,0.016,0.0023,4641,2014,3,3,Saturday,true,false,false,false,false,false,false
37388107,How to convert the PathBuf to String,"I have to convert the PathBuf variable to a String to feed my function. My code is like this:
let cwd = env::current_dir().unwrap();
let my_str: String = cwd.as_os_str().to_str().unwrap().to_string();
println!(""{:?}"", my_str);
it works but is awful with the cwd.as_os_str….
Do you have a more convenient method or any suggestions on how to handle it?
",https://stackoverflow.com/questions/37388107/how-to-convert-the-pathbuf-to-string,140,109698.0,5.0,,,2016-05-23 10:06:44,2024-05-12 14:14:04,2021-01-24 07:06:42,,,string;rust;directory;path,xiaoai,1511,2655960,registered,true,,,CC BY-SA 4.0,,431,354,4,0,0,4,false,false,false,true,true,true,36,7,false,0.046,0.0013,3834,2016,5,10,Monday,false,false,false,false,false,false,false
14154753,How do I make an HTTP request from Rust?,"How can I make an HTTP request from Rust? I can't seem to find anything in the core library.
I don't need to parse the output, just make a request and check the HTTP response code.
Bonus marks if someone can show me how to URL encode the query parameters on my URL!
",https://stackoverflow.com/questions/14154753/how-do-i-make-an-http-request-from-rust,139,166835.0,10.0,,,2013-01-04 09:50:32,2024-11-16 07:54:18,,,,http;rust,Alex Dean,16205,255627,registered,true,19052733,,CC BY-SA 3.0,,289,268,0,0,0,2,true,false,false,true,true,false,40,9,true,0.06,0.0008,5069,2013,1,9,Friday,false,false,false,false,false,false,false
54595345,What does 'let x = x' do in Rust?,"I saw this code in the wild:
fields.sort_by_key(|&(_, ref field)| field.tags().into_iter().min().unwrap());
let fields = fields;
What does the let fields = fields; line do? Why is it there?
",https://stackoverflow.com/questions/54595345/what-does-let-x-x-do-in-rust,139,8150.0,2.0,,,2019-02-08 15:13:54,2021-07-22 08:49:36,2019-02-09 20:19:26,,,rust,timthelion,2798,2126889,registered,true,54595440,,CC BY-SA 4.0,,389,197,2,1,0,1,true,false,false,true,true,true,41,9,true,0.245,0.0171,2843,2019,2,15,Friday,false,false,false,false,false,false,false
29611387,Why does the println! function use an exclamation mark in Rust?,"In Swift, ! means to unwrap an optional (possible value).
",https://stackoverflow.com/questions/29611387/why-does-the-println-function-use-an-exclamation-mark-in-rust,139,50092.0,2.0,,,2015-04-13 17:27:41,2021-11-22 10:57:57,2015-04-15 14:27:53,,,rust,Chéyo,9487,3705470,registered,true,29611728,,CC BY-SA 3.0,,78,58,1,0,0,1,true,false,false,true,true,true,63,11,true,0.04,0.0028,4240,2015,4,17,Monday,false,false,false,false,false,false,false
26243025,How to remove an element from a vector given the element?,"Is there a simple way to remove an element from a Vec<T>?
There's a method called remove(), and it takes an index: usize, but there isn't even an index_of() method that I can see.
I'm looking for something (hopefully) simple and O(n).
",https://stackoverflow.com/questions/26243025/how-to-remove-an-element-from-a-vector-given-the-element,135,184207.0,11.0,,,2014-10-07 18:45:30,2025-11-09 16:35:26,2023-01-01 11:29:44,,,rust,Kai Sellgren,30812,1364206,registered,true,26243276,,CC BY-SA 4.0,,418,243,4,1,0,1,true,false,false,true,true,true,57,11,true,0.06,0.0007,4428,2014,10,18,Tuesday,false,false,false,false,false,false,false
58368801,How do I check if a thing is in a vector,"How do I check if a thing is in a vector?
let n= vec![""-i"",""mmmm""];
if ""-i"" in n {
println!(""yes"");
} else {
println!(""no"");
I'm guessing that I need to put this in a loop and then do if ""-i"" in x where x is the iter var. But I was hopping there is a handy method available or I've confused the syntax and there is a similar way to do this.
",https://stackoverflow.com/questions/58368801/how-do-i-check-if-a-thing-is-in-a-vector,134,139682.0,2.0,,,2019-10-14 00:23:34,2023-06-05 16:14:19,,,,rust,9716278,2502,9716278,registered,true,58368936,,CC BY-SA 4.0,,456,353,3,0,0,1,true,false,false,true,true,false,40,11,false,0.014,0.001,2595,2019,10,0,Monday,false,false,false,false,false,false,false
30253422,How to print structs and arrays?,"How do I print structs and arrays in Rust? Other languages are able to print structs and arrays directly.
struct MyStruct {
a: i32,
b: i32
}
and
let arr: [i32; 10] = [1; 10];
",https://stackoverflow.com/questions/30253422/how-to-print-structs-and-arrays,134,111608.0,6.0,,,2015-05-15 07:00:38,2023-08-18 12:42:42,2023-08-18 12:42:42,,,rust,tez,5380,1390726,registered,true,30253540,,CC BY-SA 4.0,,247,185,2,0,0,1,true,false,false,true,true,true,32,6,true,0.054,0.0012,4208,2015,5,7,Friday,false,false,false,false,false,false,false
27454761,What is a crate attribute and where do I add it?,"In order to get a feel for how Rust works, I decided to look at a little terminal-based text editor called Iota. I cloned the repository and ran cargo build only to be told:
error: *if let* syntax is experimental
help: add #![feature(if_let)] to the crate attributes to enable
Where am I supposed to add #![feature(if_let)] to the crate attributes?
",https://stackoverflow.com/questions/27454761/what-is-a-crate-attribute-and-where-do-i-add-it,134,58966.0,1.0,,,2014-12-13 01:59:39,2019-07-10 15:18:16,2018-02-15 15:06:50,,,rust;rust-cargo,Soham Chowdhury,2305,1593359,registered,true,27455138,,CC BY-SA 3.0,,545,357,3,1,0,2,true,false,false,true,true,true,48,11,true,0.017,0.0023,4361,2014,12,1,Saturday,true,false,false,false,false,false,false
58226545,How to switch between Rust toolchains?,"rustup help toolchain lists the following sub-commands
SUBCOMMANDS:
list List installed toolchains
install Install or update a given toolchain
uninstall Uninstall a toolchain
link Create a custom toolchain by symlinking to a directory
help Prints this message or the help of the given subcommand(s)
I have the following toolchains installed
stable-x86_64-unknown-linux-gnu (default)
nightly-2019-09-05-x86_64-unknown-linux-gnu
nightly-x86_64-unknown-linux-gnu
master
I was trying to solve an issue for rust-clippy so I had to install the master toolchain. Even though stable is set as my default toolchain, my current toolchain is master and I would like to switch back to stable. How do I do it without uninstalling the master toolchain?
Is there no switch subcommand?
",https://stackoverflow.com/questions/58226545/how-to-switch-between-rust-toolchains,129,143709.0,5.0,,,2019-10-03 20:36:43,2025-10-13 14:00:25,2020-06-17 01:00:33,,,rust;rustup,Palash Nigam,2122,6845084,registered,true,64701936,,CC BY-SA 4.0,,996,829,3,0,0,2,true,false,false,true,true,true,38,6,true,0.035,0.0009,2606,2019,10,20,Thursday,false,false,false,false,false,false,false
32710187,How do I get an enum as a string?,"I have an enum with many values and I'd like to write the name of one of its values to a stream:
enum Foo {
Bar = 0x00,
Baz = 0x01,
Qux = 0x02,
// ...
Quux = 0xFF,
}
I can derive Debug and do
writer.write(format!(""I am {:?}"", Foo::Quux).as_bytes())
which will output e.g. I am Quux. That's fine, except that
- I want to do this for user-facing output, so
Debug isn't appropriate
- It would be very helpful to get the enum as a string (rather than writing directly to a stream), because then I can incorporate its length into some wonky formatting calculations I want to do.
",https://stackoverflow.com/questions/32710187/how-do-i-get-an-enum-as-a-string,129,145211.0,4.0,,,2015-09-22 06:48:58,2024-07-01 17:42:22,2020-03-09 18:37:02,,,rust,Iskar Jarak,5475,696485,registered,true,32712140,,CC BY-SA 4.0,,734,599,5,0,0,1,true,false,false,true,true,true,33,9,true,0.028,0.0009,4078,2015,9,6,Tuesday,false,false,false,false,false,false,false
29857002,How to define test-only dependencies?,"I have a Rust library that implements a lint plugin. I want to include compiletest, but not require it outside of testing. What is the correct way to specify that the dependency is for testing only?
",https://stackoverflow.com/questions/29857002/how-to-define-test-only-dependencies,129,28161.0,1.0,,,2015-04-24 20:35:23,2024-09-20 15:34:55,2015-04-24 22:04:51,,,rust;rust-cargo,llogiq,14701,2765603,registered,true,29857478,,CC BY-SA 3.0,,219,199,1,0,0,2,true,false,false,true,true,true,37,5,true,0.036,0.0046,4229,2015,4,20,Friday,false,false,false,false,false,false,false
27022848,How I can mutate a struct's field from a method?,"I want to do this:
struct Point {
x: i32,
y: i32,
}
impl Point {
fn up(&self) {
self.y += 1;
}
}
fn main() {
let p = Point { x: 0, y: 0 };
p.up();
}
But this code throws a compiler error:
error[E0594]: cannot assign to field `self.y` of immutable binding
--> src/main.rs:8:9
|
7 | fn up(&self) {
| ----- use `&mut self` here to make mutable
8 | self.y += 1;
| ^^^^^^^^^^^ cannot mutably borrow field of immutable binding
",https://stackoverflow.com/questions/27022848/how-i-can-mutate-a-structs-field-from-a-method,128,129970.0,2.0,,,2014-11-19 17:12:12,2020-01-06 21:59:15,2018-10-26 18:42:56,,,rust;mutable,alxkolm,2071,2008640,registered,true,27023282,,CC BY-SA 4.0,,613,512,2,0,0,2,true,false,false,true,true,true,52,10,true,0.015,0.001,4385,2014,11,17,Wednesday,false,false,false,false,false,false,false
30026893,How to use a map over vectors?,"Although vectors are best suited for procedural programming, I would like to use a map function on them. The following snippet works:
fn map<A, B>(u: &Vec<A>, f: &Fn(&A) -> B) -> Vec<B> {
let mut res: Vec<B> = Vec::with_capacity(u.len());
for x in u.iter() {
res.push(f(x));
}
res
}
fn f(x: &i32) -> i32 {
*x + 1
}
fn main() {
let u = vec![1, 2, 3];
let v = map(&u, &f);
println!("{} {} {}", v[0], v[1], v[2]);
}
Why isn't there any such function in the standard library (and also in std::collections::LinkedList)? Is there another way to deal with it?
",https://stackoverflow.com/questions/30026893/how-to-use-a-map-over-vectors,126,130946.0,2.0,,,2015-05-04 09:36:48,2023-01-01 11:12:24,2023-01-01 11:12:24,,,rust,user19018,2529,4673683,registered,true,30026986,,CC BY-SA 4.0,,727,663,3,0,0,1,true,false,false,true,true,true,30,7,true,0.015,0.001,4219,2015,5,9,Monday,false,false,false,false,false,false,false
72062935,rust-analyzer failed to discover workspace in vscode,"I'm starting to learn the Rust language and I have an issue with rust-analyzer vscode extension.
- It doesn't provide code completion as shown in the link: https://rust-analyzer.github.io/manual.html#magic-completions
- Vscode shows notification as shown in the picture below:
![]()
This picture doesn't provide me with any additional info about root of the problem. I tried to find articles related to my error, but failed. Please help!
UPD1.
Screenshot of directory:
Screenshot of Cargo.toml contents:
guessing_game directory was created with cargo new guessing_game command
",https://stackoverflow.com/questions/72062935/rust-analyzer-failed-to-discover-workspace-in-vscode,126,143095.0,17.0,,,2022-04-29 19:37:04,2024-12-16 16:10:01,2022-12-03 11:21:40,,,vs-code;rust;vscode-extensions;rust-analyzer,wowonline,1580,8279172,registered,true,72066369,,CC BY-SA 4.0,,1237,572,2,4,3,4,true,false,false,true,true,true,52,7,false,0.119,0.0009,1667,2022,4,19,Friday,false,false,false,false,false,false,false
21369876,What is the idiomatic Rust way to copy/clone a vector in a parameterized function?,"I'm trying to write a parameterized function that takes an immutable vector, clones or copies it, does something to the new vector (such as shuffle it) and returns it as a new owned vector. How can this be done and what is the most idiomatic way to do it?
Attempt #1
pub fn shuffle<T>(vec: &mut [T]) {
// ... contents removed: it shuffles the vector in place
// ... so needs a mutable vector
}
pub fn shuffle_create_new<T: Clone>(vec: &[T]) -> Vec<T> {
let mut newvec = vec.clone();
shuffle(&mut newvec);
return newvec.to_owned();
}
Fails with:
error[E0596]: cannot borrow immutable borrowed content as mutable
--> src/main.rs:8:13
|
8 | shuffle(&mut newvec);
| ^^^^^^^^^^^ cannot borrow as mutable
even though I declared newvec as mutable. I don't understand why.
Attempt #2
pub fn shuffle_owned<T: Clone>(mut vec: Vec<T>) -> Vec<T> {
shuffle(&mut vec);
return vec;
}
While this compiles, it doesn't do what I want. The vector you pass into shuffle_owned gets moved into the function, shuffled and then has its ownership transferred back to the caller (via the return value). So the original vector is modified.
I want to know how to pass in a vector that will not be mutated, but have the values cloned into a new boxed vector and returned when finished - as you do in a functional programming language that has immutable data (such as Clojure).
",https://stackoverflow.com/questions/21369876/what-is-the-idiomatic-rust-way-to-copy-clone-a-vector-in-a-parameterized-functio,126,171245.0,2.0,,,2014-01-26 22:03:59,2017-08-29 17:16:54,2017-08-29 17:11:50,,,rust,quux00,14844,871012,registered,true,21373782,,CC BY-SA 3.0,,1743,1480,5,0,0,1,true,false,false,true,true,true,82,14,true,0.012,0.0007,4682,2014,1,22,Sunday,true,false,false,false,false,false,false
30218886,How to implement Iterator and IntoIterator for a simple struct?,"How would someone implement the Iterator and IntoIterator traits for the following struct?
struct Pixel {
r: i8,
g: i8,
b: i8,
}
I've tried various forms of the following with no success.
impl IntoIterator for Pixel {
type Item = i8;
type IntoIter = Iterator<Item=Self::Item>;
fn into_iter(self) -> Self::IntoIter {
[&self.r, &self.b, &self.g].into_iter()
}
}
This code gives me a compile error
error[E0277]: the trait bound `std::iter::Iterator<Item=i8> + 'static: std::marker::Sized` is not satisfied
--> src/main.rs:7:6
|
7 | impl IntoIterator for Pixel {
| ^^^^^^^^^^^^ the trait `std::marker::Sized` is not implemented for `std::iter::Iterator<Item=i8> + 'static`
|
= note: `std::iter::Iterator<Item=i8> + 'static` does not have a constant size known at compile-time
= note: required by `std::iter::IntoIterator`
",https://stackoverflow.com/questions/30218886/how-to-implement-iterator-and-intoiterator-for-a-simple-struct,125,84859.0,2.0,,,2015-05-13 15:11:32,2021-03-29 14:35:01,2017-04-12 14:22:26,,,iterator;rust,Piper Merriam,3004,381797,registered,true,30220832,,CC BY-SA 3.0,,1079,921,5,0,0,2,true,false,false,true,true,true,63,10,true,0.024,0.0015,4210,2015,5,15,Wednesday,false,false,false,false,false,false,false
33687447,How to get a reference to a concrete type from a trait object?,"How do I get Box<B> or &B or &Box<B> from the a variable in this code:
trait A {}
struct B;
impl A for B {}
fn main() {
let mut a: Box<dyn A> = Box::new(B);
let b = a as Box<B>;
}
This code returns an error:
error[E0605]: non-primitive cast: `std::boxed::Box<dyn A>` as `std::boxed::Box<B>`
--> src/main.rs:8:13
|
8 | let b = a as Box<B>;
| ^^^^^^^^^^^
|
= note: an `as` expression can only be used to convert between primitive types. Consider using the `From` trait
",https://stackoverflow.com/questions/33687447/how-to-get-a-reference-to-a-concrete-type-from-a-trait-object,125,52696.0,2.0,,,2015-11-13 07:03:35,2023-11-05 16:45:02,2018-10-07 19:32:43,,,rust;traits,Aleksandr,2075,4981490,registered,true,33687996,,CC BY-SA 4.0,,713,560,6,0,0,2,true,false,false,true,true,true,62,13,true,0.038,0.0024,4026,2015,11,7,Friday,false,false,false,false,false,false,false
28028854,How do I match enum values with an integer?,"I can get an integer value of an enums like this:
enum MyEnum {
A = 1,
B,
C,
}
let x = MyEnum::C as i32;
but I can't seem to do this:
match x {
MyEnum::A => {}
MyEnum::B => {}
MyEnum::C => {}
_ => {}
}
How can I either match against the values of the enum or try to convert x back to a MyEnum?
I can see a function like this being useful for enums, but it probably doesn't exist:
impl MyEnum {
fn from<T>(val: &T) -> Option<MyEnum>;
}
",https://stackoverflow.com/questions/28028854/how-do-i-match-enum-values-with-an-integer,124,153766.0,10.0,,,2015-01-19 16:07:29,2023-07-28 09:18:22,2018-03-06 03:19:18,,,rust,dhardy,12644,314345,registered,true,,,CC BY-SA 3.0,,634,508,5,0,0,1,false,false,false,true,true,true,43,9,true,0.065,0.0008,4324,2015,1,16,Monday,false,false,false,false,false,false,false
34969902,How to write a Rust function that takes an iterator?,"I'd like to write a function that accepts an iterator and returns the results of some operations on it. Specifically, I'm trying to iterate over the values of a HashMap:
use std::collections::HashMap;
fn find_min<'a>(vals: Iterator<Item=&'a u32>) -> Option<&'a u32> {
vals.min()
}
fn main() {
let mut map = HashMap::new();
map.insert(""zero"", 0u32);
map.insert(""one"", 1u32);
println!(""Min value {:?}"", find_min(map.values()));
}
But alas:
error: the `min` method cannot be invoked on a trait object
--> src/main.rs:4:10
|
4 | vals.min()
| ^^^
error[E0277]: the trait bound `std::iter::Iterator<Item=&'a u32> + 'static: std::marker::Sized` is not satisfied
--> src/main.rs:3:17
|
3 | fn find_min<'a>(vals: Iterator<Item = &'a u32>) -> Option<&'a u32> {
| ^^^^ `std::iter::Iterator<Item=&'a u32> + 'static` does not have a constant size known at compile-time
|
= help: the trait `std::marker::Sized` is not implemented for `std::iter::Iterator<Item=&'a u32> + 'static`
= note: all local variables must have a statically known size
error[E0308]: mismatched types
--> src/main.rs:11:41
|
11 | println!(""Min value {:?}"", find_min(map.values()));
| ^^^^^^^^^^^^ expected trait std::iter::Iterator, found struct `std::collections::hash_map::Values`
|
= note: expected type `std::iter::Iterator<Item=&u32> + 'static`
found type `std::collections::hash_map::Values<'_, &str, u32>`
I get the same error if I try to pass by reference; if I use a Box, I get lifetime errors.
",https://stackoverflow.com/questions/34969902/how-to-write-a-rust-function-that-takes-an-iterator,124,65047.0,3.0,,,2016-01-23 22:48:42,2022-09-24 05:34:47,2017-11-07 13:55:01,,,function;iterator;rust,Doctor J,6402,171236,registered,true,34969944,,CC BY-SA 3.0,,1861,1727,4,0,0,3,true,false,false,true,true,true,52,10,true,0.046,0.0019,3955,2016,1,22,Saturday,true,false,false,false,false,false,false
23850486,How do I convert a string into a vector of bytes in rust?,"That might be the dumbest Rustlang question ever but I promise I tried my best to find the answer in the documentation or any other place on the web.
I can convert a string to a vector of bytes like this:
let bar = bytes!(""some string"");
Unfortunately I can't do it this way
let foo = ""some string"";
let bar = bytes!(foo);
Because bytes! expects a string literal.
But then, how do I get my foo converted into a vector of bytes?
",https://stackoverflow.com/questions/23850486/how-do-i-convert-a-string-into-a-vector-of-bytes-in-rust,124,150939.0,3.0,,,2014-05-24 23:03:51,2022-03-20 21:55:54,2014-05-24 23:18:25,,,type-conversion;rust,Christoph,28643,288703,registered,true,23850526,,CC BY-SA 3.0,,532,436,3,0,0,2,true,false,false,true,true,true,57,13,true,0.02,0.0008,4564,2014,5,23,Saturday,true,false,false,false,false,false,false
25754863,How to create a Rust struct with string members?,"I want the members to be owned by the struct. I'm looking for the correct declaration of a struct and instantiation examples. I wasn't able to find an example.
",https://stackoverflow.com/questions/25754863/how-to-create-a-rust-struct-with-string-members,124,73622.0,2.0,,,2014-09-09 23:03:24,2024-11-29 16:33:33,2023-01-01 11:07:50,,,string;rust,vladimir,2805,1281980,registered,true,25755178,,CC BY-SA 4.0,,167,160,0,0,0,2,true,false,false,true,true,true,48,9,true,0.027,0.0017,4456,2014,9,23,Tuesday,false,false,false,false,false,false,false
31949579,"Understanding and relationship between Box, ref, & and *","I'm a bit confused about how pointers work in Rust. There's ref, Box, &, *, and I'm not sure how they work together.
Here's how I understand it currently:
Box isn't really a pointer - it's a way to allocate data on the heap, and pass around unsized types (traits especially) in function arguments.
ref is used in pattern matching to borrow something that you match on, instead of taking it. For example,
let thing: Option<i32> = Some(4);
match thing {
None => println!(""none!""),
Some(ref x) => println!(""{}"", x), // x is a borrowed thing
}
println!(""{}"", x + 1); // wouldn't work without the ref since the block would have taken ownership of the data
& is used to make a borrow (borrowed pointer). If I have a function fn foo(&self) then I'm taking a reference to myself that will expire after the function terminates, leaving the caller's data alone. I can also pass data that I want to retain ownership of by doing bar(&mydata).
* is used to make a raw pointer: for example, let y: i32 = 4; let x = &y as *const i32. I understand pointers in C/C++ but I'm not sure how this works with Rust's type system, and how they can be safely used. I'm also not sure what the use cases are for this type of pointer. Additionally, the * symbol can be used to dereference things (what things, and why?).
Could someone explain the 4th type of pointer to me, and verify that my understanding of the other types is correct? I'd also appreciate anyone pointing out any common use cases that I haven't mentioned.
",https://stackoverflow.com/questions/31949579/understanding-and-relationship-between-box-ref-and,122,34672.0,6.0,,,2015-08-11 18:42:20,2026-08-05 16:49:01,2018-02-15 16:34:26,,,pointers;rust,zrneely,1991,3033123,registered,true,31953048,,CC BY-SA 3.0,,1804,1544,13,0,0,2,true,false,false,true,true,true,60,9,false,0.173,0.0035,4120,2015,8,18,Tuesday,false,false,false,false,false,false,false
28572101,What is a clean way to convert a Result into an Option?,"Before updating to a more recent Rust version the following used to work:
fn example(val: &[&str]) {
let parsed_value: Vec<usize> = val
.iter()
.filter_map(|e| e.parse::<usize>())
.collect();
}
However, now the parse method returns a Result type instead of an Option and I get the error:
error[E0308]: mismatched types
--> src/lib.rs:4:25
|
4 | .filter_map(|e| e.parse::<usize>())
| ^^^^^^^^^^^^^^^^^^ expected enum `std::option::Option`, found enum `std::result::Result`
|
= note: expected type `std::option::Option<_>`
found type `std::result::Result<usize, std::num::ParseIntError>`
I could create an Option through a conditional, but is there a better / cleaner way?
",https://stackoverflow.com/questions/28572101/what-is-a-clean-way-to-convert-a-result-into-an-option,122,89846.0,1.0,,,2015-02-17 22:12:27,2019-01-02 00:23:11,2019-01-02 00:17:49,,,rust;option-type,vise,13461,262956,registered,true,28572170,,CC BY-SA 4.0,,947,800,5,0,0,2,true,false,false,true,true,true,55,12,true,0.011,0.0014,4295,2015,2,22,Tuesday,false,false,false,false,false,false,false
30292752,How do I parse a JSON File?,"I have this so far in my goal to Parse this JSON data in Rust:
extern crate rustc_serialize;
use rustc_serialize::json::Json;
use std::fs::File;
use std::io::copy;
use std::io::stdout;
fn main() {
let mut file = File::open(""text.json"").unwrap();
let mut stdout = stdout();
let mut str = ©(&mut file, &mut stdout).unwrap().to_string();
let data = Json::from_str(str).unwrap();
}
and text.json is
{
""FirstName"": ""John"",
""LastName"": ""Doe"",
""Age"": 43,
""Address"": {
""Street"": ""Downing Street 10"",
""City"": ""London"",
""Country"": ""Great Britain""
},
""PhoneNumbers"": [
""+44 1234567"",
""+44 2345678""
]
}
What should be my next step into parsing it? My primary goal is to get JSON data like this, and parse a key from it, like Age.
",https://stackoverflow.com/questions/30292752/how-do-i-parse-a-json-file,121,140306.0,6.0,,,2015-05-17 22:20:10,2024-05-22 16:47:42,2015-05-17 23:43:02,,,json;rust,Vikaton,2483,4233606,registered,true,49950214,,CC BY-SA 3.0,,907,825,3,0,0,2,true,false,false,true,true,true,27,7,true,0.043,0.0009,4206,2015,5,22,Sunday,true,false,false,false,false,false,false
26212397,How do I specify that a struct field must implement a trait?,"I have a trait Foo
pub trait Foo {
fn do_something(&self) -> f64;
}
and a struct which references that trait
pub struct Bar {
foo: Foo,
}
Trying to compile I get
error: reference to trait `Foo` where a type is expected; try `Box<Foo>` or `&Foo`
Changing the struct to
struct Bar {
foo: &Foo,
}
Tells me error: missing lifetime specifier
Changing the definition to
struct Bar {
foo: Box<Foo>,
}
Compiles — yay!
However, when I want a function to return foo on bar - something like:
impl Bar {
fn get_foo(&self) -> Foo {
self.foo
}
}
Well obviously bar.foo is a Box<Foo>, so expectedly I get error: reference to trait `Foo` where a type is expected; try `Box<Foo>` or `&Foo`
Changing the signature to
impl Bar {
fn get_foo(&self) -> Box<Foo> {
let this = *self;
this.foo
}
}
But now I get error: cannot move out of dereference of `&`-pointer on trying to dereference self.
Changing to
impl Bar {
fn get_foo(self) -> Box<Foo> {
self.foo
}
}
Is all good.
So....
- Why doesn't
& in the bar struct work? I'm assuming I have to box
as structs have a set memory layout so we have to say it's a pointer
to a trait (as we can't know how big that will be), but why does the
compiler suggest something that wont compile?
- Why can't I dereference
self in get_foo() - All examples I've seen use the borrowed self syntax?
- What's the implication of removing the
& and just using self?
Learning Rust is fascinating, but the memory safety is both fascinating and intimidating!
Code in full that compiles:
trait Foo {
fn do_something(&self) -> f64;
}
struct Bar {
foo: Box<Foo>,
}
impl Bar {
fn get_foo(self) -> Box<Foo> {
let foo = self.foo;
foo.do_something();
foo
}
}
fn main() {}
",https://stackoverflow.com/questions/26212397/how-do-i-specify-that-a-struct-field-must-implement-a-trait,119,55162.0,3.0,,,2014-10-06 08:25:47,2023-08-30 05:05:32,2023-01-01 11:26:39,,,rust;traits,neil danson,1562,825320,registered,true,26213294,,CC BY-SA 4.0,,2526,1915,25,0,0,2,true,false,false,true,true,true,60,12,true,0.054,0.0022,4429,2014,10,8,Monday,false,false,false,false,false,false,false
31289588,How to convert a &str to a &[u8],"This seems trivial, but I cannot find a way to do it.
For example,
fn f(s: &[u8]) {}
pub fn main() {
let x = ""a"";
f(x)
}
Fails to compile with:
error: mismatched types:
expected `&[u8]`,
found `&str`
(expected slice,
found str) [E0308]
documentation, however, states that:
The actual representation of strs have direct mappings to slices: &str
is the same as &[u8].
",https://stackoverflow.com/questions/31289588/how-to-convert-a-str-to-a-u8,118,92421.0,1.0,,,2015-07-08 10:11:45,2023-01-01 11:10:30,2023-01-01 11:10:30,,,string;rust;slice,ynimous,5242,118958,registered,true,31290258,,CC BY-SA 4.0,,589,418,2,1,0,3,true,false,false,true,true,true,40,8,false,0.011,0.0013,4154,2015,7,10,Wednesday,false,false,false,false,false,false,false
35592750,How does "for<>" syntax differ from a regular lifetime bound?,"Consider the following code:
trait Trait<T> {}
fn foo<'a>(_b: Box<dyn Trait<&'a usize>>) {}
fn bar(_b: Box<dyn for<'a> Trait<&'a usize>>) {}
Both functions foo and bar seem to accept a Box<Trait<&'a usize>>, although foo does it more concisely than bar. What is the difference between them?
Additionally, in what situations would I need for<> syntax like that above? I know the Rust standard library uses it internally (often related to closures), but why might my code need it?
",https://stackoverflow.com/questions/35592750/how-does-for-syntax-differ-from-a-regular-lifetime-bound,117,13928.0,1.0,,,2016-02-24 03:35:20,2024-06-12 07:31:28,2022-10-01 16:02:41,,,rust;syntax,George Hilliard,16163,1830736,registered,true,35595491,,CC BY-SA 4.0,,681,558,7,0,0,2,true,false,false,true,true,true,77,10,true,0.072,0.0084,3923,2016,2,3,Wednesday,false,false,false,false,false,false,false
48794974,How to check if a string contains a substring in Rust?,"I'm trying to find whether a substring is in a string. In Python, this involves the in operator, so I wrote this code:
let a = ""abcd"";
if ""bc"" in a {
do_something();
}
I get a strange error message:
error: expected `{`, found `in`
--> src/main.rs:3:13
|
3 | if ""bc"" in a {
| _____________-^
4 | | do_something();
5 | | }
| |_____- help: try placing this code inside a block: `{ a <- { do_something(); }; }`
The message suggests that I put it in a block, but I have no idea how to do that.
",https://stackoverflow.com/questions/48794974/how-to-check-if-a-string-contains-a-substring-in-rust,117,109049.0,1.0,,,2018-02-14 19:39:55,2018-02-14 20:12:15,2018-02-14 20:11:56,,,string;rust,John Doe,1560,9361705,registered,true,48795231,,CC BY-SA 3.0,,652,531,3,0,0,2,true,false,false,true,true,true,54,11,true,0.009,0.0011,3202,2018,2,19,Wednesday,false,false,false,false,false,false,false
53136717,error[E0554]: #![feature] may not be used on the stable release channel Couldn't install racer using cargo,"I'm trying to install racer using cargo, so I executed the command cargo install racer in the terminal and it resulted in the error:
error[E0554]: #![feature] may not be used on the stable release channel
--> /home/rajkumar/.cargo/registry/src/github.com-1ecc6299db9ec823/scoped-tls-0.1.2/src/lib.rs:47:34
|
47 | #![cfg_attr(feature = ""nightly"", feature(macro_vis_matcher))]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^
error[E0554]: #![feature] may not be used on the stable release channel
--> /home/rajkumar/.cargo/registry/src/github.com-1ecc6299db9ec823/scoped-tls-0.1.2/src/lib.rs:48:34
|
48 | #![cfg_attr(feature = ""nightly"", feature(allow_internal_unstable))]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
error: aborting due to 2 previous errors
For more information about this error, try `rustc --explain E0554`.
error: failed to compile `racer v2.1.10`, intermediate artifacts can be found at `/tmp/cargo-install5YWPWW`
Caused by:
Could not compile `scoped-tls`.
To learn more, run the command again with --verbose.
Below are my Rust details:
$rustc --version
rustc 1.30.0 (da5f414c2 2018-10-24)
> rustup --version
rustup 1.14.0 (1e51b07cc 2018-10-04)
> cargo --version
cargo 1.30.0 (36d96825d 2018-10-24)
Below is my opensuse version details:
> cat /usr/lib/os-release
NAME=""openSUSE Tumbleweed""
# VERSION=""20181029""
ID=""opensuse-tumbleweed""
ID_LIKE=""opensuse suse""
VERSION_ID=""20181029""
PRETTY_NAME=""openSUSE Tumbleweed""
ANSI_COLOR=""0;32""
CPE_NAME=""cpe:/o:opensuse:tumbleweed:20181029""
BUG_REPORT_URL=""https://bugs.opensuse.org""
HOME_URL=""https://www.opensuse.org/""
Why am I not able to install racer using cargo? Am I missing anything?
",https://stackoverflow.com/questions/53136717/errore0554-feature-may-not-be-used-on-the-stable-release-channel-couldnt,116,87118.0,6.0,,,2018-11-04 00:24:11,2023-03-30 17:28:54,2018-11-04 02:03:21,,,rust;rust-cargo,user51,10655,2541276,registered,true,53137160,,CC BY-SA 4.0,,1956,1726,4,0,0,2,true,false,false,true,true,true,110,16,false,0.069,0.0013,2939,2018,11,0,Sunday,true,false,false,false,false,false,false
27831944,How do I store a closure in a struct in Rust?,"Before Rust 1.0, I could write a structure using this obsolete closure syntax:
struct Foo {
pub foo: |usize| -> usize,
}
Now I can do something like:
struct Foo<F: FnMut(usize) -> usize> {
pub foo: F,
}
But then what's the type of a Foo object I create?
let foo: Foo<???> = Foo { foo: |x| x + 1 };
I could also use a reference:
struct Foo<'a> {
pub foo: &'a mut FnMut(usize) -> usize,
}
I think this is slower because
- the pointer dereference
- there's no specialization for the type of
FnMut that actually ends up being used
",https://stackoverflow.com/questions/27831944/how-do-i-store-a-closure-in-a-struct-in-rust,116,67051.0,2.0,,,2015-01-08 02:18:33,2022-04-06 12:59:24,2019-05-29 12:05:23,,,closures;rust,bfops,5818,417803,registered,true,27832320,,CC BY-SA 4.0,,765,581,6,0,0,2,true,false,false,true,true,true,45,11,true,0.03,0.0017,4335,2015,1,2,Thursday,false,false,false,false,false,false,false
16504643,What is the overhead of Rust's Option type?,"In Rust, references can never be null, so in case where you actually need null, such as a linked list, you use the Option type:
struct Element {
value: i32,
next: Option<Box<Element>>,
}
How much overhead is involved in this in terms of memory allocation and steps to dereference compared to a simple pointer? Is there some ""magic"" in the compiler/runtime to make Option cost-free, or less costly than if one were to implement Option by oneself in a non-core library using the same enum construct, or by wrapping the pointer in a vector?
",https://stackoverflow.com/questions/16504643/what-is-the-overhead-of-rusts-option-type,116,27323.0,2.0,,,2013-05-12 05:59:23,2025-08-16 17:21:11,2017-12-18 21:35:09,,,performance;rust;null-pointer,Thilo,264177,14955,registered,true,16515488,,CC BY-SA 3.0,,651,561,5,0,0,3,true,false,false,true,true,true,47,8,true,0.073,0.0042,4941,2013,5,5,Sunday,true,false,false,false,false,false,false
59081890,Is it possible to write Quake's fast InvSqrt() function in Rust?,"This is just to satisfy my own curiosity.
Is there an implementation of this:
float InvSqrt (float x)
{
float xhalf = 0.5f*x;
int i = *(int*)&x;
i = 0x5f3759df - (i>>1);
x = *(float*)&i;
x = x*(1.5f - xhalf*x*x);
return x;
}
in Rust? If it exists, post the code.
I tried it and failed. I don't know how to encode the float number using integer format. Here is my attempt:
fn main() {
println!(""Hello, world!"");
println!(""sqrt1: {}, "",sqrt2(100f64));
}
fn sqrt1(x: f64) -> f64 {
x.sqrt()
}
fn sqrt2(x: f64) -> f64 {
let mut x = x;
let xhalf = 0.5*x;
let mut i = x as i64;
println!(""sqrt1: {}, "", i);
i = 0x5f375a86 as i64 - (i>>1);
x = i as f64;
x = x*(1.5f64 - xhalf*x*x);
1.0/x
}
Reference:
1. Origin of Quake3's Fast InvSqrt() - Page 1
2. Understanding Quake’s Fast Inverse Square Root
3. FAST INVERSE SQUARE ROOT.pdf
4. source code: q_math.c#L552-L572
",https://stackoverflow.com/questions/59081890/is-it-possible-to-write-quakes-fast-invsqrt-function-in-rust,114,12393.0,4.0,,,2019-11-28 04:45:27,2024-11-28 20:04:02,2019-11-30 10:50:27,,,rust;floating-point;sqrt;type-punning,liquan.eth,1256,5067875,registered,true,,,CC BY-SA 4.0,,1479,957,2,4,0,4,false,false,false,true,true,true,68,11,true,0.323,0.0092,2550,2019,11,4,Thursday,false,false,false,false,false,false,false
24771655,What are Some and None?,"I came across some output I don't understand using Vec::get. Here's the code:
fn main() {
let command = [('G', 'H'), ('H', '5')];
for i in 0..3 {
print!(" {} ", i);
println!("{:?}", command.get(i));
}
}
the output is
0 Some(('G', 'H'))
1 Some(('H', '5'))
2 None
I've dabbled in Haskell before, and by that I mean looked at a tutorial site for 10 minutes and ran back to C++, but I remember reading something about Some and None for Haskell. I was surprised to see this here in Rust. Could someone explain why .get() returns Some or None?
",https://stackoverflow.com/questions/24771655/what-are-some-and-none,114,121327.0,5.0,,,2014-07-16 03:19:51,2023-01-08 23:55:52,2020-10-14 13:36:46,,,rust;option-type,Syntactic Fructose,20374,1409312,registered,true,24772148,,CC BY-SA 4.0,,778,592,8,0,0,2,true,false,false,true,true,true,23,5,true,0.041,0.0009,4511,2014,7,3,Wednesday,false,false,false,false,false,false,false
50650070,What does "dyn" mean in a type?,"I have recently seen code using the dyn keyword:
fn foo(arg: &dyn Display) {}
fn bar() -> Box<dyn Display> {}
What does this syntax mean?
",https://stackoverflow.com/questions/50650070/what-does-dyn-mean-in-a-type,113,30312.0,3.0,,,2018-06-01 19:39:12,2023-07-29 18:53:24,2018-06-01 23:14:46,,,syntax;rust,Shepmaster,442509,155423,registered,true,50650071,,CC BY-SA 4.0,,206,155,2,0,0,2,true,false,false,true,true,true,41,7,true,0.099,0.0037,3095,2018,6,19,Friday,false,false,false,false,false,false,false
25576748,How to compare enum without pattern matching,"I want to apply filter on an iterator and I came up with this one and it works, but it's super verbose:
.filter(|ref my_struct| match my_struct.my_enum { Unknown => false, _ => true })
I would rather write something like this:
.filter(|ref my_struct| my_struct.my_enum != Unknown)
This gives me a compile error
binary operation `!=` cannot be applied to type `MyEnum`
Is there an alternative to the verbose pattern matching? I looked for a macro but couldn't find a suitable one.
",https://stackoverflow.com/questions/25576748/how-to-compare-enum-without-pattern-matching,112,108891.0,4.0,,,2014-08-29 21:51:43,2023-02-27 21:21:25,2018-01-21 16:04:55,,,enums;pattern-matching;rust,Christoph,28643,288703,registered,true,25577080,,CC BY-SA 3.0,,647,495,4,0,0,3,true,false,false,true,true,true,44,7,false,0.037,0.001,4467,2014,8,21,Friday,false,false,false,false,false,false,false
28580386,How do I see the expanded macro code that's causing my compile error?,"I have a compile error involving a macro:
<mdo macros>:6:19: 6:50 error: cannot move out of captured outer variable in an `FnMut` closure
<mdo macros>:6 bind ( $ e , move | $ p | mdo ! { $ ( $ t ) * } ) ) ; (
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<mdo macros>:1:1: 14:36 note: in expansion of mdo!
<mdo macros>:6:27: 6:50 note: expansion site
<mdo macros>:1:1: 14:36 note: in expansion of mdo!
<mdo macros>:6:27: 6:50 note: expansion site
<mdo macros>:1:1: 14:36 note: in expansion of mdo!
src/parser.rs:30:42: 37:11 note: expansion site
error: aborting due to previous error
Unfortunately, the macro is recursive so it's hard to figure out what the compiler is complaining about, plus it seems like the line numbers are for the expanded macro rather than my code.
How can I see the expanded macro? Is there a flag I can pass to rustc (or even better, cargo) to dump this out?
(This macro is from rust-mdo, though I don't think it matters.)
",https://stackoverflow.com/questions/28580386/how-do-i-see-the-expanded-macro-code-thats-causing-my-compile-error,111,62891.0,6.0,,,2015-02-18 09:47:20,2024-12-25 10:11:20,2021-03-01 19:36:21,,,debugging;rust;rust-macros;rust-proc-macros;rust-decl-macros,Caspar,7939,775982,registered,true,37639012,,CC BY-SA 4.0,,1117,1015,1,1,0,5,true,false,false,true,true,true,73,13,true,0.095,0.0018,4294,2015,2,9,Wednesday,false,false,false,false,false,false,false
43079077,Proper way to return a new string in Rust,"I just spent a week reading the Rust Book, and now I'm working on my first program, which returns the filepath to the system wallpaper:
pub fn get_wallpaper() -> &str {
let output = Command::new(""gsettings"");
// irrelevant code
if let Ok(message) = String::from_utf8(output.stdout) {
return message;
} else {
return """";
}
}
I'm getting the error expected lifetime parameter on &str and I know Rust wants an input &str which will be returned as the output because any &str I create inside the function will be cleaned up immediately after the function ends.
I know I can sidestep the issue by returning a String instead of a &str, and many answers to similar questions have said as much. But I can also seemingly do this:
fn main() {
println!(""message: {}"", hello_string(""""));
}
fn hello_string(x: &str) -> &str {
return ""hello world"";
}
to get a &str out of my function. Can someone explain to me why this is bad and why I should never do it? Or maybe it's not bad and okay in certain situations?
",https://stackoverflow.com/questions/43079077/proper-way-to-return-a-new-string-in-rust,111,87248.0,2.0,,,2017-03-28 20:14:54,2021-10-16 17:58:39,2017-03-28 21:24:41,,,rust,eiko,5395,7470620,registered,true,43080280,,CC BY-SA 3.0,,1241,1087,8,0,0,1,true,false,false,true,true,true,41,9,false,0.023,0.0013,3525,2017,3,20,Tuesday,false,false,false,false,false,false,false
9109872,How do you access enum values in Rust?,"struct Point {
x: f64,
y: f64,
}
enum Shape {
Circle(Point, f64),
Rectangle(Point, Point),
}
let my_shape = Shape::Circle(Point { x: 0.0, y: 0.0 }, 10.0);
I want to print out circle's second property, which is 10.0 here.
I tried my_shape.last and my_shape.second, but neither worked.
What should I do in order to print out 10.0 in this case?
",https://stackoverflow.com/questions/9109872/how-do-you-access-enum-values-in-rust,110,118386.0,8.0,,,2012-02-02 09:28:14,2024-01-08 12:41:43,2018-03-27 19:30:32,,,rust,Anders Lind,4890,947301,registered,true,9112468,,CC BY-SA 3.0,,440,363,4,0,0,1,true,false,false,true,true,true,38,8,true,0.068,0.0009,5406,2012,2,9,Thursday,false,false,false,false,false,false,false
38803760,How to get a release build with debugging information when using cargo?,"The following command
$ cargo build
produces a non-optimized build with debugging information. On the contrary,
$ cargo build --release
produces an optimized build without debugging information.
Is there a way of producing an optimized build with debugging information? I need this to get meaningful profiling information.
",https://stackoverflow.com/questions/38803760/how-to-get-a-release-build-with-debugging-information-when-using-cargo,110,63611.0,4.0,,,2016-08-06 11:27:56,2025-09-26 13:16:13,,,,rust;rust-cargo,s3rvac,10589,2580955,registered,true,38804737,,CC BY-SA 3.0,,508,330,2,0,0,2,true,false,false,true,true,false,71,12,true,0.063,0.0017,3759,2016,8,11,Saturday,true,false,false,false,false,false,false
34662713,How can I create parameterized tests in Rust?,"I want to write test cases that depend on parameters. My test case should be executed for each parameter and I want to see whether it succeeds or fails for each parameter.
I'm used to writing things like that in Java:
@RunWith(Parameterized.class)
public class FibonacciTest {
@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
{ 0, 0 }, { 1, 1 }, { 2, 1 }, { 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 }
});
}
private int fInput;
private int fExpected;
public FibonacciTest(int input, int expected) {
fInput= input;
fExpected= expected;
}
@Test
public void test() {
assertEquals(fExpected, Fibonacci.compute(fInput));
}
}
How can I achieve something similar with Rust? Simple test cases are working fine, but there are cases where they are not enough.
#[test]
fn it_works() {
assert!(true);
}
Note: I want the parameters as flexible as possible, for example: Read them from a file, or use all files from a certain directory as input, etc. So a hardcoded macro might not be enough.
",https://stackoverflow.com/questions/34662713/how-can-i-create-parameterized-tests-in-rust,110,41698.0,9.0,,,2016-01-07 18:39:07,2025-10-12 00:47:02,2016-10-26 00:54:02,,,unit-testing;testing;rust,Peanut,4031,596532,registered,true,,,CC BY-SA 3.0,,1221,1145,2,0,0,3,false,false,false,true,true,true,45,8,true,0.216,0.0026,3971,2016,1,18,Thursday,false,false,false,false,false,false,false
42264041,How do I get an owned value out of a `Box`?,"What is the implementation for this function:
fn unbox<T>(value: Box<T>) -> T {
// ???
}
The only function in the documentation that looks like what I want is Box::into_raw. The following will type check:
fn unbox<T>(value: Box<T>) -> T {
*value.into_raw()
}
This gives the error error[E0133]: dereference of raw pointer requires unsafe function or block. Wrapping it in an unsafe { ... } block fixes it.
fn unbox<T>(value: Box<T>) -> T {
unsafe { *value.into_raw() }
}
Is this the correct implementation? If so, why is it unsafe? What does it mean?
Perhaps this question shows my general uncertainty of how Boxs actually work.
",https://stackoverflow.com/questions/42264041/how-do-i-get-an-owned-value-out-of-a-box,110,100341.0,1.0,,,2017-02-16 03:02:26,2022-03-29 17:46:58,2017-02-16 03:13:17,,,rust;unsafe,Calebmer,2949,1568890,registered,true,42264074,,CC BY-SA 3.0,,854,695,7,0,0,2,true,false,false,true,true,true,43,11,true,0.01,0.0011,3565,2017,2,3,Thursday,false,false,false,false,false,false,false
36335342,What do the ampersand '&' and star '*' symbols mean in Rust?,"Despite thoroughly reading the documentation, I'm rather confused about the meaning of the & and * symbol in Rust, and more generally about what is a Rust reference exactly.
In this example, it seems to be similar to a C++ reference (that is, an address that is automatically dereferenced when used):
fn main() {
let c: i32 = 5;
let rc = &c;
let next = rc + 1;
println!(""{}"", next); // 6
}
However, the following code works exactly the same:
fn main() {
let c: i32 = 5;
let rc = &c;
let next = *rc + 1;
println!(""{}"", next); // 6
}
Using * to dereference a reference wouldn't be correct in C++. So I'd like to understand why this is correct in Rust.
My understanding so far, is that, inserting * in front of a Rust reference dereferences it, but the * is implicitly inserted anyway so you don't need to add it (while in C++, it's implicitly inserted and if you insert it you get a compilation error).
However, something like this doesn't compile:
fn main() {
let mut c: i32 = 5;
let mut next: i32 = 0;
{
let rc = &mut c;
next = rc + 1;
}
println!(""{}"", next);
}
error[E0369]: binary operation `+` cannot be applied to type `&mut i32`
--> src/main.rs:6:16
|
6 | next = rc + 1;
| ^^^^^^
|
= note: this is a reference to a type that `+` can be applied to; you need to dereference this variable once for this operation to work
= note: an implementation of `std::ops::Add` might be missing for `&mut i32`
But this works:
fn main() {
let mut c: i32 = 5;
let mut next: i32 = 0;
{
let rc = &mut c;
next = *rc + 1;
}
println!(""{}"", next); // 6
}
It seems that implicit dereferencing (a la C++) is correct for immutable references, but not for mutable references. Why is this?
",https://stackoverflow.com/questions/36335342/what-do-the-ampersand-and-star-symbols-mean-in-rust,110,57140.0,3.0,,,2016-03-31 13:48:39,2022-10-01 15:02:34,2022-10-01 15:02:34,,,rust;syntax;reference;dereference,John Smith Optional,25596,1126971,registered,true,36335679,,CC BY-SA 4.0,,2134,1854,10,0,0,4,true,false,false,true,true,true,80,12,true,0.053,0.0019,3887,2016,3,13,Thursday,false,false,false,false,false,false,false
38215753,How do I implement Copy and Clone for a type that contains a String (or any type that doesn't implement Copy)?,"I have an enum in Rust which has one value that takes a String:
#[derive(Clone, Copy)]
enum Simple {
Error(String),
Okay,
Foo([u32; 5]),
}
fn main() {
let x = Simple::Error(String::from(""blah""));
let y = x.clone();
}
The enum value Foo above represents about 10 other enums I use that take copyable types or arrays of them. The compiler doesn't seem to complain about them, only the Error(String) which causes this:
error[E0204]: the trait `Copy` may not be implemented for this type
--> src/main.rs:1:17
|
1 | #[derive(Clone, Copy)]
| ^^^^
2 | enum Simple {
3 | Error(String),
| ------ this field does not implement `Copy`
|
For some reason, String is not copyable. I don't get this. How do I implement Clone for an enum for just the one type which has a problem while using the default impl for the rest?
",https://stackoverflow.com/questions/38215753/how-do-i-implement-copy-and-clone-for-a-type-that-contains-a-string-or-any-type,110,73804.0,2.0,,,2016-07-06 03:01:56,2022-02-12 10:53:04,2020-04-28 19:51:26,,,rust,locka,6099,273924,registered,true,38216027,,CC BY-SA 4.0,,1049,876,7,0,0,1,true,false,false,true,true,true,114,21,true,0.027,0.0015,3790,2016,7,3,Wednesday,false,false,false,false,false,false,false
47618823,Cannot borrow as mutable because it is also borrowed as immutable,"I am learning Rust and I don't quite get why this is not working.
#[derive(Debug)]
struct Node {
value: String,
}
#[derive(Debug)]
pub struct Graph {
nodes: Vec<Box<Node>>,
}
fn mk_node(value: String) -> Node {
Node { value }
}
pub fn mk_graph() -> Graph {
Graph { nodes: vec![] }
}
impl Graph {
fn add_node(&mut self, value: String) {
if let None = self.nodes.iter().position(|node| node.value == value) {
let node = Box::new(mk_node(value));
self.nodes.push(node);
};
}
fn get_node_by_value(&self, value: &str) -> Option<&Node> {
match self.nodes.iter().position(|node| node.value == *value) {
None => None,
Some(idx) => self.nodes.get(idx).map(|n| &**n),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn some_test() {
let mut graph = mk_graph();
graph.add_node(""source"".to_string());
graph.add_node(""destination"".to_string());
let source = graph.get_node_by_value(""source"").unwrap();
let dest = graph.get_node_by_value(""destination"").unwrap();
graph.add_node(""destination"".to_string());
}
}
This has the error
error[E0502]: cannot borrow `graph` as mutable because it is also borrowed as immutable
--> src/main.rs:50:9
|
47 | let source = graph.get_node_by_value(""source"").unwrap();
| ----- immutable borrow occurs here
...
50 | graph.add_node(""destination"".to_string());
| ^^^^^ mutable borrow occurs here
51 | }
| - immutable borrow ends here
This example from Programming Rust is quite similar to what I have but it works:
pub struct Queue {
older: Vec<char>, // older elements, eldest last.
younger: Vec<char>, // younger elements, youngest last.
}
impl Queue {
/// Push a character onto the back of a queue.
pub fn push(&mut self, c: char) {
self.younger.push(c);
}
/// Pop a character off the front of a queue. Return `Some(c)` if there /// was a character to pop, or `None` if the queue was empty.
pub fn pop(&mut self) -> Option<char> {
if self.older.is_empty() {
if self.younger.is_empty() {
return None;
}
// Bring the elements in younger over to older, and put them in // the promised order.
use std::mem::swap;
swap(&mut self.older, &mut self.younger);
self.older.reverse();
}
// Now older is guaranteed to have something. Vec's pop method // already returns an Option, so we're set.
self.older.pop()
}
pub fn split(self) -> (Vec<char>, Vec<char>) {
(self.older, self.younger)
}
}
pub fn main() {
let mut q = Queue {
older: Vec::new(),
younger: Vec::new(),
};
q.push('P');
q.push('D');
assert_eq!(q.pop(), Some('P'));
q.push('X');
let (older, younger) = q.split(); // q is now uninitialized.
assert_eq!(older, vec!['D']);
assert_eq!(younger, vec!['X']);
}
",https://stackoverflow.com/questions/47618823/cannot-borrow-as-mutable-because-it-is-also-borrowed-as-immutable,109,119045.0,3.0,,,2017-12-03 13:24:28,2023-10-16 02:30:05,2018-03-11 21:34:51,,,reference;rust,Shulhi Sapli,2536,588611,registered,true,47619305,,CC BY-SA 3.0,,3467,3202,3,1,0,2,true,false,false,true,true,true,65,11,false,0.025,0.0009,3275,2017,12,13,Sunday,true,false,false,false,false,false,false
49510965,How to not do anything on the "rest case" when matching a string?,"I have a string where I want to check if it's a semicolon, comma or colon. If it's not any of those, I don't want to do anything:
match token.as_ref() {
"";"" => semicolons += 1,
"","" => commas += 1,
"":"" => colons += 1,
_ => println!(""""),
}
This works, but I don't really want to print a bunch of empty lines (cause a lot of the tokens don't match these criteria).
What would be the most correct way to solve this?
",https://stackoverflow.com/questions/49510965/how-to-not-do-anything-on-the-rest-case-when-matching-a-string,109,82988.0,1.0,,,2018-03-27 10:50:48,2023-04-29 12:09:04,2018-03-27 10:55:03,,,rust,kycklingsylt,1249,7574198,registered,true,49511205,,CC BY-SA 3.0,,490,445,1,0,0,1,true,false,false,true,true,true,75,13,true,0.012,0.0013,3161,2018,3,10,Tuesday,false,false,false,false,false,false,false
25413201,How do I implement a trait I don't own for a type I don't own?,"I wanted to implement the Shl trait for Vec, the code is below. This would make things like vec << 4 possible, which would be nice sugar for vec.push(4).
use std::ops::Shl;
impl<T> Shl<T> for Vec<T> {
type Output = Vec<T>;
fn shl(&self, elem: &T) -> Vec<T> {
self.push(*elem);
*self
}
}
fn main() {
let v = vec![1, 2, 3];
v << 4;
}
The compilation fails with the following error:
cannot provide an extension implementation where both trait and type are not defined in this crate [E0117]
or
type parameter T must be used as the type parameter for some local type (e.g. MyStruct<T>); only traits defined in the current crate can be implemented for a type parameter [E0210]
As I understand it, I'd have to patch the stdlib, more specifically the collections::vec crate. Is there another way to change this code to compile successfully?
",https://stackoverflow.com/questions/25413201/how-do-i-implement-a-trait-i-dont-own-for-a-type-i-dont-own,109,45993.0,3.0,,,2014-08-20 19:45:19,2022-11-09 08:53:02,2016-06-24 14:18:22,,,rust;traits,le_me,3509,1477992,registered,true,25415289,,CC BY-SA 3.0,,1153,946,8,0,0,2,true,false,false,true,true,true,70,15,true,0.065,0.0024,4476,2014,8,19,Wednesday,false,false,false,false,false,false,false
24145823,How do I convert a C string into a Rust string and back via FFI?,"I'm trying to get a C string returned by a C library and convert it to a Rust string via FFI.
mylib.c
const char* hello(){
return "Hello World!";
}
main.rs
#![feature(link_args)]
extern crate libc;
use libc::c_char;
#[link_args = "-L . -I . -lmylib"]
extern {
fn hello() -> *c_char;
}
fn main() {
//how do I get a str representation of hello() here?
}
",https://stackoverflow.com/questions/24145823/how-do-i-convert-a-c-string-into-a-rust-string-and-back-via-ffi,109,88834.0,2.0,,,2014-06-10 16:07:45,2024-06-21 10:33:54,2024-06-21 10:33:54,,,c;ffi;rust,Dirk,2154,1833511,registered,true,24148033,,CC BY-SA 4.0,,534,392,2,0,0,3,true,false,false,true,true,true,64,15,true,0.023,0.0012,4547,2014,6,16,Tuesday,false,false,false,false,false,false,false
35711044,How can I specify binary-only dependencies?,"I have a crate with both a binary and a library. The library is extremely light on dependencies, while the binary requires quite a bit more to, e.g., load files or do scoped parallel things.
Currently, I have my Cargo.toml set up like this:
[dependencies.kdtree]
path = ""../kdtree""
[dependencies]
rand=""0.3.0""
rustc-serialize = ""0.3""
csv = {git = ""https://github.com/BurntSushi/rust-csv.git""}
crossbeam = ""0.2""
num_cpus = ""0.2""
[lib]
name = ""conformal""
path = ""src/lib.rs""
[[bin]]
name = ""ucitest""
path = ""src/bin/main.rs""
The only dependencies the library needs are the kdtree and rand. However, it seems like even if you only build the library, it goes and builds the binary-only dependencies anyway. I've tried using features and other tricks like [[bin].dependencies] or [ucitest-dependencies] (or adding a dependencies= [] line under [[bin]]) that I thought might make them only build for the binary, but I can't find a way.
These aren't enough dependencies to make this a problem, but it's bothering me. Is there a way to narrow down dependencies so they only build for specific binaries?
",https://stackoverflow.com/questions/35711044/how-can-i-specify-binary-only-dependencies,109,41625.0,3.0,,,2016-02-29 22:31:33,2023-10-14 13:01:20,2019-06-24 18:23:37,,,rust;rust-cargo,Linear,22616,901827,registered,true,46017284,,CC BY-SA 4.0,,1246,1103,8,0,0,2,true,false,false,true,true,true,43,6,true,0.072,0.0026,3918,2016,2,22,Monday,false,false,false,false,false,false,false
26435102,"In Rust, what is the purpose of a mod.rs file?","In some Rust projects I've seen (i.e pczarn/rustboot), I've seen mod.rs files in directories for whatever reason. I've not been able to find documentation about this, and I've seen it in many other Rust projects.
What is the purpose of a mod.rs file, and when should I use it?
",https://stackoverflow.com/questions/26435102/in-rust-what-is-the-purpose-of-a-mod-rs-file,108,75746.0,3.0,,,2014-10-18 00:18:22,2024-12-07 10:55:42,,,,module;rust,Liam Marshall,1753,3420512,registered,true,26435155,,CC BY-SA 3.0,,363,277,1,1,0,2,true,false,false,true,true,false,46,10,true,0.04,0.0014,4417,2014,10,0,Saturday,true,false,false,false,false,false,false
29461693,How can I get cargo to recompile changed files automatically?,"I have heard cargo has the ability to automatically recompile changed source files, but I'm having a hard time figuring out how to tell it to do so.
For now, I am manually running cargo build or cargo run every time I want to type check my code. I would prefer to instead simply save the file and see the results in the neighboring terminal window.
In case you still have no idea what I'm talking about, I'm looking for the cargo equivalent of sbt ~compile or sbt ~run.
It seems strangely hard to find, so I'm starting to wonder if it's really supported. It's possible someone had said cargo could detect changed files and recompile them when what he meant to say was that cargo could detect unchanged files and avoid recompiling them, like make.
",https://stackoverflow.com/questions/29461693/how-can-i-get-cargo-to-recompile-changed-files-automatically,108,50109.0,7.0,,,2015-04-05 20:09:18,2025-08-02 14:00:44,2015-04-05 20:15:30,,,rust;rust-cargo,aij,6729,2343847,registered,true,38117745,,CC BY-SA 3.0,,861,750,5,0,0,2,true,false,false,true,true,true,61,10,true,0.14,0.0022,4248,2015,4,20,Sunday,true,false,false,false,false,false,false
40848918,Are there queue and stack collections in Rust?,"If we need FIFO or LIFO collections (with basically push, pop and front/back) what should we use in Rust? Something like std::queue or std::stack from C++.
",https://stackoverflow.com/questions/40848918/are-there-queue-and-stack-collections-in-rust,108,81327.0,3.0,,,2016-11-28 16:17:57,2023-08-31 18:39:02,2020-02-16 01:04:17,,,rust,Boiethios,44012,4498831,registered,true,40851723,,CC BY-SA 4.0,,241,156,6,0,0,1,true,false,false,true,true,true,46,8,true,0.037,0.0013,3645,2016,11,16,Monday,false,false,false,false,false,false,false
27182808,How do I get an absolute value in Rust?,"The docs are unhelpful: http://web.mit.edu/rust-lang_v0.9/doc/std/num/fn.abs.html
Obviously, I can see the function right there, but I haven't got the faintest idea how to call it.
Edit:
The problem is that it doesn't work. :)
use std::num;
let x = num::abs(value);
"Unresolved name: num::abs"
Edit 2: running the nightly from yesterday (11/26/2014); I don't know what version. I didn't realize those docs were so outdated. oO
Current docs seem to indicate there is no such function?
",https://stackoverflow.com/questions/27182808/how-do-i-get-an-absolute-value-in-rust,107,119273.0,7.0,,,2014-11-28 06:05:21,2024-03-25 14:47:56,2021-02-19 20:53:42,,,rust,user1949917,,,does_not_exist,true,27183279,,CC BY-SA 4.0,,666,495,1,1,0,1,true,false,false,true,false,true,39,9,true,0.059,0.0009,4376,2014,11,6,Friday,false,false,false,false,false,false,false
42551113,Is it possible to conditionally enable an attribute like `derive`?,"I have added a feature in my crate which adds serde support. However, I don't quite understand how to use it properly:
// #[derive(Debug, Serialize, Deserialize, Clone)] // goes to:
#[derive(Debug, Clone)]
#[cfg(feature = ""serde_support"")]
#[derive(Serialize, Deserialize)]
pub struct MyStruct;
This code treats everything below cfg(feature) as conditionally compiled, so without my serde_support feature my crate does not have MyStruct also.
I have tried to wrap it with braces but it gives another error:
Code:
#[derive(Debug, Clone)]
#[cfg(feature = ""serde_support"")] {
#[derive(Serialize, Deserialize)]
}
pub struct MyStruct;
Error:
error: expected item after attributes
--> mycrate/src/lib.rs:65:33
|
65 | #[cfg(feature = ""serde_support"")] {
| ^
So how to do this?
",https://stackoverflow.com/questions/42551113/is-it-possible-to-conditionally-enable-an-attribute-like-derive,107,26429.0,1.0,,,2017-03-02 09:12:11,2018-08-01 13:11:03,2018-08-01 13:11:03,,,rust,VP.,17145,1750757,registered,true,42551386,,CC BY-SA 4.0,,1030,825,7,0,0,1,true,false,false,true,true,true,66,10,true,0.038,0.004,3551,2017,3,9,Thursday,false,false,false,false,false,false,false
42584368,How do you define custom `Error` types in Rust?,"I'm writing a function that could return several one of several different errors.
fn foo(...) -> Result<..., MyError> {}
I'll probably need to define my own error type to represent such errors. I'm presuming it would be an enum of possible errors, with some of the enum variants having diagnostic data attached to them:
enum MyError {
GizmoError,
WidgetNotFoundError(widget_name: String)
}
Is that the most idiomatic way to go about it? And how do I implement the Error trait?
",https://stackoverflow.com/questions/42584368/how-do-you-define-custom-error-types-in-rust,107,90857.0,3.0,,,2017-03-03 16:49:35,2022-01-04 15:57:27,2017-03-03 16:53:12,,,error-handling;rust,Jo Liss,34046,525872,registered,true,42584607,,CC BY-SA 3.0,,608,500,5,0,0,2,true,false,false,true,true,true,47,9,true,0.033,0.0012,3550,2017,3,16,Friday,false,false,false,false,false,false,false
28392008,Is there a more concise or declarative way to initialize a HashMap?,"I'm using a HashMap to count the occurrences of different characters in a string:
let text = ""GATTACA"";
let mut counts: HashMap<char, i32> = HashMap::new();
counts.insert('A', 0);
counts.insert('C', 0);
counts.insert('G', 0);
counts.insert('T', 0);
for c in text.chars() {
match counts.get_mut(&c) {
Some(x) => *x += 1,
None => (),
}
}
Is there a more concise or declarative way to initialize a HashMap? For example in Python I would do:
counts = { 'A': 0, 'C': 0, 'G': 0, 'T': 0 }
or
counts = { key: 0 for key in 'ACGT' }
",https://stackoverflow.com/questions/28392008/is-there-a-more-concise-or-declarative-way-to-initialize-a-hashmap,106,61688.0,4.0,,,2015-02-08 08:28:15,2022-05-22 08:59:26,2022-05-22 08:59:26,2022-05-22 17:46:15,Duplicate,rust;hashmap,anderspitman,10870,943814,registered,true,28392068,,,,691,572,5,0,0,2,true,true,false,true,true,true,67,12,true,0.065,0.0017,4304,2015,2,8,Sunday,true,false,false,false,false,false,false
45674479,Need holistic explanation about Rust's cell and reference counted types,"There are several wrapper types in the Rust standard library:
- The cells in the
std::cell module: Cell and RefCell
- The reference-counted wrappers, like
Rc and Arc.
- The types in the
std::sync module: Mutex or AtomicBool for example
As I understand it, these are wrappers which provide further possibilities than a simple reference. While I understand some basics, I cannot see the whole picture.
What do they do exactly? Do cells and reference-counted families provide orthogonal or similar features?
",https://stackoverflow.com/questions/45674479/need-holistic-explanation-about-rusts-cell-and-reference-counted-types,105,12729.0,2.0,,,2017-08-14 12:23:47,2023-01-26 13:52:03,2018-06-05 13:40:27,,,rust,Boiethios,44012,4498831,registered,true,45674912,,CC BY-SA 4.0,2017-08-16 13:35:02,1338,505,8,8,0,1,true,false,false,true,true,true,75,10,false,0.157,0.0082,3386,2017,8,12,Monday,false,false,false,false,false,false,false
39803237,Build HashSet from a vector in Rust,"I want to build a HashSet<u8> from a Vec<u8>. I'd like to do this
- in one line of code,
- copying the data only once,
- using only
2n memory,
but the only thing I can get to compile is this piece of .. junk, which I think copies the data twice and uses 3n memory.
fn vec_to_set(vec: Vec<u8>) -> HashSet<u8> {
let mut victim = vec.clone();
let x: HashSet<u8> = victim.drain(..).collect();
return x;
}
I was hoping to write something simple, like this:
fn vec_to_set(vec: Vec<u8>) -> HashSet<u8> {
return HashSet::from_iter(vec.iter());
}
but that won't compile:
error[E0308]: mismatched types
--> <anon>:5:12
|
5 | return HashSet::from_iter(vec.iter());
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected u8, found &u8
|
= note: expected type `std::collections::HashSet<u8>`
= note: found type `std::collections::HashSet<&u8, _>`
.. and I don't really understand the error message, probably because I need to RTFM.
",https://stackoverflow.com/questions/39803237/build-hashset-from-a-vector-in-rust,105,79070.0,4.0,,,2016-10-01 05:08:46,2025-05-27 10:15:10,2016-10-03 02:02:32,,,vector;rust;hashset,Jared Beck,17778,567762,registered,true,39804262,,CC BY-SA 3.0,,1270,1036,7,0,0,3,true,false,false,true,true,true,35,7,false,0.051,0.0013,3703,2016,10,5,Saturday,true,false,false,false,false,false,false
22282117,How do I borrow a reference to what is inside an Option<T>?,"How do I pull a reference out of an Option and pass it back with the specific lifespan of the caller?
Specifically, I want to borrow a reference to a Box<Foo> from a Bar that has an Option<Box<Foo>> in it. I thought I would be able to do:
impl Bar {
fn borrow(&mut self) -> Result<&Box<Foo>, BarErr> {
match self.data {
Some(e) => Ok(&e),
None => Err(BarErr::Nope),
}
}
}
...but that results in:
error: `e` does not live long enough
--> src/main.rs:17:28
|
17 | Some(e) => Ok(&e),
| ^ does not live long enough
18 | None => Err(BarErr::Nope),
19 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the anonymous lifetime #1 defined on the body at 15:54...
--> src/main.rs:15:55
|
15 | fn borrow(&mut self) -> Result<&Box<Foo>, BarErr> {
| _______________________________________________________^ starting here...
16 | | match self.data {
17 | | Some(e) => Ok(&e),
18 | | None => Err(BarErr::Nope),
19 | | }
20 | | }
| |_____^ ...ending here
error[E0507]: cannot move out of borrowed content
--> src/main.rs:16:15
|
16 | match self.data {
| ^^^^ cannot move out of borrowed content
17 | Some(e) => Ok(&e),
| - hint: to prevent move, use `ref e` or `ref mut e`
Hm, ok. Maybe not. It looks vaguely like what I want to do is related to Option::as_ref, like maybe I could do:
impl Bar {
fn borrow(&mut self) -> Result<&Box<Foo>, BarErr> {
match self.data {
Some(e) => Ok(self.data.as_ref()),
None => Err(BarErr::Nope),
}
}
}
...but, that doesn't work either.
Full code I'm having trouble with:
#[derive(Debug)]
struct Foo;
#[derive(Debug)]
struct Bar {
data: Option<Box<Foo>>,
}
#[derive(Debug)]
enum BarErr {
Nope,
}
impl Bar {
fn borrow(&mut self) -> Result<&Box<Foo>, BarErr> {
match self.data {
Some(e) => Ok(&e),
None => Err(BarErr::Nope),
}
}
}
#[test]
fn test_create_indirect() {
let mut x = Bar { data: Some(Box::new(Foo)) };
let mut x2 = Bar { data: None };
{
let y = x.borrow();
println!(""{:?}"", y);
}
{
let z = x2.borrow();
println!(""{:?}"", z);
}
}
I'm reasonably sure what I've trying to do is valid here.
",https://stackoverflow.com/questions/22282117/how-do-i-borrow-a-reference-to-what-is-inside-an-optiont,105,55149.0,2.0,,,2014-03-09 12:22:29,2020-03-24 14:14:07,2017-03-16 14:03:44,,,rust,Doug,35764,353820,registered,true,22283089,,CC BY-SA 3.0,,3013,2665,9,1,0,1,true,false,false,true,true,true,65,12,true,0.036,0.0019,4640,2014,3,12,Sunday,true,false,false,false,false,false,false
50458144,What is the easiest way to pad a string with 0 to the left?,"What is the easiest way to pad a string with 0 to the left so that
""110"" = ""00000110""
""11110000"" = ""11110000""
I have tried to use the format! macro but it only pads to the right with space:
format!(""{:08}"", string);
",https://stackoverflow.com/questions/50458144/what-is-the-easiest-way-to-pad-a-string-with-0-to-the-left,104,83316.0,2.0,,,2018-05-22 00:21:31,2019-06-07 08:50:15,2019-02-05 12:00:18,,,rust;formatting;string-formatting;number-formatting,SeaEyeHay,1263,9746592,registered,true,50458236,,CC BY-SA 4.0,,314,222,2,0,0,4,true,false,false,true,true,true,59,14,true,0.024,0.0012,3105,2018,5,0,Tuesday,false,false,false,false,false,false,false
25818082,Vector of objects belonging to a trait,"Consider the following code:
trait Animal {
fn make_sound(&self) -> String;
}
struct Cat;
impl Animal for Cat {
fn make_sound(&self) -> String {
"meow".to_string()
}
}
struct Dog;
impl Animal for Dog {
fn make_sound(&self) -> String {
"woof".to_string()
}
}
fn main () {
let dog: Dog = Dog;
let cat: Cat = Cat;
let v: Vec<Animal> = Vec::new();
v.push(cat);
v.push(dog);
for animal in v.iter() {
println!("{}", animal.make_sound());
}
}
The compiler tells me that v is a vector of Animal when I try to push cat (type mismatch)
So, how can I make a vector of objects belonging to a trait and calls the corresponding trait method on each element?
",https://stackoverflow.com/questions/25818082/vector-of-objects-belonging-to-a-trait,104,59895.0,3.0,,,2014-09-12 23:02:57,2026-07-23 02:35:16,2022-09-30 04:45:09,,,polymorphism;rust,Jacob Wang,4944,2036669,registered,true,74974361,,CC BY-SA 4.0,,900,777,4,0,0,2,true,false,false,true,true,true,38,7,false,0.05,0.0017,4453,2014,9,23,Friday,false,false,false,false,false,false,false
28951503,How can I create a function with a variable number of arguments?,"How can I create a function with a variable number of arguments in Rust?
Like this Java code:
void foo(String... args) {
for (String arg : args) {
System.out.println(arg);
}
}
",https://stackoverflow.com/questions/28951503/how-can-i-create-a-function-with-a-variable-number-of-arguments,104,65282.0,3.0,,,2015-03-09 20:51:02,2019-08-12 01:23:17,2015-03-09 20:56:49,,,rust;variadic-functions,Tiago,3211,1091424,registered,true,28951583,,CC BY-SA 3.0,,233,195,1,0,0,2,true,false,false,true,true,true,64,12,true,0.046,0.0016,4275,2015,3,20,Monday,false,false,false,false,false,false,false
25296195,Why are recursive struct types illegal in Rust?,"I'm trying out random things to deepen my understanding of Rust. I just ran into the following error with this code:
struct Person {
mother: Option<Person>,
father: Option<Person>,
partner: Option<Person>,
}
pub fn main() {
let susan = Person {
mother: None,
father: None,
partner: None,
};
let john = Person {
mother: None,
father: None,
partner: Some(susan),
};
}
error[E0072]: recursive type `Person` has infinite size
--> src/main.rs:1:1
|
1 | struct Person {
| ^^^^^^^^^^^^^ recursive type has infinite size
2 | mother: Option<Person>,
| ---------------------- recursive without indirection
3 | father: Option<Person>,
| ---------------------- recursive without indirection
4 | partner: Option<Person>,
| ----------------------- recursive without indirection
|
= help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `Person` representable
I understand that I can fix it if I put the Person in a Box, so this works:
struct Person {
mother: Option<Box<Person>>,
father: Option<Box<Person>>,
partner: Option<Box<Person>>,
}
pub fn main() {
let susan = Person {
mother: None,
father: None,
partner: None,
};
let john = Person {
mother: None,
father: None,
partner: Some(Box::new(susan)),
};
}
I would like to understand the full story behind that. I know that boxing means that it will be stored on the heap rather than the stack but I don't get why this indirection is necessary.
",https://stackoverflow.com/questions/25296195/why-are-recursive-struct-types-illegal-in-rust,103,38201.0,3.0,,,2014-08-13 21:10:02,2022-10-19 19:58:31,2018-01-10 03:26:07,,,rust,Christoph,28643,288703,registered,true,25296420,,CC BY-SA 3.0,,2254,1705,5,4,0,1,true,false,false,true,true,true,47,8,true,0.079,0.0027,4483,2014,8,21,Wednesday,false,false,false,false,false,false,false
27904864,What does "cannot move out of index of" mean?,"I am playing with Rust, and I'm trying to access the first command line argument with this code:
use std::env;
fn main() {
let args: Vec<_> = env::args().collect();
let dir = args[1];
}
And I get this error:
error[E0507]: cannot move out of indexed content
--> src/main.rs:5:15
|
5 | let dir = args[1];
| --- ^^^^^^^ cannot move out of indexed content
| |
| hint: to prevent move, use `ref dir` or `ref mut dir`
Or in later versions of Rust:
error[E0507]: cannot move out of index of `std::vec::Vec<std::string::String>`
--> src/main.rs:5:15
|
5 | let dir = args[1];
| ^^^^^^^
| |
| move occurs because value has type `std::string::String`, which does not implement the `Copy` trait
| help: consider borrowing here: `&args[1]`
If I change it to let ref dir, it compiles, but I don't grok what's going on. Could someone explain what ""indexed content"" means?
",https://stackoverflow.com/questions/27904864/what-does-cannot-move-out-of-index-of-mean,103,42637.0,2.0,,,2015-01-12 14:59:29,2023-02-13 07:25:46,2019-10-23 14:04:37,,,rust,Amandasaurus,61767,161922,registered,true,27905403,,CC BY-SA 4.0,,1255,1007,4,1,0,1,true,false,false,true,true,true,55,9,true,0.047,0.0024,4331,2015,1,14,Monday,false,false,false,false,false,false,false
16946888,Is it possible to make a recursive closure in Rust?,"This is a very simple example, but how would I do something similar to:
let fact = |x: u32| {
match x {
0 => 1,
_ => x * fact(x - 1),
}
};
I know that this specific example can be easily done with iteration, but I'm wondering if it's possible to make a recursive function in Rust for more complicated things (such as traversing trees) or if I'm required to use my own stack instead.
",https://stackoverflow.com/questions/16946888/is-it-possible-to-make-a-recursive-closure-in-rust,103,38734.0,5.0,,,2013-06-05 18:05:58,2023-06-05 11:40:29,2016-08-12 13:02:51,,,recursion;closures;rust,Undeterminant,1408,1104684,registered,true,16953239,,CC BY-SA 3.0,,454,416,1,0,0,3,true,false,false,true,true,true,51,10,true,0.129,0.0027,4917,2013,6,18,Wednesday,false,false,false,false,false,false,false
50704279,When or why should I use a Mutex over an RwLock?,"When I read the documentations of Mutex and RwLock, the difference I see is the following:
Mutex can have only one reader or writer at a time,
RwLock can have one writer or multiple readers at a time.
When you put it that way, RwLock seems always better (less limited) than Mutex, why would I use it, then?
",https://stackoverflow.com/questions/50704279/when-or-why-should-i-use-a-mutex-over-an-rwlock,103,42817.0,2.0,,,2018-06-05 15:52:04,2022-09-17 14:50:06,2022-09-17 14:50:06,,,multithreading;rust;mutex;readwritelock,Boiethios,44012,4498831,registered,true,,,CC BY-SA 4.0,,597,309,6,2,0,4,false,false,false,true,true,true,48,11,true,0.047,0.0024,3091,2018,6,15,Tuesday,false,false,false,false,false,false,false
65553557,Why rust is failing to build command for openssl-sys v0.9.60 even after local installation?,"I'm facing the error failed to run custom build command for openssl-sys v0.9.60 while trying to build my rust program. Here are the main.rs and the Cargo.toml files.
main.rs
extern crate reqwest;
fn main() {
let mut resp = reqwest::get("http://www.governo.mg.gov.br/Institucional/Equipe").unwrap();
assert!(resp.status().is_success());
}
Cargo.toml
[package]
name = "get_sct"
version = "0.1.0"
authors = ["myname <myemail>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
reqwest = "0.10.10"
I installed openssl locally (as suggested in this question), using:
git clone git://git.openssl.org/openssl.git
cd openssl
./config --openssldir=/usr/local/ssl
make
make test
sudo make install
Finally, I ran export OPENSSL_DIR="/usr/local/ssl"
I noted I already had a anaconda instalation of openssl which was in my default path. To change the default path of openssl to the github instalation I ran chmod -x MYPATH/anaconda3/bin/openssl and now which openssl returns /usr/local/bin/openssl.
I also have pkg-config installed (as suggested in this question). Running which pkg-config returns /usr/bin/pkg-config
However, when I run cargo run again the program print the same error message. Here is the entire error message:
> cargo run
Compiling openssl-sys v0.9.60
Compiling tokio v0.2.24
Compiling pin-project-internal v0.4.27
Compiling pin-project-internal v1.0.2
Compiling mime_guess v2.0.3
Compiling url v2.2.0
error: failed to run custom build command for `openssl-sys v0.9.60`
Caused by:
process didn't exit successfully: `/PACKAGEPATH/target/debug/build/openssl-sys-db18d493257de4f7/build-script-main` (exit code: 101)
--- stdout
cargo:rustc-cfg=const_fn
cargo:rerun-if-env-changed=X86_64_UNKNOWN_LINUX_GNU_OPENSSL_LIB_DIR
X86_64_UNKNOWN_LINUX_GNU_OPENSSL_LIB_DIR unset
cargo:rerun-if-env-changed=OPENSSL_LIB_DIR
OPENSSL_LIB_DIR unset
cargo:rerun-if-env-changed=X86_64_UNKNOWN_LINUX_GNU_OPENSSL_INCLUDE_DIR
X86_64_UNKNOWN_LINUX_GNU_OPENSSL_INCLUDE_DIR unset
cargo:rerun-if-env-changed=OPENSSL_INCLUDE_DIR
OPENSSL_INCLUDE_DIR unset
cargo:rerun-if-env-changed=X86_64_UNKNOWN_LINUX_GNU_OPENSSL_DIR
X86_64_UNKNOWN_LINUX_GNU_OPENSSL_DIR unset
cargo:rerun-if-env-changed=OPENSSL_DIR
OPENSSL_DIR = /usr/local/ssl
--- stderr
thread 'main' panicked at 'OpenSSL library directory does not exist: /usr/local/ssl/lib', /home/lucas/.cargo/registry/src/github.com-1ecc6299db9ec823/openssl-sys-0.9.60/build/main.rs:66:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
warning: build failed, waiting for other jobs to finish...
error: build faile
It looks like that rust is searching for ssl in /usr/local/ssl/lib. In fact, there is a /usr/local/ssl folder in my PC, but there is no lib there.
What am I doing wrong here? How can make my local installation of openssl work with rust correctly?
",https://stackoverflow.com/questions/65553557/why-rust-is-failing-to-build-command-for-openssl-sys-v0-9-60-even-after-local-in,102,112564.0,18.0,,,2021-01-03 18:41:59,2025-02-04 00:16:07,2021-01-03 19:45:52,,,rust;openssl,Lucas,1612,9381966,registered,true,65554916,,CC BY-SA 4.0,,3743,3039,17,2,0,2,true,false,false,true,true,true,91,14,true,0.16,0.0009,2148,2021,1,18,Sunday,true,false,false,false,false,false,false
24253344,Is it possible to make a type only movable and not copyable?,"
Editor's note: this question was asked before Rust 1.0 and some of the assertions in the question are not necessarily true in Rust 1.0. Some answers have been updated to address both versions.
I have this struct
struct Triplet {
one: i32,
two: i32,
three: i32,
}
If I pass this to a function, it is implicitly copied. Now, sometimes I read that some values are not copyable and therefore have to moved.
Would it be possible to make this struct Triplet non-copyable? For example, would it be possible to implement a trait which would make Triplet non-copyable and therefore ""movable""?
I read somewhere that one has to implement the Clone trait to copy things that are not implicitly copyable, but I never read about the other way around, that is having something that is implicitly copyable and making it non-copyable so that it moves instead.
Does that even make any sense?
",https://stackoverflow.com/questions/24253344/is-it-possible-to-make-a-type-only-movable-and-not-copyable,101,28805.0,2.0,,,2014-06-16 22:47:05,2018-02-12 00:36:33,2018-02-12 00:36:33,,,rust,Christoph,28643,288703,registered,true,24253573,,CC BY-SA 3.0,,1037,898,4,0,0,1,true,false,false,true,true,true,60,12,true,0.069,0.0035,4541,2014,6,22,Monday,false,false,false,false,false,false,false
19671845,How can I generate a random number within a range in Rust?,"
Editor's note: This code example is from a version of Rust prior to 1.0 and is not syntactically valid Rust 1.0 code. Updated versions of this code produce different errors, but the answers still contain valuable information.
I came across the following example of how to generate a random number using Rust, but it doesn't appear to work. The example doesn't show which version of Rust it applies to, so perhaps it is out-of-date, or perhaps I got something wrong.
// http://static.rust-lang.org/doc/master/std/rand/trait.Rng.html
use std::rand;
use std::rand::Rng;
fn main() {
let mut rng = rand::task_rng();
let n: uint = rng.gen_range(0u, 10);
println!(""{}"", n);
let m: float = rng.gen_range(-40.0, 1.3e5);
println!(""{}"", m);
}
When I attempt to compile this, the following error results:
test_rand002.rs:6:17: 6:39 error: type `@mut std::rand::IsaacRng` does not
implement any method in scope named `gen_range`
test_rand002.rs:6 let n: uint = rng.gen_range(0u, 10);
^~~~~~~~~~~~~~~~~~~~~~
test_rand002.rs:8:18: 8:46 error: type `@mut std::rand::IsaacRng` does not
implement any method in scope named `gen_range`
test_rand002.rs:8 let m: float = rng.gen_range(-40.0, 1.3e5);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~
There is another example (as follows) on the same page (above) that does work. However, it doesn't do exactly what I want, although I could adapt it.
use std::rand;
use std::rand::Rng;
fn main() {
let mut rng = rand::task_rng();
let x: uint = rng.gen();
println!(""{}"", x);
println!(""{:?}"", rng.gen::<(f64, bool)>());
}
How can I generate a ""simple"" random number using Rust (e.g.: i64) within a given range (e.g.: 0 to n)?
",https://stackoverflow.com/questions/19671845/how-can-i-generate-a-random-number-within-a-range-in-rust,101,154749.0,5.0,,,2013-10-30 00:47:21,2025-02-09 20:27:03,2019-04-15 15:21:21,,,random;rust;rust-obsolete,Brian Oh,10970,1949390,registered,true,19674981,,CC BY-SA 4.0,,1951,1767,4,0,0,3,true,false,false,true,true,true,58,12,true,0.032,0.0007,4770,2013,10,0,Wednesday,false,false,false,false,false,false,false
30450399,Does println! borrow or own the variable?,"I am confused with borrowing and ownership. In the Rust documentation about reference and borrowing
let mut x = 5;
{
let y = &mut x;
*y += 1;
}
println!(""{}"", x);
They say
println! can borrow x.
I am confused by this. If println! borrows x, why does it pass x not &x?
I try to run this code below
fn main() {
let mut x = 5;
{
let y = &mut x;
*y += 1;
}
println!(""{}"", &x);
}
This code is identical with the code above except I pass &x to println!. It prints '6' to the console which is correct and is the same result as the first code.
",https://stackoverflow.com/questions/30450399/does-println-borrow-or-own-the-variable,101,12910.0,1.0,,,2015-05-26 05:48:49,2023-11-03 17:23:34,2018-10-14 19:36:31,,,rust;ownership,kevinyu,1487,3800474,registered,true,30451360,,CC BY-SA 4.0,,934,609,10,1,0,2,true,false,false,true,true,true,41,7,true,0.077,0.0078,4197,2015,5,5,Tuesday,false,false,false,false,false,false,false
30333607,What does the question mark mean in a type parameter bound?,"I found the definition for std::borrow::BorrowMut:
pub trait BorrowMut<Borrowed>: Borrow<Borrowed>
where
Borrowed: ?Sized,
{
fn borrow_mut(&mut self) -> &mut Borrowed;
}
What does the question mark in front of Sized mean in this type parameter bound (Borrowed: ?Sized)?
I consulted:
- The Rust Programming Language¹ book,
- The Rust Reference², and also
- What does "Sized is not implemented" mean? on Stack Overflow
but didn't find an explanation. Please give a reference in your answer.
¹ especially see section 5.20 Traits
² and section 6.1.9 Traits
",https://stackoverflow.com/questions/30333607/what-does-the-question-mark-mean-in-a-type-parameter-bound,101,16631.0,2.0,,,2015-05-19 18:40:41,2022-02-12 12:08:07,2018-01-16 19:05:32,,,generics;rust,nalply,29323,220060,registered,true,30333691,,CC BY-SA 3.0,,1209,599,4,6,0,2,true,false,false,true,true,true,59,11,true,0.12,0.0061,4204,2015,5,18,Tuesday,false,false,false,false,false,false,false
45086595,Is it considered a bad practice to implement Deref for newtypes?,"I often use the newtype pattern, but I am tired of writing my_type.0.call_to_whatever(...). I am tempted to implement the Deref trait because it permits writing simpler code since I can use my newtype as if it were the underlying type in some situations, e.g.:
use std::ops::Deref;
type Underlying = [i32; 256];
struct MyArray(Underlying);
impl Deref for MyArray {
type Target = Underlying;
fn deref(&self) -> &Self::Target {
&self.0
}
}
fn main() {
let my_array = MyArray([0; 256]);
println!(""{}"", my_array[0]); // I can use my_array just like a regular array
}
Is this a good or bad practice? Why? What can be the downsides?
",https://stackoverflow.com/questions/45086595/is-it-considered-a-bad-practice-to-implement-deref-for-newtypes,101,27618.0,3.0,,,2017-07-13 16:41:23,2024-03-30 11:13:17,2017-07-13 16:44:56,,,rust;dereference,Boiethios,44012,4498831,registered,true,45086999,,CC BY-SA 3.0,,751,678,3,0,0,2,true,false,false,true,true,true,64,11,true,0.109,0.0037,3418,2017,7,16,Thursday,false,false,false,false,false,false,false
27650312,Show u8 slice in hex representation,"I need to convert &[u8] to a hex representation. For example [ A9, 45, FF, 00 ... ].
The trait std::fmt::UpperHex is not implemented for slices (so I can't use std::fmt::format). Rust has the serialize::hex::ToHex trait, which converts &[u8] to a hex String, but I need a representation with separate bytes.
I can implement trait UpperHex for &[u8] myself, but I'm not sure how canonical this would be. What is the most canonical way to do this?
",https://stackoverflow.com/questions/27650312/show-u8-slice-in-hex-representation,100,131722.0,6.0,,,2014-12-25 19:58:42,2024-08-22 14:21:38,2014-12-25 20:14:42,,,hex;rust;slice,Aleksandr,1545,1509255,registered,true,27650405,,CC BY-SA 3.0,,585,460,8,0,0,3,true,false,false,true,true,true,35,6,false,0.046,0.0008,4349,2014,12,19,Thursday,false,false,false,false,false,false,false
34606043,How do I replace specific characters idiomatically in Rust?,"So I have the string ""Hello World!"" and want to replace the ""!"" with ""?"" so that the new string is ""Hello World?""
In Ruby we can do this easily with the gsub method:
""Hello World!"".gsub(""!"", ""?"")
How to do this idiomatically in Rust?
",https://stackoverflow.com/questions/34606043/how-do-i-replace-specific-characters-idiomatically-in-rust,100,110115.0,2.0,,,2016-01-05 07:11:37,2021-10-18 11:49:58,2016-11-27 14:29:45,,,regex;rust,Vin,1035,4385847,registered,true,34606128,,CC BY-SA 3.0,,333,238,2,0,0,2,true,false,false,true,true,true,59,9,true,0.018,0.0009,3973,2016,1,7,Tuesday,false,false,false,false,false,false,false
32900809,How to suppress "function is never used" warning for a function used by tests?,"I'm writing a program in Rust and I have some tests for it. I wrote a helper function for these tests, but whenever I build using cargo build it warns me that the function is never used:
warning: function is never used: ... #[warn(dead_code)] on by default
How I can mark this function as used so as not to get the warnings?
",https://stackoverflow.com/questions/32900809/how-to-suppress-function-is-never-used-warning-for-a-function-used-by-tests,100,57470.0,8.0,,,2015-10-02 05:00:13,2023-01-20 07:41:34,2015-10-02 14:58:59,,,rust,Derokorian,1540,1636594,registered,true,32908553,,CC BY-SA 3.0,,390,331,1,0,0,1,true,false,false,true,true,true,88,14,true,0.139,0.0017,4068,2015,10,5,Friday,false,false,false,false,false,false,false
60857222,How do I list all of the packages I've installed globally with cargo install?,"I've installed several CLI tools using cargo install (for instance, ripgrep). How do I see a list of all the crates I've downloaded using cargo install? Sort of like apt list --installed but for cargo?
",https://stackoverflow.com/questions/60857222/how-do-i-list-all-of-the-packages-ive-installed-globally-with-cargo-install,100,60635.0,4.0,,,2020-03-25 20:52:42,2024-08-26 11:50:19,2024-08-26 11:50:19,,,rust;rust-cargo,almel,8068,1484555,registered,true,,,CC BY-SA 4.0,,261,202,4,0,0,2,false,false,false,true,true,true,81,14,true,0.066,0.0016,2432,2020,3,20,Wednesday,false,false,false,false,false,false,false
53177980,How do I conditionally execute code only when an Option is None?,"I don't want to take action if the function returns a value in the optional; how do I test the None case only? This code works, but it looks horrible.
let v = ffunc();
match v {
None => { callproc() },
Some(x) => { }
}
In C, I can write:
int x = ffunc();
if ( !x ) { callproc() }
",https://stackoverflow.com/questions/53177980/how-do-i-conditionally-execute-code-only-when-an-option-is-none,99,112858.0,5.0,,,2018-11-06 18:37:48,2023-12-24 12:03:49,2018-11-06 18:49:22,,,rust,Mens Rifles,1389,9188311,registered,true,53178034,,CC BY-SA 4.0,,421,307,3,0,0,1,true,false,false,true,true,true,64,12,true,0.044,0.0009,2937,2018,11,18,Tuesday,false,false,false,false,false,false,false
33216514,How do I convert a Vec<String> to Vec<&str>?,"I can convert Vec<String> to Vec<&str> this way:
let another_items = vec!["foo".to_string(), "bar".to_string()];
let mut items = Vec::<&str>::new();
for item in &another_items {
items.push(item);
}
Are there better alternatives?
",https://stackoverflow.com/questions/33216514/how-do-i-convert-a-vecstring-to-vecstr,99,42218.0,6.0,,,2015-10-19 14:04:18,2023-05-13 17:12:09,2023-04-28 05:00:18,,,string;vector;rust;type-conversion,Kalita Alexey,1137,5463164,registered,true,,,CC BY-SA 4.0,,348,284,3,0,0,4,false,false,false,true,true,true,60,8,true,0.142,0.0023,4051,2015,10,14,Monday,false,false,false,false,false,false,false
31216646,Repeat string with integer multiplication,"Is there an easy way to do the following (from Python) in Rust?
>>> print (""Repeat"" * 4)
RepeatRepeatRepeatRepeat
I'm starting to learn the language, and it seems String doesn't override Mul, and I can't find any discussion anywhere on a compact way of doing this (other than a map or loop).
",https://stackoverflow.com/questions/31216646/repeat-string-with-integer-multiplication,99,38085.0,2.0,,,2015-07-04 03:38:07,2018-05-07 20:44:49,2016-06-14 23:13:24,,,rust,Achal Dave,4509,1291812,registered,true,31216683,,CC BY-SA 3.0,,364,304,3,0,0,1,true,false,false,true,true,true,41,5,false,0.053,0.0026,4158,2015,7,3,Saturday,true,false,false,false,false,false,false
67133056,How to test async functions that use Tokio?,"I have an async function that I need to test. This function uses a mongodb::Database object to run, so I initialize the connection in the setup() function and use tokio_test::block_on() to wrap the await expression inside.
#[cfg(test)]
mod tests {
use mongodb::{options::ClientOptions, Client};
use tokio_test;
async fn setup() -> mongodb::Database {
tokio_test::block_on(async {
let client_uri = "mongodb://127.0.0.1:27017";
let options = ClientOptions::parse(&client_uri).await;
let client_result = Client::with_options(options.unwrap());
let client = client_result.unwrap();
client.database("my_database")
})
}
#[test]
fn test_something_async() {
// for some reason, test cannot be async
let DB = setup(); // <- the DB is impl std::future::Future type
// the DB variable will be used to run another
// async function named "some_async_func"
// but it doesn't work since DB is a Future type
// Future type need await keyword
// but if I use await-async keywords here, it complains
// error: async functions cannot be used for tests
// so what to do here ?
some_async_func(DB);
}
}
",https://stackoverflow.com/questions/67133056/how-to-test-async-functions-that-use-tokio,99,49453.0,1.0,,,2021-04-16 22:55:07,2022-10-27 19:15:15,2022-04-07 01:36:41,,,rust;rust-tokio,DennyHiu,6360,1608979,registered,true,67156994,,CC BY-SA 4.0,,1394,1311,5,0,0,2,true,false,false,true,true,true,43,8,true,0.02,0.002,2045,2021,4,22,Friday,false,false,false,false,false,false,false
28005134,How do I implement the Add trait for a reference to a struct?,"I made a two element Vector struct and I want to overload the + operator.
I made all my functions and methods take references, rather than values, and I want the + operator to work the same way.
impl Add for Vector {
fn add(&self, other: &Vector) -> Vector {
Vector {
x: self.x + other.x,
y: self.y + other.y,
}
}
}
Depending on which variation I try, I either get lifetime problems or type mismatches. Specifically, the &self argument seems to not get treated as the right type.
I have seen examples with template arguments on impl as well as Add, but they just result in different errors.
I found How can an operator be overloaded for different RHS types and return values? but the code in the answer doesn't work even if I put a use std::ops::Mul; at the top.
I am using rustc 1.0.0-nightly (ed530d7a3 2015-01-16 22:41:16 +0000)
I won't accept ""you only have two fields, why use a reference"" as an answer; what if I wanted a 100 element struct? I will accept an answer that demonstrates that even with a large struct I should be passing by value, if that is the case (I don't think it is, though.) I am interested in knowing a good rule of thumb for struct size and passing by value vs struct, but that is not the current question.
",https://stackoverflow.com/questions/28005134/how-do-i-implement-the-add-trait-for-a-reference-to-a-struct,99,43270.0,2.0,,,2015-01-17 22:40:51,2021-08-11 19:38:24,2017-05-23 12:09:48,,,reference;rust;traits;lifetime,Jeremy Sorensen,1160,2325220,registered,true,28005283,,CC BY-SA 3.0,,1572,1306,8,1,0,4,true,false,false,true,true,true,61,13,true,0.046,0.0023,4326,2015,1,22,Saturday,true,false,false,false,false,false,false
43983414,How to convert a Rust char to an integer so that '1' becomes 1?,"I am trying to find the sum of the digits of a given number. For example, 134 will give 8.
My plan is to convert the number into a string using .to_string() and then use .chars() to iterate over the digits as characters. Then I want to convert every char in the iteration into an integer and add it to a variable. I want to get the final value of this variable.
I tried using the code below to convert a char into an integer:
fn main() {
let x = ""123"";
for y in x.chars() {
let z = y.parse::<i32>().unwrap();
println!(""{}"", z + 1);
}
}
But it results in this error:
error[E0599]: no method named `parse` found for type `char` in the current scope
--> src/main.rs:4:19
|
4 | let z = y.parse::<i32>().unwrap();
| ^^^^^
This code does exactly what I want to do, but first I have to convert each char into a string and then into an integer to then increment sum by z.
fn main() {
let mut sum = 0;
let x = 123;
let x = x.to_string();
for y in x.chars() {
// converting `y` to string and then to integer
let z = (y.to_string()).parse::<i32>().unwrap();
// incrementing `sum` by `z`
sum += z;
}
println!(""{}"", sum);
}
",https://stackoverflow.com/questions/43983414/how-to-convert-a-rust-char-to-an-integer-so-that-1-becomes-1,98,128533.0,4.0,,,2017-05-15 15:31:59,2021-03-11 20:50:38,2019-06-18 20:37:34,,,rust,ritiek,2877,6554943,registered,true,43985962,,CC BY-SA 4.0,,1826,1285,12,2,0,1,true,false,false,true,true,true,71,14,true,0.031,0.0008,3477,2017,5,15,Monday,false,false,false,false,false,false,false
27567849,What makes something a "trait object"?,"Recent Rust changes have made ""trait objects"" more prominent to me, but I only have a nebulous grasp of what actually makes something into a trait object. One change in particular is the upcoming change to allow trait objects to forward trait implementations to the inner type.
Given a trait Foo, I'm pretty sure that Box<Foo> / Box<dyn Foo> is a trait object. Is &Foo / &dyn Foo also a trait object? What about other smart-pointer things like Rc or Arc? How could I make my own type that would count as a trait object?
The reference only mentions trait objects once, but nothing like a definition.
",https://stackoverflow.com/questions/27567849/what-makes-something-a-trait-object,98,23328.0,4.0,,,2014-12-19 14:14:39,2023-08-08 12:54:07,2020-06-05 17:48:58,,,rust;traits;trait-objects,Shepmaster,442509,155423,registered,true,27570064,,CC BY-SA 4.0,,890,621,7,2,0,3,true,false,false,true,true,true,48,6,true,0.171,0.0042,4355,2014,12,14,Friday,false,false,false,false,false,false,false
23810032,How to specify const array in global scope in Rust?,"When I tried to add a const array in the global scope using this code:
static NUMBERS: [i32] = [1, 2, 3, 4, 5];
I got the following error:
error: mismatched types:
expected `[i32]`,
found `[i32; 5]`
(expected slice,
found array of 5 elements) [E0308]
static NUMBERS2: [i32] = [1, 2, 3, 4, 5];
^~~~~~~~~~~~~~~
The only way I found to deal with this problem is to specify the length in the type:
static NUMBERS: [i32; 5] = [1, 2, 3, 4, 5];
Is there a better way? It should be possible to create an array without manually counting its elements.
",https://stackoverflow.com/questions/23810032/how-to-specify-const-array-in-global-scope-in-rust,98,83731.0,2.0,,,2014-05-22 14:42:09,2021-04-18 10:20:12,2016-04-13 19:33:32,,,arrays;static;literals;rust,Oleg Eterevsky,1674,430693,registered,true,23810557,,CC BY-SA 3.0,,686,586,3,0,0,4,true,false,false,true,true,true,51,10,true,0.024,0.0012,4566,2014,5,14,Thursday,false,false,false,false,false,false,false
63172736,Why design a language with unique anonymous types?,"This is something that has always been bugging me as a feature of C++ lambda expressions: The type of a C++ lambda expression is unique and anonymous, I simply cannot write it down. Even if I create two lambdas that are syntactically exactly the same, the resulting types are defined to be distinct. The consequence is, that a) lambdas can only be passed to template functions that allow the compile time, unspeakable type to be passed along with the object, and b) that lambdas are only useful once they are type erased via std::function<>.
Ok, but that's just the way C++ does it, I was ready to write it off as just an irksome feature of that language. However, I just learned that Rust seemingly does the same: Each Rust function or lambda has a unique, anonymous type. And now I'm wondering: Why?
So, my question is this:
What is the advantage, from a language designer point of view, to introduce the concept of a unique, anonymous type into a language?
",https://stackoverflow.com/questions/63172736/why-design-a-language-with-unique-anonymous-types,97,7644.0,10.0,,,2020-07-30 12:01:27,2025-12-29 06:54:08,,,,c++;types;rust;language-design,cmaster - reinstate monica,41314,2445184,registered,true,63187166,,CC BY-SA 4.0,,1023,966,1,0,0,4,true,false,false,true,true,false,50,8,true,1.308,0.0127,2305,2020,7,12,Thursday,false,false,false,false,false,false,false
35458562,How can I implement Rust's Copy trait?,"I am trying to initialise an array of structs in Rust:
enum Direction {
North,
East,
South,
West,
}
struct RoadPoint {
direction: Direction,
index: i32,
}
// Initialise the array, but failed.
let data = [RoadPoint { direction: Direction::East, index: 1 }; 4];
When I try to compile, the compiler complains that the Copy trait is not implemented:
error[E0277]: the trait bound `main::RoadPoint: std::marker::Copy` is not satisfied
--> src/main.rs:15:16
|
15 | let data = [RoadPoint { direction: Direction::East, index: 1 }; 4];
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `std::marker::Copy` is not implemented for `main::RoadPoint`
|
= note: the `Copy` trait is required because the repeated element will be copied
How can the Copy trait be implemented?
",https://stackoverflow.com/questions/35458562/how-can-i-implement-rusts-copy-trait,97,115390.0,3.0,,,2016-02-17 13:51:13,2026-01-26 15:06:17,2018-06-01 18:44:15,,,rust;traits,tehnyit,1252,270943,registered,true,35458874,,CC BY-SA 4.0,,982,848,4,0,0,2,true,false,false,true,true,true,42,7,true,0.026,0.0008,3930,2016,2,13,Wednesday,false,false,false,false,false,false,false
26757355,How do I collect into an array?,"I want to call .map() on an array of enums:
enum Foo {
Value(i32),
Nothing,
}
fn main() {
let bar = [1, 2, 3];
let foos = bar.iter().map(|x| Foo::Value(*x)).collect::<[Foo; 3]>();
}
but the compiler complains:
error[E0277]: the trait bound `[Foo; 3]: std::iter::FromIterator<Foo>` is not satisfied
--> src/main.rs:8:51
|
8 | let foos = bar.iter().map(|x| Foo::Value(*x)).collect::<[Foo; 3]>();
| ^^^^^^^ a collection of type `[Foo; 3]` cannot be built from an iterator over elements of type `Foo`
|
= help: the trait `std::iter::FromIterator<Foo>` is not implemented for `[Foo; 3]`
How do I do this?
",https://stackoverflow.com/questions/26757355/how-do-i-collect-into-an-array,96,120698.0,11.0,,,2014-11-05 12:35:16,2025-10-16 10:31:34,2017-11-08 18:18:59,,,rust,rausch,3428,493886,registered,true,,,CC BY-SA 3.0,,834,713,3,0,0,1,false,false,false,true,true,true,31,7,true,0.091,0.0008,4399,2014,11,12,Wednesday,false,false,false,false,false,false,false
45724517,"How to iterate through a Hashmap, print the key/value and remove the value in Rust?","This should be a trivial task in any language. This isn't working in Rust.
use std::collections::HashMap;
fn do_it(map: &mut HashMap<String, String>) {
for (key, value) in map {
println!(""{} / {}"", key, value);
map.remove(key);
}
}
fn main() {}
Here's the compiler error:
error[E0382]: use of moved value: `*map`
--> src/main.rs:6:9
|
4 | for (key, value) in map {
| --- value moved here
5 | println!(""{} / {}"", key, value);
6 | map.remove(key);
| ^^^ value used here after move
|
= note: move occurs because `map` has type `&mut std::collections::HashMap<std::string::String, std::string::String>`, which does not implement the `Copy` trait
Why it is trying to move a reference? From the documentation, I didn't think moving/borrowing applied to references.
",https://stackoverflow.com/questions/45724517/how-to-iterate-through-a-hashmap-print-the-key-value-and-remove-the-value-in-ru,96,134537.0,3.0,,,2017-08-16 23:38:18,2021-08-30 09:10:41,2018-12-18 18:04:24,,,hashmap;rust;iteration;mutability,adapt-dev,1798,4674479,registered,true,,,CC BY-SA 4.0,,989,881,2,0,0,4,false,false,false,true,true,true,83,15,true,0.022,0.0007,3384,2017,8,23,Wednesday,false,false,false,false,false,false,false
54585804,How to run a specific unit test in Rust?,"I have unit tests in a package named school-info and there is a test function called repeat_students_should_not_get_full_marks.
I can run all tests in the module by cargo test --package school_info.
cargo test test-name will match and run tests which contain test_name though this wasn't helpful.
How can I run only the test repeat_students_should_not_get_full_marks without running all the tests? I could not find a command in the documentation to do it.
",https://stackoverflow.com/questions/54585804/how-to-run-a-specific-unit-test-in-rust,96,74663.0,1.0,,,2019-02-08 03:58:58,2023-10-13 10:10:08,2019-02-11 08:26:51,,,unit-testing;rust;rust-cargo,Kalanamith,20953,1004875,registered,true,54586148,,CC BY-SA 4.0,,565,459,6,0,0,3,true,false,false,true,true,true,40,9,true,0.013,0.0013,2843,2019,2,3,Friday,false,false,false,false,false,false,false
34953711,Unwrap inner type when enum variant is known,"I have this enum type:
enum Animal {
Dog(i32),
Cat(u8),
}
Now I have a function that takes this type as parameter. I know (for some reason) that the input is always a Cat. I want to achieve this:
fn count_legs_of_cat(animal: Animal) -> u8 {
if let Animal::Cat(c) = animal { c } else { unreachable!() }
}
Can I write this shorter and/or more idiomatic?
",https://stackoverflow.com/questions/34953711/unwrap-inner-type-when-enum-variant-is-known,96,51722.0,6.0,,,2016-01-22 18:38:35,2023-07-13 04:59:43,,,,enums;rust,Lukas Kalbertodt,91680,2408867,registered,true,34954128,,CC BY-SA 3.0,,464,373,3,0,0,2,true,false,false,true,true,false,44,8,false,0.116,0.0019,3956,2016,1,18,Friday,false,false,false,false,false,false,false
37531903,How do I print output without a trailing newline?,"The macro println! in Rust always leaves a newline character at the end of each output. For example
println!("Enter the number: ");
io::stdin().read_line(&mut num);
gives the output
Enter the number:
56
I don't want the user's input 56 to be on a new line. How do I do this?
",https://stackoverflow.com/questions/37531903/how-do-i-print-output-without-a-trailing-newline,95,60556.0,4.0,,,2016-05-30 18:38:24,2024-09-02 22:13:08,2024-09-02 22:12:48,,,rust;newline;println,7_R3X,4492,5460216,registered,true,41387232,,CC BY-SA 4.0,,426,292,4,0,0,3,true,false,false,true,true,true,49,9,true,0.066,0.0016,3827,2016,5,18,Monday,false,false,false,false,false,false,false
14189604,What is monomorphisation with context to C++?,"Dave Herman's recent talk in Rust said that they borrowed this property from C++. I couldn't find anything around the topic. Can somebody please explain what monomorphisation means?
",https://stackoverflow.com/questions/14189604/what-is-monomorphisation-with-context-to-c,95,20848.0,5.0,,,2013-01-07 03:47:12,2024-11-06 13:25:48,2015-06-08 21:43:55,,,c++;rust,unj2,53936,82368,registered,true,14198060,,CC BY-SA 3.0,,243,182,0,1,0,2,true,false,false,true,true,true,45,7,true,0.24,0.0046,5066,2013,1,3,Monday,false,false,false,false,false,false,false
27734708,println! error: expected a literal / format argument must be a string literal,"This extremely simple Rust program:
fn main() {
let c = ""hello"";
println!(c);
}
throws the following compile-time error:
error: expected a literal
--> src/main.rs:3:14
|
3 | println!(c);
| ^
In previous versions of Rust, the error said:
error: format argument must be a string literal.
println!(c);
^
Replacing the program with:
fn main() {
println!(""Hello"");
}
Works fine.
The meaning of this error isn't clear to me and a Google search hasn't really shed light on it. Why does passing c to the println! macro cause a compile time error? This seems like quite unusual behaviour.
",https://stackoverflow.com/questions/27734708/println-error-expected-a-literal-format-argument-must-be-a-string-literal,95,54735.0,4.0,,,2015-01-01 21:10:14,2021-05-25 17:23:08,2018-01-15 03:28:52,,,rust,Mike Vella,10669,592235,registered,true,27734844,,CC BY-SA 3.0,,895,653,6,0,0,1,true,false,false,true,true,true,77,13,false,0.073,0.0017,4342,2015,1,21,Thursday,false,false,false,false,false,false,false
31770604,How to generate statically linked executables?,"I am trying to create a static executable with Rust. I am not trying to link a particular library statically, I am trying to create a executable which does not use dynamic linking at all. I have the following (otherwise working) test:
$ cat hello.rs
fn main()
{
print!("Hello, world!\n");
}
$ rustc hello.rs -o hello
$ file hello
hello: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV),
dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, [etc]
Note the dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2. Static executables have statically linked instead. (And in my case corrupted section header size, although I would be pleasantly astonished if I could convince Rust to replicate that.)
What options do I need to pass to rustc to get it to generate an actual static executable (for concreteness: one which even file agrees is statically linked).
",https://stackoverflow.com/questions/31770604/how-to-generate-statically-linked-executables,95,81578.0,2.0,,,2015-08-02 09:45:07,2025-03-06 21:04:29,2024-10-07 11:31:24,,,rust;static-linking,David X,4256,163349,registered,true,,,CC BY-SA 4.0,,1035,898,6,0,0,2,false,false,false,true,true,true,46,6,true,0.025,0.0012,4129,2015,8,9,Sunday,true,false,false,false,false,false,false
21324657,Does Rust support Ruby-like string interpolation?,"In Ruby I could do this.
aaa = ""AAA""
bbb = ""BBB #{aaa}""
puts(bbb)
> ""BBB AAA""
The point of this syntax is eliminating repetition, and making it to feel like a shell script - great for heavy string manipulation.
Does Rust support this? Or have plan to support this? Or have some feature which can mimic this?
",https://stackoverflow.com/questions/21324657/does-rust-support-ruby-like-string-interpolation,94,61134.0,4.0,,,2014-01-24 04:47:58,2024-03-25 05:22:33,2014-01-24 05:06:56,,,rust;string-interpolation,Cage,86979,246776,registered,true,,,CC BY-SA 3.0,,362,317,1,0,0,2,false,false,false,true,true,true,49,6,true,0.065,0.0015,4684,2014,1,4,Friday,false,false,false,false,false,false,false
24842271,What is the purpose of the unit type in Rust?,"Rust has the unit type, (), a type with a single zero-size value. The value of this unit type is also specified using ().
What is the purpose of the unit type and its value? Is it a mechanism to avoid using null (or nil) like other languages have?
",https://stackoverflow.com/questions/24842271/what-is-the-purpose-of-the-unit-type-in-rust,94,32084.0,4.0,,,2014-07-19 16:04:06,2024-02-28 14:01:24,2023-01-22 01:04:44,,,rust;unit-type,Will,1653,803976,registered,true,24843106,,CC BY-SA 4.0,,315,248,2,0,0,2,true,false,false,true,true,true,45,10,true,0.125,0.0029,4508,2014,7,16,Saturday,true,false,false,false,false,false,false
36384840,What is the prelude?,"When talking about imports, the word prelude is used every so often by the rustaceans.
What is this prelude they talk about?
How does it affect my Rust programs?
",https://stackoverflow.com/questions/36384840/what-is-the-prelude,94,19696.0,1.0,,,2016-04-03 11:27:53,2016-04-04 13:08:03,2016-04-04 13:08:03,,,rust,Matthieu M.,304968,147192,registered,true,36384841,,CC BY-SA 3.0,,203,164,0,0,0,1,true,false,false,true,true,true,20,4,true,0.051,0.0048,3884,2016,4,11,Sunday,true,false,false,false,false,false,false
45786955,How to compose functions in Rust?,"I'm trying to write a function that composes two functions. The initial design is pretty simple: a function that takes two functions and returns a composed function which I can then compose with other functions, since Rust doesn't have rest parameters. I've run into a wall built with frustrating non-helpful compiler errors.
My compose function:
fn compose<'a, A, B, C, G, F>(f: F, g: G) -> Box<Fn(A) -> C + 'a>
where
F: 'a + Fn(A) -> B + Sized,
G: 'a + Fn(B) -> C + Sized,
{
Box::new(move |x| g(f(x)))
}
How I would like to use it:
fn main() {
let addAndMultiply = compose(|x| x * 2, |x| x + 2);
let divideAndSubtract = compose(|x| x / 2, |x| x - 2);
let finally = compose(*addAndMultiply, *divideAndSubtract);
println!(""Result is {}"", finally(10));
}
The compiler doesn't like that, no matter what I try, the trait bounds are never satisfied. The error is:
error[E0277]: the size for values of type `dyn std::ops::Fn(_) -> _` cannot be known at compilation time
--> src/main.rs:13:19
|
13 | let finally = compose(*addAndMultiply, *divideAndSubtract);
| ^^^^^^^ doesn't have a size known at compile-time
|
= help: the trait `std::marker::Sized` is not implemented for `dyn std::ops::Fn(_) -> _`
= note: to learn more, visit <https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>
note: required by `compose`
--> src/main.rs:1:1
|
1 | / fn compose<'a, A, B, C, G, F>(f: F, g: G) -> Box<Fn(A) -> C + 'a>
2 | | where
3 | | F: 'a + Fn(A) -> B + Sized,
4 | | G: 'a + Fn(B) -> C + Sized,
5 | | {
6 | | Box::new(move |x| g(f(x)))
7 | | }
| |_^
",https://stackoverflow.com/questions/45786955/how-to-compose-functions-in-rust,93,21767.0,3.0,,,2017-08-20 21:27:35,2021-06-14 21:56:33,2019-04-07 12:58:20,,,functional-programming;rust,Seun Lanlege,1356,6394734,registered,true,45792463,,CC BY-SA 4.0,,1897,1758,3,0,0,2,true,false,false,true,true,true,33,6,true,0.138,0.0043,3380,2017,8,21,Sunday,true,false,false,false,false,false,false
18479648,Does Rust have support for functions that return multiple values?,"Does Rust have native support for functions that return multiple values like Go?
func addsub(x, y int) (int, int) {
return x + y, x - y
}
It seems that we could use a tuple to simulate it. Rosetta Code introduces how to return multiple values in different languages, but I didn't see Rust.
",https://stackoverflow.com/questions/18479648/does-rust-have-support-for-functions-that-return-multiple-values,92,68541.0,4.0,,,2013-08-28 04:47:07,2019-11-17 05:22:43,2015-10-28 02:36:37,,,rust,sunny2016,1515,876824,registered,true,18517044,,CC BY-SA 3.0,,400,297,1,1,0,1,true,false,false,true,true,true,65,10,true,0.058,0.0013,4833,2013,8,4,Wednesday,false,false,false,false,false,false,false
45519176,How do I "use" or import a local Rust file?,"How do I include a file with the full path my_project/src/include_me.rs in main.rs?
I've checked the dependencies guide, and all of them appear to be including a binary. I've also checked "The Book", but none of the examples there end in ".rs" either.
How do I make include_me.rs compile with the rest of the project?
",https://stackoverflow.com/questions/45519176/how-do-i-use-or-import-a-local-rust-file,92,111177.0,1.0,,,2017-08-05 06:54:14,2022-06-27 07:29:28,2022-05-05 21:24:15,2017-08-06 13:16:34,Duplicate,import;rust,Seph Reed,11584,4808079,registered,true,45520092,,,,595,339,3,2,0,2,true,true,false,true,true,true,53,10,true,0.009,0.0008,3395,2017,8,6,Saturday,true,false,false,false,false,false,false
30353462,How to clone a struct storing a boxed trait object?,"I wrote a program that has the trait Animal and the struct Dog implementing the trait. It also has a struct AnimalHouse storing an animal as a trait object Box<Animal>.
trait Animal {
fn speak(&self);
}
struct Dog {
name: String,
}
impl Dog {
fn new(name: &str) -> Dog {
return Dog {
name: name.to_string(),
};
}
}
impl Animal for Dog {
fn speak(&self) {
println!{""{}: ruff, ruff!"", self.name};
}
}
struct AnimalHouse {
animal: Box<Animal>,
}
fn main() {
let house = AnimalHouse {
animal: Box::new(Dog::new(""Bobby"")),
};
house.animal.speak();
}
It returns ""Bobby: ruff, ruff!"" as expected, but if I try to clone house the compiler returns errors:
fn main() {
let house = AnimalHouse {
animal: Box::new(Dog::new(""Bobby"")),
};
let house2 = house.clone();
house2.animal.speak();
}
error[E0599]: no method named `clone` found for type `AnimalHouse` in the current scope
--> src/main.rs:31:24
|
23 | struct AnimalHouse {
| ------------------ method `clone` not found for this
...
31 | let house2 = house.clone();
| ^^^^^
|
= help: items from traits can only be used if the trait is implemented and in scope
= note: the following trait defines an item `clone`, perhaps you need to implement it:
candidate #1: `std::clone::Clone`
I tried to add #[derive(Clone)] before struct AnimalHouse and got another error:
error[E0277]: the trait bound `Animal: std::clone::Clone` is not satisfied
--> src/main.rs:25:5
|
25 | animal: Box<Animal>,
| ^^^^^^^^^^^^^^^^^^^ the trait `std::clone::Clone` is not implemented for `Animal`
|
= note: required because of the requirements on the impl of `std::clone::Clone` for `std::boxed::Box<Animal>`
= note: required by `std::clone::Clone::clone`
How do I make the struct AnimalHouse cloneable? Is it idiomatic Rust to use a trait object actively, in general?
",https://stackoverflow.com/questions/30353462/how-to-clone-a-struct-storing-a-boxed-trait-object,91,30759.0,3.0,,,2015-05-20 15:00:34,2025-07-16 17:05:35,2018-03-24 23:51:22,,,struct;clone;rust;traits;cloneable,Denis Kreshikhin,9560,1062636,registered,true,30353928,,CC BY-SA 3.0,,2342,2036,12,0,0,5,true,false,false,true,true,true,51,10,true,0.098,0.003,4203,2015,5,15,Wednesday,false,false,false,false,false,false,false
26033976,How do I create a Vec from a range and shuffle it?,"I have the following code:
extern crate rand;
use rand::{thread_rng, Rng};
fn main() {
let mut vec: Vec<u32> = (0..10).collect();
let mut slice: &[u32] = vec.as_mut_slice();
thread_rng().shuffle(slice);
}
and get the following error:
error[E0308]: mismatched types
--> src/main.rs:9:26
|
9 | thread_rng().shuffle(slice);
| ^^^^^ types differ in mutability
|
= note: expected type `&mut [_]`
found type `&[u32]`
I think I understand that the content of vectors and slices is immutable and that causes the error here, but I'm unsure.
The signature of as_mut_slice is pub fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T], so the slice should be mutable, but it somehow isn't.
I know that there must be an easy fix, but I tried my best and couldn't get it to work.
",https://stackoverflow.com/questions/26033976/how-do-i-create-a-vec-from-a-range-and-shuffle-it,91,94666.0,3.0,,,2014-09-25 08:32:02,2024-08-07 12:27:11,2018-05-02 20:57:06,,,iterator;immutability;rust;mutability,le_me,3509,1477992,registered,true,26035435,,CC BY-SA 4.0,,1021,873,4,0,0,4,true,false,false,true,true,true,50,12,true,0.032,0.001,4440,2014,9,8,Thursday,false,false,false,false,false,false,false
29428227,Return local String as a slice (&str),"There are several questions that seem to be about the same problem I'm having. For example see here and here. Basically I'm trying to build a String in a local function, but then return it as a &str. Slicing isn't working because the lifetime is too short. I can't use str directly in the function because I need to build it dynamically. However, I'd also prefer not to return a String since the nature of the object this is going into is static once it's built. Is there a way to have my cake and eat it too?
Here's a minimal non-compiling reproduction:
fn return_str<'a>() -> &'a str {
let mut string = """".to_string();
for i in 0..10 {
string.push_str(""ACTG"");
}
&string[..]
}
",https://stackoverflow.com/questions/29428227/return-local-string-as-a-slice-str,91,34588.0,7.0,,,2015-04-03 07:42:17,2022-11-22 18:31:33,2017-05-23 11:46:49,,,rust,anderspitman,10870,943814,registered,true,29429698,,CC BY-SA 3.0,,1020,729,5,2,0,1,true,false,false,true,true,true,41,7,false,0.202,0.0026,4250,2015,4,7,Friday,false,false,false,false,false,false,false
43143327,How to allow optional trailing commas in macros?,"Here's a synthetic example of what I want:
macro_rules! define_enum {
($Name:ident { $($Variant:ident),* }) => {
pub enum $Name {
None,
$($Variant),*,
}
}
}
define_enum!(Foo { A, B });
This code compiles, but if add a comma to it:
define_enum!(Foo { A, B, });
// ^
The compilation fails. I can fix it with:
($Name:ident { $($Variant:ident,)* })
// ^
but then define_enum!(Foo { A, B }); fails,
How should I write a macro to handle both cases:
define_enum!(Foo { A, B });
define_enum!(Foo { A, B, });
",https://stackoverflow.com/questions/43143327/how-to-allow-optional-trailing-commas-in-macros,91,16659.0,3.0,,,2017-03-31 14:35:06,2023-03-28 13:45:19,2017-03-31 14:37:35,,,macros;rust,user1244932,8382,1244932,registered,true,43143459,,CC BY-SA 3.0,,756,612,5,0,0,2,true,false,false,true,true,true,48,8,true,0.18,0.0055,3522,2017,3,14,Friday,false,false,false,false,false,false,false
49229332,Should trait bounds be duplicated in struct and impl?,"The following code uses a struct with generic type. While its implementation is only valid for the given trait bound, the struct can be defined with or without the same bound. The struct's fields are private so no other code could create an instance anyway.
trait Trait {
fn foo(&self);
}
struct Object<T: Trait> {
value: T,
}
impl<T: Trait> Object<T> {
fn bar(object: Object<T>) {
object.value.foo();
}
}
Should the trait bound for the structure should be omitted to conform to the DRY principle, or should it be given to clarify the dependency? Or are there circumstances one solution should be preferred over the other?
",https://stackoverflow.com/questions/49229332/should-trait-bounds-be-duplicated-in-struct-and-impl,90,20956.0,3.0,,,2018-03-12 06:34:16,2022-09-24 16:28:41,2021-02-25 14:09:28,,,rust,user2011659,1321,2011659,registered,true,49231175,,CC BY-SA 4.0,,716,678,1,0,0,1,true,false,false,true,true,true,53,9,true,0.143,0.0043,3176,2018,3,6,Monday,false,false,false,false,false,false,false
30441698,How do I create a map from a list in a functional way?,"In Scala, there is a method named toMap that works on any list of tuples and converts it to a map where the key is the first item on the tuple and the value is the second one:
val listOfTuples = List((""one"", 1), (""two"", 2))
val map = listOfTuples.toMap
What is the closest thing to toMap in Rust?
",https://stackoverflow.com/questions/30441698/how-do-i-create-a-map-from-a-list-in-a-functional-way,90,77241.0,3.0,,,2015-05-25 15:37:35,2022-05-06 19:56:36,2018-01-19 15:53:52,,,rust,Eran Medan,45975,239168,registered,true,30441736,,CC BY-SA 3.0,,405,301,3,0,0,1,true,false,false,true,true,true,54,13,true,0.039,0.0012,4198,2015,5,15,Monday,false,false,false,false,false,false,false
36416773,How does Rust implement reflection?,"Rust has the Any trait, but it also has a ""do not pay for what you do not use"" policy. How does Rust implement reflection?
My guess is that Rust uses lazy tagging. Every type is initially unassigned, but later if an instance of the type is passed to a function expecting an Any trait, the type is assigned a TypeId.
Or maybe Rust puts a TypeId on every type that its instance is possibly passed to that function? I guess the former would be expensive.
",https://stackoverflow.com/questions/36416773/how-does-rust-implement-reflection,90,44050.0,1.0,,,2016-04-05 03:46:43,2023-12-14 23:48:31,2016-04-05 14:57:15,,,reflection;rust,Xwtek,1311,5784051,registered,true,36416972,,CC BY-SA 3.0,,528,455,4,0,0,2,true,false,false,true,true,true,35,5,true,0.023,0.002,3882,2016,4,3,Tuesday,false,false,false,false,false,false,false
39219961,How to get assembly output from building with Cargo?,"While I've seen docs on using rustc directly to output assembly, having to manually extract commands used by Cargo and edit them to write assembly is tedious.
Is there a way to run Cargo that writes out assembly files?
",https://stackoverflow.com/questions/39219961/how-to-get-assembly-output-from-building-with-cargo,89,52745.0,4.0,,,2016-08-30 06:11:03,2022-08-12 14:37:11,2016-08-30 08:05:22,,,assembly;rust;rust-cargo,ideasman42,49986,432509,registered,true,39220789,,CC BY-SA 3.0,,247,220,1,0,0,3,true,false,false,true,true,true,52,9,true,0.076,0.0017,3735,2016,8,6,Tuesday,false,false,false,false,false,false,false
34684261,How to set a Rust array length dynamically?,"I want to create array like this:
let arr = [0; length];
Where length is a usize. But I get this error
E0307
The length of an array is part of its type. For this reason, this length
must be a compile-time constant.
Is it possible to create array with dynamic length? I want an array, not a Vec.
",https://stackoverflow.com/questions/34684261/how-to-set-a-rust-array-length-dynamically,89,117770.0,3.0,,,2016-01-08 19:05:03,2024-09-26 00:25:02,2017-07-16 00:12:07,,,arrays;rust,Dima Kudosh,7454,4790988,registered,true,34684869,,CC BY-SA 3.0,,436,302,4,0,0,2,true,false,false,true,true,true,43,8,true,0.025,0.0008,3970,2016,1,19,Friday,false,false,false,false,false,false,false
46388386,What exactly does '#[derive(Debug)]' mean in Rust?,"What exactly does #[derive(Debug)] mean? Does it have something to do with 'a? For example:
#[derive(Debug)]
struct Person<'a> {
name: &'a str,
age: u8
}
",https://stackoverflow.com/questions/46388386/what-exactly-does-derivedebug-mean-in-rust,89,37244.0,1.0,,,2017-09-24 09:01:15,2022-10-01 15:47:40,2022-10-01 15:47:40,,,rust;syntax,Amani,18723,852063,registered,true,46389319,,CC BY-SA 4.0,,231,174,3,0,0,2,true,false,false,true,true,true,58,7,true,0.027,0.0024,3345,2017,9,9,Sunday,true,false,false,false,false,false,false
32554285,"Compare enums only by variant, not value","I have an enum with the following structure:
enum Expression {
Add(Add),
Mul(Mul),
Var(Var),
Coeff(Coeff)
}
where the 'members' of each variant are structs.
Now I want to compare if two enums have the same variant. So if I have
let a = Expression::Add({something});
let b = Expression::Add({somethingelse});
cmpvariant(a, b) should be true. I can imagine a simple double match code that goes through all the options for both enum instances. However, I am looking for a fancier solution, if it exists. If not, is there overhead for the double match? I imagine that internally I am just comparing two ints (ideally).
",https://stackoverflow.com/questions/32554285/compare-enums-only-by-variant-not-value,89,31237.0,1.0,,,2015-09-13 20:34:47,2022-04-19 17:44:04,2017-03-20 14:36:55,,,rust,Ben Ruijl,5153,314784,registered,true,32554326,,CC BY-SA 3.0,,753,638,5,0,0,1,true,false,false,true,true,true,40,7,false,0.032,0.0028,4087,2015,9,20,Sunday,true,false,false,false,false,false,false
29998515,What's the idiomatic way to append a slice to a vector?,"I have a slice of &[u8] and I'd like to append it to a Vec<u8> with minimal copying. Here are two approaches that I know work:
let s = [0u8, 1u8, 2u8];
let mut v = Vec::new();
v.extend(s.iter().map(|&i| i));
v.extend(s.to_vec().into_iter()); // allocates an extra copy of the slice
Is there a better way to do this in Rust stable? (rustc 1.0.0-beta.2)
",https://stackoverflow.com/questions/29998515/whats-the-idiomatic-way-to-append-a-slice-to-a-vector,88,61410.0,3.0,,,2015-05-02 04:49:07,2016-12-17 05:05:04,2016-12-17 05:05:04,,,vector;rust,Kai,3002,1079493,registered,true,35952229,,CC BY-SA 3.0,,446,369,4,0,0,2,true,false,false,true,true,true,59,11,true,0.049,0.0014,4221,2015,5,4,Saturday,true,false,false,false,false,false,false
43704758,How to idiomatically convert between u32 and usize?,"This code works and prints ""b"":
fn main() {
let s = ""abc"";
let ch = s.chars().nth(1).unwrap();
println!(""{}"", ch);
}
On the other hand, this code results in a mismatch type error.
fn main() {
let s = ""abc"";
let n: u32 = 1;
let ch = s.chars().nth(n).unwrap();
println!(""{}"", ch);
}
error[E0308]: mismatched types
--> src/main.rs:5:28
|
5 | let ch = s.chars().nth(n).unwrap();
| ^ expected usize, found u32
For some external reason, I have to use the u32 type for variable n. How can I convert u32 to usize and use it in nth()?
",https://stackoverflow.com/questions/43704758/how-to-idiomatically-convert-between-u32-and-usize,88,112985.0,3.0,,,2017-04-30 09:09:36,2022-02-14 19:32:44,2019-04-20 00:01:14,,,types;rust;type-conversion,Sajuuk,3169,7526319,registered,true,43705031,,CC BY-SA 4.0,,798,601,8,0,0,3,true,false,false,true,true,true,51,8,true,0.027,0.0008,3492,2017,4,9,Sunday,true,false,false,false,false,false,false
28632968,Why doesn't Rust support trait object upcasting?,"Given this code:
trait Base {
fn a(&self);
fn b(&self);
fn c(&self);
fn d(&self);
}
trait Derived : Base {
fn e(&self);
fn f(&self);
fn g(&self);
}
struct S;
impl Derived for S {
fn e(&self) {}
fn f(&self) {}
fn g(&self) {}
}
impl Base for S {
fn a(&self) {}
fn b(&self) {}
fn c(&self) {}
fn d(&self) {}
}
Unfortunately, I cannot cast &Derived to &Base:
fn example(v: &Derived) {
v as &Base;
}
error[E0605]: non-primitive cast: `&Derived` as `&Base`
--> src/main.rs:30:5
|
30 | v as &Base;
| ^^^^^^^^^^
|
= note: an `as` expression can only be used to convert between primitive types. Consider using the `From` trait
Why is that? The Derived vtable has to reference the Base methods in one way or another.
Inspecting the LLVM IR reveals the following:
@vtable4 = internal unnamed_addr constant {
void (i8*)*,
i64,
i64,
void (%struct.S*)*,
void (%struct.S*)*,
void (%struct.S*)*,
void (%struct.S*)*
} {
void (i8*)* @_ZN2i813glue_drop.98717h857b3af62872ffacE,
i64 0,
i64 1,
void (%struct.S*)* @_ZN6S.Base1a20h57ba36716de00921jbaE,
void (%struct.S*)* @_ZN6S.Base1b20h3d50ba92e362d050pbaE,
void (%struct.S*)* @_ZN6S.Base1c20h794e6e72e0a45cc2vbaE,
void (%struct.S*)* @_ZN6S.Base1d20hda31e564669a8cdaBbaE
}
@vtable26 = internal unnamed_addr constant {
void (i8*)*,
i64,
i64,
void (%struct.S*)*,
void (%struct.S*)*,
void (%struct.S*)*,
void (%struct.S*)*,
void (%struct.S*)*,
void (%struct.S*)*,
void (%struct.S*)*
} {
void (i8*)* @_ZN2i813glue_drop.98717h857b3af62872ffacE,
i64 0,
i64 1,
void (%struct.S*)* @_ZN9S.Derived1e20h9992ddd0854253d1WaaE,
void (%struct.S*)* @_ZN9S.Derived1f20h849d0c78b0615f092aaE,
void (%struct.S*)* @_ZN9S.Derived1g20hae95d0f1a38ed23b8aaE,
void (%struct.S*)* @_ZN6S.Base1a20h57ba36716de00921jbaE,
void (%struct.S*)* @_ZN6S.Base1b20h3d50ba92e362d050pbaE,
void (%struct.S*)* @_ZN6S.Base1c20h794e6e72e0a45cc2vbaE,
void (%struct.S*)* @_ZN6S.Base1d20hda31e564669a8cdaBbaE
}
All Rust vtables contain a pointer to the destructor, size and alignment in the first fields, and the subtrait vtables don't duplicate them when referencing supertrait methods, nor use indirect reference to supertrait vtables. They just have copies of the method pointers verbatim and nothing else.
Given that design, it's easy to understand why this does not work. A new vtable would need to be constructed at runtime, which would likely reside on the stack, and that isn't exactly an elegant (or optimal) solution.
There are some workarounds, of course, like adding explicit upcast methods to the interface, but that requires quite a bit of boilerplate (or macro frenzy) to work properly.
Now, the question is - why isn't it implemented in some way that would enable trait object upcasting? Like, adding a pointer to the supertrait's vtable in the subtrait's vtable. For now, Rust's dynamic dispatch doesn't seem to satisfy the Liskov substitution principle, which is a very basic principle for object-oriented design.
Of course you can use static dispatch, which is indeed very elegant to use in Rust, but it easily leads to code bloat which is sometimes more important than computational performance - like on embedded systems, and Rust developers claim to support such use cases of the language. Also, in many cases you can successfully use a model which is not purely Object-Oriented, which seems to be encouraged by Rust's functional design. Still, Rust supports many of the useful OO patterns... so why not the LSP?
Does anyone know the rationale for such design?
",https://stackoverflow.com/questions/28632968/why-doesnt-rust-support-trait-object-upcasting,88,26694.0,7.0,,,2015-02-20 15:49:49,2025-04-03 19:09:28,2018-04-24 14:57:27,,,oop;rust;language-design;liskov-substitution-principle,kFYatek,5983,403742,registered,true,,,CC BY-SA 3.0,,4143,3792,8,1,0,4,false,false,false,true,true,true,52,7,true,0.262,0.0033,4292,2015,2,15,Friday,false,false,false,false,false,false,false
30938499,Why is the `Sized` bound necessary in this trait?,"I have a trait with two associated functions:
trait WithConstructor: Sized {
fn new_with_param(param: usize) -> Self;
fn new() -> Self {
Self::new_with_param(0)
}
}
Why does the default implementation of the second method (new()) force me to put the Sized bound on the type? I think it's because of the stack pointer manipulation, but I'm not sure.
If the compiler needs to know the size to allocate memory on the stack,
why does the following example not require Sized for T?
struct SimpleStruct<T> {
field: T,
}
fn main() {
let s = SimpleStruct { field: 0u32 };
}
",https://stackoverflow.com/questions/30938499/why-is-the-sized-bound-necessary-in-this-trait,87,45243.0,2.0,,,2015-06-19 12:45:06,2018-01-19 03:07:59,2018-01-19 03:03:06,,,rust;traits,eulerdisk,4809,4998184,registered,true,30941589,,CC BY-SA 3.0,,737,616,6,0,0,2,true,false,false,true,true,true,49,9,true,0.044,0.0019,4173,2015,6,12,Friday,false,false,false,false,false,false,false
46885292,How to launch a Rust application from Visual Studio Code?,"I have installed the Visual Studio Code extensions for Rust:
I want to run my project and I don't understand where to click.
I tried clicking Run Task, Run build task, Configure Default build task, but nothing reasonable happens.
",https://stackoverflow.com/questions/46885292/how-to-launch-a-rust-application-from-visual-studio-code,87,83244.0,7.0,,,2017-10-23 08:51:10,2025-03-24 21:30:46,2017-10-23 14:40:30,,,rust;vs-code;rust-cargo;rust-language-server,Stepan Yakovenko,9376,517073,registered,true,,,CC BY-SA 3.0,,605,237,0,2,2,4,false,false,false,true,true,true,57,10,true,0.084,0.001,3316,2017,10,8,Monday,false,false,false,false,false,false,false
24245276,"Why does Rust not have a return value in the main function, and how to return a value anyway?","In Rust the main function is defined like this:
fn main() {
}
This function does not allow for a return value though. Why would a language not allow for a return value and is there a way to return something anyway? Would I be able to safely use the C exit(int) function, or will this cause leaks and whatnot?
",https://stackoverflow.com/questions/24245276/why-does-rust-not-have-a-return-value-in-the-main-function-and-how-to-return-a,87,62029.0,6.0,,,2014-06-16 13:47:09,2023-08-16 08:50:49,2015-10-16 12:09:44,,,return;program-entry-point;rust,Jeroen,17304,2558778,registered,true,50459909,,CC BY-SA 3.0,,365,314,2,0,0,3,true,false,false,true,true,true,93,19,true,0.097,0.0014,4541,2014,6,13,Monday,false,false,false,false,false,false,false
25649423,Sending trait objects between threads in Rust,"I'd like to send a trait object between threads, but can't figure out if it's possible. It seems like it might not be, as they apparently do not fulfill the Send trait.
The following code demonstrates what I'm trying to do:
use std::{
sync::mpsc::{channel, Receiver, Sender},
thread,
};
trait Bar {
fn bar(&self);
}
struct Foo {
foo: i32,
}
impl Bar for Foo {
fn bar(&self) {
println!(""foo: {}"", self.foo);
}
}
fn main() {
let foo = Box::new(Foo { foo: 1 }) as Box<dyn Bar>;
let (tx, rx): (Sender<Box<dyn Bar>>, Receiver<Box<dyn Bar>>) = channel();
thread::spawn(move || {
tx.send(foo).unwrap();
});
let sent = rx.recv().unwrap();
sent.bar();
}
This fails with the following message:
error[E0277]: `dyn Bar` cannot be sent between threads safely
--> src/main.rs:25:5
|
25 | thread::spawn(move || {
| ^^^^^^^^^^^^^ `dyn Bar` cannot be sent between threads safely
|
= help: the trait `std::marker::Send` is not implemented for `dyn Bar`
= note: required because of the requirements on the impl of `std::marker::Send` for `std::ptr::Unique<dyn Bar>`
= note: required because it appears within the type `std::boxed::Box<dyn Bar>`
= note: required because it appears within the type `[closure@src/main.rs:25:19: 27:6 tx:std::sync::mpsc::Sender<std::boxed::Box<dyn Bar>>, foo:std::boxed::Box<dyn Bar>]`
Trying to send a plain, unboxed trait object results in a bunch of other errors, mostly complaining about not fulfilling Send + Sized.
I'm still fairly new to Rust, so I'm not sure if there's something I'm missing, but I get the impression that there isn't a way to convince the compiler to make the trait object Send.
If it isn't currently possible, is there any work currently under way that may allow for this in the future?
",https://stackoverflow.com/questions/25649423/sending-trait-objects-between-threads-in-rust,87,37250.0,1.0,,,2014-09-03 16:32:49,2019-11-25 17:20:24,2019-11-25 17:20:24,,,rust;trait-objects,guff,993,1100990,registered,true,25649509,,CC BY-SA 4.0,,2085,1917,5,0,0,2,true,false,false,true,true,true,45,7,false,0.027,0.0023,4462,2014,9,16,Wednesday,false,false,false,false,false,false,false
13212212,Creating two dimensional arrays in Rust,"How do I create an empty mutable two dimensional array in Rust?
This is what I have tried so far:
let mut state[[u8 * 4] * 4];
This produces the error
error: expected one of `:`, `;`, `=`, or `@`, found `[`
--> src/main.rs:2:18
|
2 | let mut state[[u8 * 4] * 4];
| ^ expected one of `:`, `;`, `=`, or `@` here
",https://stackoverflow.com/questions/13212212/creating-two-dimensional-arrays-in-rust,85,160664.0,13.0,,,2012-11-03 18:31:15,2026-04-15 17:35:38,2018-02-15 17:40:42,,,arrays;vector;multidimensional-array;rust,php--,3347,946299,registered,true,13235399,,CC BY-SA 3.0,,453,345,2,0,0,4,true,false,false,true,true,true,39,6,false,0.081,0.0005,5131,2012,11,18,Saturday,true,false,false,false,false,false,false
69909997,How can I remove type annotation help when using rust-analyzer?,"For VS Code, I use rust-analyzer to handle syntax highlighting and flychecking.
How do I remove the inlay type and parameter annotations in grey below?
",https://stackoverflow.com/questions/69909997/how-can-i-remove-type-annotation-help-when-using-rust-analyzer,85,32469.0,2.0,,,2021-11-10 08:33:48,2023-11-30 21:19:53,2022-10-17 17:03:00,,,vs-code;rust;rust-analyzer,Thorkil Værge,4255,2574407,registered,true,69910667,,CC BY-SA 4.0,,330,153,1,1,1,3,true,false,false,true,true,true,63,10,true,0.062,0.0026,1837,2021,11,8,Wednesday,false,false,false,false,false,false,false
27996430,Reversing a string in Rust,"What is wrong with this:
fn main() {
let word: &str = ""lowks"";
assert_eq!(word.chars().rev(), ""skwol"");
}
I get an error like this:
error[E0369]: binary operation `==` cannot be applied to type `std::iter::Rev<std::str::Chars<'_>>`
--> src/main.rs:4:5
|
4 | assert_eq!(word.chars().rev(), ""skwol"");
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: an implementation of `std::cmp::PartialEq` might be missing for `std::iter::Rev<std::str::Chars<'_>>`
= note: this error originates in a macro outside of the current crate
What is the correct way to do this?
",https://stackoverflow.com/questions/27996430/reversing-a-string-in-rust,85,87356.0,3.0,,,2015-01-17 05:21:05,2024-01-18 20:45:14,2018-01-10 03:23:42,,,rust,Muhammad Lukman Low,8609,501800,registered,true,27996791,,CC BY-SA 3.0,,732,624,2,0,0,1,true,false,false,true,true,true,26,5,false,0.034,0.001,4326,2015,1,5,Saturday,true,false,false,false,false,false,false
59428096,Understanding the Send trait,"I am trying to wrap my head around Send + Sync traits. I get the intuition behind Sync - this is the traditional thread safety(like in C++). The object does the necessary locking(interior mutability if needed), so threads can safely access it.
But the Send part is bit unclear. I understand why things like Rc are Send only - the object can be given to a different thread, but non-atomic operations make it thread unsafe.
What is the intuition behind Send? Does it mean the object can be copied/moved into another thread context, and continues to be valid after the copy/move?
Any examples scenarios for ""Sync but no Send"" would really help. Please also point to any rust libraries for this case (I found several for the opposite though)
For (2), I found some threads which use structs with pointers to data on stack/thread local storage as examples. But these are unsafe anyways(Sync or otherwise).
",https://stackoverflow.com/questions/59428096/understanding-the-send-trait,85,38017.0,4.0,,,2019-12-20 15:58:05,2023-01-04 12:59:09,2020-03-26 09:24:18,,,rust,rusty,1199,12167264,registered,true,,,CC BY-SA 4.0,,1084,905,9,0,0,1,false,false,false,true,true,true,28,4,false,0.105,0.0022,2528,2019,12,15,Friday,false,false,false,false,false,false,false
26685666,A local function in Rust,"In there any way in Rust to create a local function which can be called more than once. The way I'd do that in Python is:
def method1():
def inner_method1():
print("Hello")
inner_method1()
inner_method1()
",https://stackoverflow.com/questions/26685666/a-local-function-in-rust,85,36828.0,2.0,,,2014-11-01 02:18:20,2023-01-24 03:13:45,2021-01-07 15:23:24,,,rust,Incerteza,35684,2813589,registered,true,26685687,,CC BY-SA 4.0,,329,227,1,0,0,1,true,false,false,true,true,true,24,5,false,0.054,0.0023,4403,2014,11,2,Saturday,true,false,false,false,false,false,false
30511331,Getting the absolute path from a PathBuf,"Given a relative path:
PathBuf::from(""./cargo_home"")
Is there a way to get the absolute path?
",https://stackoverflow.com/questions/30511331/getting-the-absolute-path-from-a-pathbuf,84,59659.0,5.0,,,2015-05-28 15:46:32,2024-10-24 13:35:59,,,,rust,Eduardo Bautista,1488,1254034,registered,true,38384901,,CC BY-SA 3.0,,135,97,1,0,0,1,true,false,false,true,true,false,40,7,false,0.084,0.0014,4195,2015,5,15,Thursday,false,false,false,false,false,false,false
30186037,How can I read a single line from stdin in Rust?,"I'm asking for the equivalent of fgets() in C.
let line = ...;
println!(""You entered: {}"", line);
I've read How to read user input in Rust?, but it asks how to read multiple lines; I want only one line.
I also read How do I read a single String from standard input?, but I'm not sure if it behaves like fgets() or sscanf(""%s"",...).
",https://stackoverflow.com/questions/30186037/how-can-i-read-a-single-line-from-stdin-in-rust,84,84226.0,7.0,,,2015-05-12 08:51:38,2025-03-03 14:10:59,2023-10-28 14:42:28,,,rust,sashoalm,81158,492336,registered,true,30186553,,CC BY-SA 4.0,,620,337,4,2,0,1,true,false,false,true,true,true,48,11,true,0.083,0.001,4211,2015,5,8,Tuesday,false,false,false,false,false,false,false
52751597,What is the difference between a constant and a static variable and which should I choose?,"I know this from RFC 246:
- constants declare constant values. These represent a value, not a memory address. This is the most common thing one would reach for and would replace
static as we know it today in almost all cases.
- statics declare global variables. These represent a memory address. They would be rarely used: the primary use cases are global locks, global atomic counters, and interfacing with legacy C libraries.
I don't know what is actually different between the two when I try to maintain a table.
Which one should I choose?
",https://stackoverflow.com/questions/52751597/what-is-the-difference-between-a-constant-and-a-static-variable-and-which-should,84,37223.0,5.0,,,2018-10-11 03:11:42,2025-05-18 17:58:17,2021-03-10 20:35:46,,,variables;rust;static;constants,aurexav,3085,6819040,registered,true,52753798,,CC BY-SA 4.0,,803,559,1,1,0,4,true,false,false,true,true,true,90,16,true,0.134,0.0023,2963,2018,10,3,Thursday,false,false,false,false,false,false,false
48053933,How to check if a directory exists and create a new one if it doesn't?,"I tried the following but I don't think it's particularly pretty:
let path = ""target/dir"";
if !std::path::Path::new(&path).exists() {
std::fs::create_dir(path)?;
}
",https://stackoverflow.com/questions/48053933/how-to-check-if-a-directory-exists-and-create-a-new-one-if-it-doesnt,84,43058.0,1.0,,,2018-01-01 22:56:05,2022-04-04 15:52:36,2022-04-04 15:52:36,,,directory;rust,user1350184,,,does_not_exist,true,48053959,,CC BY-SA 4.0,,205,174,1,0,0,2,true,false,false,true,false,true,74,15,true,0.023,0.002,3246,2018,1,22,Monday,false,false,false,false,false,false,false
66362625,Why is Rust's .expect() called expect?,"Rust's .expect() is one of the most surprising names in the Result/Option space. While unwrap makes sense -- get a value from a Result by "unwrapping" it -- expect is surprisingly counterintuitive (to me).
Since so much of Rust is inspired by conventions from functional programming languages, I have been assuming that this is another example of "strange homage to obscurity," but when I asked the Duck it couldn't find an answer for me.
So, I give up. Why is .expect() the name for Rust's .unwrap_or_panic_with_this_message() function? Is this a reference to a feature in yet another functional language? Is it back-handed shade (or a complement) to Tcl? The result of too many late nights and too much Espresso at Mozilla?
What is the etymology of this plucky (but fierce!) little member of the standard library?
Edit:
Great news, everyone! After more than a year, we now have both an "explanation" in @GManNickG's tremendously well-researched and documented answer, below, and a "mental model" provided by @Peng's comment and link:
https://doc.rust-lang.org/std/error/index.html#common-message-styles
In short, it is now recommended that diagnostics for expect() should be written as "expect...should" or maybe "expect...should have". This makes more sense in the diagnostic output (see the link for examples) but also makes the source code scan better:
foo.expect("something bad happened") // NO!
foo.expect("gollywumpus should be current") // YES!
",https://stackoverflow.com/questions/66362625/why-is-rusts-expect-called-expect,84,30859.0,1.0,,,2021-02-25 04:53:37,2022-09-17 17:30:54,2022-09-17 17:30:54,2021-02-25 15:40:45,Opinion-based,rust,aghast,15498,4029014,registered,true,66364221,,,,1827,1539,8,1,0,1,true,true,false,true,true,true,42,6,true,0.032,0.0027,2095,2021,2,4,Thursday,false,false,false,false,false,false,false
29445026,"Converting number primitives (i32, f64, etc) to byte representations","I am writing a library that encodes/decodes data to/from a binary format. Part of the format is numbers, which I'm using Rust's native primitive types for (like i8, i64, f32 etc.).
Is there an easy, built-in way to convert these data types into/from binary, i.e. convert a f64/f32/i64/etc. into a Vec<u8>? Likewise is there a way to convert 4 u8s (in a Vec<u8> say) into an f32?
",https://stackoverflow.com/questions/29445026/converting-number-primitives-i32-f64-etc-to-byte-representations,83,76480.0,5.0,,,2015-04-04 09:55:49,2019-12-22 23:00:43,2018-05-30 10:40:17,,,types;rust,Amandasaurus,61767,161922,registered,true,29445654,,CC BY-SA 4.0,,536,392,10,0,0,2,true,false,false,true,true,true,68,9,false,0.065,0.0011,4249,2015,4,9,Saturday,true,false,false,false,false,false,false
31582064,How to link to other fns/structs/enums/traits in rustdoc?,"I'm building a Rust library and want to give it some polish. In the rustdoc, I'd sometimes like to link to other parts of the library within the docs, e.g. fns, traits or structs. What is the official syntax for this?
",https://stackoverflow.com/questions/31582064/how-to-link-to-other-fns-structs-enums-traits-in-rustdoc,83,26342.0,5.0,,,2015-07-23 08:30:29,2020-12-11 02:32:07,2016-08-17 12:17:20,,,rust;rustdoc,llogiq,14701,2765603,registered,true,38993391,,CC BY-SA 3.0,,273,218,3,0,0,2,true,false,false,true,true,true,57,8,true,0.19,0.0032,4139,2015,7,8,Thursday,false,false,false,false,false,false,false
16421033,Lazy sequence generation in Rust,"How can I create what other languages call a lazy sequence or a ""generator"" function?
In Python, I can use yield as in the following example (from Python's docs) to lazily generate a sequence that is iterable in a way that does not use the memory of an intermediary list:
# a generator that yields items instead of returning a list
def firstn(n):
num = 0
while num < n:
yield num
num += 1
sum_of_first_n = sum(firstn(1000000))
How can I do something similar in Rust?
",https://stackoverflow.com/questions/16421033/lazy-sequence-generation-in-rust,83,36615.0,5.0,,,2013-05-07 14:02:22,2025-08-11 08:02:23,2017-04-21 18:55:57,,,rust;lazy-sequences,NathanD,8281,30544,registered,true,16421232,,CC BY-SA 3.0,,594,499,2,0,0,2,true,false,false,true,true,true,32,5,false,0.137,0.0023,4946,2013,5,14,Tuesday,false,false,false,false,false,false,false
28024373,Is there a way to print enum values?,"Is there an easy way to format and print enum values? I expected that they'd have a default implementation of std::fmt::Display, but that doesn't appear to be the case.
enum Suit {
Heart,
Diamond,
Spade,
Club
}
fn main() {
let s: Suit = Suit::Heart;
println!(""{}"", s);
}
Desired output: Heart
Error:
error[E0277]: the trait bound `Suit: std::fmt::Display` is not satisfied
--> src/main.rs:10:20
|
10 | println!(""{}"", s);
| ^ the trait `std::fmt::Display` is not implemented for `Suit`
|
= note: `Suit` cannot be formatted with the default formatter; try using `:?` instead if you are using a format string
= note: required by `std::fmt::Display::fmt`
",https://stackoverflow.com/questions/28024373/is-there-a-way-to-print-enum-values,82,73633.0,6.0,,,2015-01-19 12:10:32,2024-09-14 06:26:07,2017-01-22 21:42:47,,,enums;rust,Daniel Lucraft,7386,11951,registered,true,28024504,,CC BY-SA 3.0,,860,726,4,0,0,2,true,false,false,true,true,true,36,8,true,0.081,0.0011,4324,2015,1,12,Monday,false,false,false,false,false,false,false
26665471,Are semicolons optional in Rust?,"Since semicolons are apparently optional in Rust, why, if I do this:
fn fn1() -> i32 {
let a = 1
let b = 2
3
}
I get the error:
error: expected one of `.`, `;`, `?`, or an operator, found `let`
--> src/main.rs:3:9
|
2 | let a = 1
| - expected one of `.`, `;`, `?`, or an operator here
3 | let b = 2
| ^^^ unexpected token
",https://stackoverflow.com/questions/26665471/are-semicolons-optional-in-rust,82,29848.0,3.0,,,2014-10-30 23:59:20,2024-07-20 18:23:40,2019-03-24 11:15:58,,,syntax;rust,Incerteza,35684,2813589,registered,true,26665514,,CC BY-SA 4.0,,500,399,2,0,0,2,true,false,false,true,true,true,32,5,true,0.101,0.0027,4405,2014,10,23,Thursday,false,false,false,false,false,false,false
45882329,Read large files line by line in Rust,"My Rust program is intented to read a very large (up to several GB), simple text file line by line. The problem is, that this file is too large to be read at once, or to transfer all lines into a Vec<String>.
What would be an idiomatic way to handle this in Rust?
",https://stackoverflow.com/questions/45882329/read-large-files-line-by-line-in-rust,82,106897.0,1.0,,,2017-08-25 13:15:41,2020-09-04 06:56:11,2017-08-25 13:36:10,2017-08-25 13:31:46,Duplicate,rust,Piwo,1519,7855177,registered,true,45882510,,,,298,271,1,0,0,1,true,true,false,true,true,true,37,8,false,0.009,0.0008,3375,2017,8,13,Friday,false,false,false,false,false,false,false
30009650,How to document Rust function arguments?,"rustdoc allows you to document struct fields and enum variants by including a doc comment above each line:
enum Choices {
/// The first choice.
First,
/// The second choice.
Second,
}
struct Person {
/// The person's name.
name: String,
/// The person's age.
age: u8,
}
These will show up with nice formatting in the HTML generated by rustdoc. However, I haven't seen any way of making similar nicely-formatted documents for function arguments. Is there an ""official"" way to document them or do you just have to describe them freeform in the function's main documentation section?
",https://stackoverflow.com/questions/30009650/how-to-document-rust-function-arguments,82,43690.0,4.0,,,2015-05-03 02:34:53,2024-07-24 19:19:43,2023-09-12 13:41:04,,,rust;rustdoc,Jimmy,37681,242493,registered,true,68983052,,CC BY-SA 4.0,,639,601,1,0,0,2,true,false,false,true,true,true,40,6,true,0.092,0.0019,4220,2015,5,2,Sunday,true,false,false,false,false,false,false
42722169,Generate pretty (indented) JSON with serde,"Using the serde_json crate, I can use
::serde_json::to_string(&obj)
to serialize an object into a JSON string. The resulting JSON uses compact formatting, like:
{""foo"":1,""bar"":2}
But how do I generate pretty/indented JSON? For example, I'd like to get this:
{
""foo"": 1,
""bar"": 2
}
",https://stackoverflow.com/questions/42722169/generate-pretty-indented-json-with-serde,82,48513.0,3.0,,,2017-03-10 15:34:23,2025-12-12 01:11:08,2017-03-10 15:37:30,,,json;rust;serde,Jo Liss,34046,525872,registered,true,49087292,,CC BY-SA 3.0,,454,297,3,1,0,3,true,false,false,true,true,true,42,6,false,0.062,0.0017,3543,2017,3,15,Friday,false,false,false,false,false,false,false
16494822,Why is it called "Rust"?,"Why is the Rust programming language called ""Rust""?
Is there anything known about who named it, and why? (I am having a hard time coming up with a positive association).
",https://stackoverflow.com/questions/16494822/why-is-it-called-rust,82,30852.0,2.0,,,2013-05-11 07:22:50,2023-02-18 16:20:30,,2023-02-18 16:47:00,Not suitable for this site,naming;rust,Thilo,264177,14955,registered,true,,,,,185,171,0,0,0,2,false,true,false,true,true,false,34,5,true,0.065,0.0027,4942,2013,5,7,Saturday,true,false,false,false,false,false,false
27961879,Why is using return as the last statement in a function considered bad style?,"I was reading through the Rust documentation and came across the following example and statement
Using a return as the last line of a function works, but is considered poor style:
fn foo(x: i32) -> i32 {
if x < 5 { return x; }
return x + 1;
}
I know I could have written the above as
fn foo(x: i32) -> i32 {
if x < 5 { return x; }
x + 1
}
but I am more tempted to write the former, as that is more intuitive. I do understand that the function return value should be used as an expression so the later works but then why wouldn't the former be encouraged?
",https://stackoverflow.com/questions/27961879/why-is-using-return-as-the-last-statement-in-a-function-considered-bad-style,82,30223.0,6.0,,,2015-01-15 10:58:17,2023-01-25 11:26:01,2015-01-15 16:00:39,,,rust,Abhijit,64133,977038,registered,true,,,CC BY-SA 3.0,,669,593,2,0,0,1,false,false,false,true,true,true,77,14,true,0.199,0.0027,4328,2015,1,10,Thursday,false,false,false,false,false,false,false
34215280,How can I randomly select one element from a vector or array?,"I have a vector where the element is a (String, String). How can I randomly pick one of these elements?
",https://stackoverflow.com/questions/34215280/how-can-i-randomly-select-one-element-from-a-vector-or-array,81,65213.0,6.0,,,2015-12-11 02:41:26,2025-04-09 18:55:06,2017-02-16 14:33:05,,,rust,coco,991,4559989,registered,true,34215930,,CC BY-SA 3.0,,124,104,1,0,0,1,true,false,false,true,true,true,61,12,true,0.092,0.0012,3998,2015,12,2,Friday,false,false,false,false,false,false,false
29861388,When is it useful to define multiple lifetimes in a struct?,"In Rust, when we want a struct to contain references, we typically define their lifetimes as such:
struct Foo<'a> {
x: &'a i32,
y: &'a i32,
}
But it's also possible to define multiple lifetimes for different references in the same struct:
struct Foo<'a, 'b> {
x: &'a i32,
y: &'b i32,
}
When is it ever useful to do this? Can someone provide some example code that doesn't compile when both lifetimes are 'a but does compile when the lifetimes are 'a and 'b (or vice versa)?
",https://stackoverflow.com/questions/29861388/when-is-it-useful-to-define-multiple-lifetimes-in-a-struct,81,13811.0,4.0,,,2015-04-25 05:29:42,2023-07-28 20:50:20,,,,rust;lifetime,Kai,3002,1079493,registered,true,29862184,,CC BY-SA 3.0,,632,524,5,0,0,2,true,false,false,true,true,false,59,11,true,0.29,0.0059,4228,2015,4,5,Saturday,true,false,false,false,false,false,false
32429369,How to opt out of running a doc test?,"I'm writing a Rust library and I want to provide examples in my documentation that
- compile as part of running
cargo test
- do not run.
Is this possible?
I'm writing a database client library, and the examples make use of a hypothetical, non-existing database server. As such, the examples always fail when run, but it's important that the examples be valid syntactically. Hence my requirements above.
If there's no way to do what I want, then how does one opt out of having cargo test run a specific doc test? I.e., have cargo run compile-and-run some doc tests but completely ignore some others?
",https://stackoverflow.com/questions/32429369/how-to-opt-out-of-running-a-doc-test,80,25522.0,3.0,,,2015-09-06 23:42:07,2024-02-01 06:20:02,2017-06-01 14:56:59,,,rust;rust-cargo,Craig M. Brandenburg,3704,1094609,registered,true,32429385,,CC BY-SA 3.0,,705,602,3,0,0,2,true,false,false,true,true,true,37,9,true,0.118,0.0031,4094,2015,9,23,Sunday,true,false,false,false,false,false,false
29490670,How does Rust provide move semantics?,"The Rust language website claims move semantics as one of the features of the language. But I can't see how move semantics are implemented in Rust.
Rust boxes are the only place where move semantics are used.
let x = Box::new(5);
let y: Box<i32> = x; // x is 'moved'
The above Rust code can be written in C++ as
auto x = std::make_unique<int>(5);
auto y = std::move(x); // Note the explicit move
As far as I know (correct me if I'm wrong),
- Rust doesn't have constructors at all, let alone move constructors.
- No support for rvalue references.
- No way to create functions overloads with rvalue parameters.
How does Rust provide move semantics?
",https://stackoverflow.com/questions/29490670/how-does-rust-provide-move-semantics,80,23832.0,5.0,,,2015-04-07 11:37:57,2023-08-24 07:46:39,2023-08-24 07:42:39,,,rust;move-semantics,Fish,1275,3711299,registered,true,29490907,,CC BY-SA 4.0,,911,657,2,1,0,2,true,false,false,true,true,true,37,6,true,0.21,0.0034,4246,2015,4,11,Tuesday,false,false,false,false,false,false,false
52521201,How do I synchronously return a value calculated in an asynchronous Future?,"I am trying to use hyper to grab the content of an HTML page and would like to synchronously return the output of a future. I realized I could have picked a better example since synchronous HTTP requests already exist, but I am more interested in understanding whether we could return a value from an async calculation.
extern crate futures;
extern crate hyper;
extern crate hyper_tls;
extern crate tokio;
use futures::{future, Future, Stream};
use hyper::Client;
use hyper::Uri;
use hyper_tls::HttpsConnector;
use std::str;
fn scrap() -> Result<String, String> {
let scraped_content = future::lazy(|| {
let https = HttpsConnector::new(4).unwrap();
let client = Client::builder().build::<_, hyper::Body>(https);
client
.get(""https://hyper.rs"".parse::<Uri>().unwrap())
.and_then(|res| {
res.into_body().concat2().and_then(|body| {
let s_body: String = str::from_utf8(&body).unwrap().to_string();
futures::future::ok(s_body)
})
}).map_err(|err| format!(""Error scraping web page: {:?}"", &err))
});
scraped_content.wait()
}
fn read() {
let scraped_content = future::lazy(|| {
let https = HttpsConnector::new(4).unwrap();
let client = Client::builder().build::<_, hyper::Body>(https);
client
.get(""https://hyper.rs"".parse::<Uri>().unwrap())
.and_then(|res| {
res.into_body().concat2().and_then(|body| {
let s_body: String = str::from_utf8(&body).unwrap().to_string();
println!(""Reading body: {}"", s_body);
Ok(())
})
}).map_err(|err| {
println!(""Error reading webpage: {:?}"", &err);
})
});
tokio::run(scraped_content);
}
fn main() {
read();
let content = scrap();
println!(""Content = {:?}"", &content);
}
The example compiles and the call to read() succeeds, but the call to scrap() panics with the following error message:
Content = Err(""Error scraping web page: Error { kind: Execute, cause: None }"")
I understand that I failed to launch the task properly before calling .wait() on the future but I couldn't find how to properly do it, assuming it's even possible.
",https://stackoverflow.com/questions/52521201/how-do-i-synchronously-return-a-value-calculated-in-an-asynchronous-future,80,57526.0,3.0,,,2018-09-26 15:21:11,2022-09-14 01:17:19,2022-09-14 01:17:19,,,rust;async-await;future,Boris,1301,5223795,registered,true,52521592,,CC BY-SA 4.0,,2525,2378,5,0,0,3,true,false,false,true,true,true,75,12,true,0.052,0.0014,2978,2018,9,15,Wednesday,false,false,false,false,false,false,false
32381414,Converting a hexadecimal string to a decimal integer,"I'm writing a Rust program that reads off of an I2C bus and saves the data. When I read the I2C bus, I get hex values like 0x11, 0x22, etc.
Right now, I can only handle this as a string and save it as is. Is there a way I can parse this into an integer? Is there any built in function for it?
",https://stackoverflow.com/questions/32381414/converting-a-hexadecimal-string-to-a-decimal-integer,80,71360.0,2.0,,,2015-09-03 16:52:45,2024-09-18 19:19:14,2018-10-25 12:27:09,,,parsing;hex;rust,tsf144,997,1542937,registered,true,32381836,,CC BY-SA 4.0,,334,294,2,0,0,3,true,false,false,true,true,true,52,8,false,0.028,0.0011,4097,2015,9,16,Thursday,false,false,false,false,false,false,false
47980023,How to convert from &[u8] to Vec<u8>?,"I'm attempting to simply convert a slice to a vector. The following code:
let a = &[0u8];
let b: Vec<u8> = a.iter().collect();
fails with the following error message:
3 | let b: Vec<u8> = a.iter().collect();
| ^^^^^^^ a collection of type `std::vec::Vec<u8>` cannot be built from an iterator over elements of type `&u8`
What am I missing?
",https://stackoverflow.com/questions/47980023/how-to-convert-from-u8-to-vecu8,79,73893.0,4.0,,,2017-12-26 14:36:55,2024-12-12 20:14:26,,,,rust,user8370684,,,does_not_exist,true,47980272,,CC BY-SA 3.0,,477,408,2,0,0,1,true,false,false,true,false,false,47,7,true,0.054,0.0011,3252,2017,12,14,Tuesday,false,false,false,false,false,false,false
37506672,Convert float to integer in Rust,"double b = a / 100000;
b = (int) b;
b *= 100000;
How the above C code is converted to Rust? Especially the line #2 that rounds the number.
",https://stackoverflow.com/questions/37506672/convert-float-to-integer-in-rust,79,109915.0,3.0,,,2016-05-29 05:53:29,2022-11-27 11:24:17,,,,rust,exebook,34719,1968972,registered,true,37508518,,CC BY-SA 3.0,,172,141,1,0,0,1,true,false,false,true,true,false,32,6,false,0.027,0.0007,3828,2016,5,5,Sunday,true,false,false,false,false,false,false
51429501,How do I conditionally check if an enum is one variant or another?,"I have an enum with two variants:
enum DatabaseType {
Memory,
RocksDB,
}
What do I need in order to make a conditional if inside a function that checks if an argument is DatabaseType::Memory or DatabaseType::RocksDB?
fn initialize(datastore: DatabaseType) -> Result<V, E> {
if /* Memory */ {
//..........
} else if /* RocksDB */ {
//..........
}
}
",https://stackoverflow.com/questions/51429501/how-do-i-conditionally-check-if-an-enum-is-one-variant-or-another,79,69547.0,3.0,,,2018-07-19 18:22:42,2023-12-08 01:38:25,2018-07-19 18:25:31,,,enums;rust;conditional-statements,Splatrac,975,6629864,registered,true,51429606,,CC BY-SA 4.0,,486,398,4,0,0,3,true,false,false,true,true,true,66,13,true,0.043,0.0011,3047,2018,7,18,Thursday,false,false,false,false,false,false,false
39482131,Is it possible to use `impl Trait` as a function's return type in a trait definition?,"Is it at all possible to define functions inside of traits as having impl Trait return types? I want to create a trait that can be implemented by multiple structs so that the new() functions of all of them returns an object that they can all be used in the same way without having to write code specific to each one.
trait A {
fn new() -> impl A;
}
However, I get the following error:
error[E0562]: `impl Trait` not allowed outside of function and inherent method return types
--> src/lib.rs:2:17
|
2 | fn new() -> impl A;
| ^^^^^^
Is this a limitation of the current implementation of impl Trait or am I using it wrong?
",https://stackoverflow.com/questions/39482131/is-it-possible-to-use-impl-trait-as-a-functions-return-type-in-a-trait-defini,79,38019.0,5.0,,,2016-09-14 03:38:25,2024-02-26 19:09:03,2019-11-06 17:02:22,,,rust;traits,Ameo,2577,3833068,registered,true,39482164,,CC BY-SA 4.0,,813,666,5,0,0,2,true,false,false,true,true,true,89,16,true,0.132,0.0021,3720,2016,9,3,Wednesday,false,false,false,false,false,false,false
23100534,"How to sum the values in an array, slice, or Vec in Rust?","
Editor's note: This question's example is from a version of Rust prior to 1.0 and references types and methods no longer found in Rust. The answers still contain valuable information.
The following code
let mut numbers = new_serial.as_bytes().iter().map(|&x| (x - 48));
let sum = numbers.sum();
results in the following error:
std::iter::Map<,&u8,u8,std::slice::Items<,u8>>` does not implement any method in scope named `sum`
What must I do to sum an array of bytes?
The following works:
for byte in new_serial.as_bytes().iter() {
sum = sum + (byte - 48);
}
",https://stackoverflow.com/questions/23100534/how-to-sum-the-values-in-an-array-slice-or-vec-in-rust,79,100428.0,2.0,,,2014-04-16 05:15:28,2023-05-24 19:07:04,2019-07-06 14:35:18,,,rust,rogergl,3789,1528246,registered,true,23100794,,CC BY-SA 4.0,,768,597,3,0,0,1,true,false,false,true,true,true,57,13,true,0.02,0.0008,4602,2014,4,5,Wednesday,false,false,false,false,false,false,false
29871967,What is the difference between macros and functions in Rust?,"Quoted from the Rust blog:
One last thing to mention: Rust’s macros are significantly different from C macros, if you’ve used those
What is the difference between macros and function in Rust? How is it different from C?
",https://stackoverflow.com/questions/29871967/what-is-the-difference-between-macros-and-functions-in-rust,79,31697.0,4.0,,,2015-04-25 23:40:05,2024-06-02 06:29:51,2015-04-26 23:36:40,,,rust,geckob,8238,4144667,registered,true,29872492,,CC BY-SA 3.0,,351,226,0,1,0,1,true,false,false,true,true,true,60,10,true,0.126,0.0025,4228,2015,4,23,Saturday,true,false,false,false,false,false,false
37149831,What is the difference between these 3 ways of declaring a string in Rust?,"let hello1 = ""Hello, world!"";
let hello2 = ""Hello, world!"".to_string();
let hello3 = String::from(""Hello, world!"");
",https://stackoverflow.com/questions/37149831/what-is-the-difference-between-these-3-ways-of-declaring-a-string-in-rust,79,15765.0,1.0,,,2016-05-10 22:11:29,2018-01-24 01:59:19,2016-05-10 22:14:02,,,string;rust,user,3259,744184,registered,true,37149882,,CC BY-SA 3.0,,141,117,1,0,0,2,true,false,false,true,true,true,74,14,true,0.063,0.005,3847,2016,5,22,Tuesday,false,false,false,false,false,false,false
41069865,"How to create an in-memory object that can be used as a Reader, Writer, or Seek in Rust?","I need a completely in-memory object that I can give to BufReader and BufWriter. Something like Python's StringIO. I want to write to and read from such an object using methods ordinarily used with Files.
Is there a way to do this using the standard library?
",https://stackoverflow.com/questions/41069865/how-to-create-an-in-memory-object-that-can-be-used-as-a-reader-writer-or-seek,78,34925.0,3.0,,,2016-12-09 22:27:22,2019-12-17 16:39:02,2018-11-05 01:08:46,,,rust;in-memory,liszt,1249,2869868,registered,true,41069910,,CC BY-SA 4.0,,326,260,4,0,0,2,true,false,false,true,true,true,88,18,true,0.086,0.0022,3634,2016,12,22,Friday,false,false,false,false,false,false,false
20922091,How do you use parent module imports in Rust?,"If you have a directory structure like this:
src/main.rs
src/module1/blah.rs
src/module1/blah2.rs
src/utils/logging.rs
How do you use functions from other files?
From the Rust tutorial, it sounds like I should be able to do this:
main.rs
mod utils { pub mod logging; }
mod module1 { pub mod blah; }
fn main() {
utils::logging::trace(""Logging works"");
module1::blah::doit();
}
logging.rs
pub fn trace(msg: &str) {
println!("": {}\n"", msg);
}
blah.rs
mod blah2;
pub fn doit() {
blah2::doit();
}
blah2.rs
mod utils { pub mod logging; }
pub fn doit() {
utils::logging::trace(""Blah2 invoked"");
}
However, this produces an error:
error[E0583]: file not found for module `logging`
--> src/main.rs:1:21
|
1 | mod utils { pub mod logging; }
| ^^^^^^^
|
= help: name the file either logging.rs or logging/mod.rs inside the directory ""src/utils""
It appears that importing down the path, i.e. from main to module1/blah.rs works, and importing peers, i.e. blah2 from blah works, but importing from the parent scope doesn't.
If I use the magical #[path] directive, I can make this work:
blah2.rs
#[path=""../utils/logging.rs""]
mod logging;
pub fn doit() {
logging::trace(""Blah2 invoked"");
}
Do I really have to manually use relative file paths to import something from a parent scope level? Isn't there some better way of doing this in Rust?
In Python, you use from .blah import x for the local scope, but if you want to access an absolute path you can use from project.namespace.blah import x.
",https://stackoverflow.com/questions/20922091/how-do-you-use-parent-module-imports-in-rust,78,65797.0,6.0,,,2014-01-04 14:17:15,2024-01-14 21:35:42,2018-02-07 14:07:37,,,rust,Doug,35764,353820,registered,true,20931520,,CC BY-SA 3.0,,2080,1567,14,0,0,1,true,false,false,true,true,true,45,9,true,0.091,0.0012,4704,2014,1,14,Saturday,true,false,false,false,false,false,false
55402812,How to disable a clippy lint for a single line / block?,"I am getting some Clippy lints that look like this:
warning: methods called `to_*` usually take self by reference; consider choosing a less ambiguous name
--> src/helpers/mod.rs:29:32
|
29 | pub fn to_vec_sorted<U, F>(self, mapper: F) -> Vec<U>
| ^^^^
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#wrong_self_convention
I have no problem dealing with this lint, I just picked it because it doesn't show any proprietary code. Suppose I had a really good reason why I needed to name the function this way, and also that Clippy is integrated into my CI, so I need to have zero Clippy errors / warnings.
Is there a way to disable a Clippy lint for a particular line or code block, analogous to @SuppressWarnings(""whatever"") in Java? I feel like there must be, but I can't find any examples of doing this in the documentation.
",https://stackoverflow.com/questions/55402812/how-to-disable-a-clippy-lint-for-a-single-line-block,78,65449.0,1.0,,,2019-03-28 16:39:52,2022-06-07 07:10:53,2019-03-28 18:13:03,2019-03-28 18:12:08,Duplicate,rust;rust-clippy,Richard Rast,2097,850659,registered,true,55402970,,,,1051,945,2,0,0,2,true,true,false,true,true,true,55,12,true,0.015,0.0012,2795,2019,3,16,Thursday,false,false,false,false,false,false,false
29548819,How do I sum a vector using fold?,"This Rust tutorial explains the fold() mechanism well, and this example code:
let sum = (1..4).fold(0, |sum, x| sum + x);
works as expected.
I'd like to run it on a vector, so based on that example, first I wrote this:
let sum: u32 = vec![1,2,3,4,5,6].iter().fold(0, |sum, val| sum += val);
which threw an error:
error: binary assignment operation `+=` cannot be applied to types `_` and `&u32` [E0368]
let sum = ratings.values().fold(0, |sum, val| sum += val);
^~~~~~~~~~
I guessed this might be a reference-related error for some reason, so I changed that to fold(0, |sum, &val| sum += val), which resulted in
error: mismatched types:
expected `u32`,
found `()`
Hm, maybe something's wrong with the closure? Using {sum += x; sum }, I got
binary assignment operation `+=` cannot be applied to types `_` and `&u32`
again.
After further trial and error, adding mut to sum worked:
let sum = vec![1,2,3,4,5,6].iter().fold(0, |mut sum, &x| {sum += x; sum});
Could someone explain the reason why fold() for vectors differs so much from the tutorial? Or is there a better way to handle this?
For reference, I'm using Rust beta, 2015-04-02.
",https://stackoverflow.com/questions/29548819/how-do-i-sum-a-vector-using-fold,78,79359.0,2.0,,,2015-04-09 20:55:45,2021-01-10 14:04:47,2018-07-31 15:35:32,,,vector;rust,mmatyas,1083,4766077,registered,true,29551508,,CC BY-SA 4.0,,1589,1220,12,1,0,2,true,false,false,true,true,true,33,8,true,0.025,0.001,4244,2015,4,20,Thursday,false,false,false,false,false,false,false
56045846,What are the similarities and differences between C++'s concepts and Rust's traits?,"In Rust, the main tool for abstraction are traits. In C++, there are two tools for abstractions: abstract classes and templates. To get rid of some of the disadvantages of using templates (e.g. hard to read error messages), C++ introduced concepts which are ""named sets of requirements"".
Both features seem to be fairly similar:
- Defining a trait/concept is done by listing requirements.
- Both can be used to bound/restrict generic/template type parameters.
- Rust traits and C++ templates with concepts are both monomorphized (I know Rust traits can also be used with dynamic dispatch, but that's a different story).
But from what I understand, there are also notable differences. For example, C++'s concepts seem to define a set of expressions that have to be valid instead of listing function signatures. But there is a lot of different and confusing information out there (maybe because concepts only land in C++20?). That's why I'd like to know: what exactly are the differences between and the similarities of C++'s concepts and Rust's traits?
Are there features that are only offered by either concepts or traits? E.g. what about Rust's associated types and consts? Or bounding a type by multiple traits/concepts?
",https://stackoverflow.com/questions/56045846/what-are-the-similarities-and-differences-between-cs-concepts-and-rusts-trai,78,13812.0,1.0,,,2019-05-08 17:09:32,2019-05-15 16:35:06,2019-05-15 16:35:06,,,c++;rust;traits;c++-concepts,Lukas Kalbertodt,91680,2408867,registered,true,,,CC BY-SA 4.0,,1422,1228,0,1,0,4,false,false,false,true,true,true,91,12,true,0.072,0.0056,2754,2019,5,17,Wednesday,false,false,false,false,false,false,false
45282970,Does Rust have an equivalent to Python's list comprehension syntax?,"Python list comprehension is really simple:
>>> l = [x for x in range(1, 10) if x % 2 == 0]
>>> [2, 4, 6, 8]
Does Rust have an equivalent syntax like:
let vector = vec![x for x in (1..10) if x % 2 == 0]
// [2, 4, 6, 8]
",https://stackoverflow.com/questions/45282970/does-rust-have-an-equivalent-to-pythons-list-comprehension-syntax,77,31049.0,4.0,,,2017-07-24 14:18:51,2023-03-17 22:02:26,2019-10-08 06:58:16,,,syntax;rust;list-comprehension;iterable,Darkaird,2960,7546477,registered,true,45283083,,CC BY-SA 4.0,,342,243,2,0,0,4,true,false,false,true,true,true,71,10,true,0.129,0.0025,3407,2017,7,14,Monday,false,false,false,false,false,false,false
30275982,"When I can use either Cell or RefCell, which should I choose?","From the std::cell documentation, I see that Cell is ""only compatible with types that implement Copy"". This means I must use RefCell for non-Copy types.
When I do have a Copy type, is there a benefit to using one type of cell over another? I assume the answer is ""yes"", because otherwise both types wouldn't exist! What are the benefits and tradeoffs of using one type over the other?
Here's a silly, made-up example that uses both Cell and RefCell to accomplish the same goal:
use std::cell::{Cell,RefCell};
struct ThingWithCell {
counter: Cell<u8>,
}
impl ThingWithCell {
fn new() -> ThingWithCell {
ThingWithCell { counter: Cell::new(0) }
}
fn increment(&self) {
self.counter.set(self.counter.get() + 1);
}
fn count(&self) -> u8 { self.counter.get() }
}
struct ThingWithRefCell {
counter: RefCell<u8>,
}
impl ThingWithRefCell {
fn new() -> ThingWithRefCell {
ThingWithRefCell { counter: RefCell::new(0) }
}
fn increment(&self) {
let mut counter = self.counter.borrow_mut();
*counter = *counter + 1;
}
fn count(&self) -> u8 { *self.counter.borrow_mut() }
}
fn main() {
let cell = ThingWithCell::new();
cell.increment();
println!(""{}"", cell.count());
let cell = ThingWithRefCell::new();
cell.increment();
println!(""{}"", cell.count());
}
",https://stackoverflow.com/questions/30275982/when-i-can-use-either-cell-or-refcell-which-should-i-choose,77,39067.0,3.0,,,2015-05-16 13:01:53,2018-12-07 14:21:03,,,,rust,Shepmaster,442509,155423,registered,true,30276150,,CC BY-SA 3.0,,1639,1405,9,1,0,1,true,false,false,true,true,false,61,12,true,0.077,0.002,4207,2015,5,13,Saturday,true,false,false,false,false,false,false
21257686,What is unwrap and unwrap_or in Rust?,"
Note: The specifics in this question regarding read_line and ~str pertain to a pre-1.0 version of Rust. The general concepts about unwrap and unwrap_or remain relevant.
I encountered this while reading Rust for Rubyists:
let mut reader = BufferedReader::new(io::stdin());
let input = reader.read_line().unwrap_or(~"nothing");
Sometimes it's unwrap, sometimes it's unwrap_or. What is unwrap and unwrap_or?
",https://stackoverflow.com/questions/21257686/what-is-unwrap-and-unwrap-or-in-rust,77,33920.0,2.0,,,2014-01-21 12:06:08,2023-07-01 23:08:16,2023-07-01 23:08:16,,,rust;error-handling,rofrol,15476,588759,registered,true,21258003,,CC BY-SA 4.0,,784,418,9,1,0,2,true,false,false,true,true,true,37,7,true,0.059,0.0023,4687,2014,1,12,Tuesday,false,false,false,false,false,false,false
28136739,Is it possible to control the size of an array using the type parameter of a generic?,"What follows is just used as an example, and not valid Rust code.
struct Vec<T: Sized, Count> {
a: [T; Count]
}
Something like it is possible in C++ templates, but I haven't seen it in Rust.
",https://stackoverflow.com/questions/28136739/is-it-possible-to-control-the-size-of-an-array-using-the-type-parameter-of-a-gen,77,29182.0,3.0,,,2015-01-25 13:07:24,2024-10-20 20:58:57,2017-03-10 02:33:14,,,rust,Byron,4361,651368,registered,true,28137604,,CC BY-SA 3.0,,242,204,1,0,0,1,true,false,false,true,true,true,85,17,true,0.103,0.0026,4318,2015,1,13,Sunday,true,false,false,false,false,false,false
31358826,How do I convert an enum reference to a number?,"I have an enum:
enum Foo {
Bar = 1,
}
How do I convert a reference to this enum into an integer to be used in math?
fn f(foo: &Foo) {
let f = foo as u8; // error[E0606]: casting `&Foo` as `u8` is invalid
let f = foo as &u8; // error[E0605]: non-primitive cast: `&Foo` as `&u8`
let f = *foo as u8; // error[E0507]: cannot move out of borrowed content
}
",https://stackoverflow.com/questions/31358826/how-do-i-convert-an-enum-reference-to-a-number,77,69701.0,1.0,,,2015-07-11 15:38:08,2024-01-26 13:52:50,2018-03-06 03:14:22,,,rust,Vitaly Kushner,9485,74235,registered,true,31359044,,CC BY-SA 3.0,,456,394,2,0,0,1,true,false,false,true,true,true,47,10,true,0.014,0.0011,4151,2015,7,15,Saturday,true,false,false,false,false,false,false
66026309,When and why to use AsRef<T> instead of &T,"AsRef documentation writes
Used to do a cheap reference-to-reference conversion.
I understand reference-to-reference part what does it mean by cheap? I hope it has nothing to do with complexity theoretic (big Oh,. etc) "cheapness".
Example:
struct User {
email: String,
age: u8,
}
impl AsRef<User> for User {
fn as_ref(&self) -> &User {
&self
}
}
fn main() {
let user = User { email: String::from("myemail@example.com"), age: 25 };
let user_ref = &user;
//...
}
What is the reason to implement AsRef for User if I can take a reference by simply &user?
What is the rule for implementing AsRef?
PS: I couldn't find anything answering these questions in other forums and docs.
",https://stackoverflow.com/questions/66026309/when-and-why-to-use-asreft-instead-of-t,76,31709.0,2.0,,,2021-02-03 11:11:29,2023-02-16 16:16:33,2021-08-11 20:56:22,,,generics;rust;polymorphism;traits;parametric-polymorphism,HardFork,1153,12297337,registered,true,66029109,,CC BY-SA 4.0,,969,748,8,0,0,5,true,false,false,true,true,true,52,9,false,0.063,0.0024,2117,2021,2,11,Wednesday,false,false,false,false,false,false,false
22243527,How to implement a custom 'fmt::Debug' trait?,"I presume you do something like this:
extern crate uuid;
use uuid::Uuid;
use std::fmt::Formatter;
use std::fmt::Debug;
#[derive(Debug)]
struct BlahLF {
id: Uuid,
}
impl BlahLF {
fn new() -> BlahLF {
return BlahLF { id: Uuid::new_v4() };
}
}
impl Debug for BlahLF {
fn fmt(&self, &mut f: Formatter) -> Result {
write!(f.buf, ""Hi: {}"", self.id);
}
}
...but attempting to implement this trait generates:
error[E0243]: wrong number of type arguments
--> src/main.rs:19:41
|
19 | fn fmt(&self, &mut f: Formatter) -> Result {
| ^^^^^^ expected 2 type arguments, found 0
However, that seems to be how other implementations do it. What am I doing wrong?
",https://stackoverflow.com/questions/22243527/how-to-implement-a-custom-fmtdebug-trait,76,40595.0,2.0,,,2014-03-07 06:52:44,2024-02-27 16:29:16,2017-01-29 14:49:13,,,rust,Doug,35764,353820,registered,true,,,CC BY-SA 3.0,,880,772,2,0,0,1,false,false,false,true,true,true,53,7,true,0.049,0.0019,4642,2014,3,6,Friday,false,false,false,false,false,false,false
30352802,What does the "box" keyword do?,"In Rust, we can use the Box<T> type to allocate things on the heap. This type is used to safely abstract pointers to heap memory. Box<T> is provided by the Rust standard library.
I was curious about how Box<T> allocation is implemented, so I found its source code. Here is the code for Box<T>::new (as of Rust 1.0):
impl<T> Box<T> {
/// Allocates memory on the heap and then moves `x` into it.
/// [...]
#[stable(feature = "rust1", since = "1.0.0")]
#[inline(always)]
pub fn new(x: T) -> Box<T> {
box x
}
}
The only line in the implementation returns the value box x. This box keyword is not explained anywhere in the official documentation; in fact, it is only mentioned briefly on the std::boxed documentation page.
",https://stackoverflow.com/questions/30352802/what-does-the-box-keyword-do,76,26031.0,3.0,,,2015-05-20 14:35:10,2023-01-13 13:57:57,2023-01-13 13:57:57,,,rust,George Hilliard,16163,1830736,registered,true,30356213,,CC BY-SA 4.0,,1172,820,8,2,0,1,true,false,false,true,true,true,41,6,true,0.115,0.0029,4203,2015,5,14,Wednesday,false,false,false,false,false,false,false
58006033,How to run setup code before any tests run in Rust?,"I have a Rust app (a simple interpreter) that needs some setup (initialize a repo) before the environment is usable.
I understand that Rust runs its tests (via cargo test) in a multithreaded manner, so I need to initialize the repo before any tests run. I also need to do this only once per run, not before each test.
In Java's JUnit this would be done with a @BeforeClass (or @BeforeAll in JUnit 5) method. How can I acheive the same thing in Rust?
",https://stackoverflow.com/questions/58006033/how-to-run-setup-code-before-any-tests-run-in-rust,75,42694.0,3.0,,,2019-09-19 07:39:04,2024-12-24 12:35:25,,,,unit-testing;rust,user650228,,,does_not_exist,true,,,CC BY-SA 4.0,,473,452,0,0,0,2,false,false,false,true,false,false,51,11,true,0.07,0.0018,2620,2019,9,7,Thursday,false,false,false,false,false,false,false
16267578,How can I convert char to string?,"
This question pertains to a pre-release version of Rust.
This younger question is similar.
I tried to print one symbol with println:
fn main() {
println!('c');
}
But I got next error:
$ rustc pdst.rs
pdst.rs:2:16: 2:19 error: mismatched types: expected `&str` but found `char` (expected &str but found char)
pdst.rs:2 println!('c');
^~~
error: aborting due to previous error
How do I convert char to string?
Direct typecast does not work:
let text:str = 'c';
let text:&str = 'c';
It returns:
pdst.rs:7:13: 7:16 error: bare `str` is not a type
pdst.rs:7 let text:str = 'c';
^~~
pdst.rs:7:19: 7:22 error: mismatched types: expected `~str` but found `char` (expected ~str but found char)
pdst.rs:7 let text:str = 'c';
^~~
pdst.rs:8:20: 8:23 error: mismatched types: expected `&str` but found `char` (expected &str but found char)
pdst.rs:8 let text:&str = 'c';
^~~
",https://stackoverflow.com/questions/16267578/how-can-i-convert-char-to-string,75,76109.0,3.0,,,2013-04-28 20:38:32,2021-11-14 02:22:49,2021-04-09 22:16:34,,,rust;rust-obsolete,Denis Kreshikhin,9560,1062636,registered,true,16267760,,CC BY-SA 4.0,,1336,1025,5,1,0,2,true,false,false,true,true,true,33,7,true,0.039,0.001,4955,2013,4,20,Sunday,true,false,false,false,false,false,false
25072930,How can I clear the Cargo cache?,"When I run cargo build, various libraries get stored within the folder /usr/local/lib/rustlib/.
What is the correct way to clear these libraries? I could rm these files manually, but would that be the right thing to do? I noticed that /usr/local/lib/rustlib/manifest is a file containing a list of the fill file paths of all the libraries, and hence might be breaking something if I remove these files manually.
",https://stackoverflow.com/questions/25072930/how-can-i-clear-the-cargo-cache,75,114571.0,2.0,,,2014-08-01 04:34:16,2026-06-13 18:37:17,2026-06-13 18:24:46,,,rust;rust-crates;rust-cargo,bojangle,1178,3885962,registered,true,25073142,,CC BY-SA 4.0,,470,412,2,0,0,3,true,false,false,true,true,true,32,7,true,0.017,0.0007,4495,2014,8,4,Friday,false,false,false,false,false,false,false
56724014,How do I collect the values of a HashMap into a vector?,"I can not find a way to collect the values of a HashMap into a Vec in the documentation. I have score_table: HashMap<Id, Score> and I want to get all the Scores into all_scores: Vec<Score>.
I was tempted to use the values method (all_scores = score_table.values()), but it does not work since values is not a Vec.
I know that Values implements the ExactSizeIterator trait, but I do not know how to collect all values of an iterator into a vector without manually writing a for loop and pushing the values in the vector one after one.
I also tried to use std::iter::FromIterator; but ended with something like:
all_scores = Vec::from_iter(score_table.values());
expected type `std::vec::Vec<Score>`
found type `std::vec::Vec<&Score>`
Thanks to Hash map macro refuses to type-check, failing with a misleading (and seemingly buggy) error message?, I changed it to:
all_scores = Vec::from_iter(score_table.values().cloned());
and it does not produce errors to cargo check.
Is this a good way to do it?
",https://stackoverflow.com/questions/56724014/how-do-i-collect-the-values-of-a-hashmap-into-a-vector,75,59859.0,3.0,,,2019-06-23 12:45:18,2024-05-22 13:58:31,2020-03-27 20:04:32,,,rust;hashmap,Hugo Trentesaux,2111,6314254,registered,true,69785278,,CC BY-SA 4.0,,1496,1042,15,1,0,2,true,false,false,true,true,true,55,12,true,0.05,0.0013,2708,2019,6,12,Sunday,true,false,false,false,false,false,false
38157335,What does {:?} mean in a Rust format string?,"I found out that {:?} prints an entire array in Rust. I want to know what is it called and how exactly it works. Is it only limited to printing arrays or could it also be used elsewhere for other purposes?
",https://stackoverflow.com/questions/38157335/what-does-mean-in-a-rust-format-string,75,28025.0,2.0,,,2016-07-02 06:46:24,2022-01-17 23:42:28,2016-07-03 13:25:53,,,arrays;rust,7_R3X,4492,5460216,registered,true,38157410,,CC BY-SA 3.0,,226,206,1,0,0,2,true,false,false,true,true,true,44,9,true,0.071,0.0027,3794,2016,7,6,Saturday,true,false,false,false,false,false,false
27852613,Why does printing a pointer print the same thing as printing the dereferenced pointer?,"From the Rust guide:
To dereference (get the value being referred to rather than the reference itself) y, we use the asterisk (*)
So I did it:
fn main() {
let x = 1;
let ptr_y = &x;
println!(""x: {}, ptr_y: {}"", x, *ptr_y);
}
This gives me the same results (x=1; y=1) even without an explicit dereference:
fn main() {
let x = 1;
let ptr_y = &x;
println!(""x: {}, ptr_y: {}"", x, ptr_y);
}
Why? Shouldn't ptr_y print the memory address and *ptr_y print 1? Is there some kind of auto-dereference or did I miss something?
",https://stackoverflow.com/questions/27852613/why-does-printing-a-pointer-print-the-same-thing-as-printing-the-dereferenced-po,75,31131.0,2.0,,,2015-01-09 01:43:23,2019-01-25 08:48:14,2017-07-15 13:31:04,,,pointers;rust;dereference,Vega,3030,4435175,registered,true,27852760,,CC BY-SA 3.0,,720,560,6,0,0,3,true,false,false,true,true,true,86,14,true,0.064,0.0024,4334,2015,1,1,Friday,false,false,false,false,false,false,false
60916194,How to sort a Vector in descending order in Rust?,"In Rust, the sorting methods of a Vec always arrange the elements from smallest to largest. What is a general-purpose way of sorting from largest to smallest instead?
If you have a vector of numbers, you can provide a key extraction function that ""inverts"" the number like this:
let mut numbers: Vec<u32> = vec![100_000, 3, 6, 2];
numbers.sort_by_key(|n| std::u32::MAX - n);
But that's not very clear, and it's not straightforward to extend that method to other types like strings.
",https://stackoverflow.com/questions/60916194/how-to-sort-a-vector-in-descending-order-in-rust,74,51333.0,1.0,,,2020-03-29 15:08:13,2020-03-30 13:18:22,,,,sorting;rust,nnnmmm,9064,1726797,registered,true,60916195,,CC BY-SA 4.0,,551,493,2,0,0,2,true,false,false,true,true,false,49,10,true,0.019,0.0014,2428,2020,3,15,Sunday,true,false,false,false,false,false,false
40053550,"The compiler suggests I add a 'static lifetime because the parameter type may not live long enough, but I don't think that's what I want","I'm trying to implement something that looks like this minimal example:
trait Bar<T> {}
struct Foo<T> {
data: Vec<Box<Bar<T>>>,
}
impl<T> Foo<T> {
fn add<U: Bar<T>>(&mut self, x: U) {
self.data.push(Box::new(x));
}
}
Since Rust defaults to (as far as I can tell) pass-by-ownership, my mental model thinks this should work. The add method takes ownership of object x and is able to move this object into a Box because it knows the full type U (and not just trait Bar<T>). Once moved into a Box, the lifetime of the item inside the box should be tied to the actual lifetime of the box (e.g., when pop()ed off the vector the object will be destroyed).
Clearly, however, the compiler disagrees (and I'm sure knows a bit more than I...), asking me to consider adding a 'static lifetime qualifier (E0310). I am 99% sure that's not what I want, but I'm not exactly sure what I'm supposed to do.
To clarify what I'm thinking and help identify misconceptions, my mental model, coming from a C++ background, is:
Box<T> is essentially std::unique_ptr<T>
- Without any annotations, variables are passed by value if
Copy and rvalue-reference otherwise
- With a reference annotation,
& is roughly const& and &mut is roughly &
- The default lifetime is lexical scope
",https://stackoverflow.com/questions/40053550/the-compiler-suggests-i-add-a-static-lifetime-because-the-parameter-type-may-no,74,25526.0,2.0,,,2016-10-14 23:51:45,2018-08-03 11:52:03,2018-06-25 17:01:25,,,rust;lifetime,Robert Mason,4057,251860,registered,true,40053651,,CC BY-SA 4.0,,1663,1371,16,0,0,2,true,false,false,true,true,true,148,25,false,0.078,0.0029,3690,2016,10,23,Friday,false,false,false,false,false,false,false
17490716,Lifetimes in Rust,"Occasionally I've found myself wanting to write functions that can be called in either of two ways:
// With a string literal:
let lines = read_file_lines(""data.txt"");
// With a string pointer:
let file_name = ~""data.txt"";
let lines = read_file_lines(file_name);
My first guess was to use a borrowed pointer (&str) for the parameter type, but when that didn't work (it only allowed me to use @str and ~str), I tried the following (by copying the Rust libraries), which did work.
fn read_file_lines<'a>(path: &'a str) -> ~[~str] {
let read_result = file_reader(~Path(path));
match read_result {
Ok(file) => file.read_lines(),
Err(e) => fail!(fmt!(""Error reading file: %?"", e))
}
}
The problem is that I don't understand what I'm doing. From what I can gather (mostly from compiler errors), I'm declaring a lifetime on which there is no restriction, and using it to describe the path parameter (meaning that any lifetime can be passed as the parameter).
So:
- Is my understanding vaguely accurate?
- What is a lifetime? Where can I learn more about them?
- What is the difference between a parameter of type
&str and a parameter of type &'a str in the example above?
- And while I'm at it, what is
'self?
(I'm using Rust 0.7, if it makes a difference to the answer)
",https://stackoverflow.com/questions/17490716/lifetimes-in-rust,74,15957.0,1.0,,,2013-07-05 14:00:43,2016-09-08 14:22:12,2016-09-08 14:22:12,,,rust;lifetime,Daniel,10275,259747,registered,true,17493553,,CC BY-SA 3.0,,1532,1326,8,0,0,2,true,false,false,true,true,true,17,3,false,0.063,0.0046,4887,2013,7,14,Friday,false,false,false,false,false,false,false
43385142,How is Rust compiled to machine code?,"I've recently been looking at the Rust programming language. How does it work? Rust code seems to be compiled into ELF or PE (etc) binaries, but I've not been able to find any information on how that's done? Is it compiled to an intermediate format then compiled the rest of the way with gxx for example? Any help (or links) would be really appreciated.
",https://stackoverflow.com/questions/43385142/how-is-rust-compiled-to-machine-code,73,27404.0,1.0,,,2017-04-13 06:34:38,2020-06-16 20:33:35,2020-06-16 17:42:04,,,rust,Dllewellyn,914,1210888,registered,true,43385776,,CC BY-SA 4.0,,425,354,0,1,0,1,true,false,false,true,true,true,37,7,true,0.036,0.0027,3509,2017,4,6,Thursday,false,false,false,false,false,false,false
30281235,How to cleanly end the program with an exit code?,"Is there a way of returning an exit code in Rust 1.0?
I've tried env::set_exit_status(exit_code); but this generates a compiler error.
There is also this question: Exit Rust program early which is similar but asks about the case when the process has to be exited early.
EDIT: I'm looking for a solution that will also allow the process to tidy up the stack, call destructors, etc.
",https://stackoverflow.com/questions/30281235/how-to-cleanly-end-the-program-with-an-exit-code,73,42865.0,3.0,,,2015-05-16 22:03:55,2022-07-26 00:02:41,2017-05-23 12:18:10,,,rust,Thomas Bratt,53632,15985,registered,true,30285110,,CC BY-SA 3.0,,523,386,1,1,0,1,true,false,false,true,true,true,49,10,true,0.07,0.0017,4207,2015,5,22,Saturday,true,false,false,false,false,false,false
39878382,Is it possible to unpack a tuple into function arguments?,"If I want to unpack a tuple and pass it as arguments is there a way to do this:
//Does not compile
fn main() {
let tuple = (10, Vec::new());
foo(tuple);
}
fn foo(a: i32, b: Vec<i32>) {
//Does stuff.
}
Instead of having to do this:
fn main() {
let tuple = (10, Vec::new());
foo(tuple.0, tuple.1);
}
fn foo(a: i32, b: Vec<i32>) {
//Does stuff.
}
",https://stackoverflow.com/questions/39878382/is-it-possible-to-unpack-a-tuple-into-function-arguments,73,37574.0,5.0,,,2016-10-05 15:41:29,2025-06-24 19:39:11,2020-02-24 18:13:13,,,rust;tuples,HiDefender,2468,6844327,registered,true,39878701,,CC BY-SA 4.0,,447,385,2,0,0,2,true,false,false,true,true,true,57,10,true,0.133,0.0019,3699,2016,10,15,Wednesday,false,false,false,false,false,false,false
41366896,How to make a Rust mutable reference immutable?,"I'm trying to convert a mutable vector to an immutable vector in Rust. I thought this would work but it doesn't:
let data = &mut vec![];
let x = data; // I thought x would now be an immutable reference
How can I turn a mutable reference into an immutable binding?
",https://stackoverflow.com/questions/41366896/how-to-make-a-rust-mutable-reference-immutable,73,50603.0,2.0,,,2016-12-28 17:25:54,2022-11-14 09:06:07,2016-12-28 17:43:58,,,rust,jbrown,8083,2400966,registered,true,41367094,,CC BY-SA 3.0,,318,280,1,0,0,1,true,false,false,true,true,true,47,8,true,0.04,0.0014,3615,2016,12,17,Wednesday,false,false,false,false,false,false,false
63798662,"How do I convert a Vec<Result<T, E>> to Result<Vec<T>, E>?","Is there any opinionated and more elegant way to convert Vec<Result<T, E>> to Result<Vec<T>, E>? I want to get Ok<Vec<T>> if all values of vector are Ok<T> and Err<E> if at least one is Err<E>.
Example:
fn vec_of_result_to_result_of_vec<T, E>(v: Vec<Result<T, E>>) -> Result<Vec<T>, E>
where
T: std::fmt::Debug,
E: std::fmt::Debug,
{
let mut new: Vec<T> = Vec::new();
for el in v.into_iter() {
if el.is_ok() {
new.push(el.unwrap());
} else {
return Err(el.unwrap_err());
}
}
Ok(new)
}
I'm looking for a more declarative way to write this. This function forces me to write a where clause which will never be used and Err(el.unwrap_err()) looks useless. In other words, the code does many things just to make the compiler happy. I feel like this is such a common case that there's a better way to do it.
",https://stackoverflow.com/questions/63798662/how-do-i-convert-a-vecresultt-e-to-resultvect-e,73,36851.0,2.0,,,2020-09-08 17:15:39,2023-05-11 09:50:02,2020-09-08 17:40:36,2020-09-08 17:39:20,Duplicate,rust;monads,Arek C.,1701,10364449,registered,true,63798748,,,,1119,970,9,0,0,2,true,true,false,true,true,true,82,10,true,0.054,0.002,2265,2020,9,17,Tuesday,false,false,false,false,false,false,false
26549480,How do I declare a "static" field in a struct in Rust?,"How do I declare a ""static"" field in a struct in Rust, preferably with a default value:
struct MyStruct {
x: i32, // instance
y: i32, // instance
my_static: i32 = 123, // static, how?
}
fn main() {
let a = get_value();
if a == MyStruct::my_static {
//...
} else {
//...
}
}
",https://stackoverflow.com/questions/26549480/how-do-i-declare-a-static-field-in-a-struct-in-rust,72,65225.0,3.0,,,2014-10-24 14:02:15,2021-05-16 03:02:13,2021-05-16 03:02:13,,,rust;static,Incerteza,35684,2813589,registered,true,26550218,,CC BY-SA 4.0,,380,349,1,0,0,2,true,false,false,true,true,true,64,12,true,0.046,0.0011,4411,2014,10,14,Friday,false,false,false,false,false,false,false
27588416,How to send output to stderr?,"One uses this to send output to stdout:
println!(""some output"")
I think there is no corresponding macro to do the same for stderr.
",https://stackoverflow.com/questions/27588416/how-to-send-output-to-stderr,72,35926.0,5.0,,,2014-12-21 10:11:37,2019-08-25 14:58:25,2019-08-25 14:58:25,,,rust;stdio,tshepang,12577,321731,registered,true,27590832,,CC BY-SA 4.0,,172,134,1,0,0,2,true,false,false,true,true,true,29,6,true,0.139,0.002,4353,2014,12,10,Sunday,true,false,false,false,false,false,false
30684624,What is the best variant for appending a new line in a text file?,"I am using this code to append a new line to the end of a file:
let text = ""New line"".to_string();
let mut option = OpenOptions::new();
option.read(true);
option.write(true);
option.create(true);
match option.open(""foo.txt"") {
Err(e) => {
println!(""Error"");
}
Ok(mut f) => {
println!(""File opened"");
let size = f.seek(SeekFrom::End(0)).unwrap();
let n_text = match size {
0 => text.clone(),
_ => format!(""\n{}"", text),
};
match f.write_all(n_text.as_bytes()) {
Err(e) => {
println!(""Write error"");
}
Ok(_) => {
println!(""Write success"");
}
}
f.sync_all();
}
}
It works, but I think it's too difficult. I found option.append(true);, but if I use it instead of option.write(true); I get ""Write error"".
",https://stackoverflow.com/questions/30684624/what-is-the-best-variant-for-appending-a-new-line-in-a-text-file,72,55265.0,1.0,,,2015-06-06 15:34:09,2025-10-10 01:36:20,2018-01-29 22:12:16,,,file-io;rust,Aleksandr,2075,4981490,registered,true,30684735,,CC BY-SA 3.0,,972,908,3,0,0,2,true,false,false,true,true,true,65,14,true,0.018,0.0013,4186,2015,6,15,Saturday,true,false,false,false,false,false,false
15265198,How do I write a multi-line string in Rust?,"Is it possible to write something like:
fn main() {
let my_string: &str = ""Testing for new lines \
might work like this?"";
}
",https://stackoverflow.com/questions/15265198/how-do-i-write-a-multi-line-string-in-rust,72,58799.0,5.0,,,2013-03-07 07:14:09,2023-01-31 11:17:50,2017-10-29 22:11:07,2021-08-16 05:04:59,Duplicate,rust,sdasdadas,25681,904316,registered,true,15266782,,,,193,162,1,0,0,1,true,true,false,true,true,true,43,9,true,0.085,0.0012,5007,2013,3,7,Thursday,false,false,false,false,false,false,false
38896155,What is the bitwise NOT operator in Rust?,"Looking at the list of bitwise operators in the Rust Book, I don't see a NOT operator (like ~ in C). Is there no NOT operator in Rust?
",https://stackoverflow.com/questions/38896155/what-is-the-bitwise-not-operator-in-rust,72,42113.0,1.0,,,2016-08-11 12:16:20,2019-07-08 09:26:29,2019-07-08 09:26:29,,,rust;operators,Verax,2579,539972,registered,true,38896376,,CC BY-SA 4.0,,246,136,1,1,0,2,true,false,false,true,true,true,41,8,true,0.024,0.0017,3754,2016,8,12,Thursday,false,false,false,false,false,false,false
36878044,What is the idiomatic way to return an error from a function with no result if successful?,"In Rust, I believe the idiomatic way to deal with recoverable errors is to use Result. For example this function clearly is idiomatic:
fn do_work() -> Result<u64, WorkError> {...}
Of course, there are also functions that have a single, obvious, failure state, and therefore use the Option type instead. An idiomatic example would be this:
fn do_work() -> Option<u64>
This all is straightforwardly addressed in the documentation. However, I'm confused about the case where a function can fail, but has no meaningful value when successful. Compare the following two functions:
fn do_work() -> Option<WorkError>
// vs
fn do_work() -> Result<(), WorkError>
I'm just not sure which one of these is more idiomatic, or is used more often in real world Rust code. My go-to resource for questions like this is the Rust book, but I don't think this is addressed in its ""Error Handling"" section. I haven't had much luck with any other Rust documentation either.
Of course this seems pretty subjective, but I'm looking for authoritative sources that either state which form is idiomatic, or on why one form is superior (or inferior) to the other. (I'm also curious how the convention compares to other languages that heavily utilize ""errors as values"", like Go and Haskell.)
",https://stackoverflow.com/questions/36878044/what-is-the-idiomatic-way-to-return-an-error-from-a-function-with-no-result-if-s,72,39271.0,2.0,,,2016-04-27 00:14:35,2019-05-01 23:16:59,2019-05-01 23:16:59,,,error-handling;rust;option-type;idioms;rust-result,Others,3071,1981468,registered,true,36878464,,CC BY-SA 4.0,,1481,1309,3,1,0,5,true,false,false,true,true,true,90,17,true,0.051,0.0018,3860,2016,4,0,Wednesday,false,false,false,false,false,false,false
28656387,"Initialize a large, fixed-size array with non-Copy types","I’m trying to initialize a fixed-size array of some nullable, non-copyable type, like an Option<Box<Thing>> for some kind of Thing. I’d like to pack two of them into a struct without any extra indirection. I’d like to write something like this:
let array: [Option<Box<Thing>>; SIZE] = [None; SIZE];
But it doesn’t work because the [e; n] syntax requires that e implements Copy. Of course, I could expand it into SIZE Nones, but that can be unwieldy when SIZE is large. I don’t believe this can be done with a macro without an unnatural encoding of SIZE. Is there a good way to do it?
Yes, this is easy with unsafe; is there a way to do it without unsafe?
",https://stackoverflow.com/questions/28656387/initialize-a-large-fixed-size-array-with-non-copy-types,71,22704.0,9.0,,,2015-02-22 09:33:13,2025-11-04 16:16:22,2016-12-06 14:05:37,,,rust,rieux,889,627303,registered,true,,,CC BY-SA 3.0,,871,683,12,0,0,1,false,false,false,true,true,true,56,8,false,0.396,0.0031,4290,2015,2,9,Sunday,true,false,false,false,false,false,false
55755552,What Is the Rust Equivalent to a Try-Catch Statement?,"Is it possible to handle multiple different errors at once instead of individually in Rust without using additional functions? In short: what is the Rust equivalent to a Try-Catch statement?
A similar feature was suggested back in 2016, but I don't know what came of it.
For example, doing something like this:
try {
do_step_1()?;
do_step_2()?;
do_step_3()?;
// etc.
} catch {
alert_user("Failed to perform necessary steps");
}
Instead of:
match do_steps() {
Ok(_) => (),
_ => alert_user("Failed to perform necessary steps")
}
// Additional function:
fn do_steps() -> Result<(), Error>{
do_step_1()?;
do_step_2()?;
do_step_3()?;
// etc.
Ok(())
}
My program has a function which checks a variety of different places in the registry for different data values and returns some aggregate data. It would need to use many of these try-cache statements with try-catch inside of other try-catch inside of loops.
",https://stackoverflow.com/questions/55755552/what-is-the-rust-equivalent-to-a-try-catch-statement,71,81858.0,8.0,,,2019-04-19 01:34:51,2023-07-20 18:35:25,2023-07-04 18:06:52,,,error-handling;rust;try-catch,Marc,3682,3489291,registered,true,55758013,,CC BY-SA 4.0,,1225,990,2,1,0,3,true,false,false,true,true,true,53,9,true,0.098,0.0009,2773,2019,4,1,Friday,false,false,false,false,false,false,false
30073684,How to get mutable references to two array elements at the same time?,"fn change(a: &mut i32, b: &mut i32) {
let c = *a;
*a = *b;
*b = c;
}
fn main() {
let mut v = vec![1, 2, 3];
change(&mut v[0], &mut v[1]);
}
When I compile the code above, it has the error:
error[E0499]: cannot borrow `v` as mutable more than once at a time
--> src/main.rs:9:32
|
9 | change(&mut v[0], &mut v[1]);
| - ^ - first borrow ends here
| | |
| | second mutable borrow occurs here
| first mutable borrow occurs here
Why does the compiler prohibit it? v[0] and v[1] occupy different memory positions, so it's not dangerous to use these together. And what should I do if I come across this problem?
",https://stackoverflow.com/questions/30073684/how-to-get-mutable-references-to-two-array-elements-at-the-same-time,71,23715.0,9.0,,,2015-05-06 10:09:37,2025-04-03 19:48:08,2024-11-12 13:58:31,,,arrays;rust;mutable,user2925565,1442,2925565,registered,true,30075629,,CC BY-SA 4.0,,913,786,4,0,0,3,true,false,false,true,true,true,69,13,true,0.38,0.003,4217,2015,5,10,Wednesday,false,false,false,false,false,false,false
45633269,How do you declare an interface in Rust?,"I have multiple types with similar methods. I want to abstract over them by writing an interface, like I would in Java:
public interface Shape {
public float area();
}
class Circle implements Shape {
public float area() {
return radius * radius * Math.PI;
}
public float radius;
}
However, there is no interface keyword in Rust. Doesn't Rust offer the possibility to abstract over multiple types?
",https://stackoverflow.com/questions/45633269/how-do-you-declare-an-interface-in-rust,71,41760.0,1.0,,,2017-08-11 10:43:25,2021-06-08 07:59:33,2021-06-08 07:59:33,,,interface;rust,Lukas Kalbertodt,91680,2408867,registered,true,45636553,,CC BY-SA 4.0,,514,424,2,0,0,2,true,false,false,true,true,true,40,8,true,0.024,0.0017,3389,2017,8,10,Friday,false,false,false,false,false,false,false
57707966,How to get Timestamp of the current Date and time in Rust,"I simply want to retrieve the current Time and Date and store it in a variable.
For this, I tried to use the chrono::DateTime.
In the documentation I found this:
use chrono::{DateTime, TimeZone, NaiveDateTime, Utc};
let dt = DateTime::<Utc>::from_utc(NaiveDate::from_ymd(2016, 7, 8).and_hms(9, 10, 11), Utc);
This lets me store a specific Date and Time but I couldn't figure out how to retrieve the actual current date and time and put it in my DateTime-Variable.
",https://stackoverflow.com/questions/57707966/how-to-get-timestamp-of-the-current-date-and-time-in-rust,71,98704.0,5.0,,,2019-08-29 10:14:36,2025-11-23 15:27:59,2022-10-09 12:12:30,,,datetime;rust,Samuel Dressel,1513,11378334,registered,true,57708129,,CC BY-SA 4.0,,573,476,2,0,0,2,true,false,false,true,true,true,57,12,false,0.051,0.0007,2641,2019,8,10,Thursday,false,false,false,false,false,false,false
29669287,How can I zip more than two iterators?,"Is there a more direct and readable way to accomplish the following:
fn main() {
let a = [1, 2, 3];
let b = [4, 5, 6];
let c = [7, 8, 9];
let iter = a.iter()
.zip(b.iter())
.zip(c.iter())
.map(|((x, y), z)| (x, y, z));
}
That is, how can I build an iterator from n iterables which yields n-tuples?
",https://stackoverflow.com/questions/29669287/how-can-i-zip-more-than-two-iterators,71,46145.0,3.0,,,2015-04-16 08:27:36,2022-11-25 01:49:41,2018-03-18 13:43:04,,,iterator;rust,anderspitman,10870,943814,registered,true,29669741,,CC BY-SA 3.0,,379,341,1,0,0,2,true,false,false,true,true,true,38,8,true,0.065,0.0015,4237,2015,4,8,Thursday,false,false,false,false,false,false,false
41666235,"How do I make an Rust item public within a crate, but private outside it?","I have a crate that has lots of code, so I've split it into multiple files/modules. However, some modules have internal unsafe stuff (e.g. raw pointers) that I need to make public to the different modules, but I don't want to expose to users of my crate. How can I do that?
The only way I can think of is to actually have my crate just be one big module, but then there's no way to split it into different files, other than this solution which seems a bit hacky.
Normally when I come up against a real world problem that the simple examples in the Rust docs don't adequately explain I just copy a popular real world crate, e.g. git2-rs, but that just seems to effectively make everything public, including the raw pointers.
",https://stackoverflow.com/questions/41666235/how-do-i-make-an-rust-item-public-within-a-crate-but-private-outside-it,71,29946.0,1.0,,,2017-01-15 20:56:20,2017-07-29 19:35:31,2017-05-23 11:54:12,,,module;rust;public;rust-crates,Timmmm,100381,265521,registered,true,41667202,,CC BY-SA 3.0,,885,726,0,2,0,4,true,false,false,true,true,true,73,15,true,0.033,0.0024,3597,2017,1,20,Sunday,true,false,false,false,false,false,false
33116317,When would you use a Mutex without an Arc?,"An extremely common pattern in Rust is Arc<Mutex<T>>, where Arc provides the memory management, and Mutex provides safe multi-threaded access to the resource. What else could be used in place of Arc, and under what circumstances?
",https://stackoverflow.com/questions/33116317/when-would-you-use-a-mutex-without-an-arc,71,29501.0,1.0,,,2015-10-14 03:51:18,2020-02-18 18:21:11,,,,rust,Alex Gaynor,15159,37181,registered,true,33116578,,CC BY-SA 3.0,,310,242,4,0,0,1,true,false,false,true,true,false,42,9,true,0.034,0.0024,4056,2015,10,3,Wednesday,false,false,false,false,false,false,false
37233735,Interfaces vs Types in TypeScript,"What is the difference between these statements (interface vs type) in TypeScript?
interface X {
a: number
b: string
}
type X = {
a: number
b: string
};
",https://stackoverflow.com/questions/37233735/interfaces-vs-types-in-typescript,2813,1142099.0,25.0,,,2016-05-15 01:53:52,2026-07-27 16:04:10,2023-07-16 08:38:38,,,typescript;interface;typescript-types,user6101582,,,does_not_exist,true,37233777,,CC BY-SA 4.0,2023-04-26 05:48:42,265,171,3,0,0,3,true,false,false,true,false,true,33,5,false,0.022,0.0025,3842,2016,5,1,Sunday,true,false,false,false,false,false,false
42273853,"In TypeScript, what is the ! (exclamation mark / bang) operator when dereferencing a member?","When looking at the source code for a tslint rule, I came across the following statement:
if (node.parent!.kind === ts.SyntaxKind.ObjectLiteralExpression) {
return;
}
Notice the ! operator after node.parent. Interesting!
I first tried compiling the file locally with my currently installed version of TS (1.5.3). The resulting error pointed to the exact location of the bang:
$ tsc --noImplicitAny memberAccessRule.ts
noPublicModifierRule.ts(57,24): error TS1005: ')' expected.
Next, I upgraded to the latest TS (2.1.6), which compiled it without issue. So it seems to be a feature of TS 2.x. But, the transpilation ignored the bang completely, resulting in the following JS:
if (node.parent.kind === ts.SyntaxKind.ObjectLiteralExpression) {
return;
}
My Google fu has thus far failed me.
What is TS's exclamation mark operator, and how does it work?
",https://stackoverflow.com/questions/42273853/in-typescript-what-is-the-exclamation-mark-bang-operator-when-dereferenci,1469,672437.0,9.0,,,2017-02-16 12:22:26,2025-11-21 01:07:12,2024-09-27 02:14:45,,,typescript,Mike Chamberlain,43276,289319,registered,true,42274019,,CC BY-SA 4.0,,1046,863,5,0,0,1,true,false,false,true,true,true,92,15,true,0.013,0.0022,3565,2017,2,12,Thursday,false,false,false,false,false,false,false
39152071,Can't bind to 'formGroup' since it isn't a known property of 'form',"The situation
I am trying to make what should be a very simple form in my Angular application, but no matter what, it never works.
The Angular version
Angular 2.0.0 RC5
The error
Can't bind to 'formGroup' since it isn't a known property of 'form'
The code
The view
<form [formGroup]="newTaskForm" (submit)="createNewTask()">
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" required>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
The controller
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';
import {FormsModule,ReactiveFormsModule} from '@angular/forms';
import { Task } from './task';
@Component({
selector: 'task-add',
templateUrl: 'app/task-add.component.html'
})
export class TaskAddComponent {
newTaskForm: FormGroup;
constructor(fb: FormBuilder)
{
this.newTaskForm = fb.group({
name: ["", Validators.required]
});
}
createNewTask()
{
console.log(this.newTaskForm.value)
}
}
The ngModule
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { routing } from './app.routing';
import { AppComponent } from './app.component';
import { TaskService } from './task.service'
@NgModule({
imports: [
BrowserModule,
routing,
FormsModule
],
declarations: [ AppComponent ],
providers: [
TaskService
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
The question
Why am I getting that error? Am I missing something?
",https://stackoverflow.com/questions/39152071/cant-bind-to-formgroup-since-it-isnt-a-known-property-of-form,1390,1577173.0,52.0,,,2016-08-25 18:09:06,2024-10-27 21:33:34,2021-10-21 13:24:37,,,angular;typescript;angular2-forms,FrancescoMussi,21770,2433664,registered,true,39152110,,CC BY-SA 4.0,2017-10-18 08:21:27,2276,1890,3,1,1,3,true,false,false,true,true,true,91,12,false,0.033,0.0009,3740,2016,8,18,Thursday,false,false,false,false,false,false,false
12709074,How do you explicitly set a new property on `window` in TypeScript?,"I setup global namespaces for my objects by explicitly setting a property on window.
window.MyNamespace = window.MyNamespace || {};
TypeScript underlines MyNamespace and complains that:
The property 'MyNamespace' does not exist on value of type 'window'
any""
I can make the code work by declaring MyNamespace as an ambient variable and dropping the window explicitness but I don't want to do that.
declare var MyNamespace: any;
MyNamespace = MyNamespace || {};
How can I keep window in there and make TypeScript happy?
As a side note I find it especially funny that TypeScript complains since it tells me that window is of type any which by definitely can contain anything.
",https://stackoverflow.com/questions/12709074/how-do-you-explicitly-set-a-new-property-on-window-in-typescript,1327,900784.0,30.0,,,2012-10-03 13:01:15,2025-08-21 22:20:25,,,,typescript,joshuapoehls,35877,31308,registered,true,12709880,,CC BY-SA 3.0,,896,690,9,0,0,1,true,false,false,true,true,false,67,12,true,0.033,0.0015,5162,2012,10,13,Wednesday,false,false,false,false,false,false,false
41292559,Could not find a declaration file for module 'module-name'. '/path/to/module-name.js' implicitly has an 'any' type,"I read how TypeScript module resolution works.
I have the following repository: @ts-stack/di.
After compiling the directory structure is as follows:
├── dist
│ ├── annotations.d.ts
│ ├── annotations.js
│ ├── index.d.ts
│ ├── index.js
│ ├── injector.d.ts
│ ├── injector.js
│ ├── profiler.d.ts
│ ├── profiler.js
│ ├── providers.d.ts
│ ├── providers.js
│ ├── util.d.ts
│ └── util.js
├── LICENSE
├── package.json
├── README.md
├── src
│ ├── annotations.ts
│ ├── index.ts
│ ├── injector.ts
│ ├── profiler.ts
│ ├── providers.ts
│ └── util.ts
└── tsconfig.json
In my package.json I wrote ""main"": ""dist/index.js"".
In Node.js everything works fine, but TypeScript:
import {Injector} from '@ts-stack/di';
Could not find a declaration file for module '@ts-stack/di'. '/path/to/node_modules/@ts-stack/di/dist/index.js' implicitly has an 'any' type.
And yet, if I import as follows, then everything works:
import {Injector} from '/path/to/node_modules/@ts-stack/di/dist/index.js';
What am I doing wrong?
",https://stackoverflow.com/questions/41292559/could-not-find-a-declaration-file-for-module-module-name-path-to-module-nam,1133,1891638.0,42.0,,,2016-12-22 22:28:24,2025-06-09 04:01:07,2020-02-21 14:06:14,,,typescript;node-modules,ktretyak,32379,1716560,registered,true,41307319,,CC BY-SA 4.0,2022-01-21 09:31:34,1363,1043,4,2,0,2,true,false,false,true,true,true,138,15,false,0.022,0.0006,3621,2016,12,22,Thursday,false,false,false,false,false,false,false
49699067,Property '...' has no initializer and is not definitely assigned in the constructor,"in my Angular app I have a component:
import { MakeService } from './../../services/make.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-vehicle-form',
templateUrl: './vehicle-form.component.html',
styleUrls: ['./vehicle-form.component.css']
})
export class VehicleFormComponent implements OnInit {
makes: any[];
vehicle = {};
constructor(private makeService: MakeService) { }
ngOnInit() {
this.makeService.getMakes().subscribe(makes => { this.makes = makes
console.log("MAKES", this.makes);
});
}
onMakeChange(){
console.log("VEHICLE", this.vehicle);
}
}
but in the "makes" property I have a mistake. I don't know what to do with it.
",https://stackoverflow.com/questions/49699067/property-has-no-initializer-and-is-not-definitely-assigned-in-the-construc,1026,1432114.0,41.0,,,2018-04-06 18:33:21,2025-07-01 08:37:29,2025-04-19 21:39:09,,,angular;typescript,Mikhail Kostiuchenko,10741,9528118,registered,true,49699097,,CC BY-SA 4.0,2021-02-23 10:06:35,920,753,1,1,1,2,true,false,false,true,true,true,91,13,false,0.029,0.0007,3151,2018,4,18,Friday,false,false,false,false,false,false,false
12827266,get and set in TypeScript,"I'm trying to create get and set method for a property:
private _name: string;
Name() {
get:
{
return this._name;
}
set:
{
this._name = ???;
}
}
What's the keyword to set a value?
",https://stackoverflow.com/questions/12827266/get-and-set-in-typescript,959,1045317.0,12.0,,,2012-10-10 19:52:14,2023-11-20 05:20:35,2012-10-10 20:31:22,,,typescript,MuriloKunze,15630,1304456,registered,true,12850536,,CC BY-SA 3.0,2017-10-09 20:12:27,262,224,1,0,0,1,true,false,false,true,true,true,25,5,false,0.011,0.0009,5155,2012,10,19,Wednesday,false,false,false,false,false,false,false
52423842,What is "not assignable to parameter of type never" error in TypeScript?,"Code is:
const foo = (foo: string) => {
const result = []
result.push(foo)
}
I get the following TS error:
[ts] Argument of type 'string' is not assignable to parameter of type 'never'.
What am I doing wrong? Is this a bug?
",https://stackoverflow.com/questions/52423842/what-is-not-assignable-to-parameter-of-type-never-error-in-typescript,906,1483159.0,22.0,,,2018-09-20 11:13:28,2025-07-01 10:47:45,2024-03-04 12:32:53,,,typescript,Lev,16084,6797267,registered,true,52423919,,CC BY-SA 4.0,2022-06-04 02:21:01,302,233,2,0,0,1,true,false,false,true,true,true,82,12,true,0.015,0.0006,2984,2018,9,11,Thursday,false,false,false,false,false,false,false
12710905,How do I dynamically assign properties to an object in TypeScript?,"If I wanted to programmatically assign a property to an object in Javascript, I would do it like this:
var obj = {};
obj.prop = "value";
But in TypeScript, this generates an error:
The property 'prop' does not exist on value of type '{}'
How do I assign any new property to an object in TypeScript?
",https://stackoverflow.com/questions/12710905/how-do-i-dynamically-assign-properties-to-an-object-in-typescript,901,1086393.0,31.0,,,2012-10-03 14:42:54,2024-08-22 21:53:48,2024-04-25 16:19:03,,,typescript,Peter Olson,143557,546661,registered,true,44441178,,CC BY-SA 4.0,2022-03-30 15:36:32,389,312,1,0,0,1,true,false,false,true,true,true,66,11,true,0.029,0.0008,5162,2012,10,14,Wednesday,false,false,false,false,false,false,false
51439843,'unknown' vs. 'any',"TypeScript 3.0 introduces unknown type, according to their wiki:
unknown is now a reserved type name, as it is now a built-in type.
Depending on your intended use of unknown, you may want to remove the
declaration entirely (favoring the newly introduced unknown type), or
rename it to something else.
What is difference between unknown and any? When should we use unknown over any?
",https://stackoverflow.com/questions/51439843/unknown-vs-any,900,388662.0,12.0,,,2018-07-20 09:50:26,2025-03-23 06:09:55,2019-02-25 15:12:22,,,typescript;typescript3.0,Jac Mos,9636,4492194,registered,true,51439876,,CC BY-SA 4.0,,505,394,5,0,0,2,true,false,false,true,true,true,35,3,false,0.031,0.0023,3046,2018,7,9,Friday,false,false,false,false,false,false,false
57086672,Element implicitly has an 'any' type because expression of type 'string' can't be used to index,"Trying out TypeScript for a React project and I'm stuck on this error:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ train_1: boolean; train_2: boolean; train_3: boolean; train_4: boolean; }'.
No index signature with a parameter of type 'string' was found on type '{ train_1: boolean; train_2: boolean; train_3: boolean; train_4: boolean; }'
Which appears when I try to filter the array in my component
.filter(({ name }) => plotOptions[name]);
So far I looked at the article ""Indexing objects in TypeScript"" (https://dev.to/kingdaro/indexing-objects-in-typescript-1cgi) since it had a similar error, but I tried to add the index signature to type plotTypes and I still get the same error.
My component code:
import React, { Component } from ""react"";
import createPlotlyComponent from ""react-plotly.js/factory"";
import Plotly from ""plotly.js-basic-dist"";
const Plot = createPlotlyComponent(Plotly);
interface IProps {
data: any;
}
interface IState {
[key: string]: plotTypes;
plotOptions: plotTypes;
}
type plotTypes = {
[key: string]: boolean;
train_1: boolean;
train_2: boolean;
train_3: boolean;
train_4: boolean;
};
interface trainInfo {
name: string;
x: Array<number>;
y: Array<number>;
type: string;
mode: string;
}
class FiltrationPlots extends Component<IProps, IState> {
readonly state = {
plotOptions: {
train_1: true,
train_2: true,
train_3: true,
train_4: true
}
};
render() {
const { data } = this.props;
const { plotOptions } = this.state;
if (data.filtrationData) {
const plotData: Array<trainInfo> = [
{
name: ""train_1"",
x: data.filtrationData.map((i: any) => i[""1-CumVol""]),
y: data.filtrationData.map((i: any) => i[""1-PressureA""]),
type: ""scatter"",
mode: ""lines""
},
{
name: ""train_2"",
x: data.filtrationData.map((i: any) => i[""2-CumVol""]),
y: data.filtrationData.map((i: any) => i[""2-PressureA""]),
type: ""scatter"",
mode: ""lines""
},
{
name: ""train_3"",
x: data.filtrationData.map((i: any) => i[""3-CumVol""]),
y: data.filtrationData.map((i: any) => i[""3-PressureA""]),
type: ""scatter"",
mode: ""lines""
},
{
name: ""train_4"",
x: data.filtrationData.map((i: any) => i[""4-CumVol""]),
y: data.filtrationData.map((i: any) => i[""4-PressureA""]),
type: ""scatter"",
mode: ""lines""
}
].filter(({ name }) => plotOptions[name]);
return (
<Plot
data={plotData}
layout={{ width: 1000, height: 1000, title: ""A Fancy Plot"" }}
/>
);
} else {
return <h1>No Data Loaded</h1>;
}
}
}
export default FiltrationPlots;
",https://stackoverflow.com/questions/57086672/element-implicitly-has-an-any-type-because-expression-of-type-string-cant-b,889,1144627.0,24.0,,,2019-07-18 03:21:56,2025-03-14 12:25:35,2022-03-03 11:25:47,,,typescript,DLee,9854,5920070,registered,true,57088282,,CC BY-SA 4.0,2023-04-05 11:41:03,3171,2967,4,1,0,1,true,false,false,true,true,true,115,16,false,0.021,0.0008,2683,2019,7,3,Thursday,false,false,false,false,false,false,false
21247278,About "*.d.ts" in TypeScript,"I am curious about .d.ts declaration files. I was told by someone that .d.ts files are similar to .h header files in the C & C++ programming languages, however, the .d.ts files don't seem to work quite the same. Currently, I am failing to understand how to properly use the .d.ts files.
It would appear that I can't add my .js or .ts files to the .d.ts files, so the only way my project will work is if it contains all three file types. My questions are:
What is the relationship between the three files?
How can I use the *.d.ts file, does it mean I can delete the *.ts file permanently?
If so, how can the *.d.ts file know which JS file is mapping to itself?
",https://stackoverflow.com/questions/21247278/about-d-ts-in-typescript,840,519918.0,10.0,,,2014-01-21 01:05:15,2024-08-02 18:59:29,2024-04-04 11:25:46,,,typescript,user3221822,,,does_not_exist,true,21247316,,CC BY-SA 4.0,,871,670,10,0,0,1,true,false,false,true,false,true,38,4,false,0.019,0.0016,4687,2014,1,1,Tuesday,false,false,false,false,false,false,false
14638990,Are strongly-typed functions as parameters possible in TypeScript?,"In TypeScript, I can declare a parameter of a function as a type Function. Is there a ""type-safe"" way of doing this that I am missing? For example, consider this:
class Foo {
save(callback: Function) : void {
//Do the save
var result : number = 42; //We get a number from the save operation
//Can I at compile-time ensure the callback accepts a single parameter of type number somehow?
callback(result);
}
}
var foo = new Foo();
var callback = (result: string) : void => {
alert(result);
}
foo.save(callback);
The save callback is not type safe, I am giving it a callback function where the function's parameter is a string but I am passing it a number, and compiles with no errors. Can I make the result parameter in save a type-safe function?
TL;DR version: is there an equivalent of a .NET delegate in TypeScript?
",https://stackoverflow.com/questions/14638990/are-strongly-typed-functions-as-parameters-possible-in-typescript,839,618667.0,9.0,,,2013-02-01 02:56:27,2022-12-07 14:21:55,2018-10-05 14:40:27,,,typescript,vcsjones,142341,492405,registered,true,14639219,,CC BY-SA 4.0,,914,869,1,0,0,1,true,false,false,true,true,true,66,8,true,0.015,0.0014,5041,2013,2,2,Friday,false,false,false,false,false,false,false
17380845,How do I convert a string to enum in TypeScript?,"I have defined the following enum in TypeScript:
enum Color{
Red, Green
}
Now in my function I receive color as a string. I have tried the following code:
var green= ""Green"";
var color : Color = <Color>green; // Error: can't convert string to enum
How can I convert that value to an enum?
",https://stackoverflow.com/questions/17380845/how-do-i-convert-a-string-to-enum-in-typescript,829,869124.0,31.0,,,2013-06-29 13:45:41,2025-07-31 02:30:14,2019-04-23 23:08:42,,,typescript,Amitabh,61759,248827,registered,true,17381004,,CC BY-SA 4.0,,374,305,2,0,0,1,true,false,false,true,true,true,48,10,true,0.036,0.001,4893,2013,6,13,Saturday,true,false,false,false,false,false,false
32308370,What is the syntax for Typescript arrow functions with generics?,"The typescript handbook currently has nothing on arrow functions. Normal functions
can be generically typed with this syntax:
example:
function identity<T>(arg: T): T {
return arg;
}
What is the syntax for arrow functions?
",https://stackoverflow.com/questions/32308370/what-is-the-syntax-for-typescript-arrow-functions-with-generics,827,526269.0,18.0,,,2015-08-31 09:46:38,2024-09-05 01:09:21,2015-08-31 09:50:25,,,typescript,Andreas Frische,10233,884359,registered,true,45576880,,CC BY-SA 3.0,,275,237,1,0,0,1,true,false,false,true,true,true,64,10,true,0.034,0.0016,4100,2015,8,9,Monday,false,false,false,false,false,false,false
41385059,Possible to extend types in Typescript?,"Say I have the following type:
type Event = {
name: string;
dateCreated: string;
type: string;
}
I now want to extend this type, i.e.
type UserEvent extends Event = {
UserId: string;
}
This doesn't work. How can I do this?
",https://stackoverflow.com/questions/41385059/possible-to-extend-types-in-typescript,816,940876.0,8.0,,,2016-12-29 18:10:25,2025-04-03 13:15:05,,,,javascript;typescript,Kousha,36827,834045,registered,true,41385149,,CC BY-SA 3.0,,311,242,2,0,0,2,true,false,false,true,true,false,39,6,true,0.009,0.0009,3614,2016,12,18,Thursday,false,false,true,false,false,false,false
15292278,How do I remove an array item in TypeScript?,"I have an array that I've created in TypeScript and it has a property that I use as a key. If I have that key, how can I remove an item from it?
",https://stackoverflow.com/questions/15292278/how-do-i-remove-an-array-item-in-typescript,803,1435164.0,20.0,,,2013-03-08 10:52:18,2024-07-26 02:24:43,2019-08-05 11:04:24,,,arrays;typescript;collections,Tim Almond,12846,56861,registered,true,15295806,,CC BY-SA 4.0,,152,145,0,0,0,3,true,false,false,true,true,true,44,9,true,0.014,0.0006,5006,2013,3,10,Friday,false,false,false,false,false,false,false
28975896,Is there a way to check for both `null` and `undefined`?,"Since TypeScript is strongly-typed, simply using if () {} to check for null and undefined doesn't sound right.
Does TypeScript have any dedicated function or syntax sugar for this?
",https://stackoverflow.com/questions/28975896/is-there-a-way-to-check-for-both-null-and-undefined,782,1355758.0,29.0,,,2015-03-10 23:23:22,2025-09-27 03:36:39,2020-04-23 07:53:31,,,typescript;null-check,David Liu,18094,554241,registered,true,,,CC BY-SA 4.0,,236,183,3,0,0,2,false,false,false,true,true,true,56,11,true,0.021,0.0006,4274,2015,3,23,Tuesday,false,false,false,false,false,false,false
47236963,No provider for HttpClient,"After upgrading from angular 4.4 to 5.0 and after updating all HttpModule and Http to HttpClientModule I started to get this error.
I also added HttpModule again to be sure it's not due to some dependency but it doesn't resolve the issue
In app.module, I have all correctly set
import { HttpModule } from '@angular/http';
import { HttpClientModule, HttpClient } from '@angular/common/http';
.
.
.
@NgModule({
imports: [
BrowserModule,
HttpClientModule,
HttpModule,
BrowserAnimationsModule,
FormsModule,
AppRoutingModule,
.
.
.
I don't know from where this error is coming, or I have no clue how to get inner of it. I also have a warning (put it below too) maybe its related.
Error: StaticInjectorError[HttpClient]:
StaticInjectorError[HttpClient]:
NullInjectorError: No provider for HttpClient!
at _NullInjector.get (vendor.js?v=mekBM8IVBK72-MIZOVSTJizGi_TD_xK3uhPOCRlEHwg:5665)
at resolveToken (vendor.js?v=mekBM8IVBK72-MIZOVSTJizGi_TD_xK3uhPOCRlEHwg:5953)
at tryResolveToken (vendor.js?v=mekBM8IVBK72-MIZOVSTJizGi_TD_xK3uhPOCRlEHwg:5895)
at StaticInjector.get (vendor.js?v=mekBM8IVBK72-MIZOVSTJizGi_TD_xK3uhPOCRlEHwg:5766)
at resolveToken (vendor.js?v=mekBM8IVBK72-MIZOVSTJizGi_TD_xK3uhPOCRlEHwg:5953)
at tryResolveToken (vendor.js?v=mekBM8IVBK72-MIZOVSTJizGi_TD_xK3uhPOCRlEHwg:5895)
at StaticInjector.get (vendor.js?v=mekBM8IVBK72-MIZOVSTJizGi_TD_xK3uhPOCRlEHwg:5766)
at resolveNgModuleDep (vendor.js?v=mekBM8IVBK72-MIZOVSTJizGi_TD_xK3uhPOCRlEHwg:15328)
at _createClass (vendor.js?v=mekBM8IVBK72-MIZOVSTJizGi_TD_xK3uhPOCRlEHwg:15373)
at _createProviderInstance$1 (vendor.js?v=mekBM8IVBK72-MIZOVSTJizGi_TD_xK3uhPOCRlEHwg:15339)
Warning Message:
./node_modules/@angular/Common/esm5/http.js
There are multiple modules with names that only differ in casing.
This can lead to unexpected behavior when compiling on a filesystem with other case-semantic.
Use equal casing. Compare these module identifiers:
* D:\XXX\node_modules\@angular\Common\esm5\http.js
Used by 21 module(s), i. e.
D:\XXX\node_modules\awesome-typescript-loader\dist\entry.js?silent=true!D:\XXX\node_modules\angular2-template-loader\index.js!D:\XXX\ClientApp\app\services\notification-endpoint.service.ts
* D:\XXX\node_modules\@angular\common\esm5\http.js
Used by 1 module(s), i. e.
D:\XXX\node_modules\awesome-typescript-loader\dist\entry.js?silent=true!D:\XXX\node_modules\angular2-template-loader\index.js!D:\XXX\ClientApp\app\app.module.ts
@ ./node_modules/@angular/Common/esm5/http.js
@ ./ClientApp/app/services/notification-endpoint.service.ts
@ ./ClientApp/app/app.module.ts
@ ./ClientApp/boot.browser.ts
@ multi event-source-polyfill webpack-hot-middleware/client?path=__webpack_hmr&dynamicPublicPath=true ./ClientApp/boot.browser.ts
Current behavior
StaticInjectorError[HttpClient]: StaticInjectorError[HttpClient]: NullInjectorError: No provider for HttpClient!
Environment
Angular version: 5.0.0 and 5.0.1 (also 5.1 beta)
Browser:
- all
For Tooling issues:
- Node version: 8.5.0
- Platform: windows
{
""name"": ""X"",
""version"": ""1.0.0"",
""description"": ""X"",
""author"": {
""name"": ""X X"",
""email"": ""XX"",
""url"": ""X""
},
""homepage"": ""X"",
""dependencies"": {
""@angular/animations"": ""^5.1.0-beta.0"",
""@angular/common"": ""^5.1.0-beta.0"",
""@angular/compiler"": ""^5.1.0-beta.0"",
""@angular/compiler-cli"": ""^5.1.0-beta.0"",
""@angular/core"": ""^5.1.0-beta.0"",
""@angular/forms"": ""^5.1.0-beta.0"",
""@angular/http"": ""^5.1.0-beta.0"",
""@angular/platform-browser"": ""^5.1.0-beta.0"",
""@angular/platform-browser-dynamic"": ""^5.1.0-beta.0"",
""@angular/platform-server"": ""^5.1.0-beta.0"",
""@angular/router"": ""^5.1.0-beta.0"",
""@ngtools/webpack"": ""^1.8.0"",
""@ngx-translate/core"": ""^8.0.0"",
""@ngx-translate/http-loader"": ""^2.0.0"",
""@swimlane/ngx-datatable"": ""^11.0.3"",
""@types/jquery"": ""^3.2.16"",
""@types/webpack-env"": ""^1.13.2"",
""angular2-template-loader"": ""^0.6.2"",
""aspnet-webpack"": ""^2.0.1"",
""awesome-typescript-loader"": ""^3.3.0"",
""bootstrap"": ""^3.3.7"",
""bootstrap-datepicker"": ""^1.7.1"",
""bootstrap-select"": ""^1.12.4"",
""bootstrap-toggle"": ""^2.2.2"",
""bootstrap-vertical-tabs"": ""^1.2.2"",
""chart.js"": ""^2.7.1"",
""core-js"": ""^2.5.1"",
""css"": ""^2.2.1"",
""css-loader"": ""^0.28.7"",
""event-source-polyfill"": ""^0.0.11"",
""expose-loader"": ""^0.7.3"",
""extract-text-webpack-plugin"": ""^3.0.2"",
""file-loader"": ""^1.1.5"",
""font-awesome"": ""^4.7.0"",
""html-loader"": ""^0.5.1"",
""jquery"": ""^3.2.1"",
""json-loader"": ""^0.5.7"",
""ng2-charts"": ""^1.6.0"",
""ng2-toasty"": ""^4.0.3"",
""ngx-bootstrap"": ""^2.0.0-beta.8"",
""node-sass"": ""^4.6.0"",
""popper.js"": ""^1.12.6"",
""raw-loader"": ""^0.5.1"",
""rxjs"": ""^5.5.2"",
""sass-loader"": ""^6.0.6"",
""style-loader"": ""^0.19.0"",
""to-string-loader"": ""^1.1.5"",
""typescript"": ""^2.6.1"",
""url-loader"": ""^0.6.2"",
""web-animations-js"": ""^2.3.1"",
""webpack"": ""^3.8.1"",
""webpack-hot-middleware"": ""^2.20.0"",
""webpack-merge"": ""^4.1.1"",
""zone.js"": ""^0.8.18""
},
""devDependencies"": {
""@types/chai"": ""^4.0.4"",
""@types/jasmine"": ""^2.6.3"",
""chai"": ""^4.1.2"",
""jasmine-core"": ""^2.8.0"",
""karma"": ""^1.7.1"",
""karma-chai"": ""^0.1.0"",
""karma-chrome-launcher"": ""^2.2.0"",
""karma-cli"": ""^1.0.1"",
""karma-jasmine"": ""^1.1.0"",
""karma-jasmine-html-reporter"": ""^0.2.2"",
""karma-webpack"": ""^2.0.5""
},
""scripts"": {
""dev-build"": ""node node_modules/webpack/bin/webpack.js --config webpack.config.vendor.js"",
""test"": ""karma start ClientApp/test/karma.conf.js""
}
}
webpack.config.js
const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const AotPlugin = require('@ngtools/webpack').AotPlugin;
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
module.exports = (env) => {
// Configuration in common to both client-side and server-side bundles
const isDevBuild = !(env && env.prod);
const sharedConfig = {
stats: { modules: false },
context: __dirname,
resolve: { extensions: ['.js', '.ts'] },
output: {
filename: '[name].js',
publicPath: 'dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
},
module: {
rules: [
{ test: /\.ts$/, use: isDevBuild ? ['awesome-typescript-loader?silent=true', 'angular2-template-loader'] : '@ngtools/webpack' },
{ test: /\.html$/, use: 'html-loader?minimize=false' },
{ test: /\.css$/, use: ['to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize'] },
{ test: /\.scss$/, use: ['to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize', 'sass-loader'] },
{ test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' }
]
},
plugins: [new CheckerPlugin()]
};
// Configuration for client-side bundle suitable for running in browsers
const clientBundleOutputDir = './wwwroot/dist';
const clientBundleConfig = merge(sharedConfig, {
entry: { 'main-client': './ClientApp/boot.browser.ts' },
output: { path: path.join(__dirname, clientBundleOutputDir) },
plugins: [
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./wwwroot/dist/vendor-manifest.json')
})
].concat(isDevBuild ? [
// Plugins that apply in development build",https://stackoverflow.com/questions/47236963/no-provider-for-httpclient,768,1090216.0,30.0,,,2017-11-11 10:36:35,2024-09-03 18:27:27,2020-06-11 07:45:21,,,angular;typescript,Himmet Yelekin,7769,1191043,registered,true,,,CC BY-SA 4.0,2019-07-29 16:20:35,12399,11994,8,0,0,2,false,false,false,true,true,true,26,4,false,0.028,0.0007,3297,2017,11,10,Saturday,true,false,false,false,false,false,false
32693061,How can I select an element in a component template?,"Does anybody know how to get hold of an element defined in a component template? Polymer makes it really easy with the $ and $$.
I was just wondering how to go about it in Angular.
Take the example from the tutorial:
import {Component} from '@angular/core';
@Component({
selector:'display',
template:`
<input #myname (input)=""updateName(myname.value)""/>
<p>My name : {{myName}}</p>
`
})
export class DisplayComponent {
myName: string = ""Aman"";
updateName(input: String) {
this.myName = input;
}
}
How do I catch hold or get a reference of the p or input element from within the class definition?
",https://stackoverflow.com/questions/32693061/how-can-i-select-an-element-in-a-component-template,754,1031519.0,15.0,,,2015-09-21 10:34:45,2023-08-17 19:00:48,2019-12-15 22:35:12,,,angular;typescript;angular-components,Aman Gupta,8171,2748475,registered,true,35209681,,CC BY-SA 4.0,2018-07-11 12:25:25,770,666,5,0,0,3,true,false,false,true,true,true,52,10,true,0.015,0.0007,4079,2015,9,10,Monday,false,false,false,false,false,false,false
18111657,How to get names of enum entries?,"I would like to iterate a TypeScript enum object and get each enumerated symbol name, for example:
enum myEnum { entry1, entry2 }
for (var entry in myEnum) {
// use entry's name here, e.g., "entry1"
}
",https://stackoverflow.com/questions/18111657/how-to-get-names-of-enum-entries,738,1097077.0,45.0,,,2013-08-07 19:01:56,2025-07-31 02:33:07,2021-10-05 01:58:30,,,enums;typescript,CalvinDale,9879,852956,registered,true,18112157,,CC BY-SA 4.0,,248,217,1,0,0,2,true,false,false,true,true,true,33,7,true,0.041,0.0007,4854,2013,8,19,Wednesday,false,false,false,false,false,false,false
29689966,"How to define type for a function callback (as any function type, not universal any) used in a method parameter","Currently I have type definition as:
interface Param {
title: string;
callback: any;
}
I need something like:
interface Param {
title: string;
callback: function;
}
but the 2nd one is not being accepted.
",https://stackoverflow.com/questions/29689966/how-to-define-type-for-a-function-callback-as-any-function-type-not-universal,738,852936.0,13.0,,,2015-04-17 03:53:19,2024-02-02 15:44:21,2023-05-24 16:18:02,,,typescript,Smrutiranjan Sahu,7699,2702809,registered,true,,,CC BY-SA 4.0,,295,226,2,0,0,1,false,false,false,true,true,true,111,20,false,0.015,0.0009,4236,2015,4,3,Friday,false,false,false,false,false,false,false
13315131,Enforcing the type of the indexed members of a Typescript object?,"I would like to store a mapping of string -> string in a Typescript object, and enforce that all of the values map to strings. For example:
var stuff = {};
stuff["a"] = "foo"; // okay
stuff["b"] = "bar"; // okay
stuff["c"] = false; // ERROR! bool != string
Is there a way for me to enforce that the values must be strings (or whatever type..)?
",https://stackoverflow.com/questions/13315131/enforcing-the-type-of-the-indexed-members-of-a-typescript-object,737,848404.0,9.0,,,2012-11-09 20:02:45,2023-05-08 15:49:25,2022-11-12 00:00:40,,,typescript,Armentage,12953,78576,registered,true,13315210,,CC BY-SA 4.0,,444,406,1,0,0,1,true,false,false,true,true,true,65,11,true,0.011,0.0009,5125,2012,11,20,Friday,false,false,false,false,false,false,false
14425568,Interface type check with Typescript,"This question is the direct analogon to Class type check in TypeScript
I need to find out at runtime if a variable of type any implements an interface. Here's my code:
interface A {
member: string;
}
var a: any = { member: "foobar" };
if (a instanceof A) alert(a.member);
If you enter this code in the typescript playground, the last line will be marked as an error, "The name A does not exist in the current scope". But that isn't true, the name does exist in the current scope. I can even change the variable declaration to var a:A={member:"foobar"}; without complaints from the editor. After browsing the web and finding the other question on SO I changed the interface to a class but then I can't use object literals to create instances.
I wondered how the type A could vanish like that but a look at the generated javascript explains the problem:
var a = {
member: "foobar"
};
if (a instanceof A) {
alert(a.member);
}
There is no representation of A as an interface, therefore no runtime type checks are possible.
I understand that javascript as a dynamic language has no concept of interfaces. Is there any way to type check for interfaces?
The typescript playground's autocompletion reveals that typescript even offers a method implements. How can I use it ?
",https://stackoverflow.com/questions/14425568/interface-type-check-with-typescript,723,988698.0,30.0,,,2013-01-20 14:37:38,2024-03-03 19:17:53,2024-01-28 16:36:53,,,javascript;typescript;interface,lhk,30846,497600,registered,true,14426274,,CC BY-SA 4.0,,1620,1331,4,1,0,3,true,false,false,true,true,true,36,5,false,0.03,0.0007,5053,2013,1,14,Sunday,true,false,true,false,false,false,false
35534959,access key and value of object using *ngFor,"I am a bit confused about how to get the key and value of an object in angular2 while using *ngFor for iterating over the object. I know in angular 1.x there is a syntax like
ng-repeat=""(key, value) in demo""
but I don't know how to do the same in angular2. I have tried something similar, without success:
<ul>
<li *ngFor='#key of demo'>{{key}}</li>
</ul>
demo = {
'key1': [{'key11':'value11'}, {'key12':'value12'}],
'key2': [{'key21':'value21'}, {'key22':'value22'}],
}
Here is a plnkr with my attempt:
http://plnkr.co/edit/mIj619FncOpfdwrR0KeG?p=preview
How can I get key1 and key2 dynamically using *ngFor? After searching extensively, I found the idea of using pipes but I don't know how to go about it.
Is there any inbuilt pipe for doing the same in angular2?
",https://stackoverflow.com/questions/35534959/access-key-and-value-of-object-using-ngfor,702,790745.0,21.0,,,2016-02-21 10:28:24,2022-06-10 01:39:46,2020-06-19 14:43:01,,,angular;typescript;object,Pardeep Jain,86936,5043867,registered,true,51491848,,CC BY-SA 4.0,2018-08-18 15:11:03,1154,839,8,1,0,3,true,false,false,true,true,true,43,8,false,0.027,0.0009,3926,2016,2,10,Sunday,true,false,false,false,false,false,false
37265275,How to implement class constants?,"In TypeScript, the const keyword cannot be used to declare class properties. Doing so causes the compiler to an error with "A class member cannot have the 'const' keyword."
I find myself in need to clearly indicate in code that a property should not be changed. I want the IDE or compiler to error if I attempt to assign a new value to the property once it has been declared. How do you guys achieve this?
I'm currently using a read-only property, but I wonder if there is a better way:
get MY_CONSTANT():number {return 10};
I'm using typescript 1.8. Suggestions?
PS: I'm now using typescript 2.0.3, so I've accepted David's answer
",https://stackoverflow.com/questions/37265275/how-to-implement-class-constants,691,591212.0,10.0,,,2016-05-17 00:32:02,2023-07-30 13:37:44,2022-12-28 23:59:36,,,typescript;class-constants,BeetleJuice,41126,3977061,registered,true,37265481,,CC BY-SA 4.0,,775,644,2,1,0,2,true,false,false,true,true,true,33,5,true,0.017,0.0012,3840,2016,5,0,Tuesday,false,false,false,false,false,false,false
51936369,What is the Record type?,"What does Record<K, T> mean in Typescript?
Typescript 2.1 introduced the Record type, describing it in an example:
// For every properties K of type T, transform it to U
function mapObject<K extends string, T, U>(obj: Record<K, T>, f: (x: T) => U): Record<K, U>
see Typescript 2.1
And the Advanced Types page mentions Record under the Mapped Types heading alongside Readonly, Partial, and Pick, in what appears to be its definition:
type Record<K extends string, T> = {
[P in K]: T;
}
Readonly, Partial and Pick are homomorphic whereas Record is not. One clue that Record is not homomorphic is that it doesn’t take an input type to copy properties from:
type ThreeStringProps = Record<'prop1' | 'prop2' | 'prop3', string>
And that's it. Besides the above quotes, there is no other mention of Record on typescriptlang.org.
Questions
Can someone give a simple definition of what Record is?
Is Record<K,T> merely a way of saying "all properties on this object will have type T"? Probably not all properties, since K has some purpose...
Does the K generic forbid additional keys on the object that are not K, or does it allow them and just indicate that their properties are not transformed to T?
With the given example:
type ThreeStringProps = Record<'prop1' | 'prop2' | 'prop3', string>
Is it exactly the same as this?:
type ThreeStringProps = {prop1: string, prop2: string, prop3: string}
",https://stackoverflow.com/questions/51936369/what-is-the-record-type,685,710283.0,4.0,,,2018-08-20 18:11:29,2024-05-28 13:08:22,2022-09-29 13:24:37,,,typescript;typescript2.0,Matthias,16003,802138,registered,true,51937036,,CC BY-SA 4.0,,2371,1470,19,3,0,2,true,false,false,true,true,true,24,5,true,0.006,0.001,3015,2018,8,18,Monday,false,false,false,false,false,false,false
22875636,How do I cast a JSON object to a TypeScript class?,"I read a JSON object from a remote REST server. This JSON object has all the properties of a TypeScript class (by design). How do I cast that received JSON object to a type var?
I don't want to populate a TypeScript var (i.e. have a constructor that takes this JSON object). It's large and copying everything across sub-object by sub-object & property by property would take a lot of time.
",https://stackoverflow.com/questions/22875636/how-do-i-cast-a-json-object-to-a-typescript-class,663,925365.0,29.0,,,2014-04-05 01:46:18,2025-11-28 12:55:55,2025-11-28 12:55:55,,,json;typescript,David Thielen,33986,509627,registered,true,22875957,,CC BY-SA 4.0,,408,394,0,0,0,2,true,false,false,true,true,true,50,11,true,0.031,0.0007,4613,2014,4,1,Saturday,true,false,false,false,false,false,false
15260732,"Does Typescript support the ?. operator? (And, what's it called?)","Does Typescript currently (or are there plans to) support the safe navigation operator of ?.
ie:
var thing = foo?.bar
// same as:
var thing = (foo) ? foo.bar : null;
Also, is there a more common name for this operator (it's incedibly hard to google for).
",https://stackoverflow.com/questions/15260732/does-typescript-support-the-operator-and-whats-it-called,647,504712.0,15.0,,,2013-03-07 00:11:24,2023-10-27 08:18:35,2013-03-07 01:36:09,,,typescript,Marty Pitt,29460,59015,registered,true,15260828,,CC BY-SA 3.0,,409,259,2,1,0,1,true,false,false,true,true,true,69,10,false,0.03,0.0013,5007,2013,3,0,Thursday,false,false,false,false,false,false,false
51145180,How to use `@ts-ignore` for a block?,"The // @ts-ignore comment enables the TypeScript compiler to ignore the line below it.
How can one ignore a whole block of code with TypeScript?
",https://stackoverflow.com/questions/51145180/how-to-use-ts-ignore-for-a-block,646,1056626.0,12.0,,,2018-07-03 00:24:50,2025-02-19 17:05:16,2021-10-04 16:24:56,,,typescript;tslint,vadersfather,9749,3599414,registered,true,51774725,,CC BY-SA 4.0,2024-01-18 15:41:36,172,145,1,0,0,2,true,false,false,true,true,true,36,7,true,0.011,0.0006,3063,2018,7,0,Tuesday,false,false,false,false,false,false,false
54496398,TypeScript: Type 'string | undefined' is not assignable to type 'string',"When I make any property of an interface optional, and while assigning its member to some other variable like this:
interface Person {
name?: string,
age?: string,
gender?: string,
occupation?: string,
}
function getPerson() {
let person = <Person>{name:"John"};
return person;
}
let person: Person = getPerson();
let name1: string = person.name; // <<< Error here
I get an error like the following:
TS2322: Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'.
How do I get around this error?
",https://stackoverflow.com/questions/54496398/typescript-type-string-undefined-is-not-assignable-to-type-string,635,1319221.0,21.0,,,2019-02-02 18:51:07,2025-03-25 03:13:43,2025-03-25 02:51:57,,,typescript,asdasd,7360,10183456,registered,true,,,CC BY-SA 4.0,2021-11-22 15:05:41,704,596,2,0,0,1,false,false,false,true,true,true,133,2,false,0.016,0.0005,2849,2019,2,18,Saturday,true,false,false,false,false,false,false
42790602,How do I check whether an array contains a string in TypeScript?,"Currently I am using Angular 2.0. I have an array as follows:
var channelArray: Array<string> = ['one', 'two', 'three'];
How can I check in TypeScript whether the channelArray contains a string 'three'?
",https://stackoverflow.com/questions/42790602/how-do-i-check-whether-an-array-contains-a-string-in-typescript,630,1389815.0,10.0,,,2017-03-14 15:50:26,2024-03-21 01:16:43,2018-05-14 12:15:15,,,javascript;arrays;typescript,code1,9209,7679343,registered,true,42790792,,CC BY-SA 4.0,,250,212,1,0,0,3,true,false,false,true,true,true,64,12,true,0.007,0.0005,3539,2017,3,15,Tuesday,false,false,true,false,false,false,false
12702548,Constructor overload in TypeScript,"I want to do constructor overloading in TypeScript. On page 64 of the language specification (v 0.8), there are statements describing constructor overloads, but there wasn't any sample code given.
I'm trying out a really basic class declaration right now; it looks like this,
interface IBox {
x : number;
y : number;
height : number;
width : number;
}
class Box {
public x: number;
public y: number;
public height: number;
public width: number;
constructor(obj: IBox) {
this.x = obj.x;
this.y = obj.y;
this.height = obj.height;
this.width = obj.width;
}
constructor() {
this.x = 0;
this.y = 0;
this.width = 0;
this.height = 0;
}
}
When ran with tsc BoxSample.ts, it throws out a duplicate constructor definition -- which is obvious.
",https://stackoverflow.com/questions/12702548/constructor-overload-in-typescript,625,469027.0,18.0,,,2012-10-03 05:48:08,2025-06-18 21:04:35,2025-06-18 21:04:35,,,typescript;constructor;overloading,Ted,6351,1716118,registered,true,,,CC BY-SA 4.0,,918,860,2,0,0,3,false,false,false,true,true,true,34,4,false,0.038,0.0013,5162,2012,10,5,Wednesday,false,false,false,false,false,false,false
54438012,An index signature parameter type cannot be a union type. Consider using a mapped object type instead,"I'm trying to use the following pattern:
enum Option {
ONE = 'one',
TWO = 'two',
THREE = 'three'
}
interface OptionRequirement {
someBool: boolean;
someString: string;
}
interface OptionRequirements {
[key: Option]: OptionRequirement;
}
This seems very straightforward to me, however I get the following error:
An index signature parameter type cannot be a union type. Consider using a mapped object type instead.
What am I doing wrong?
",https://stackoverflow.com/questions/54438012/an-index-signature-parameter-type-cannot-be-a-union-type-consider-using-a-mappe,615,286258.0,10.0,,,2019-01-30 10:10:27,2024-02-23 04:35:33,2019-06-17 21:20:46,,,javascript;typescript,john maccarthy,6483,9192577,registered,true,,,CC BY-SA 4.0,,537,460,1,0,0,2,false,false,false,true,true,true,101,17,false,0.035,0.0021,2852,2019,1,10,Wednesday,false,false,true,false,false,false,false
40140149,Use async await with Array.map,"Given the following code:
var arr = [1,2,3,4,5];
var results: number[] = await arr.map(async (item): Promise<number> => {
await callAsynchronousOperation(item);
return item + 1;
});
which produces the following error:
TS2322: Type 'Promise<number>[]' is not assignable to type 'number[]'.
Type 'Promise<number> is not assignable to type 'number'.
How can I fix it? How can I make async await and Array.map work together?
",https://stackoverflow.com/questions/40140149/use-async-await-with-array-map,614,632311.0,11.0,,,2016-10-19 19:39:06,2024-10-17 16:49:11,2017-07-26 07:32:08,,,javascript;typescript;promise;async-await;ecmascript-2017,Alon,12215,1026271,registered,true,40140562,,CC BY-SA 3.0,,577,474,3,0,0,5,true,false,false,true,true,true,30,5,false,0.017,0.001,3685,2016,10,19,Wednesday,false,false,true,false,false,false,false
12787781,Type definition in object literal in TypeScript,"In TypeScript classes it's possible to declare types for properties, for example:
class className {
property: string;
};
How do declare the type of a property in an object literal?
I've tried the following code but it doesn't compile:
var obj = {
property: string;
};
I'm getting the following error:
The name 'string' does not exist in the current scope
Am I doing something wrong or is this a bug?
",https://stackoverflow.com/questions/12787781/type-definition-in-object-literal-in-typescript,614,772503.0,15.0,,,2012-10-08 18:58:31,2023-05-31 06:13:39,2019-06-19 16:30:14,,,typescript,Dace Zarina,6952,842158,registered,true,12787919,,CC BY-SA 4.0,,532,417,2,0,0,1,true,false,false,true,true,true,47,7,false,0.019,0.0008,5157,2012,10,18,Monday,false,false,false,false,false,false,false
13142635,How can I create an object based on an interface file definition in TypeScript?,"I have defined an interface like this:
interface IModal {
content: string;
form: string;
href: string;
$form: JQuery;
$message: JQuery;
$modal: JQuery;
$submits: JQuery;
}
I define a variable like this:
var modal: IModal;
However, when I try to set the property of modal it gives me a message saying that
""cannot set property content of undefined""
Is it okay to use an interface to describe my modal object and if so how should I create it?
",https://stackoverflow.com/questions/13142635/how-can-i-create-an-object-based-on-an-interface-file-definition-in-typescript,596,834071.0,17.0,,,2012-10-30 15:42:44,2026-05-03 15:22:17,2019-04-25 15:21:48,,,typescript,user1679941,,,does_not_exist,true,13142840,,CC BY-SA 4.0,,580,480,3,0,0,1,true,false,false,true,false,true,79,14,true,0.02,0.0007,5135,2012,10,15,Tuesday,false,false,false,false,false,false,false
40349987,How to suppress "error TS2533: Object is possibly 'null' or 'undefined'"?,"I have a type:
type tSelectProtected = {
handleSelector?: string,
data?: tSelectDataItem[],
wrapperEle?: HTMLElement,
inputEle?: HTMLElement,
listEle?: HTMLElement,
resultEle?: HTMLElement,
maxVisibleListItems?: number
}
I declare a global module-wise variable:
var $protected : tSelectProtected = {};
I'm assigning proper value in function1() scope:
$protected.listEle = document.createElement('DIV');
Later in function2() scope, I'm calling:
$protected.listEle.classList.add('visible');
I'm getting TypeScript error:
error TS2533: Object is possibly 'null' or 'undefined'
I know that I can do explicit check using if ($protected.listEle) {$protected.listEle} to calm down compiler but this seems to be very unhandy for most non trivial cases.
How this situation can or should be handled without disabling TS compiler checks?
",https://stackoverflow.com/questions/40349987/how-to-suppress-error-ts2533-object-is-possibly-null-or-undefined,573,1027851.0,31.0,,,2016-10-31 20:22:21,2024-07-17 20:57:41,2019-08-19 20:44:01,,,typescript,user1151646,,,does_not_exist,true,40350182,,CC BY-SA 4.0,,1080,859,9,0,0,1,true,false,false,true,false,true,99,11,true,0.03,0.0006,3673,2016,10,20,Monday,false,false,false,false,false,false,false
43220348,Can't bind to 'formControl' since it isn't a known property of 'input' - Angular2 Material Autocomplete issue,"I am trying to use Angular Material Autocomplete component in my Angular 2 project. I added the following to my template.
<md-input-container>
<input mdInput placeholder=""Category"" [mdAutocomplete]=""auto"" [formControl]=""stateCtrl"">
</md-input-container>
<md-autocomplete #auto=""mdAutocomplete"">
<md-option *ngFor=""let state of filteredStates | async"" [value]=""state"">
{{ state }}
</md-option>
</md-autocomplete>
Following is my component.
import {Component, OnInit} from ""@angular/core"";
import {ActivatedRoute, Router} from ""@angular/router"";
import {FormControl} from ""@angular/forms"";
@Component({
templateUrl: './edit_item.component.html',
styleUrls: ['./edit_item.component.scss']
})
export class EditItemComponent implements OnInit {
stateCtrl: FormControl;
states = [....some data....];
constructor(private route: ActivatedRoute, private router: Router) {
this.stateCtrl = new FormControl();
this.filteredStates = this.stateCtrl.valueChanges.startWith(null).map(name => this.filterStates(name));
}
ngOnInit(): void {
}
filterStates(val: string) {
return val ? this.states.filter((s) => new RegExp(val, 'gi').test(s)) : this.states;
}
}
I'm getting the following error. It looks like the formControl directive is not being found.
Can't bind to 'formControl' since it isn't a known property of 'input'
What is the issue here?
",https://stackoverflow.com/questions/43220348/cant-bind-to-formcontrol-since-it-isnt-a-known-property-of-input-angular,572,397513.0,11.0,,,2017-04-05 01:32:57,2023-06-21 06:02:41,2020-03-27 17:55:16,,,angular;typescript;angular-material2;angular-forms,Lahiru Chandima,24406,1015678,registered,true,43220824,,CC BY-SA 4.0,,1726,1473,3,1,0,4,true,false,false,true,true,true,133,17,false,0.028,0.0014,3517,2017,4,1,Wednesday,false,false,false,false,false,false,false
41285211,Overriding interface property type defined in Typescript d.ts file,"Is there a way to change the type of interface property defined in a *.d.ts in typescript?
for example:
An interface in x.d.ts is defined as
interface A {
property: number;
}
I want to change it in the typescript files that I write to
interface A {
property: Object;
}
or even this would work
interface B extends A {
property: Object;
}
Will this approach work? It didn't work when I tried on my system. Just want to confirm if it's even possible?
",https://stackoverflow.com/questions/41285211/overriding-interface-property-type-defined-in-typescript-d-ts-file,569,563479.0,23.0,,,2016-12-22 14:18:14,2024-11-28 20:50:42,2019-02-14 11:14:44,,,javascript;typescript;typescript-typings,Abdul23,6145,3835632,registered,true,51507473,,CC BY-SA 4.0,,600,467,5,0,0,3,true,false,false,true,true,true,66,9,false,0.041,0.001,3621,2016,12,14,Thursday,false,false,true,false,false,false,false
14727044,What is the difference between types String and string?,"Does anyone know the difference between String and string in TypeScript? Am I correct in assuming that they ought to be the same?
var a: String = "test";
var b: string = "another test";
a = b;
b = a; // this gives a compiler error!
Current version of the compiler says:
Type 'String' is not assignable to type 'string'.
'string' is a primitive, but 'String' is a wrapper object.
Prefer using 'string' when possible.
Is that a bug?
",https://stackoverflow.com/questions/14727044/what-is-the-difference-between-types-string-and-string,568,263963.0,10.0,,,2013-02-06 10:43:00,2025-01-08 16:12:27,2021-12-04 15:40:22,,,typescript,Paul0515,25755,1627079,registered,true,14727461,,CC BY-SA 4.0,,555,460,4,0,0,1,true,false,false,true,true,true,55,9,true,0.038,0.0022,5036,2013,2,10,Wednesday,false,false,false,false,false,false,false
32680244,@Directive vs @Component in Angular,"What is the difference between @Component and @Directive in Angular?
Both of them seem to do the same task and have the same attributes.
What are the use cases and when to prefer one over another?
",https://stackoverflow.com/questions/32680244/directive-vs-component-in-angular,562,173732.0,12.0,,,2015-09-20 14:03:51,2023-02-14 11:26:02,2022-01-28 08:00:38,,,angular;typescript,Prasanjit Dey,6034,4917853,registered,true,32681774,,CC BY-SA 4.0,2017-04-06 12:57:39,238,198,2,0,0,2,true,false,false,true,true,true,35,5,false,0.069,0.0032,4080,2015,9,14,Sunday,true,false,false,false,false,false,false
43804805,Check if value exists in enum in TypeScript,"I receive a number type = 3 and have to check if it exists in this enum:
export const MESSAGE_TYPE = {
INFO: 1,
SUCCESS: 2,
WARNING: 3,
ERROR: 4,
};
The best way I found is by getting all Enum Values as an array and using indexOf on it. But the resulting code isn't very legible:
if( -1 < _.values( MESSAGE_TYPE ).indexOf( _.toInteger( type ) ) ) {
// do stuff ...
}
Is there a simpler way of doing this?
",https://stackoverflow.com/questions/43804805/check-if-value-exists-in-enum-in-typescript,561,617903.0,15.0,,,2017-05-05 12:20:24,2025-07-31 02:37:09,2022-05-26 15:03:38,,,javascript;typescript;enums,Tim Schoch,6664,5476434,registered,true,47755096,,CC BY-SA 4.0,2021-07-23 10:48:40,512,430,3,0,0,3,true,false,false,true,true,true,43,8,false,0.024,0.0009,3487,2017,5,12,Friday,false,false,true,false,false,false,false
37979489,How to watch and reload ts-node when TypeScript files change,"I'm trying to run a dev server with TypeScript and an Angular application without transpiling ts files every time.
What I found is that I can run .ts files with ts-node but I want also to watch .ts files and reload my app/server. An example of this is the command gulp watch.
",https://stackoverflow.com/questions/37979489/how-to-watch-and-reload-ts-node-when-typescript-files-change,550,554070.0,25.0,,,2016-06-22 22:50:36,2025-08-19 16:49:08,2023-01-05 21:28:30,,,typescript;development-environment;nodemon,Ieltxu Algañarás,5534,5725211,registered,true,37979548,,CC BY-SA 4.0,,351,276,4,0,0,3,true,false,false,true,true,true,60,10,false,0.045,0.001,3804,2016,6,22,Wednesday,false,false,false,false,false,false,false
46705101,mat-form-field must contain a MatFormFieldControl,"We are trying to build our own form-field-Components at our Company. We are trying to wrap material design's Components like this:
field:
<mat-form-field>
<ng-content></ng-content>
<mat-hint align="start"><strong>{{hint}}</strong> </mat-hint>
<mat-hint align="end">{{message.value.length}} / 256</mat-hint>
<mat-error>This field is required</mat-error>
</mat-form-field>
textbox:
<field hint="hint">
<input matInput
[placeholder]="placeholder"
[value]="value"
(change)="onChange($event)"
(keydown)="onKeydown($event)"
(keyup)="onKeyup($event)"
(keypress)="onKeypress($event)">
</field>
Usage:
<textbox value="test" hint="my hint"></textbox>
This results in approximately this:
<textbox placeholder="Personnummer/samordningsnummer" value="" ng-reflect-placeholder="Personnummer/samordningsnummer">
<field>
<mat-form-field class="mat-input-container mat-form-field">
<div class="mat-input-wrapper mat-form-field-wrapper">
<div class="mat-input-flex mat-form-field-flex">
<div class="mat-input-infix mat-form-field-infix">
<input _ngcontent-c4="" class="mat-input-element mat-form-field-autofill-control" matinput="" ng-reflect-placeholder="Personnummer/samordningsnummer" ng-reflect-value="" id="mat-input-2" placeholder="Personnummer/samordningsnummer" aria-invalid="false">
<span class="mat-input-placeholder-wrapper mat-form-field-placeholder-wrapper"></span>
</div>
</div>
<div class="mat-input-underline mat-form-field-underline">
<span class="mat-input-ripple mat-form-field-ripple"></span>
</div>
<div class="mat-input-subscript-wrapper mat-form-field-subscript-wrapper"></div>
</div>
</mat-form-field>
</field>
</textbox>
But I'm getting "mat-form-field must contain a MatFormFieldControl" in the console. I guess this has to do with mat-form-field not directly containing a matInput-field. But it is containing it, it's just withing the ng-content projection.
Here is a blitz:
https://stackblitz.com/edit/angular-xpvwzf
",https://stackoverflow.com/questions/46705101/mat-form-field-must-contain-a-matformfieldcontrol,542,846720.0,44.0,,,2017-10-12 08:42:28,2024-08-06 09:24:50,2022-11-04 17:45:04,,,angular;typescript;angular-material,Viktor Eriksson,6361,479045,registered,true,49658335,,CC BY-SA 4.0,2021-08-10 06:11:37,3026,2637,4,1,0,3,true,false,false,true,true,true,49,5,false,0.052,0.0006,3327,2017,10,8,Thursday,false,false,false,false,false,false,false
38271273,Experimental decorators warning in TypeScript compilation,"I receive the warning...
Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option `to remove this warning.
... even though my compilerOptions in tsconfig.json have the following settings:
""emitDecoratorMetadata"": true,
""experimentalDecorators"": true,
What is weird is that some random classes that use decorators do not show that warning but the rest in the same project do.
What could cause such behavior in the TypeScript compiler?
",https://stackoverflow.com/questions/38271273/experimental-decorators-warning-in-typescript-compilation,542,511969.0,40.0,,,2016-07-08 16:15:34,2024-01-09 15:10:00,2020-03-25 17:49:18,,,typescript;decorator;vs-code,bensiu,25704,367878,registered,true,38296690,,CC BY-SA 4.0,2018-05-06 13:25:03,607,523,1,0,0,3,true,false,false,true,true,true,57,6,false,0.078,0.0011,3788,2016,7,16,Friday,false,false,false,false,false,false,false
49996456,Importing JSON file in TypeScript,"I have a JSON file that looks like following:
{
""primaryBright"": ""#2DC6FB"",
""primaryMain"": ""#05B4F0"",
""primaryDarker"": ""#04A1D7"",
""primaryDarkest"": ""#048FBE"",
""secondaryBright"": ""#4CD2C0"",
""secondaryMain"": ""#00BFA5"",
""secondaryDarker"": ""#009884"",
""secondaryDarkest"": ""#007F6E"",
""tertiaryMain"": ""#FA555A"",
""tertiaryDarker"": ""#F93C42"",
""tertiaryDarkest"": ""#F9232A"",
""darkGrey"": ""#333333"",
""lightGrey"": ""#777777""
}
I'm trying to import it into a .tsx file. For this I added this to the type definition:
declare module ""*.json"" {
const value: any;
export default value;
}
And I'm importing it like this.
import colors = require('../colors.json')
And in the file, I use the color primaryMain as colors.primaryMain. However I get an error:
Property 'primaryMain' does not exist on type 'typeof ""*.json""
",https://stackoverflow.com/questions/49996456/importing-json-file-in-typescript,532,851340.0,16.0,,,2018-04-24 08:05:47,2025-03-24 13:16:59,2021-04-01 16:31:57,,,json;typescript,Sooraj,10777,3096546,registered,true,49997144,,CC BY-SA 4.0,2022-07-21 19:24:32,1067,887,7,0,0,2,true,false,false,true,true,true,33,5,false,0.019,0.0006,3133,2018,4,8,Tuesday,false,false,false,false,false,false,false
49285864,Is there a `valueof` similar to `keyof` in TypeScript?,"I want to be able to assign an object property to a value given a key and value as inputs yet still be able to determine the type of the value. It's a bit hard to explain so this code should reveal the problem:
type JWT = { id: string, token: string, expire: Date };
const obj: JWT = { id: 'abc123', token: 'tk01', expire: new Date(2018, 2, 14) };
function print(key: keyof JWT) {
switch (key) {
case 'id':
case 'token':
console.log(obj[key].toUpperCase());
break;
case 'expire':
console.log(obj[key].toISOString());
break;
}
}
function onChange(key: keyof JWT, value: any) {
switch (key) {
case 'id':
case 'token':
obj[key] = value + ' (assigned)';
break;
case 'expire':
obj[key] = value;
break;
}
}
print('id');
print('expire');
onChange('id', 'def456');
onChange('expire', new Date(2018, 3, 14));
print('id');
print('expire');
onChange('expire', 1337); // should fail here at compile time
print('expire'); // actually fails here at run time
I tried changing value: any to value: valueof JWT but that didn't work.
Ideally, onChange('expire', 1337) would fail because 1337 is not a Date type.
How can I change value: any to be the value of the given key?
",https://stackoverflow.com/questions/49285864/is-there-a-valueof-similar-to-keyof-in-typescript,529,300066.0,12.0,,,2018-03-14 19:05:54,2025-08-15 12:20:48,2024-09-16 18:41:48,,,typescript,styfle,25086,266535,registered,true,49286056,,CC BY-SA 4.0,,1442,1325,6,0,0,1,true,false,false,true,true,true,54,9,true,0.04,0.0018,3174,2018,3,19,Wednesday,false,false,false,false,false,false,false
17220114,How to declare a type as nullable in TypeScript?,"I have an interface in TypeScript.
interface Employee{
id: number;
name: string;
salary: number;
}
I would like to make salary as a nullable field (Like we can do in C#). Is this possible to do in TypeScript?
",https://stackoverflow.com/questions/17220114/how-to-declare-a-type-as-nullable-in-typescript,526,862086.0,14.0,,,2013-06-20 17:33:23,2023-11-11 04:08:32,2020-06-19 16:00:11,,,typescript;nullable,Amitabh,61759,248827,registered,true,17220359,,CC BY-SA 4.0,,275,224,2,0,0,2,true,false,false,true,true,true,48,9,true,0.016,0.0006,4902,2013,6,17,Thursday,false,false,false,false,false,false,false
48215950,Exclude property from type,"I'd like to exclude a single property from the type. How can I do that?
For example I have
interface XYZ {
x: number;
y: number;
z: number;
}
And I want to exclude property z to get
type XY = { x: number, y: number };
",https://stackoverflow.com/questions/48215950/exclude-property-from-type,525,586457.0,8.0,,,2018-01-11 21:18:44,2022-05-12 16:48:26,2020-12-06 09:07:40,,,typescript,Qwertiy,21969,4928642,registered,true,48216010,,CC BY-SA 4.0,,382,226,3,0,0,1,true,false,false,true,true,true,26,4,false,0.014,0.0009,3236,2018,1,21,Thursday,false,false,false,false,false,false,false
12789231,Class type check in TypeScript,"In ActionScript, it is possible to check the type at run-time using the is operator:
var mySprite:Sprite = new Sprite();
trace(mySprite is Sprite); // true
trace(mySprite is DisplayObject);// true
trace(mySprite is IEventDispatcher); // true
Is it possible to detect if a variable (extends or) is a certain class or interface with TypeScript?
I couldn't find anything about it in the language specs. It should be there when working with classes/interfaces.
",https://stackoverflow.com/questions/12789231/class-type-check-in-typescript,525,1098819.0,5.0,,,2012-10-08 20:47:32,2024-03-26 18:53:56,2024-01-04 08:29:00,,,typescript;typechecking;typeguards,Mark Knol,10291,508029,registered,true,12789324,,CC BY-SA 4.0,,647,464,1,1,0,3,true,false,false,true,true,true,30,5,false,0.005,0.0005,5157,2012,10,20,Monday,false,false,false,false,false,false,false
45176661,How do I decide whether @types/* goes into `dependencies` or `devDependencies`?,"I use TypeScript 2 in my project. I'd like to use some js library, but also typings for that library. I can install types with simple npm install @types/some-library. I'm not sure if I should --save or --save-dev them. It seems to me that even DefinetelyTyped GitHub readme kind of mentions both versions, but never explains them. I would think that @types should be in devDependencies, as types are needed for development and aren't used in runtime, but I saw many times @types in just dependencies. I'm confused.
How should I decide whether @types/* goes into dependencies or devDependencies? Are there actually some more or less official instructions?
",https://stackoverflow.com/questions/45176661/how-do-i-decide-whether-types-goes-into-dependencies-or-devdependencies,523,166541.0,5.0,,,2017-07-18 20:40:54,2023-09-04 09:30:39,,,,typescript;npm;typescript-typings;package.json,kamyl,6476,4530649,registered,true,46011417,,CC BY-SA 3.0,,761,656,7,0,0,4,true,false,false,true,true,false,79,11,true,0.03,0.0031,3413,2017,7,20,Tuesday,false,false,false,false,false,false,false
33700266,How can I get new selection in "select" in Angular 2?,"I am using Angular 2 (TypeScript).
I want to do something with the new selection, but what I get in onChange() is always the last selection. How can I get the new selection?
<select [(ngModel)]=""selectedDevice"" (change)=""onChange($event)"">
<option *ngFor=""#i of devices"">{{i}}</option>
</select>
onChange($event) {
console.log(this.selectedDevice);
// I want to do something here with the new selectedDevice, but what I
// get here is always the last selection, not the one I just selected.
}
",https://stackoverflow.com/questions/33700266/how-can-i-get-new-selection-in-select-in-angular-2,518,894096.0,14.0,,,2015-11-13 19:20:02,2022-05-04 15:06:14,2020-10-19 09:59:23,,,angular;typescript;html-select,Hongbo Miao,50917,2000548,registered,true,33716321,,CC BY-SA 4.0,2019-10-29 06:45:34,651,537,3,0,0,3,true,false,false,true,true,true,63,11,true,0.016,0.0006,4026,2015,11,19,Friday,false,false,false,false,false,false,false
37997824,"Error when trying to inject a service into an angular component "EXCEPTION: Can't resolve all parameters for component", why?","I've built a basic app in Angular, but I have encountered a strange issue where I cannot inject a service into one of my components. It injects fine into any of the three other components I have created, however.
For starters, this is the service:
import { Injectable } from '@angular/core';
@Injectable()
export class MobileService {
screenWidth: number;
screenHeight: number;
constructor() {
this.screenWidth = window.outerWidth;
this.screenHeight = window.outerHeight;
window.addEventListener("resize", this.onWindowResize.bind(this) )
}
onWindowResize(ev: Event) {
var win = (ev.currentTarget as Window);
this.screenWidth = win.outerWidth;
this.screenHeight = win.outerHeight;
}
}
And the component that it refuses to work with:
import { Component, } from '@angular/core';
import { NgClass } from '@angular/common';
import { ROUTER_DIRECTIVES } from '@angular/router';
import {MobileService} from '../';
@Component({
moduleId: module.id,
selector: 'pm-header',
templateUrl: 'header.component.html',
styleUrls: ['header.component.css'],
directives: [ROUTER_DIRECTIVES, NgClass],
})
export class HeaderComponent {
mobileNav: boolean = false;
constructor(public ms: MobileService) {
console.log(ms);
}
}
The error I get in the browser console is this:
EXCEPTION: Can't resolve all parameters for HeaderComponent: (?).
I have the service in the bootstrap function so it has a provider. And I seem to be able to inject it into the constructor of any of my other components without issue.
",https://stackoverflow.com/questions/37997824/error-when-trying-to-inject-a-service-into-an-angular-component-exception-can,515,487464.0,49.0,,,2016-06-23 17:07:45,2022-10-26 19:20:00,2020-10-16 12:10:52,,,angular;typescript;dependency-injection,Keith Otto,5208,4321757,registered,true,38000323,,CC BY-SA 4.0,2017-10-20 10:23:59,1760,1571,2,0,0,3,true,false,false,true,true,true,139,19,true,0.101,0.0011,3803,2016,6,17,Thursday,false,false,false,false,false,false,false
36916989,How can I generate a tsconfig.json file?,"How can I generate a tsconfig.json via the command line?
I tried command tsc init, but this doesn't work.
",https://stackoverflow.com/questions/36916989/how-can-i-generate-a-tsconfig-json-file,513,604107.0,14.0,,,2016-04-28 14:01:02,2024-05-16 09:21:22,2024-05-16 09:21:22,,,typescript;tsconfig.json,Rajab Shakirov,8175,3914072,registered,true,36917406,,CC BY-SA 4.0,,140,107,2,0,0,2,true,false,false,true,true,true,40,7,true,0.023,0.0008,3859,2016,4,14,Thursday,false,false,false,false,false,false,false
37978528,TypeScript Type 'string' is not assignable to type,"Here's what I have in file fruit.ts:
export type Fruit = "Orange" | "Apple" | "Banana"
Now I'm importing fruit.ts in another TypeScript file. Here's what I have
myString:string = "Banana";
myFruit:Fruit = myString;
When I do
myFruit = myString;
I get an error:
Type 'string' is not assignable to type '"Orange" | "Apple" |
"Banana"'
How can I assign a string to a variable of custom type Fruit?
",https://stackoverflow.com/questions/37978528/typescript-type-string-is-not-assignable-to-type,513,933871.0,14.0,,,2016-06-22 21:25:26,2025-04-04 19:33:13,2025-03-25 02:32:45,,,javascript;typescript,user6123723,11286,1324816,registered,true,37978675,,CC BY-SA 4.0,,628,471,3,0,0,2,true,false,false,true,true,true,58,8,false,0.015,0.0005,3804,2016,6,21,Wednesday,false,false,true,false,false,false,false
30734509,How to pass optional parameters while omitting some other optional parameters?,"Given the following signature:
export interface INotificationService {
error(message: string, title?: string, autoHideAfter?: number);
}
How can I call the function error() not specifying the title parameter, but setting autoHideAfter to say 1000?
",https://stackoverflow.com/questions/30734509/how-to-pass-optional-parameters-while-omitting-some-other-optional-parameters,511,644633.0,12.0,,,2015-06-09 14:09:09,2022-07-31 15:53:25,2019-09-03 21:06:32,,,typescript,g.pickardou,36829,1157814,registered,true,30734778,,CC BY-SA 4.0,,354,255,5,0,0,1,true,false,false,true,true,true,78,11,true,0.019,0.0008,4183,2015,6,14,Tuesday,false,false,false,false,false,false,false
29382389,Defining array with multiple types in TypeScript,"I have an array of the form: [ 1, ""message"" ].
How would I define this in TypeScript?
",https://stackoverflow.com/questions/29382389/defining-array-with-multiple-types-in-typescript,505,404537.0,10.0,,,2015-04-01 03:32:12,2023-01-19 11:06:14,2020-10-23 20:15:09,,,arrays;typescript,dk123,19938,1709725,registered,true,29382420,,CC BY-SA 4.0,,114,87,1,0,0,2,true,false,false,true,true,true,48,7,false,0.025,0.0012,4252,2015,4,3,Wednesday,false,false,false,false,false,false,false
12989741,The property 'value' does not exist on value of type 'HTMLElement',"I am playing around with typescript and am trying to create a script that will update a p-element as text is inputted in a input box.
The html looks as following:
<html>
<head>
</head>
<body>
<p id=""greet""></p>
<form>
<input id=""name"" type=""text"" name=""name"" value="""" onkeyup=""greet('name')"" />
</form>
</body>
<script src=""greeter.js""></script>
</html>
And the greeter.ts file:
function greeter(person)
{
return ""Hello, "" + person;
}
function greet(elementId)
{
var inputValue = document.getElementById(elementId).value;
if (inputValue.trim() == """")
inputValue = ""World"";
document.getElementById(""greet"").innerText = greeter(inputValue);
}
When I compile with tsc I get the following ""error"":
/home/bjarkef/sandbox/greeter.ts(8,53): The property 'value' does not exist on value of type 'HTMLElement'
However the compiler does output a javascript file, which works just fine in chrome.
How come I get this error? And how can I fix it?
Also, where can I look up which properties are valid on a 'HTMLElement' according to typescript?
Please note I am very new to javascript and typescript, so I might be missing something obvious. :)
",https://stackoverflow.com/questions/12989741/the-property-value-does-not-exist-on-value-of-type-htmlelement,500,603943.0,20.0,,,2012-10-20 15:07:45,2024-10-30 20:18:54,2020-03-02 21:27:23,,,typescript,Bjarke Freund-Hansen,30352,81398,registered,true,12990166,,CC BY-SA 4.0,,1524,1305,6,0,0,1,true,false,false,true,true,true,82,11,false,0.033,0.0008,5145,2012,10,15,Saturday,true,false,false,false,false,false,false
42453683,How to reject in async/await syntax?,"How can I reject a promise that returned by an async/await function?
e.g. Originally:
foo(id: string): Promise<A> {
return new Promise((resolve, reject) => {
someAsyncPromise().then((value)=>resolve(200)).catch((err)=>reject(400))
});
}
Translate into async/await:
async foo(id: string): Promise<A> {
try{
await someAsyncPromise();
return 200;
} catch(error) {//here goes if someAsyncPromise() rejected}
return 400; //this will result in a resolved promise.
});
}
So, how could I properly reject this promise in this case?
",https://stackoverflow.com/questions/42453683/how-to-reject-in-async-await-syntax,499,303079.0,8.0,,,2017-02-25 08:20:24,2024-06-10 09:01:29,2024-06-10 09:01:29,,,javascript;typescript;asynchronous;es6-promise;ecmascript-2017,Phoenix,5123,6448132,registered,true,42453705,,CC BY-SA 4.0,,774,572,6,0,0,5,true,false,false,true,true,true,36,6,true,0.026,0.0016,3556,2017,2,8,Saturday,true,false,true,false,false,false,false
66993264,What does the "as const" mean in TypeScript and what is its use case?,"I am confused about the as const cast. I checked a few documents and videos, but I did not understand it fully.
What does the as const mean in the code below and what is the benefit of using it?
const args = [8, 5] as const;
const angle = Math.atan2(...args);
console.log(angle);
",https://stackoverflow.com/questions/66993264/what-does-the-as-const-mean-in-typescript-and-what-is-its-use-case,496,244901.0,7.0,,,2021-04-07 19:53:24,2026-04-13 13:13:07,2025-10-18 22:59:01,,,typescript;type-assertion,Cihat Saman,5364,7901430,registered,true,66993654,,CC BY-SA 4.0,,382,281,3,0,0,2,true,false,false,true,true,true,79,14,true,0.029,0.002,2054,2021,4,19,Wednesday,false,false,false,false,false,false,false
39601026,Angular 2 Scroll to top on Route Change,"In my Angular 2 app when I scroll down a page and click the link at the bottom of the page, it does change the route and takes me to the next page but it doesn't scroll to the top of the page. As a result, if the first page is lengthy and 2nd page has few contents, it gives an impression that the 2nd page lacks the contents. Since the contents are visible only if a user scrolls to the top of the page.
I can scroll the window to the top of the page in ngInit of the component but, is there any better solution that can automatically handle all routes in my app?
",https://stackoverflow.com/questions/39601026/angular-2-scroll-to-top-on-route-change,490,294066.0,30.0,,,2016-09-20 18:13:46,2025-04-18 15:53:54,2021-04-29 15:08:18,,,angular;typescript;angular2-routing;angular2-template;angular2-directives,Naveed Ahmed,10446,2755616,registered,true,44372167,,CC BY-SA 4.0,2018-04-15 07:07:24,579,565,0,0,0,5,true,false,false,true,true,true,39,8,false,0.102,0.0017,3714,2016,9,18,Tuesday,false,false,false,false,false,false,false
13212625,TypeScript function overloading,"Section 6.3 of the TypeScript language spec talks about function overloading and gives concrete examples on how to implement this. However if I try something like this:
export class LayerFactory {
constructor(public styleFactory: Symbology.StyleFactory) {
// Init...
}
createFeatureLayer(userContext: Model.UserContext, mapWrapperObj: MapWrapperBase): any {
throw new Error('not implemented');
}
createFeatureLayer(layerName: string, style: any): any {
throw new Error('not implemented');
}
}
I get a compiler error indicating duplicate identifier even though function parameters are of different types. Even if I add an additional parameter to the second createFeatureLayer function, I still get a compiler error. Ideas, please.
",https://stackoverflow.com/questions/13212625/typescript-function-overloading,482,469334.0,6.0,,,2012-11-03 19:22:23,2024-06-06 22:33:29,2024-06-06 22:33:29,,,typescript;overloading,Klaus Nji,19027,187279,registered,true,13212862,,CC BY-SA 4.0,,832,794,1,0,0,2,true,false,false,true,true,true,31,3,false,0.013,0.001,5131,2012,11,19,Saturday,true,false,false,false,false,false,false
43064221,Typescript: TS7006: Parameter 'xxx' implicitly has an 'any' type,"In testing my UserRouter, I am using a json file
data.json
[
{
""id"": 1,
""name"": ""Luke Cage"",
""aliases"": [""Carl Lucas"", ""Power Man"", ""Mr. Bulletproof"", ""Hero for Hire""],
""occupation"": ""bartender"",
""gender"": ""male"",
""height"": {
""ft"": 6,
""in"": 3
},
""hair"": ""bald"",
""eyes"": ""brown"",
""powers"": [
""strength"",
""durability"",
""healing""
]
},
{
...
}
]
Building my app, I get the following TS error
ERROR in ...../UserRouter.ts
(30,27): error TS7006: Parameter 'user' implicitly has an 'any' type.
UserRouter.ts
import {Router, Request, Response, NextFunction} from 'express';
const Users = require('../data');
export class UserRouter {
router: Router;
constructor() {
...
}
/**
* GET one User by id
*/
public getOne(req: Request, res: Response, _next: NextFunction) {
let query = parseInt(req.params.id);
/*[30]->*/let user = Users.find(user => user.id === query);
if (user) {
res.status(200)
.send({
message: 'Success',
status: res.status,
user
});
}
else {
res.status(404)
.send({
message: 'No User found with the given id.',
status: res.status
});
}
}
}
const userRouter = new UserRouter().router;
export default userRouter;
",https://stackoverflow.com/questions/43064221/typescript-ts7006-parameter-xxx-implicitly-has-an-any-type,480,1030956.0,14.0,,,2017-03-28 08:20:02,2024-11-29 19:40:02,2017-03-28 08:22:48,,,typescript,user762579,,,does_not_exist,true,43070857,,CC BY-SA 3.0,2021-08-20 07:45:50,1493,1359,3,0,0,1,true,false,false,true,false,true,80,9,false,0.014,0.0005,3525,2017,3,8,Tuesday,false,false,false,false,false,false,false
43348463,What is the difference between Subject and BehaviorSubject?,"I'm not clear on the difference between a Subject and a BehaviorSubject. Is it just that a BehaviorSubject has the getValue() function?
",https://stackoverflow.com/questions/43348463/what-is-the-difference-between-subject-and-behaviorsubject,475,357148.0,10.0,,,2017-04-11 14:12:01,2023-03-03 12:27:28,2022-02-07 11:45:28,,,angular;typescript;rxjs;behaviorsubject;subject,Mike Jerred,10725,4854046,registered,true,43351340,,CC BY-SA 4.0,2022-08-30 16:02:51,195,136,4,0,0,5,true,false,false,true,true,true,59,8,true,0.028,0.0013,3511,2017,4,14,Tuesday,false,false,false,false,false,false,false
13613524,Get an object's class name at runtime,"Is it possible to get an object's class/type name at runtime using TypeScript?
class MyClass{}
var instance = new MyClass();
console.log(instance.????); // Should output ""MyClass""
",https://stackoverflow.com/questions/13613524/get-an-objects-class-name-at-runtime,475,514097.0,11.0,,,2012-11-28 20:07:26,2023-06-10 10:18:05,2019-06-06 22:28:59,,,typescript,Adam Mills,8209,83806,registered,true,36643177,,CC BY-SA 4.0,,214,183,1,0,0,1,true,false,false,true,true,true,41,7,false,0.021,0.0009,5106,2012,11,20,Wednesday,false,false,false,false,false,false,false
35435042,How can I define an array of objects?,"I am creating an array of objects in TypeScript:
userTestStatus xxxx = {
""0"": { ""id"": 0, ""name"": ""Available"" },
""1"": { ""id"": 1, ""name"": ""Ready"" },
""2"": { ""id"": 2, ""name"": ""Started"" }
};
Can someone tell me how I could declare its type correctly? Is it possible to do inline or would I need two definitions?
I'm looking to replace the xxx with a type declaration, so that later on TypeScript would alert me if I used something like userTestStatus[3].nammme by mistake.
",https://stackoverflow.com/questions/35435042/how-can-i-define-an-array-of-objects,473,1224312.0,11.0,,,2016-02-16 14:23:23,2024-08-13 10:01:14,2019-06-06 21:52:24,,,typescript,user1679941,,,does_not_exist,true,35435879,,CC BY-SA 4.0,,557,486,3,0,0,1,true,false,false,true,false,true,37,8,true,0.009,0.0004,3931,2016,2,14,Tuesday,false,false,false,false,false,false,false
41211566,tsconfig.json: Build:No inputs were found in config file,"I have an ASP.NET core project and I'm getting this error when I try to build it:
error TS18003: Build:No inputs were found in config file 'Z:/Projects/client/ZV/src/ZV/Scripts/tsconfig.json'. Specified 'include' paths were '[""**/*""]' and 'exclude' paths were '[""../wwwroot/app"",""node_modules/*""]'.
1> The command exited with code 1.
1> Done executing task ""VsTsc"" -- FAILED.
This is my tsconfig.json file:
{
""compileOnSave"": true,
""compilerOptions"": {
""emitDecoratorMetadata"": true,
""experimentalDecorators"": true,
""lib"": [ ""es5"", ""dom"" ],
""module"": ""commonjs"",
""moduleResolution"": ""node"",
""noEmitOnError"": true,
""noImplicitAny"": false,
""outDir"": ""../wwwroot/app/"",
""removeComments"": false,
""sourceMap"": true,
""target"": ""es6""
},
""exclude"": [
""../wwwroot/app"",
""node_modules/*""
]
}
Is this a bug or am I doing something wrong? I did recently upgrade Visual Studio 2015 to update 3. Has anyone encountered this before?
",https://stackoverflow.com/questions/41211566/tsconfig-json-buildno-inputs-were-found-in-config-file,471,513343.0,39.0,,,2016-12-18 18:37:10,2025-09-24 07:57:43,2017-04-10 22:33:06,,,json;typescript;visual-studio-2015;asp.net-core,rood,13165,2373759,registered,true,41211721,,CC BY-SA 3.0,2018-06-30 02:49:37,1088,1006,3,0,0,4,true,false,false,true,true,true,56,8,false,0.076,0.0009,3625,2016,12,18,Sunday,true,false,false,false,false,false,false
45485073,How do I express a date type in TypeScript?,"How do I express dates in TypeScript? Dates aren't a TypeScript type, so do I use any or object? Seems like there would be a ""right"" way to do:
let myDate: any = new Date();
I couldn't find much on Google, despite it being such a simple question.
",https://stackoverflow.com/questions/45485073/how-do-i-express-a-date-type-in-typescript,469,834603.0,4.0,,,2017-08-03 13:04:22,2025-08-09 22:42:34,2022-03-31 08:16:39,,,date;typescript,VSO,12924,4977957,registered,true,45485105,,CC BY-SA 4.0,,407,250,3,1,0,2,true,false,false,true,true,true,43,9,true,0.005,0.0006,3397,2017,8,13,Thursday,false,false,false,false,false,false,false
33305954,TypeScript export vs. default export,"What is the difference in TypeScript between export and default export?
In all the tutorials, I see people exporting their classes and I cannot compile my code if I don't add the default keyword before exporting.
Also, I couldn't find any trace of the default export keyword in the official TypeScript documentation.
export class MyClass {
collection = [1,2,3];
}
Does not compile. But:
export default class MyClass {
collection = [1,2,3];
}
Does.
The error is:
error TS1192: Module '"src/app/MyClass"' has no default export.
",https://stackoverflow.com/questions/33305954/typescript-export-vs-default-export,468,358087.0,4.0,,,2015-10-23 15:19:17,2023-02-17 04:27:35,2023-02-17 04:23:56,,,javascript;typescript;ecmascript-6,fos.alex,5747,2812727,registered,true,33307487,,CC BY-SA 4.0,2018-06-10 17:11:22,784,548,6,1,0,3,true,false,false,true,true,true,36,5,false,0.011,0.0013,4047,2015,10,15,Friday,false,false,true,false,false,false,false
43335962,Purpose of `declare` keyword in TypeScript,"What is the meaning of the declare keyword?
type Callback = (err: Error | String, data: Array<CalledBackData>) => void;
vs.
declare type Callback = (err: Error | String, data:Array<CalledBackData>) => void;
Cannot find docs that explain the purpose of the declare keyword in TS. What does this mean?
",https://stackoverflow.com/questions/43335962/purpose-of-declare-keyword-in-typescript,467,171124.0,5.0,,,2017-04-11 02:49:19,2024-12-20 15:38:28,2024-12-20 15:38:28,,,typescript;typescript2.0,Alexander Mills,102786,1223975,registered,true,,,CC BY-SA 4.0,,415,320,4,0,0,2,false,false,false,true,true,true,42,6,false,0.029,0.0027,3511,2017,4,2,Tuesday,false,false,false,false,false,false,false
34364880,Expression ___ has changed after it was checked,"Why is the component in this simple plunk
@Component({
selector: 'my-app',
template: `<div>I'm {{message}} </div>`,
})
export class App {
message:string = 'loading :(';
ngAfterViewInit() {
this.updateMessage();
}
updateMessage(){
this.message = 'all done loading :)'
}
}
throwing:
EXCEPTION: Expression 'I'm {{message}} in App@0:5' has changed after it was checked. Previous value: 'I'm loading :( '. Current value: 'I'm all done loading :) ' in [I'm {{message}} in App@0:5]
when all I'm doing is updating a simple binding when my view is initiated?
",https://stackoverflow.com/questions/34364880/expression-has-changed-after-it-was-checked,462,537082.0,24.0,,,2015-12-18 22:28:42,2025-02-17 13:17:29,2016-02-07 21:38:05,,,typescript;angular,drew moore,32850,1988693,registered,true,34364881,,CC BY-SA 3.0,,742,599,1,1,0,2,true,false,false,true,true,true,47,8,false,0.045,0.0009,3991,2015,12,22,Friday,false,false,false,false,false,false,false
42066421,Property 'value' does not exist on type 'EventTarget',"I am using TypeScript Version 2 for an Angular 2 component code.
I am getting error "Property 'value' does not exist on type 'EventTarget'" for below code, what could be the solution. Thanks!
e.target.value.match(/\S+/g) || []).length
import { Component, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'text-editor',
template: `
<textarea (keyup)="emitWordCount($event)"></textarea>
`
})
export class TextEditorComponent {
@Output() countUpdate = new EventEmitter<number>();
emitWordCount(e: Event) {
this.countUpdate.emit(
(e.target.value.match(/\S+/g) || []).length);
}
}
",https://stackoverflow.com/questions/42066421/property-value-does-not-exist-on-type-eventtarget,460,549449.0,19.0,,,2017-02-06 11:15:41,2023-08-16 19:01:36,2020-11-14 21:46:08,,,angular;typescript;properties,user584018,11624,584018,registered,true,42066698,,CC BY-SA 4.0,2021-05-31 20:02:24,763,668,2,0,0,3,true,false,false,true,true,true,69,8,false,0.035,0.0008,3575,2017,2,11,Monday,false,false,false,false,false,false,false
45802988,TypeScript - use correct version of setTimeout (node vs window),"I am working on upgrading some old TypeScript code to use the latest compiler version, and I'm having trouble with a call to setTimeout. The code expects to call the browser's setTimeout function which returns a number:
setTimeout(handler: (...args: any[]) => void, timeout: number): number;
However, the compiler is resolving this to the node implementation instead, which returns a NodeJS.Timer:
setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer;
This code does not run in node, but the node typings are getting pulled in as a dependency to something else (not sure what).
How can I instruct the compiler to pick the version of setTimeout that I want?
Here is the code in question:
let n: number;
n = setTimeout(function () { /* snip */ }, 500);
This produces the compiler error:
TS2322: Type 'Timer' is not assignable to type 'number'.
",https://stackoverflow.com/questions/45802988/typescript-use-correct-version-of-settimeout-node-vs-window,453,409437.0,12.0,,,2017-08-21 17:49:52,2023-07-13 07:37:56,2019-12-18 04:56:39,,,typescript;settimeout,Kevin Tighe,21381,39461,registered,true,50428377,,CC BY-SA 4.0,,1060,890,6,0,0,2,true,false,false,true,true,true,63,10,false,0.029,0.0011,3379,2017,8,17,Monday,false,false,false,false,false,false,false
15877362,Declare and initialize a Dictionary in Typescript,"Given the following code
interface IPerson {
firstName: string;
lastName: string;
}
var persons: { [id: string]: IPerson; } = {
""p1"": { firstName: ""F1"", lastName: ""L1"" },
""p2"": { firstName: ""F2"" }
};
Why isn't the initialization rejected? After all, the second object does not have the ""lastName"" property.
",https://stackoverflow.com/questions/15877362/declare-and-initialize-a-dictionary-in-typescript,453,1033944.0,9.0,,,2013-04-08 10:56:38,2024-09-30 01:52:57,,,,dictionary;initialization;typescript,mgs,5212,1993304,registered,true,15879330,,CC BY-SA 3.0,,361,323,1,0,0,3,true,false,false,true,true,false,49,7,false,0.009,0.0004,4975,2013,4,10,Monday,false,false,false,false,false,false,false
39372804,How can I loop through enum values for display in radio buttons?,"What is the proper way to loop through literals of an enum in TypeScript?
(I am currently using TypeScript 1.8.1.)
I've got the following enum:
export enum MotifIntervention {
Intrusion,
Identification,
AbsenceTest,
Autre
}
export class InterventionDetails implements OnInit
{
constructor(private interService: InterventionService)
{
let i:number = 0;
for (let motif in MotifIntervention) {
console.log(motif);
}
}
The result displayed is a list
0
1
2
3
Intrusion,
Identification,
AbsenceTest,
Autre
I do want only four iterations in the loop as there are only four elements in the enum. I don't want to have 0 1 2 and 3 that seem to be index numbers of the enum.
",https://stackoverflow.com/questions/39372804/how-can-i-loop-through-enum-values-for-display-in-radio-buttons,444,489863.0,4.0,,,2016-09-07 14:35:34,2024-11-26 23:53:34,2020-10-11 01:32:12,,,javascript;arrays;typescript;enums;element,Anthony Brenelière,63860,3433751,registered,true,39372911,,CC BY-SA 4.0,,814,731,2,0,0,5,true,false,false,true,true,true,64,12,true,0.008,0.0009,3727,2016,9,14,Wednesday,false,false,true,false,false,false,false
23314806,Setting default value for TypeScript object passed as argument,"function sayName(params: {firstName: string; lastName?: string}) {
params.lastName = params.lastName || 'smith'; // <<-- any better alternative to this?
var name = params.firstName + params.lastName
alert(name);
}
sayName({firstName: 'bob'});
I had imagined something like this might work:
function sayName(params: {firstName: string; lastName: string = 'smith'}) {
Obviously if these were plain arguments you could do it with:
function sayName(firstName: string, lastName = 'smith') {
var name = firstName + lastName;
alert(name);
}
sayName('bob');
And in coffeescript you have access to the conditional existence operator so can do:
param.lastName ?= 'smith'
Which compiles to the javascript:
if (param.lastName == null) {
param.lastName = 'smith';
}
",https://stackoverflow.com/questions/23314806/setting-default-value-for-typescript-object-passed-as-argument,437,604522.0,9.0,,,2014-04-26 18:17:33,2024-07-05 14:27:15,2021-11-18 18:19:50,,,typescript;arguments,AJP,29239,539490,registered,true,32596200,,CC BY-SA 4.0,,948,800,5,0,0,2,true,false,false,true,true,true,62,9,false,0.015,0.0007,4592,2014,4,18,Saturday,true,false,false,false,false,false,false
36835123,How do I pass data to Angular routed components?,"In one of my Angular 2 routes's templates (FirstComponent) I have a button
first.component.html
<div class=""button"" click=""routeWithData()"">Pass data and route</div>
My goal is to achieve:
Button click -> route to another component while preserving data and without using the other component as a directive.
This is what I tried...
1ST APPROACH
In the same view I am storing collecting same data based on user interaction.
first.component.ts
export class FirstComponent {
constructor(private _router: Router) { }
property1: number;
property2: string;
property3: TypeXY; // this a class, not a primitive type
// here some class methods set the properties above
// DOM events
routeWithData(){
// here route
}
}
Normally I'd route to SecondComponent by
this._router.navigate(['SecondComponent']);
eventually passing the data by
this._router.navigate(['SecondComponent', {p1: this.property1, p2: property2 }]);
whereas the definition of the link with parameters would be
@RouteConfig([
// ...
{ path: '/SecondComponent/:p1:p2', name: 'SecondComponent', component: SecondComponent}
)]
The issue with this approach is that I guess I can't pass complex data (e.g. an object like property3) in-url;
2ND APPROACH
An alternative would be including SecondComponent as directive in FirstComponent.
<SecondComponent [p3]=""property3""></SecondComponent>
However I want to route to that component, not include it!
3RD APPROACH
The most viable solution I see here would be to use a Service (e.g. FirstComponentService) to
- store the data (_firstComponentService.storeData()) on routeWithData() in FirstComponent
- retrieve the data (_firstComponentService.retrieveData()) in ngOnInit() in SecondComponent
While this approach seems perfectly viable, I wonder whether this is the easiest / most elegant way to achieve the goal.
In general I'd like to know whether I'm missing other potential approaches to pass the data between components, particularly with the less possible amount of code
",https://stackoverflow.com/questions/36835123/how-do-i-pass-data-to-angular-routed-components,436,947982.0,22.0,,,2016-04-25 08:10:46,2024-06-14 15:30:31,2018-12-05 14:24:34,,,angular;typescript,dragonmnl,15678,1219368,registered,true,36835156,,CC BY-SA 4.0,,2749,2097,6,0,0,2,true,false,false,true,true,true,48,9,true,0.023,0.0005,3862,2016,4,8,Monday,false,false,false,false,false,false,false
36842158,Array<Type> VS Type[] in Typescript,"As far as I know a property's type can be defined in two ways when it's an array:
property_name: type
where type can be either
Array<string>
Array<MyType>
// etc. (e.g. let prop1: Array<string>)
and
string[]
MyType[]
// etc. (e.g. let prop1: string[])
What is the difference between the two cases? Or am I misunderstanding something (perhaps something about <> used in casting)?
",https://stackoverflow.com/questions/36842158/arraytype-vs-type-in-typescript,427,200252.0,2.0,,,2016-04-25 13:34:09,2024-11-17 10:38:07,2024-11-17 10:38:07,,,typescript,dragonmnl,15678,1219368,registered,true,36843084,,CC BY-SA 4.0,,519,406,4,0,0,1,true,false,false,true,true,true,41,5,false,0.01,0.0021,3862,2016,4,13,Monday,false,false,false,false,false,false,false
43909566,Get keys of a Typescript interface as array of strings,"I've a lot of tables in Lovefield and their respective Interfaces for what columns they have.
Example:
export interface IMyTable {
id: number;
title: string;
createdAt: Date;
isDeleted: boolean;
}
I'd like to have the property names of this interface in an array like this:
const IMyTable = ["id", "title", "createdAt", "isDeleted"];
I cannot make an object/array based on the interface IMyTable directly which should do the trick because I'd be getting the interface names of the tables dynamically. Hence I need to iterate over these properties in the interface and get an array out of it.
How do I achieve this result?
",https://stackoverflow.com/questions/43909566/get-keys-of-a-typescript-interface-as-array-of-strings,425,596905.0,20.0,,,2017-05-11 07:53:52,2024-12-18 19:03:53,2020-11-28 04:52:57,,,javascript;typescript,Tushar Shukla,6785,2996624,registered,true,,,CC BY-SA 4.0,,909,672,3,1,0,2,false,false,false,true,true,true,54,10,false,0.034,0.0007,3481,2017,5,7,Thursday,false,false,true,false,false,false,false
44717164,Unable to import svg files in typescript,"In typescript(*.tsx) files I cannot import svg file with this statement:
import logo from './logo.svg';
Transpiler says:[ts] cannot find module './logo.svg'.
My svg file is just <svg>...</svg>.
But in .js file I'm able to import it without any issues with exact the same import statement. I suppose it has something to do with type of svg file which must be set somehow for ts transpiler.
Could you please share how to make this work in ts files?
",https://stackoverflow.com/questions/44717164/unable-to-import-svg-files-in-typescript,422,453268.0,28.0,,,2017-06-23 08:54:16,2025-03-12 14:51:41,,,,typescript;svg,AngryBoy,5243,1187454,registered,true,,,CC BY-SA 3.0,,569,465,5,0,0,2,false,false,false,true,true,false,40,7,false,0.062,0.0009,3438,2017,6,8,Friday,false,false,false,false,false,false,false
43281741,How can I use paths in tsconfig.json?,"I was reading about path-mapping in file tsconfig.json, and I wanted to use it to avoid using the following ugly paths:
The project organization is a bit weird because we have a mono-repository that contains projects and libraries. The projects are grouped by company and by browser / server / universal.
How can I configure the paths in file tsconfig.json, so instead of:
import { Something } from "../../../../../lib/src/[browser/server/universal]/...";
I can use:
import { Something } from "lib/src/[browser/server/universal]/...";
Will something else be required in the Webpack configuration? Or is the tsconfig.json file enough?
",https://stackoverflow.com/questions/43281741/how-can-i-use-paths-in-tsconfig-json,419,568341.0,21.0,,,2017-04-07 15:20:59,2025-12-15 12:30:08,2023-10-22 15:04:49,,,typescript;node-modules;tsconfig,Remo H. Jansen,25306,606821,registered,true,43330003,,CC BY-SA 4.0,,1353,658,2,5,2,3,true,false,false,true,true,true,37,7,true,0.037,0.0007,3515,2017,4,15,Friday,false,false,false,false,false,false,false
46053414,npm WARN ... requires a peer of ... but none is installed. You must install peer dependencies yourself,"I tried to run a project downloaded from github. Unfortunately, during npm install the following warnings were shown. I tried to change the version based on this question. However, I had a problem, because some packages require multiple versions other packages. Consider these two lines:
npm WARN @angular/cdk@2.0.0-beta.10 requires a peer of @angular/core@^4.3.0 but none is installed. You must install peer dependencies yourself.
npm WARN @angular/forms@4.3.6 requires a peer of @angular/core@4.3.6 but none is installed. You must install peer dependencies yourself.
So, installing some packages causes the list of dependencies to grow substantially.
Does anyone have a solution?
npm WARN @angular/animations@4.3.6 requires a peer of @angular/core@4.3.6 but none is installed. You must install peer dependencies yourself.
npm WARN @angular/cdk@2.0.0-beta.10 requires a peer of @angular/core@^4.3.0 but none is installed. You must install peer dependencies yourself.
npm WARN @angular/cdk@2.0.0-beta.10 requires a peer of @angular/common@^4.3.0 but none is installed. You must install peer dependencies yourself.
npm WARN @angular/compiler@4.3.6 requires a peer of @angular/core@4.3.6 but none is installed. You must install peer dependencies yourself.
npm WARN @angular/compiler-cli@4.3.6 requires a peer of @angular/core@4.3.6 but none is installed. You must install peer dependencies yourself.
npm WARN @angular/forms@4.3.6 requires a peer of @angular/core@4.3.6 but none is installed. You must install peer dependencies yourself.
npm WARN @angular/forms@4.3.6 requires a peer of @angular/common@4.3.6 but none is installed. You must install peer dependencies yourself.
npm WARN @angular/forms@4.3.6 requires a peer of @angular/platform-browser@4.3.6 but none is installed. You must install peer dependencies yourself.
npm WARN @angular/http@4.3.6 requires a peer of @angular/core@4.3.6 but none is installed. You must install peer dependencies yourself.
npm WARN @angular/http@4.3.6 requires a peer of @angular/platform-browser@4.3.6 but none is installed. You must install peer dependencies yourself.
npm WARN @angular/material@2.0.0-beta.10 requires a peer of @angular/core@^4.3.0 but none is installed. You must install peer dependencies yourself.
npm WARN @angular/material@2.0.0-beta.10 requires a peer of @angular/common@^4.3.0 but none is installed. You must install peer dependencies yourself.
npm WARN @angular/platform-browser-dynamic@2.4.10 requires a peer of @angular/compiler@2.4.10 but none is installed. You must install peer dependencies yourself.
npm WARN @angular/platform-server@4.3.6 requires a peer of @angular/core@4.3.6 but none is installed. You must install peer dependencies yourself.
npm WARN @angular/platform-server@4.3.6 requires a peer of @angular/common@4.3.6 but none is installed. You must install peer dependencies yourself.
npm WARN @angular/platform-server@4.3.6 requires a peer of @angular/platform-browser@4.3.6 but none is installed. You must install peer dependencies yourself.
npm WARN @angular/router@4.3.6 requires a peer of @angular/core@4.3.6 but none is installed. You must install peer dependencies yourself.
npm WARN @angular/router@4.3.6 requires a peer of @angular/common@4.3.6 but none is installed. You must install peer dependencies yourself.
npm WARN @angular/router@4.3.6 requires a peer of @angular/platform-browser@4.3.6 but none is installed. You must install peer dependencies yourself.
npm WARN angularfire2@2.0.0-beta.7-pre requires a peer of @angular/compiler@^2.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN extract-text-webpack-plugin@3.0.0 requires a peer of webpack@^3.1.0 but none is installed. You must install peer dependencies yourself.
Here are the contents of package.json:
{
"name": "fireplace",
"version": "0.0.0",
"license": "MIT",
"angular-cli": {},
"scripts": {
"ng": "ng",
"start": "ng serve",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"repository": {
"type": "git",
"url": "https://github.com/name/fireplace.git"
},
"author": "name",
"bugs": {
"url": "https://github.com/name/fireplace/issues"
},
"homepage": "https://github.com/name/fireplace",
"private": true,
"dependencies": {
"@angular/animations": "^4.0.0-rc.2",
"@angular/common": "^4.0.0-rc.2",
"@angular/compiler": "^4.0.0-rc.2",
"@angular/compiler-cli": "^4.0.0-rc.2",
"@angular/core": "^4.0.0-rc.2",
"@angular/flex-layout": "^2.0.0-rc.1",
"@angular/forms": "^4.0.0-rc.2",
"@angular/http": "^4.0.0-rc.2",
"@angular/material": "^2.0.0-beta.2",
"@angular/platform-browser": "^4.0.0-rc.2",
"@angular/platform-browser-dynamic": "^4.0.0-rc.2",
"@angular/platform-server": "^4.0.0-rc.2",
"@angular/router": "^4.0.0-rc.2",
"@types/lodash": "^4.14.53",
"angular2-google-maps": "^0.17.0",
"angular2-moment": "^1.2.0",
"angularfire2": "^2.0.0-beta.8",
"core-js": "^2.4.1",
"d3": "^4.7.1",
"d3-cloud": "^1.2.4",
"firebase": "^3.6.10",
"hammerjs": "^2.0.8",
"lodash": "^4.17.4",
"rxjs": "^5.2.0",
"ts-helpers": "^1.1.1",
"zone.js": "^0.7.6"
},
"devDependencies": {
"@angular/cli": "^1.0.0-rc.1",
"@angular/compiler-cli": "^2.4.0",
"@types/jasmine": "2.5.38",
"@types/node": "~6.0.60",
"codelyzer": "~2.0.0",
"jasmine-core": "2.5.2",
"karma": "~1.4.1",
"karma-chrome-launcher": "~2.0.0",
"karma-cli": "~1.0.1",
"karma-jasmine": "~1.1.0",
"karma-jasmine-html-reporter": "^0.2.2",
"karma-coverage-istanbul-reporter": "^0.2.1",
"protractor": "~5.1.0",
"ts-node": "~2.0.0",
"tslint": "~4.4.2",
"typescript": "^2.2.1",
"webpack": "^2.2.1"
}
}
ng serve returns(I pasted only the beginning and the end):
ERROR in /Users/username/Projects/fireplace/node_modules/@angular/material/typings/core/bidi/index.d.ts (8,99): Cannot find module '@angular/cdk/bidi'.
ERROR in /Users/username/Projects/fireplace/node_modules/@angular/material/typings/core/portal/portal.d.ts (8,85): Cannot find module '@angular/cdk/portal'.
ERROR in /Users/username/Projects/fireplace/node_modules/@angular/material/typings/core/portal/portal-directives.d.ts (8,76): Cannot find module '@angular/cdk/portal'.
ERROR in /Users/username/Projects/fireplace/node_modules/@angular/material/typings/core/portal/dom-portal-host.d.ts (8,31): Cannot find module '",https://stackoverflow.com/questions/46053414/npm-warn-requires-a-peer-of-but-none-is-installed-you-must-install-peer,417,700854.0,16.0,,,2017-09-05 11:05:38,2024-03-13 11:25:49,2024-03-13 11:25:49,,,javascript;angular;typescript;npm,user7304253,,,does_not_exist,true,,,CC BY-SA 4.0,2023-03-17 02:16:31,22825,22444,7,2,0,4,false,false,false,true,false,true,102,18,false,0.023,0.0006,3364,2017,9,11,Tuesday,false,false,true,false,false,false,false
43492354,How to allow access outside localhost,"How can I allow access outside the localhost at Angular2? I can navigate at localhost:3030/panel easily but I can not navigate when I write my IP such as 10.123.14.12:3030/panel/.
Could you please allow me how to fix it? I am not using npm (node project manage - node install/node start ) to install and run the project.
If you want, I can provide my package.json and index.html.
",https://stackoverflow.com/questions/43492354/how-to-allow-access-outside-localhost,412,514803.0,19.0,,,2017-04-19 09:57:38,2023-07-19 20:21:56,2020-01-30 13:23:19,,,angular;typescript;ng-build,Tonyukuk,6345,2307786,registered,true,43492433,,CC BY-SA 4.0,,469,383,5,0,0,3,true,false,false,true,true,true,37,6,false,0.037,0.0008,3503,2017,4,9,Wednesday,false,false,false,false,false,false,false
56238356,Understanding esModuleInterop in tsconfig file,"I was checking out someone .tsconfig file and there I spotted --esModuleInterop
This is his .tsconfig file
{
"compilerOptions": {
"moduleResolution": "node",
"target": "es6",
"module": "commonjs",
"lib": ["esnext"],
"strict": true,
"sourceMap": true,
"declaration": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"declarationDir": "./dist",
"outDir": "./dist",
"typeRoots": ["node_modules/@types"]
},
"include": ["src/**/*.ts"],
"exclude": ["node_modules"]
}
Here, My primary question is what is "esModuleInterop": true, and
"allowSyntheticDefaultImports": true,. I know they are sort of dependent on the "module": "commonjs", . Can someone try to explain it in the best human language possible?
The official docs for allowSyntheticDefaultImports states
Allow default imports from modules with no default export. This does
not affect code emit, just typechecking.
What does that mean? If there isn't any export default then I think the only use case of the import default would be to initialize something? Like a singleton?
The following question/answer does not make sense as well
Is there a way to use --esModuleInterop in tsconfig as opposed to it being a flag?
And --esModuleInterop definition on the compiler page
Emit __importStar and __importDefault helpers for runtime babel
ecosystem compatibility and enable --allowSyntheticDefaultImports for
typesystem compatibility.
Also seemed difficult for me to understand/comprehend
",https://stackoverflow.com/questions/56238356/understanding-esmoduleinterop-in-tsconfig-file,412,348380.0,3.0,,,2019-05-21 12:31:12,2024-03-10 04:16:47,2024-03-10 04:16:47,,,typescript,Alwaysblue,12318,8701527,registered,true,56348146,,CC BY-SA 4.0,,2277,1891,9,1,0,1,true,false,false,true,true,true,46,5,false,0.009,0.0012,2741,2019,5,12,Tuesday,false,false,false,false,false,false,false
14142071,TypeScript and field initializers,"How to init a new class in TS in such a way (example in C# to show what I want):
// ... some code before
return new MyClass { Field1 = "ASD", Field2 = "QWE" };
// ... some code after
",https://stackoverflow.com/questions/14142071/typescript-and-field-initializers,411,434591.0,21.0,,,2013-01-03 15:36:45,2023-02-24 01:37:47,2021-03-28 15:32:13,,,typescript,Nickon,10227,1252575,registered,true,14142198,,CC BY-SA 4.0,,236,205,1,0,0,1,true,false,false,true,true,true,33,4,false,0.048,0.0009,5070,2013,1,15,Thursday,false,false,false,false,false,false,false
46851399,How to generate components in a specific folder with Angular CLI?,"I am using Angular 4 with Angular CLI and I am able to create a new component with the following command.
E:\HiddenWords>ng generate component plainsight
But I need to generate a child component inside plainsight. Is there a way to do it with Angular CLI?
",https://stackoverflow.com/questions/46851399/how-to-generate-components-in-a-specific-folder-with-angular-cli,409,681151.0,24.0,,,2017-10-20 14:32:01,2024-06-29 16:07:00,2020-12-18 00:35:58,,,angular;typescript;angular-cli,user8520658,,,does_not_exist,true,,,CC BY-SA 4.0,,298,260,1,0,0,3,false,false,false,true,false,true,65,11,true,0.035,0.0006,3319,2017,10,14,Friday,false,false,false,false,false,false,false
58510287,"parserOptions.project" has been set for @typescript-eslint/parser,"I created a new React Native project with --template typescript
I deleted the template directory which came as part of the boilerplate.
I then proceeded to add ESLint:
module.exports = {
parser: "@typescript-eslint/parser",
plugins: ["@typescript-eslint"],
extends: ["airbnb-typescript-prettier"]
};
However, when I open babel.config.js, I get this error
Parsing error: "parserOptions.project" has been set for @typescript-eslint/parser.
The file does not match your project config: /Users/Dan/site/babel.config.js.
The file must be included in at least one of the projects provided.eslint
",https://stackoverflow.com/questions/58510287/parseroptions-project-has-been-set-for-typescript-eslint-parser,406,529699.0,31.0,,,2019-10-22 18:24:46,2024-12-20 02:07:14,2021-08-03 23:47:09,,,typescript;eslint;typescript-eslint,Dan,8942,2026768,registered,true,,,CC BY-SA 4.0,,789,639,5,0,0,3,false,false,false,true,true,true,76,6,false,0.059,0.0008,2587,2019,10,18,Tuesday,false,false,false,false,false,false,false
34947154,Angular 2 @ViewChild annotation returns undefined,"I am trying to learn Angular 2.
I would like to access to a child component from a parent component using the @ViewChild Annotation.
Here some lines of code:
In BodyContent.ts I have:
import { ViewChild, Component, Injectable } from 'angular2/core';
import { FilterTiles } from '../Components/FilterTiles/FilterTiles';
@Component({
selector: 'ico-body-content',
templateUrl: 'App/Pages/Filters/BodyContent/BodyContent.html',
directives: [FilterTiles]
})
export class BodyContent {
@ViewChild(FilterTiles) ft: FilterTiles;
public onClickSidebar(clickedElement: string) {
console.log(this.ft);
var startingFilter = {
title: 'cognomi',
values: [ 'griffin', 'simpson' ]
}
this.ft.tiles.push(startingFilter);
}
}
while in FilterTiles.ts:
import { Component } from 'angular2/core';
@Component({
selector: 'ico-filter-tiles',
templateUrl: 'App/Pages/Filters/Components/FilterTiles/FilterTiles.html'
})
export class FilterTiles {
public tiles = [];
public constructor(){};
}
Finally here the templates (as suggested in comments):
BodyContent.html
<div (click)="onClickSidebar()" class="row" style="height:200px; background-color:red;">
<ico-filter-tiles></ico-filter-tiles>
</div>
FilterTiles.html
<h1>Tiles loaded</h1>
<div *ngFor="#tile of tiles" class="col-md-4">
... stuff ...
</div>
FilterTiles.html template is correctly loaded into ico-filter-tiles tag (indeed I am able to see the header).
Note: the BodyContent class is injected inside another template (Body) using DynamicComponetLoader: dcl.loadAsRoot(BodyContent, '#ico-bodyContent', injector):
import { ViewChild, Component, DynamicComponentLoader, Injector } from 'angular2/core';
import { Body } from '../../Layout/Dashboard/Body/Body';
import { BodyContent } from './BodyContent/BodyContent';
@Component({
selector: 'filters',
templateUrl: 'App/Pages/Filters/Filters.html',
directives: [Body, Sidebar, Navbar]
})
export class Filters {
constructor(dcl: DynamicComponentLoader, injector: Injector) {
dcl.loadAsRoot(BodyContent, '#ico-bodyContent', injector);
dcl.loadAsRoot(SidebarContent, '#ico-sidebarContent', injector);
}
}
The problem is that when I try to write ft into the console log, I get undefined, and of course I get an exception when I try to push something inside the "tiles" array: 'no property tiles for "undefined"'.
One more thing: FilterTiles component seems to be correctly loaded, since I'm able to see the html template for it.
Any suggestions?
",https://stackoverflow.com/questions/34947154/angular-2-viewchild-annotation-returns-undefined,403,496385.0,29.0,,,2016-01-22 12:50:07,2025-08-11 13:01:56,2021-08-10 06:01:14,,,typescript;angular,Andrea Ialenti,4580,2332293,registered,true,36488227,,CC BY-SA 4.0,,3210,2709,10,0,0,2,true,false,false,true,true,true,49,6,false,0.058,0.0008,3956,2016,1,12,Friday,false,false,false,false,false,false,false
13631557,TypeScript Objects as Dictionary types as in C#,"I have some JavaScript code that uses objects as dictionaries; for example a 'person' object will hold a some personal details keyed off the email address.
var people = {<email> : <'some personal data'>};
adding > ""people[<email>] = <data>;""
getting > ""var data = people[<email>];""
deleting > ""delete people[<email>];""
Is it possible to describe this in Typescript? or do I have to use an Array?
",https://stackoverflow.com/questions/13631557/typescript-objects-as-dictionary-types-as-in-c,398,345650.0,6.0,,,2012-11-29 17:41:44,2020-05-29 04:07:58,2018-11-25 15:22:34,,,arrays;object;dictionary;typescript,Robert Taylor,4235,1259088,registered,true,13631733,,CC BY-SA 4.0,,488,450,1,0,0,4,true,false,false,true,true,true,47,8,false,0.017,0.0012,5105,2012,11,17,Thursday,false,false,false,false,false,false,false
43118692,TypeScript filter out nulls from an array,"TypeScript, --strictNullChecks mode.
Suppose I have an array of nullable strings (string | null)[]. What would be a single-expression way to remove all nulls in a such a way that the result has type string[]?
const array: (string | null)[] = ["foo", "bar", null, "zoo", null];
const filterdArray: string[] = ???;
Array.filter does not work here:
// Type '(string | null)[]' is not assignable to type 'string[]'
array.filter(x => x != null);
Array comprehensions could've work but they are not supported by TypeScript.
Actually the question can be generalized to the problem of filtering an array of any union type by removing entries having one particular type from the union. But let's focus on unions with null and perhaps undefined as these are the most common usecases.
",https://stackoverflow.com/questions/43118692/typescript-filter-out-nulls-from-an-array,396,229204.0,22.0,,,2017-03-30 13:02:39,2025-04-22 16:31:36,2021-07-05 12:55:12,,,typescript;null,SergeyS,4580,966604,registered,true,46700791,,CC BY-SA 4.0,,949,810,5,0,0,2,true,false,false,true,true,true,41,7,false,0.096,0.0017,3523,2017,3,13,Thursday,false,false,false,false,false,false,false
55377365,What does "keyof typeof" mean in TypeScript?,"Explain to me what keyof typeof means in TypeScript
Example:
enum ColorsEnum {
white = '#ffffff',
black = '#000000',
}
type Colors = keyof typeof ColorsEnum;
The last row is equivalent to:
type Colors = "white" | "black"
But how does it work?
I would expect typeof ColorsEnum to return something like "Object" and then keyof "Object" to not do anything interesting. But I am obviously wrong.
",https://stackoverflow.com/questions/55377365/what-does-keyof-typeof-mean-in-typescript,395,241537.0,5.0,,,2019-03-27 12:36:37,2022-12-24 09:19:13,2022-09-12 11:50:00,,,typescript;typeof;union-types;keyof,user1283776,22274,1283776,registered,true,65958095,,CC BY-SA 4.0,,578,443,6,0,0,4,true,false,false,true,true,true,54,7,true,0.021,0.0016,2796,2019,3,12,Wednesday,false,false,false,false,false,false,false
34323480,"In Angular, how do you determine the active route?","NOTE: There are many different answers here, and most have been valid at one time or another. The fact is that what works has changed a number of times as the Angular team has changed its Router. The Router 3.0 version that will eventually be the router in Angular breaks many of these solutions, but offers a very simple solution of its own. As of RC.3, the preferred solution is to use [routerLinkActive] as shown in this answer.
In an Angular application (current in the 2.0.0-beta.0 release as I write this), how do you determine what the currently active route is?
I'm working on an app that uses Bootstrap 4 and I need a way to mark navigation links/buttons as active when their associated component is being shown in a <router-output> tag.
I realize that I could maintain the state myself when one of the buttons is clicked upon, but that wouldn't cover the case of having multiple paths into the same route (say a main navigation menu as well as a local menu in the main component).
Any suggestions or links would be appreciated. Thanks.
",https://stackoverflow.com/questions/34323480/in-angular-how-do-you-determine-the-active-route,395,447685.0,31.0,,,2015-12-16 22:37:56,2024-12-04 14:02:27,2017-12-16 21:33:07,,,javascript;typescript;angular;angular2-routing,Michael Oryl,21830,1480995,registered,true,37947435,,CC BY-SA 3.0,2016-07-16 13:34:37,1221,1058,2,1,0,4,true,false,false,true,true,true,50,9,true,0.069,0.0009,3993,2015,12,22,Wednesday,false,false,true,false,false,false,false
30580083,Angular no provider for NameService,"I've got a problem loading a class into an Angular component. I've been trying to solve it for a long time; I've even tried joining it all in a single file. What I have is:
Application.ts
/// <reference path=""../typings/angular2/angular2.d.ts"" />
import {Component,View,bootstrap,NgFor} from ""angular2/angular2"";
import {NameService} from ""./services/NameService"";
@Component({
selector:'my-app',
injectables: [NameService]
})
@View({
template:'<h1>Hi {{name}}</h1>' +
'<p>Friends</p>' +
'<ul>' +
' <li *ng-for=""#name of names"">{{name}}</li>' +
'</ul>',
directives:[NgFor]
})
class MyAppComponent
{
name:string;
names:Array<string>;
constructor(nameService:NameService)
{
this.name = 'Michal';
this.names = nameService.getNames();
}
}
bootstrap(MyAppComponent);
services/NameService.ts
export class NameService {
names: Array<string>;
constructor() {
this.names = [""Alice"", ""Aarav"", ""Martín"", ""Shannon"", ""Ariana"", ""Kai""];
}
getNames()
{
return this.names;
}
}
I keep getting an error message saying No provider for NameService.
Can someone help me spot the issue with my code?
",https://stackoverflow.com/questions/30580083/angular-no-provider-for-nameservice,395,479089.0,18.0,,,2015-06-01 17:57:24,2019-07-02 06:43:16,2019-02-27 15:34:00,,,typescript;angular;systemjs,M.Svrcek,5645,2667885,registered,true,32298993,,CC BY-SA 4.0,,1396,1266,3,0,0,3,true,false,false,true,true,true,35,5,false,0.038,0.0008,4191,2015,6,17,Monday,false,false,false,false,false,false,false
55198502,Using eslint with typescript - Unable to resolve path to module,"I have this import in my file app.spec.ts:
import app from './app';
Which causes this Typescript error
2:17 error Unable to resolve path to module './app' import/no-unresolved
./app.ts does exist, but I have not compiled the .ts file into a .js file. As soon as I compile the .ts file to a .js, the error goes away.
However, since eslint is supposed to work with typescript, it should resolve modules with the .ts and not the .js.
I've also added the typescript information in my eslint config file:
"parser": "@typescript-eslint/parser",
"parserOptions": {
"project": "./tsconfig.json"
}
How can I config eslint in such a way that it tries to resolve modules with the .ts and not the .js?
EDIT #1
Content of app.ts:
import bodyParser from 'body-parser';
import express from 'express';
import graphqlHTTP from 'express-graphql';
import { buildSchema } from 'graphql';
const app = express();
const schema = buildSchema(`
type Query {
hello: String
}
`);
const root = { hello: () => 'Hello world!' };
app.use(bodyParser());
app.use('/graphql', graphqlHTTP({
schema,
rootValue: root,
graphiql: true,
}));
export default app;
",https://stackoverflow.com/questions/55198502/using-eslint-with-typescript-unable-to-resolve-path-to-module,394,492621.0,26.0,,,2019-03-16 15:35:58,2025-06-06 17:38:30,2022-12-24 08:56:52,,,typescript;eslint,Maxime Dupré,5817,5086286,registered,true,55280867,,CC BY-SA 4.0,,1447,1218,6,0,0,2,true,false,false,true,true,true,63,11,false,0.053,0.0008,2807,2019,3,15,Saturday,true,false,false,false,false,false,false
43298011,Angular error: "Can't bind to 'ngModel' since it isn't a known property of 'input'","I'm using Angular 4 and I am getting an error in the console:
Can't bind to 'ngModel' since it isn't a known property of 'input'
How can I resolve this?
",https://stackoverflow.com/questions/43298011/angular-error-cant-bind-to-ngmodel-since-it-isnt-a-known-property-of-inpu,394,612216.0,21.0,,,2017-04-08 17:09:19,2024-05-10 06:32:17,2020-04-10 01:01:19,,,angular;typescript;angular-ngmodel;angular-forms,Vijay Kumar,4049,5362201,registered,true,43298039,,CC BY-SA 4.0,2019-04-15 16:56:50,205,159,0,0,0,4,true,false,false,true,true,true,117,14,false,0.034,0.0006,3514,2017,4,17,Saturday,true,false,false,false,false,false,false
28150967,typescript - cloning object,"I have a super class that is the parent (Entity) for many subclass (Customer, Product, ProductCategory...)
I'm looking to clone dynamically an object that contains different sub objects in Typescript.
In example : a Customer that has different Product who has a ProductCategory
var cust:Customer = new Customer ();
cust.name = ""someName"";
cust.products.push(new Product(someId1));
cust.products.push(new Product(someId2));
In order to clone the whole tree of object I created a function in Entity
public clone():any {
var cloneObj = new this.constructor();
for (var attribut in this) {
if(typeof this[attribut] === ""object""){
cloneObj[attribut] = this.clone();
} else {
cloneObj[attribut] = this[attribut];
}
}
return cloneObj;
}
The new rises the following error when it is transpiled to javascript: error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature.
Although the script works, I would like to get rid of the transpiled error
",https://stackoverflow.com/questions/28150967/typescript-cloning-object,389,745738.0,29.0,,,2015-01-26 13:25:23,2024-05-22 22:00:37,,,,javascript;typescript,David Laberge,16149,732497,registered,true,28152032,,CC BY-SA 3.0,,1295,1049,12,0,0,2,true,false,false,true,true,false,27,4,false,0.039,0.0005,4317,2015,1,13,Monday,false,false,true,false,false,false,false
36467469,Is key-value pair available in TypeScript?,"Is key-value pair available in TypeScript? If so, how do I do that? Can anyone provide sample, example, or links?
",https://stackoverflow.com/questions/36467469/is-key-value-pair-available-in-typescript,389,710465.0,14.0,,,2016-04-07 05:33:02,2023-11-14 01:57:36,2023-11-14 01:57:36,,,typescript,CodeHunter,3983,6170306,registered,true,,,CC BY-SA 4.0,,121,114,0,0,0,1,false,false,false,true,true,true,42,6,true,0.02,0.0005,3880,2016,4,5,Thursday,false,false,false,false,false,false,false
40081332,What does the `is` keyword do in typescript?,"I came across some code that looks like this:
export function foo(arg: string): arg is MyType {
return ...
}
I haven't been able to search for is in either the docs or google, it's a pretty common word and shows up on basically every page.
What does the keyword do in that context?
",https://stackoverflow.com/questions/40081332/what-does-the-is-keyword-do-in-typescript,387,221430.0,3.0,,,2016-10-17 08:06:49,2025-04-19 18:59:03,2022-06-23 14:59:31,,,typescript;keyword,Drew,13646,595605,registered,true,45748366,,CC BY-SA 4.0,,348,290,2,0,0,2,true,false,false,true,true,true,44,8,true,0.014,0.0017,3687,2016,10,8,Monday,false,false,false,false,false,false,false
32968332,How do I prevent the error "Index signature of object type implicitly has an 'any' type" when compiling typescript with noImplicitAny flag enabled?,"I always compile TypeScript with the flag --noImplicitAny. This makes sense as I want my type checking to be as tight as possible.
My problem is that with the following code I get the error:
Index signature of object type implicitly has an 'any' type
interface ISomeObject {
firstKey: string;
secondKey: string;
thirdKey: string;
}
let someObject: ISomeObject = {
firstKey: 'firstValue',
secondKey: 'secondValue',
thirdKey: 'thirdValue'
};
let key: string = 'secondKey';
let secondValue: string = someObject[key];
Important to note is that the idea is that the key variable comes from somewhere else in the application and can be any of the keys in the object.
I've tried explicitly casting the type by:
let secondValue: string = <string>someObject[key];
Or is my scenario just not possible with --noImplicitAny?
",https://stackoverflow.com/questions/32968332/how-do-i-prevent-the-error-index-signature-of-object-type-implicitly-has-an-an,386,294378.0,17.0,,,2015-10-06 11:02:48,2024-12-13 14:54:25,2022-05-27 04:19:37,,,typescript,Jasper Schulte,7411,1888394,registered,true,32968953,,CC BY-SA 4.0,2020-06-08 00:19:20,993,860,5,0,0,1,true,false,false,true,true,true,165,23,true,0.058,0.0013,4064,2015,10,11,Tuesday,false,false,false,false,false,false,false
34164413,How to apply filters to *ngFor?,"Apparently, Angular 2 will use pipes instead of filters as in Angular1 in conjunction with ng-for to filter results, although the implementation still seems to be vague, with no clear documentation.
Namely what I'm trying to achieve could be viewed from the following perspective
<div *ng-for=""#item of itemsList"" *ng-if=""conditon(item)""></div>
How to implement so using pipes?
",https://stackoverflow.com/questions/34164413/how-to-apply-filters-to-ngfor,380,595650.0,25.0,,,2015-12-08 19:30:31,2025-07-21 00:46:45,2019-02-19 18:14:28,,,angular;typescript,Khaled,8633,1657309,registered,true,34165371,,CC BY-SA 4.0,2018-11-19 02:19:24,439,394,1,0,0,2,true,false,false,true,true,true,31,6,true,0.042,0.0006,4001,2015,12,19,Tuesday,false,false,false,false,false,false,false
36311284,Is there a way to "extract" the type of TypeScript interface property?,"Let's suppose there's a typing file for library X which includes some interfaces.
interface I1 {
x: any;
}
interface I2 {
y: {
a: I1,
b: I1,
c: I1
}
z: any
}
In order to work with this library I need pass around an object that is of exactly the same type as I2.y. I can of course create identical interface in my source files:
interface MyInterface {
a: I1,
b: I1,
c: I1
}
let myVar: MyInterface;
but then I get the burden of keeping it up to date with the one from library, moreover it can be very large and result in lot of code duplication.
Therefore, is there any way to "extract" the type of this specific property of the interface? Something similar to let myVar: typeof I2.y (which doesn't work and results in "Cannot find name I2" error).
Edit: after playing a bit in TS Playground I noticed that following code achieves exactly what I want to:
declare var x: I2;
let y: typeof x.y;
However it requires a redundant variable x to be declared. I am looking for a way to achieve this without that declaration.
",https://stackoverflow.com/questions/36311284/is-there-a-way-to-extract-the-type-of-typescript-interface-property,378,230328.0,7.0,,,2016-03-30 14:06:35,2026-01-23 14:17:31,2021-08-11 23:29:14,,,typescript;typing;definitelytyped,Kuba Jagoda,5627,2148667,registered,true,41075862,,CC BY-SA 4.0,,1273,1097,6,0,0,3,true,false,false,true,true,true,80,12,true,0.03,0.0016,3888,2016,3,14,Wednesday,false,false,false,false,false,false,false
39779272,WebStorm/PhpStorm double quotes in TypeScript auto import,"I'm using TypeScript style with single quotes, double quotes are used exclusively in HTML templates.
WebStorm/PhpStorm auto import adds import statements with double quotes and ruins the style. I guess this applies to all JetBrains products.
How can this behaviour be fixed?
",https://stackoverflow.com/questions/39779272/webstorm-phpstorm-double-quotes-in-typescript-auto-import,377,110427.0,5.0,,,2016-09-29 20:18:58,2020-03-02 01:33:32,2020-03-02 01:33:32,,,typescript;intellij-idea;phpstorm;webstorm;jetbrains-ide,Estus Flask,227334,3731501,registered,true,39779498,,CC BY-SA 4.0,,311,277,1,0,0,5,true,false,false,true,true,true,57,7,false,0.045,0.0034,3705,2016,9,20,Thursday,false,false,false,false,false,false,false
15490560,Create an enum with string values,"Following code can be used to create an enum in TypeScript:
enum e {
hello = 1,
world = 2
};
And the values can be accessed by:
e.hello;
e.world;
How do I create an enum with string values?
enum e {
hello = ""hello"", // error: cannot convert string to e
world = ""world"" // error
};
",https://stackoverflow.com/questions/15490560/create-an-enum-with-string-values,375,417661.0,28.0,,,2013-03-19 02:32:44,2023-12-19 13:36:09,2023-12-19 13:36:09,,,typescript;enums,FacePalm,11918,868791,registered,true,15491832,,CC BY-SA 4.0,,427,308,5,0,0,2,true,false,false,true,true,true,33,6,false,0.067,0.0009,4995,2013,3,2,Tuesday,false,false,false,false,false,false,false
39672807,Types in object destructuring,"This
const { foo: IFoo[] } = bar;
and this
const { foo: Array<IFoo> } = bar;
will reasonably cause an error.
And this
const { foo: TFoo } = bar;
will just destructure TFoo property.
How can types be specified for destructured object properties?
",https://stackoverflow.com/questions/39672807/types-in-object-destructuring,375,243982.0,8.0,,,2016-09-24 05:16:25,2024-09-02 06:33:25,,,,typescript;destructuring,Estus Flask,227334,3731501,registered,true,39672914,,CC BY-SA 3.0,,389,262,4,0,0,2,true,false,false,true,true,false,29,4,false,0.033,0.0015,3710,2016,9,5,Saturday,true,false,false,false,false,false,false
45399951,How to perform string interpolation in TypeScript?,"C# uses string interpolation
int value = 100;
Console.WriteLine($""The size is {value}."");
Output:
The size is 100.
How to do the same thing in TypeScript?
",https://stackoverflow.com/questions/45399951/how-to-perform-string-interpolation-in-typescript,373,378535.0,3.0,,,2017-07-30 12:44:17,2023-02-24 18:40:43,2020-04-10 19:36:02,,,javascript;typescript;string-interpolation,zshanabek,4800,6200054,registered,true,45399981,,CC BY-SA 4.0,,241,164,1,0,0,3,true,false,false,true,true,true,50,7,true,0.008,0.001,3401,2017,7,12,Sunday,true,false,true,false,false,false,false
56568423,No index signature with a parameter of type 'string' was found on type '{ "A": string; },"I have vanilla JavaScript code that takes a string input, splits the string into characters, then matches those characters to a key on an object:
DNATranscriber = {
"G": "C",
"C": "G",
"T": "A",
"A": "U"
}
function toRna(sequence){
const sequenceArray = [...sequence];
const transcriptionArray = sequenceArray.map(character =>{
return this.DNATranscriber[character];
});
return transcriptionArray.join("");
}
console.log(toRna("ACGTGGTCTTAA")); // Returns UGCACCAGAAUU
I'd like to convert this to TypeScript:
class Transcriptor {
DNATranscriber = {
G: "C",
C: "G",
T: "A",
A: "U"
}
toRna(sequence: string) {
const sequenceArray = [...sequence];
const transcriptionArray = sequenceArray.map(character =>{
return this.DNATranscriber[character];
});
}
}
export default Transcriptor
But I'm getting the following error:
TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ "A": string; }'.
No index signature with a parameter of type 'string' was found on type >'{ "A": string; }'.
I thought that the issue was that I needed my object key to be a string. But converting them to strings didn't work:
DNATranscriber = {
"G": "C",
"C": "G",
"T": "A",
"A": "U"
}
It says that no index signature with a type of string exists on my object, but I'm sure that it does. What am I doing wrong? Note: The error message is not raised if I explicitly annotate the variable as having the any type.
",https://stackoverflow.com/questions/56568423/no-index-signature-with-a-parameter-of-type-string-was-found-on-type-a-s,371,583521.0,24.0,,,2019-06-12 18:33:58,2025-06-15 00:37:42,2025-06-12 17:59:15,,,javascript;typescript,onTheInternet,7393,2070478,registered,true,56569217,,CC BY-SA 4.0,,2096,1833,4,0,0,2,true,false,false,true,true,true,110,17,false,0.041,0.0006,2719,2019,6,18,Wednesday,false,false,true,false,false,false,false
44321326,Property 'value' does not exist on type EventTarget in TypeScript,"So the following code is in Angular 4 and I can't figure out why it doesn't work the way as expected.
Here is a snippet of my handler:
onUpdatingServerName(event: Event) {
console.log(event);
this.newserverName = event.target.value; //this wont work
}
HTML element:
<input type=""text"" class=""form-control"" (input)=""onUpdatingServerName($event)"">
The code gives me the error:
Property 'value' does not exist on type 'EventTarget'.
But as it can be seen in the console.log that value does exist on the event.target.
",https://stackoverflow.com/questions/44321326/property-value-does-not-exist-on-type-eventtarget-in-typescript,365,471212.0,17.0,,,2017-06-02 05:20:02,2022-06-21 19:08:42,2017-12-18 00:24:26,2022-07-05 08:05:15,Duplicate,javascript;angular;typescript,Ravy,4089,6099587,registered,true,44321394,,,,678,537,4,0,0,3,true,true,false,true,true,true,73,10,false,0.036,0.0008,3459,2017,6,5,Friday,false,false,true,false,false,false,false
44147937,'Property does not exist on type 'never',"This is similar to #40796374 but that is around types, while I am using interfaces.
Given the code below:
interface Foo {
name: string;
}
function go() {
let instance: Foo | null = null;
let mutator = () => {
instance = {
name: 'string'
};
};
mutator();
if (instance == null) {
console.log('Instance is null or undefined');
} else {
console.log(instance.name);
}
}
I have an error saying 'Property 'name' does not exist on type 'never'.
I don't understand how instance could ever be a 'never'. Can anyone shed some light on this?
",https://stackoverflow.com/questions/44147937/property-does-not-exist-on-type-never,365,836751.0,25.0,,,2017-05-24 02:26:21,2024-11-07 05:54:07,2024-02-01 19:04:10,,,typescript;vue.js,Ray Booysen,30240,42124,registered,true,44147953,,CC BY-SA 4.0,,735,584,1,1,0,2,true,false,false,true,true,true,52,7,false,0.03,0.0004,3468,2017,5,2,Wednesday,false,false,false,false,false,false,false
51851677,How to get argument types from function in Typescript,"I may have missed something in the docs, but I can't find any way in typescript to get the types of the parameters in a function. That is, I've got a function
function test(a: string, b: number) {
console.log(a);
console.log(b)
}
I want access to the types string and number, likely as a tuple.
I know I can get the type of the function itself, as typeof test, or the return type via ReturnType<test>.
When I tried keyof typeof test, it returned never, which I also couldn't explain.
Other answers like this one point to extends, but I don't really understand how that works and don't give me an easy way to access the set-of-all-params as a type.
",https://stackoverflow.com/questions/51851677/how-to-get-argument-types-from-function-in-typescript,364,407030.0,1.0,,,2018-08-15 01:14:52,2024-07-02 20:24:47,2023-01-22 10:30:45,2018-08-15 05:13:41,Duplicate,typescript;typescript-conditional-types,ABMagil,5823,2483138,registered,true,51851844,,,,929,670,8,1,0,2,true,true,false,true,true,true,53,9,false,0.002,0.0009,3020,2018,8,1,Wednesday,false,false,false,false,false,false,false
42609768,Typescript error "Cannot write file ... because it would overwrite input file.","In my Typescript 2.2.1 project in Visual Studio 2015 Update 3, I am getting hundreds of errors in the error list like:
Cannot write file 'C:/{{my-project}}/node_modules/buffer-shims/index.js' because it would overwrite input file.
It looks like this all the time. It doesn't actually prevent building, and everything works just fine, but the error list is distracting and difficult to locate ""real"" errors when they occur.
Here is my tsconfig.json file
{
""compileOnSave"": true,
""compilerOptions"": {
""baseUrl"": ""."",
""module"": ""commonjs"",
""noImplicitAny"": true,
""removeComments"": true,
""sourceMap"": true,
""target"": ""ES5"",
""forceConsistentCasingInFileNames"": true,
""strictNullChecks"": true,
""allowUnreachableCode"": false,
""allowUnusedLabels"": false,
""noFallthroughCasesInSwitch"": true,
""noImplicitReturns"": true,
""noImplicitThis"": true,
""noUnusedLocals"": true,
""noUnusedParameters"": true,
""typeRoots"": [],
""types"": [] //Explicitly specify an empty array so that the TS2 @types modules are not acquired since we aren't ready for them yet.
},
""exclude"": [""node_modules""]
}
How can I get rid of all these errors?
",https://stackoverflow.com/questions/42609768/typescript-error-cannot-write-file-because-it-would-overwrite-input-file,362,272239.0,32.0,,,2017-03-05 14:45:41,2024-05-31 21:32:56,2017-03-05 22:56:12,,,visual-studio;typescript;visual-studio-2015;typescript2.0,Chris Barr,34830,79677,registered,true,44499314,,CC BY-SA 3.0,2022-03-01 22:34:41,1438,1197,2,1,1,4,true,false,false,true,true,true,89,12,false,0.118,0.0013,3548,2017,3,14,Sunday,true,false,false,false,false,false,false
34012291,Exception: Can't bind to 'ngFor' since it isn't a known native property,"What am I doing wrong?
import {bootstrap, Component} from 'angular2/angular2'
@Component({
selector: 'conf-talks',
template: `<div *ngFor=""talk of talks"">
{{talk.title}} by {{talk.speaker}}
<p>{{talk.description}}
</div>`
})
class ConfTalks {
talks = [ {title: 't1', speaker: 'Brian', description: 'talk 1'},
{title: 't2', speaker: 'Julie', description: 'talk 2'}];
}
@Component({
selector: 'my-app',
directives: [ConfTalks],
template: '<conf-talks></conf-talks>'
})
class App {}
bootstrap(App, [])
The error is
EXCEPTION: Template parse errors:
Can't bind to 'ngFor' since it isn't a known native property
(""<div [ERROR ->]*ngFor=""talk of talks"">
",https://stackoverflow.com/questions/34012291/exception-cant-bind-to-ngfor-since-it-isnt-a-known-native-property,360,237115.0,17.0,,,2015-12-01 03:52:41,2022-04-13 10:07:09,2019-07-02 16:00:47,,,angular;typescript;angular2-directives;ngfor,Mark Rajcok,364985,215945,registered,true,34012292,,CC BY-SA 4.0,,792,730,2,0,0,4,true,false,false,true,true,true,87,12,false,0.072,0.0015,4008,2015,12,3,Tuesday,false,false,false,false,false,false,false
16174182,"TypeScript, Looping through a dictionary","In my code, I have a couple of dictionaries (as suggested here) which is String indexed. Due to this being a bit of an improvised type, I was wondering if there any suggestions on how I would be able to loop through each key (or value, all I need the keys for anyway). Any help appreciated!
myDictionary: { [index: string]: any; } = {};
",https://stackoverflow.com/questions/16174182/typescript-looping-through-a-dictionary,356,593647.0,11.0,,,2013-04-23 16:07:40,2022-07-22 06:59:48,2022-04-28 09:14:02,,,javascript;typescript,ben657,3902,933601,registered,true,16174759,,CC BY-SA 4.0,,495,339,1,1,0,2,true,false,false,true,true,true,40,5,false,0.019,0.0006,4960,2013,4,16,Tuesday,false,false,true,false,false,false,false
23437476,"In Typescript, How to check if a string is Numeric","In Typescript, this shows an error saying isNaN accepts only numeric values
isNaN('9BX46B6A')
and this returns false because parseFloat('9BX46B6A') evaluates to 9
isNaN(parseFloat('9BX46B6A'))
I can still run with the error showing up in Visual Studio, but I would like to do it the right way.
Currently, I have written this modified function -
static isNaNModified = (inputStr: string) => {
var numericRepr = parseFloat(inputStr);
return isNaN(numericRepr) || numericRepr.toString().length != inputStr.length;
}
",https://stackoverflow.com/questions/23437476/in-typescript-how-to-check-if-a-string-is-numeric,356,558680.0,18.0,,,2014-05-02 21:47:28,2024-01-02 13:36:38,,,,typescript,user3509546,3697,3509546,registered,true,23440948,,CC BY-SA 3.0,,660,534,5,0,0,1,true,false,false,true,true,false,50,10,false,0.032,0.0006,4586,2014,5,21,Friday,false,false,false,false,false,false,false
35074365,Typescript interface default values,"I have the following interface in TypeScript:
interface IX {
a: string,
b: any,
c: AnotherType
}
I declare a variable of that type and I initialize all the properties
let x: IX = {
a: 'abc',
b: null,
c: null
}
Then I assign real values to them in an init function later
x.a = 'xyz'
x.b = 123
x.c = new AnotherType()
But I don't like having to specify a bunch of default null values for each property when declaring the object when they're going to just be set later to real values. Can I tell the interface to default the properties I don't supply to null? What would let me do this:
let x: IX = {
a: 'abc'
}
without getting a compiler error. Right now it tells me
TS2322: Type '{}' is not assignable to type
'IX'. Property 'b' is missing in type '{}'.
",https://stackoverflow.com/questions/35074365/typescript-interface-default-values,355,802980.0,18.0,,,2016-01-28 23:47:01,2025-02-25 21:15:58,2017-12-13 13:45:32,,,typescript,d512,34623,1334007,registered,true,35074490,,CC BY-SA 3.0,,964,801,4,0,0,1,true,false,false,true,true,true,35,4,false,0.022,0.0004,3950,2016,1,23,Thursday,false,false,false,false,false,false,false
42035387,Can't bind to 'routerLink' since it isn't a known property,"Recently, I have started playing with angular 2. It's awesome so far. So, i have started a demo personal project for the sake of learning using angular-cli.
With the basic routing setup, I now want to navigate to some routes from header, but since my header is a parent to the router-outlet, I receive this error.
app.component.html
<app-header></app-header> // Trying to navigate from this component
<router-outlet></router-outlet>
<app-footer></app-footer>
header.component.html
<a [routerLink]="['/signin']">Sign in</a>
Now I understand partially I guess that since that component is a wrapper around router-outlet it would not be possible this way to access router. So, is there a possibility to access navigation from outside for a scenario like this?
I would be really happy to add any more information if needed. Thank you in advance.
Update
1- My package.json already has the stable @angular/router 3.3.1 version.
2- In my main app module, I have imported the routing-module. Please see below.
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AlertModule } from 'ng2-bootstrap';
import { LayoutModule } from './layout/layout.module';
import { UsersModule } from './users/users.module';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { PageNotFoundComponent } from './shared/components/not-found.component';
@NgModule({
declarations: [
AppComponent,
PageNotFoundComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
AlertModule.forRoot(),
LayoutModule,
UsersModule,
AppRoutingModule --> This is the routing module.
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { SigninComponent } from './users/signin/signin.component';
import { PageNotFoundComponent } from './shared/components/not-found.component';
const routes: Routes = [
{ path: '**', component: PageNotFoundComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
The route I am trying to access is delegated from another module that is the UsersModule
user-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { SigninComponent } from './signin/signin.component';
const usersRoutes: Routes = [
{ path: 'signin', component: SigninComponent }
];
@NgModule({
imports: [
RouterModule.forChild(usersRoutes)
],
exports: [
RouterModule
]
})
export class UsersRoutingModule { }
While I am trying to navigate from a component that is part of the Layout module, but has no notion of the router module. Is that what is causing the error.
Layout.module.ts
import { NgModule } from '@angular/core';
import { HeaderComponent } from './header/header.component';
import { FooterComponent } from './footer/footer.component';
@NgModule({
declarations: [HeaderComponent, FooterComponent],
exports: [HeaderComponent, FooterComponent]
})
export class LayoutModule{}
I am trying to navigate from the HeaderComponent. I would be happy to provide more information if needed.
",https://stackoverflow.com/questions/42035387/cant-bind-to-routerlink-since-it-isnt-a-known-property,352,473734.0,17.0,,,2017-02-04 01:04:44,2023-10-26 18:18:58,2020-12-25 09:32:53,,,angular;typescript;angular2-routing,Umair,6314,4367609,registered,true,42052263,,CC BY-SA 4.0,2022-01-31 14:59:06,4116,3514,18,0,0,3,true,false,false,true,true,true,74,10,false,0.036,0.0007,3577,2017,2,1,Saturday,true,false,false,false,false,false,false
31587949,Hide .js.map files in Visual Studio Code: File Nesting,"I am working on a typescript project in Visual Studio code and would like to hide the .js.map (and maybe even the .js) files from appearing in the file explorer.
Is it possible to display only the .ts files in the file explorer?
",https://stackoverflow.com/questions/31587949/hide-js-map-files-in-visual-studio-code-file-nesting,350,93897.0,13.0,,,2015-07-23 12:52:29,2022-04-30 02:41:13,2022-04-30 02:41:13,2024-04-09 22:03:23,Duplicate,typescript;vs-code,Tyler,18235,2282538,registered,true,31589058,,,,285,232,3,0,0,2,true,true,false,true,true,true,54,9,false,0.138,0.0037,4139,2015,7,12,Thursday,false,false,false,false,false,false,false
34515173,Angular HTTP GET with TypeScript error http.get(...).map is not a function in [null],"I have a problem with HTTP in Angular.
I just want to GET a JSON list and show it in the view.
Service class
import {Injectable} from ""angular2/core"";
import {Hall} from ""./hall"";
import {Http} from ""angular2/http"";
@Injectable()
export class HallService {
public http:Http;
public static PATH:string = 'app/backend/'
constructor(http:Http) {
this.http=http;
}
getHalls() {
return this.http.get(HallService.PATH + 'hall.json').map((res:Response) => res.json());
}
}
And in the HallListComponent I call the getHalls method from the service:
export class HallListComponent implements OnInit {
public halls:Hall[];
public _selectedId:number;
constructor(private _router:Router,
private _routeParams:RouteParams,
private _service:HallService) {
this._selectedId = +_routeParams.get('id');
}
ngOnInit() {
this._service.getHalls().subscribe((halls:Hall[])=>{
this.halls=halls;
});
}
}
However, I got an exception:
TypeError: this.http.get(...).map is not a function in [null]
hall-center.component
import {Component} from ""angular2/core"";
import {RouterOutlet} from ""angular2/router"";
import {HallService} from ""./hall.service"";
import {RouteConfig} from ""angular2/router"";
import {HallListComponent} from ""./hall-list.component"";
import {HallDetailComponent} from ""./hall-detail.component"";
@Component({
template:`
<h2>my app</h2>
<router-outlet></router-outlet>
`,
directives: [RouterOutlet],
providers: [HallService]
})
@RouteConfig([
{path: '/', name: 'HallCenter', component:HallListComponent, useAsDefault:true},
{path: '/hall-list', name: 'HallList', component:HallListComponent}
])
export class HallCenterComponent{}
app.component
import {Component} from 'angular2/core';
import {ROUTER_DIRECTIVES} from ""angular2/router"";
import {RouteConfig} from ""angular2/router"";
import {HallCenterComponent} from ""./hall/hall-center.component"";
@Component({
selector: 'my-app',
template: `
<h1>Examenopdracht Factory</h1>
<a [routerLink]=""['HallCenter']"">Hall overview</a>
<router-outlet></router-outlet>
`,
directives: [ROUTER_DIRECTIVES]
})
@RouteConfig([
{path: '/hall-center/...', name:'HallCenter',component:HallCenterComponent,useAsDefault:true}
])
export class AppComponent { }
tsconfig.json
{
""compilerOptions"": {
""target"": ""ES5"",
""module"": ""system"",
""moduleResolution"": ""node"",
""sourceMap"": true,
""emitDecoratorMetadata"": true,
""experimentalDecorators"": true,
""removeComments"": false,
""noImplicitAny"": false
},
""exclude"": [
""node_modules""
]
}
",https://stackoverflow.com/questions/34515173/angular-http-get-with-typescript-error-http-get-map-is-not-a-function-in-n,348,267153.0,19.0,,,2015-12-29 16:35:48,2022-11-28 04:20:51,2022-11-28 04:20:51,,,javascript;angular;typescript;rxjs,Claudiu Matei,4111,4834129,registered,true,34515276,,CC BY-SA 4.0,2019-06-10 04:34:37,3085,2817,9,0,0,4,true,false,false,true,true,true,84,13,false,0.071,0.0013,3980,2015,12,16,Tuesday,false,false,true,false,false,false,false
34475523,How to pass url arguments (query string) to a HTTP request on Angular?,"I would like to trigger HTTP request from an Angular component, but I do not know how to add URL arguments (query string) to it.
this.http.get(StaticSettings.BASE_URL).subscribe(
(response) => this.onGetForecastResult(response.json()),
(error) => this.onGetForecastError(error.json()),
() => this.onGetForecastComplete()
)
Now my StaticSettings.BASE_URL is like a URL without query string like: http://atsomeplace.com/ but I want it to be like http://atsomeplace.com/?var1=val1&var2=val2
How to add var1, and var2 to my HTTP request object as an object?
{
query: {
var1: val1,
var2: val2
}
}
and then just the HTTP module does the job to parse it into URL query string.
",https://stackoverflow.com/questions/34475523/how-to-pass-url-arguments-query-string-to-a-http-request-on-angular,345,737229.0,12.0,,,2015-12-26 21:48:29,2025-07-21 06:18:45,2020-12-24 09:00:18,,,http;angular;typescript,Miguel Lattuada,5447,3276721,registered,true,34475594,,CC BY-SA 4.0,2019-10-29 06:46:08,918,703,7,0,0,3,true,false,false,true,true,true,70,13,true,0.016,0.0005,3983,2015,12,21,Saturday,true,false,false,false,false,false,false
35328652,Angular pass callback function to child component as @Input similar to AngularJS way,"AngularJS has the & parameters where you could pass a callback to a directive (e.g AngularJS way of callbacks. Is it possible to pass a callback as an @Input for an Angular Component (something like below)? If not what would be the closest thing to what AngularJS does?
@Component({
selector: 'suggestion-menu',
providers: [SuggestService],
template: `
<div (mousedown)=""suggestionWasClicked(suggestion)"">
</div>`,
changeDetection: ChangeDetectionStrategy.Default
})
export class SuggestionMenuComponent {
@Input() callback: Function;
suggestionWasClicked(clickedEntry: SomeModel): void {
this.callback(clickedEntry, this.query);
}
}
<suggestion-menu callback=""insertSuggestion"">
</suggestion-menu>
",https://stackoverflow.com/questions/35328652/angular-pass-callback-function-to-child-component-as-input-similar-to-angularjs,344,392893.0,14.0,,,2016-02-11 00:25:24,2024-10-18 05:43:23,2019-07-19 10:31:03,,,angularjs;angular;typescript,Michail Michailidis,12335,986160,registered,true,39620352,,CC BY-SA 4.0,,915,776,2,1,0,3,true,false,false,true,true,true,84,13,false,0.036,0.0009,3936,2016,2,0,Thursday,false,false,false,false,false,false,false
59623674,How can I use optional chaining with arrays and functions?,"I'm trying to use optional chaining with an array instead of an object but not sure how to do that:
Here's what I'm trying to do myArray.filter(x => x.testKey === myTestKey)?[0].
Also trying similar thing with a function:
let x = {a: () => {}, b: null}
console.log(x?b());
But it's giving a similar error - how can I use optional chaining with an array or a function?
",https://stackoverflow.com/questions/59623674/how-can-i-use-optional-chaining-with-arrays-and-functions,342,176570.0,5.0,,,2020-01-07 07:05:02,2023-11-30 16:13:49,2022-04-26 18:53:29,,,javascript;arrays;typescript;function;optional-chaining,Black Mamba,15820,6517383,registered,true,59623717,,CC BY-SA 4.0,,433,375,2,0,0,5,true,false,false,true,true,true,58,10,true,0.028,0.0019,2510,2020,1,7,Tuesday,false,false,true,false,false,false,false
47455734,How to get query parameters from URL in Angular 5?,"I'm using angular 5.0.3, I would like to start my application with a bunch of query parameters like /app?param1=hallo¶m2=123. Every tip given in How to get query params from url in Angular 2? does not work for me.
Any ideas how to get query parameters work?
private getQueryParameter(key: string): string {
const parameters = new URLSearchParams(window.location.search);
return parameters.get(key);
}
This private function helps me to get my parameters, but I don't think it is the right way in new Angular environment.
[update:]
My main app looks like
@Component({...})
export class AppComponent implements OnInit {
constructor(private route: ActivatedRoute) {}
ngOnInit(): void {
// would like to get query parameters here...
// this.route...
}
}
",https://stackoverflow.com/questions/47455734/how-to-get-query-parameters-from-url-in-angular-5,339,628030.0,20.0,,,2017-11-23 12:36:55,2024-10-13 08:46:20,2020-01-23 14:33:53,,,angular;typescript;angular-routing,Lars,3930,4077981,registered,true,,,CC BY-SA 4.0,,983,784,3,1,0,3,false,false,false,true,true,true,50,10,true,0.032,0.0005,3285,2017,11,12,Thursday,false,false,false,false,false,false,false
26855423,How to require a specific string in TypeScript interface,"I'm creating a TypeScript definition file for a 3rd party js library. One of the methods allows for an options object, and one of the properties of the options object accepts a string from the list: ""collapse"", ""expand"", ""end-expand"", and ""none"".
I have an interface for the options object:
interface IOptions {
indent_size?: number;
indent_char?: string;
brace_style?: // ""collapse"" | ""expand"" | ""end-expand"" | ""none""
}
Can the interface enforce this, so if you include an IOptions object with the brace_style property, it will only allow a string that is in the acceptable list?
",https://stackoverflow.com/questions/26855423/how-to-require-a-specific-string-in-typescript-interface,338,301795.0,10.0,,,2014-11-11 00:18:08,2024-04-27 18:07:00,,,,typescript,thetallweeks,7495,1660815,registered,true,35312363,,CC BY-SA 3.0,,714,591,7,0,0,1,true,false,false,true,true,false,56,9,false,0.033,0.0011,4393,2014,11,0,Tuesday,false,false,false,false,false,false,false
47936183,Angular File Upload,"I'm a beginner with Angular, I want to know how to create Angular 5 File upload part, I'm trying to find any tutorial or doc, but I don't see anything anywhere. Any idea for this? And I tried ng4-files but it's not working for Angular 5
",https://stackoverflow.com/questions/47936183/angular-file-upload,338,837803.0,16.0,,,2017-12-22 05:18:28,2025-10-21 19:36:36,2020-07-07 06:00:39,,,angular;typescript,core114,5327,8268644,registered,true,47938117,,CC BY-SA 4.0,2025-10-21 19:40:16,336,238,0,1,0,2,true,false,false,true,true,true,19,3,false,0.019,0.0004,3256,2017,12,5,Friday,false,false,false,false,false,false,false
37632760,What is the question mark for in a Typescript parameter name,"export class Thread {
id: string;
lastMessage: Message;
name: string;
avatarSrc: string;
constructor(id?: string,
name?: string,
avatarSrc?: string) {
this.id = id || uuid();
this.name = name;
this.avatarSrc = avatarSrc;
}
}
In id? what's the ? for?
",https://stackoverflow.com/questions/37632760/what-is-the-question-mark-for-in-a-typescript-parameter-name,336,375973.0,5.0,,,2016-06-04 16:53:20,2024-03-22 22:36:17,2017-03-25 14:00:14,,,typescript,Whisher,32986,356380,registered,true,37632914,,CC BY-SA 3.0,,362,305,3,0,0,1,true,false,false,true,true,true,60,11,false,0.013,0.0009,3822,2016,6,16,Saturday,true,false,false,false,false,false,false
54884488,How can I solve the error 'TS2532: Object is possibly 'undefined'?,"I'm trying to rebuild a web app example that uses Firebase Cloud Functions and Firestore. When deploying a function I get the following error:
src/index.ts:45:18 - error TS2532: Object is possibly 'undefined'.
45 const data = change.after.data();
This is the function:
export const archiveChat = functions.firestore
.document(""chats/{chatId}"")
.onUpdate(change => {
const data = change.after.data();
const maxLen = 100;
const msgLen = data.messages.length;
const charLen = JSON.stringify(data).length;
const batch = db.batch();
if (charLen >= 10000 || msgLen >= maxLen) {
// Always delete at least 1 message
const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
data.messages.splice(0, deleteCount);
const ref = db.collection(""chats"").doc(change.after.id);
batch.set(ref, data, { merge: true });
return batch.commit();
} else {
return null;
}
});
I'm just trying to deploy the function to test it. And already searched the web for similar problems, but couldn't find any other posts that match my problem.
",https://stackoverflow.com/questions/54884488/how-can-i-solve-the-error-ts2532-object-is-possibly-undefined,335,730953.0,7.0,,,2019-02-26 11:27:41,2024-10-20 18:37:57,,,,typescript;firebase;google-cloud-firestore;google-cloud-functions,Constantin Beer,5923,9696675,registered,true,58401023,,CC BY-SA 4.0,,1195,1126,2,0,0,4,true,false,false,true,true,false,78,11,true,0.01,0.0005,2825,2019,2,11,Tuesday,false,false,false,false,false,false,false
15826745,TypeScript: Creating an empty typed container array,"I am creating simple logic game called ""Three of a Crime"" in TypeScript.
When trying to pre-allocated typed array in TypeScript, I tried to do something like this:
var arr = Criminal[];
which gave the error
""Check format of expression term"" .
also tried doing this
var arr : Criminal = [];
and this produced ""cannot convert any[] to 'Criminal'
what is the 'TypeScript' way to do this?
",https://stackoverflow.com/questions/15826745/typescript-creating-an-empty-typed-container-array,331,459765.0,7.0,,,2013-04-05 05:43:23,2022-12-23 06:04:39,2018-02-26 05:02:21,,,javascript;arrays;typescript,darethas,7727,1307186,registered,true,43230812,,CC BY-SA 3.0,,489,399,2,0,0,3,true,false,false,true,true,true,51,7,false,0.015,0.0007,4978,2013,4,5,Friday,false,false,true,false,false,false,false
36015691,Obtaining the return type of a function,"I have the following function:
function test(): number {
return 42;
}
I can obtain the type of the function by using typeof:
type t = typeof test;
Here, t will be () => number.
Is there a way to obtain the return type of the function? I would like t to be number instead of () => number.
",https://stackoverflow.com/questions/36015691/obtaining-the-return-type-of-a-function,329,258221.0,9.0,,,2016-03-15 15:34:22,2024-04-04 12:34:17,2016-03-15 16:47:11,,,typescript;typescript1.8,rid,64143,732284,registered,true,42549370,,CC BY-SA 3.0,,459,305,8,0,0,2,true,false,false,true,true,true,39,7,false,0.035,0.0013,3903,2016,3,15,Tuesday,false,false,false,false,false,false,false
35546421,How to get a variable type in Typescript?,"I have a variable.
abc:number|string;
How can I check its type? I want to do something like below:
if (abc.type === ""number"") {
// do something
}
",https://stackoverflow.com/questions/35546421/how-to-get-a-variable-type-in-typescript,329,680487.0,10.0,,,2016-02-22 05:33:43,2024-11-10 18:28:59,,,,typescript,Hongbo Miao,50917,2000548,registered,true,35546468,,CC BY-SA 3.0,,217,155,2,0,0,1,true,false,false,true,true,false,41,8,true,0.015,0.0005,3925,2016,2,5,Monday,false,false,false,false,false,false,false
51197940,'File name differs from already included file name only in casing' on relative path with same casing,"
Error TS1149: File name 'C:/Project/frontend/scripts/State.ts' differs from already included file name '../frontend/scripts/State.ts' only in casing.
I've triple checked the casing in our references and the actual files have the correct casing as well. As far as I can tell, this is solely because the relative path uses incorrect casing, or perhaps it's just because of the relative path itself?
The thing is, it compiles just fine on Mac and Linux, but throws this error on Windows.
If it helps, forceConsistentCasingInFileNames is enabled in the tsconfig, and we're using tsify to compile.
",https://stackoverflow.com/questions/51197940/file-name-differs-from-already-included-file-name-only-in-casing-on-relative-p,326,351112.0,36.0,,,2018-07-05 18:40:09,2025-07-11 08:45:50,,,,javascript;windows;typescript;compiler-errors,zuddsy,3585,1982313,registered,true,51213274,,CC BY-SA 4.0,2021-05-09 11:15:09,666,600,1,0,0,4,true,false,false,true,true,false,108,17,false,0.103,0.0009,3061,2018,7,18,Thursday,false,false,true,false,false,false,false
18083389,Ignore Typescript Errors "property does not exist on value of type","In VS2013 building stops when tsc exits with code 1. This was not the case in VS2012.
How can I run my solution while ignoring the tsc.exe error?
I get many The property 'x' does not exist on value of type 'y' errors, which I want to ignore when using javascript functions.
",https://stackoverflow.com/questions/18083389/ignore-typescript-errors-property-does-not-exist-on-value-of-type,326,529232.0,10.0,,,2013-08-06 14:45:24,2025-02-12 07:07:04,2019-01-23 14:45:05,,,javascript;typescript;visual-studio-2013,daniel,35951,516389,registered,true,23553128,,CC BY-SA 4.0,,310,276,1,0,0,3,true,false,false,true,true,true,77,11,false,0.019,0.0006,4855,2013,8,14,Tuesday,false,false,true,false,false,false,false
38688822,How to parse JSON string in Typescript,"Is there a way to parse strings as JSON in TypeScript?
For example in JavaScript, we can use JSON.parse(). Is there a similar function in TypeScript?
I have a JSON object string as follows:
{"name": "Bob", "error": false}
",https://stackoverflow.com/questions/38688822/how-to-parse-json-string-in-typescript,325,719850.0,12.0,,,2016-07-31 22:15:32,2024-12-18 14:24:16,2023-02-20 21:01:35,,,javascript;json;string;typescript,ssd20072,3521,4489122,registered,true,38688861,,CC BY-SA 4.0,,473,253,2,1,0,4,true,false,false,true,true,true,38,7,false,0.017,0.0005,3765,2016,7,22,Sunday,true,false,true,false,false,false,false
39404922,'tsc command not found' in compiling typescript,"I want to install typescript, so I used the following command:
npm install -g typescript
and test tsc --version, but it just show 'tsc command not found'. I have tried many ways as suggested in stackoverflow, github and other sites. but it doesn't work. How could I know typescript is installed and where it is.
my OS is Unix, OS X El Capitan 10.11.6,
node version is 4.4.3,
npm version is 3.10.5
",https://stackoverflow.com/questions/39404922/tsc-command-not-found-in-compiling-typescript,324,621359.0,30.0,,,2016-09-09 06:13:02,2024-02-28 10:31:05,2016-09-09 06:32:48,,,typescript;npm;tsc,Aung Thet,3750,3152790,registered,true,39413342,,CC BY-SA 3.0,2021-06-21 20:27:21,468,410,2,0,0,3,true,false,false,true,true,true,55,7,false,0.048,0.0005,3725,2016,9,6,Friday,false,false,false,false,false,false,false
56704164,"Angular @ViewChild() error: Expected 2 arguments, but got 1","When trying ViewChild I am getting the error. Error is ""An argument for 'opts' was not provided.""
Both @ViewChild is giving the error.
import { Component, OnInit, ElementRef, ViewChild, Output, EventEmitter } from '@angular/core';
import { Ingredient } from 'src/app/shared/ingredient.model';
@Component({
selector: 'app-shopping-edit',
templateUrl: './shopping-edit.component.html',
styleUrls: ['./shopping-edit.component.css']
})
export class ShoppingEditComponent implements OnInit {
@ViewChild('nameInput') nameInputRef: ElementRef;
@ViewChild('amountInput') amountInputRef: ElementRef;
@Output() ingredientAdded = new EventEmitter<Ingredient>();
constructor() {}
ngOnInit() {
}
onAddItem() {
const ingName = this.nameInputRef.nativeElement.value;
const ingAmount = this.amountInputRef.nativeElement.value;
const newIngredient = new Ingredient(ingName, ingAmount);
this.ingredientAdded.emit(newIngredient);
}
}
ts(11,2): error TS2554: Expected 2 arguments, but got 1.
",https://stackoverflow.com/questions/56704164/angular-viewchild-error-expected-2-arguments-but-got-1,319,188953.0,11.0,,,2019-06-21 13:11:35,2021-11-13 19:56:35,2021-11-13 19:56:35,,,angular;typescript;viewchild,stack overflow,3215,11657190,registered,true,56704219,,CC BY-SA 4.0,,1130,1023,1,0,0,3,true,false,false,true,true,true,59,9,false,0.058,0.0017,2710,2019,6,13,Friday,false,false,false,false,false,false,false
39601784,Use component from another module,"I have Angular 2.0.0 app generated with angular-cli.
When I create a component and add it to AppModule's declarations array it's all good, it works.
I decided to separate the components, so I created a TaskModule and a component TaskCard. Now I want to use the TaskCard in one of the components of the AppModule (the Board component).
AppModule:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { BoardComponent } from './board/board.component';
import { LoginComponent } from './login/login.component';
import { MdButtonModule } from '@angular2-material/button';
import { MdInputModule } from '@angular2-material/input';
import { MdToolbarModule } from '@angular2-material/toolbar';
import { routing, appRoutingProviders} from './app.routing';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
import { UserService } from './services/user/user.service';
import { TaskModule } from './task/task.module';
@NgModule({
declarations: [
AppComponent,
BoardComponent,// I want to use TaskCard in this component
LoginComponent,
PageNotFoundComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
MdButtonModule,
MdInputModule,
MdToolbarModule,
routing,
TaskModule // TaskCard is in this module
],
providers: [UserService],
bootstrap: [AppComponent]
})
export class AppModule { }
TaskModule:
import { NgModule } from '@angular/core';
import { TaskCardComponent } from './task-card/task-card.component';
import { MdCardModule } from '@angular2-material/card';
@NgModule({
declarations: [TaskCardComponent],
imports: [MdCardModule],
providers: []
})
export class TaskModule{}
The whole project is available on https://github.com/evgdim/angular2 (kanban-board folder)
What am I missing? What do I have to do to use TaskCardComponent in BoardComponent?
",https://stackoverflow.com/questions/39601784/use-component-from-another-module,319,379519.0,8.0,,,2016-09-20 18:55:29,2024-02-15 06:22:15,2020-02-05 21:36:01,,,angular;typescript;angular-module,Evgeni Dimitrov,22576,383087,registered,true,39601837,,CC BY-SA 4.0,,2333,2066,10,1,0,3,true,false,false,true,true,true,33,5,false,0.021,0.0008,3714,2016,9,18,Tuesday,false,false,false,false,false,false,false
23072286,Where is the syntax for TypeScript comments documented?,"Is the syntax for TypeScript comments documented anywhere?
And by any chance, does it now support the C# /// system?
",https://stackoverflow.com/questions/23072286/where-is-the-syntax-for-typescript-comments-documented,319,380695.0,5.0,,,2014-04-14 23:43:47,2024-08-19 08:06:53,2016-02-15 15:26:00,,,comments;typescript,David Thielen,33986,509627,registered,true,53222546,,CC BY-SA 3.0,,145,118,1,0,0,2,true,false,false,true,true,true,55,8,true,0.013,0.0008,4604,2014,4,23,Monday,false,false,false,false,false,false,false
37764665,How to implement sleep function in TypeScript?,"I'm developing a website in Angular 2 using TypeScript and I was wondering if there was a way to implement thread.sleep(ms) functionality.
My use case is to redirect the users after submitting a form after a few seconds which is very easy in JavaScript but I'm not sure how to do it in TypeScript.
",https://stackoverflow.com/questions/37764665/how-to-implement-sleep-function-in-typescript,317,866048.0,9.0,,,2016-06-11 14:07:11,2023-02-03 21:13:36,2022-01-13 12:47:24,,,angular;typescript;sleep,kha,20153,3839882,registered,true,37764963,,CC BY-SA 4.0,,325,298,1,0,0,3,true,false,false,true,true,true,46,7,true,0.01,0.0004,3815,2016,6,14,Saturday,true,false,false,false,false,false,false
38974896,Call child component method from parent class - Angular,"I have created a child component which has a method I want to invoke.
When I invoke this method it only fires the console.log() line, it will not set the test property??
Below is the quick start Angular app with my changes.
Parent
import { Component } from '@angular/core';
import { NotifyComponent } from './notify.component';
@Component({
selector: 'my-app',
template:
`
<button (click)="submit()">Call Child Component Method</button>
`
})
export class AppComponent {
private notify: NotifyComponent;
constructor() {
this.notify = new NotifyComponent();
}
submit(): void {
// execute child component method
notify.callMethod();
}
}
Child
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'notify',
template: '<h3>Notify {{test}}</h3>'
})
export class NotifyComponent implements OnInit {
test:string;
constructor() { }
ngOnInit() { }
callMethod(): void {
console.log('successfully executed.');
this.test = 'Me';
}
}
How can I set the test property as well?
",https://stackoverflow.com/questions/38974896/call-child-component-method-from-parent-class-angular,317,469402.0,9.0,,,2016-08-16 12:24:15,2023-11-19 15:24:00,2021-09-17 14:11:47,,,angular;typescript;angular-components,shammelburg,7374,2370262,registered,true,38974968,,CC BY-SA 4.0,,1294,1131,5,0,0,3,true,false,false,true,true,true,55,9,false,0.019,0.0007,3749,2016,8,12,Tuesday,false,false,false,false,false,false,false
35987055,How to write unit testing for Angular / TypeScript for private methods with Jasmine,"How do you test a private function in angular 2 ?
class FooBar {
private _status: number;
constructor( private foo : Bar ) {
this.initFooBar();
}
private initFooBar(){
this.foo.bar( ""data"" );
this._status = this.fooo.foo();
}
public get status(){
return this._status;
}
}
The solution I found
Put the test code itself inside the closure or Add code inside the closure that stores references to the local variables on existing objects in the outer scope.
Later strip out the test code using a tool.
http://philipwalton.com/articles/how-to-unit-test-private-functions-in-javascript/
Please suggest me a better way to solve this problem if you have done any?
P.S
Most of the answer for similar type of question like this one doesn't give a solution to problem, that's why I'm asking this question
Most of the developer say you Don’t test private functions but I don't say they are wrong or right, but there are necessities for my case to test private.
",https://stackoverflow.com/questions/35987055/how-to-write-unit-testing-for-angular-typescript-for-private-methods-with-jasm,316,239834.0,12.0,,,2016-03-14 12:03:22,2022-08-06 17:19:30,2019-06-26 12:26:11,,,angular;unit-testing;typescript;jasmine,mehdhi,4320,3029163,registered,true,35991491,,CC BY-SA 4.0,,1269,1030,1,1,0,4,true,false,false,true,true,true,83,14,false,0.05,0.0013,3904,2016,3,12,Monday,false,false,false,false,false,false,false
45194598,using process.env in TypeScript,"How do I read node environment variables in TypeScript?
If i use process.env.NODE_ENV I have this error :
Property 'NODE_ENV' does not exist on type 'ProcessEnv'
I have installed @types/node but it didn't help.
",https://stackoverflow.com/questions/45194598/using-process-env-in-typescript,315,511877.0,22.0,,,2017-07-19 15:11:22,2025-03-04 07:52:47,,,,node.js;typescript,Christophe Le Besnerais,4913,990193,registered,true,45195359,,CC BY-SA 3.0,,287,216,3,0,0,2,true,false,false,true,true,false,31,4,false,0.043,0.0006,3412,2017,7,15,Wednesday,false,false,false,false,false,false,false
43618878,How to disable a ts rule for a specific line?,"Summernote is a jQuery plugin, and I don't need type definitions for it. I just want to modify the object, but TS keeps throwing errors. The line bellow still gives me: ""Property 'summernote' does not exist on type 'jQueryStatic'."" error.
(function ($) {
/* tslint:disable */
delete $.summernote.options.keyMap.pc.TAB;
delete $.summernote.options.keyMap.mac.TAB;
/* tslint:enable */
})(jQuery)
Edit:
Here is my tsconfig.json
{
""compilerOptions"": {
""outDir"": ""./dist/"",
""sourceMap"": true,
""noImplicitAny"": true,
""module"": ""commonjs"",
""target"": ""es5"",
""allowJs"": true,
""noUnusedParameters"": true
},
""include"": [
""js/**/*""
],
""exclude"": [
""node_modules"",
""**/*.spec.ts""
]
}
",https://stackoverflow.com/questions/43618878/how-to-disable-a-ts-rule-for-a-specific-line,313,523008.0,7.0,,,2017-04-25 19:00:25,2025-02-07 16:50:14,2017-04-25 23:12:48,,,javascript;jquery;typescript;summernote,Amir,4920,1245564,registered,true,43620820,,CC BY-SA 3.0,,848,745,2,0,0,4,true,false,false,true,true,true,45,10,true,0.013,0.0006,3497,2017,4,19,Tuesday,false,false,true,false,false,false,false
38834625,What's the difference between 'extends' and 'implements' in TypeScript,"I would like to know what Man and Child have in common and how they differ.
class Person {
name: string;
age: number;
}
class Child extends Person {}
class Man implements Person {}
",https://stackoverflow.com/questions/38834625/whats-the-difference-between-extends-and-implements-in-typescript,310,278028.0,8.0,,,2016-08-08 16:49:59,2024-07-17 16:14:21,2024-07-05 22:41:58,,,typescript;extends;implements,davejoem,5612,5368261,registered,true,38834997,,CC BY-SA 4.0,,306,186,1,0,0,3,true,false,false,true,true,true,90,9,false,0.029,0.0011,3757,2016,8,16,Monday,false,false,false,false,false,false,false
30019542,ES6 Map in Typescript,"I'm creating a class in typescript that has a property that is an ES6 (ECMAscript 2016) Map like so:
class Item {
configs: ????;
constructor () {
this.configs = new Map();
}
}
How do I declare an ES6 Map type in typescript?
",https://stackoverflow.com/questions/30019542/es6-map-in-typescript,308,812261.0,11.0,,,2015-05-03 21:18:52,2023-01-29 13:47:48,2015-05-03 23:59:11,,,javascript;typescript;typescript1.5,nicksrandall,3178,3565997,registered,true,30019750,,CC BY-SA 3.0,,276,238,1,0,0,3,true,false,false,true,true,true,21,4,false,0.014,0.0004,4220,2015,5,21,Sunday,true,false,true,false,false,false,false
34986922,Define global constants,"In Angular 1.x you can define constants like this:
angular.module('mainApp.config', [])
.constant('API_ENDPOINT', 'http://127.0.0.1:6666/api/')
What would be the equivalent in Angular (with TypeScript)?
I just don't want to repeat the API base url over and over again in all my services.
",https://stackoverflow.com/questions/34986922/define-global-constants,306,465507.0,17.0,,,2016-01-25 07:10:26,2021-03-11 11:27:58,2019-12-28 22:26:03,,,typescript;angular,AndreFeijo,10725,2946773,registered,true,34988045,,CC BY-SA 4.0,,378,296,1,0,0,2,true,false,false,true,true,true,23,3,false,0.037,0.0007,3953,2016,1,7,Monday,false,false,false,false,false,false,false
39677437,How to update TypeScript to latest version with npm?,"Currently I have TypeScript 1.0.3 version installed on my machine.
I want to update it to latest one such as 2.0.0.
How to do this with npm?
",https://stackoverflow.com/questions/39677437/how-to-update-typescript-to-latest-version-with-npm,306,533117.0,11.0,,,2016-09-24 14:27:43,2025-01-10 11:05:25,2025-01-10 11:05:25,,,typescript;npm;npm-install;npm-package,blueMoon,3151,2635046,registered,true,39677450,,CC BY-SA 4.0,2022-04-11 10:46:51,161,141,0,0,0,4,true,false,false,true,true,true,52,9,true,0.021,0.0006,3710,2016,9,14,Saturday,true,false,false,false,false,false,false
34660265,Importing lodash into angular2 + typescript application,"I am having a hard time trying to get the lodash modules imported. I've setup my project using npm+gulp, and keep hitting the same wall. I've tried the regular lodash, but also lodash-es.
The lodash npm package: (has an index.js file in the package root folder)
import * as _ from 'lodash';
Results in:
error TS2307: Cannot find module 'lodash'.
The lodash-es npm package: (has a default export in lodash.js i the package root folder)
import * as _ from 'lodash-es/lodash';
Results in:
error TS2307: Cannot find module 'lodash-es'.
Both the gulp task and webstorm report the same issue.
Funny fact, this returns no error:
import 'lodash-es/lodash';
... but of course there is no "_" ...
My tsconfig.json file:
{
"compilerOptions": {
"target": "es5",
"module": "system",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": false
},
"exclude": [
"node_modules"
]
}
My gulpfile.js:
var gulp = require('gulp'),
ts = require('gulp-typescript'),
uglify = require('gulp-uglify'),
sourcemaps = require('gulp-sourcemaps'),
tsPath = 'app/**/*.ts';
gulp.task('ts', function () {
var tscConfig = require('./tsconfig.json');
gulp.src([tsPath])
.pipe(sourcemaps.init())
.pipe(ts(tscConfig.compilerOptions))
.pipe(sourcemaps.write('./../js'));
});
gulp.task('watch', function() {
gulp.watch([tsPath], ['ts']);
});
gulp.task('default', ['ts', 'watch']);
If I understood correctly, moduleResolution:'node' in my tsconfig should point the import statements to the node_modules folder, where lodash and lodash-es are installed. I've also tried lots of different ways to import: absolute paths, relative paths, but nothing seems to work. Any ideas?
If necessary I can provide a small zip file to illustrate the problem.
",https://stackoverflow.com/questions/34660265/importing-lodash-into-angular2-typescript-application,306,246607.0,23.0,,,2016-01-07 16:28:17,2021-05-01 17:33:24,2021-05-01 17:33:24,,,javascript;angular;typescript;lodash;es6-module-loader,Davy,6451,1854793,registered,true,39209948,,CC BY-SA 4.0,,2320,2068,7,0,0,5,true,false,false,true,true,true,55,7,false,0.093,0.0012,3971,2016,1,16,Thursday,false,false,true,false,false,false,false
50848357,What is the purpose of providedIn with the Injectable decorator when generating Services in Angular 6?,"When generating services in the Angular CLI, it is adding extra metadata with a 'provided in' property with a default of 'root' for the Injectable decorator.
@Injectable({
providedIn: 'root',
})
What exactly does providedIn do? I am assuming this is making the service available like a 'global' type singleton service for the whole application, however, wouldn't be cleaner to declare such services in the provider array of the AppModule?
",https://stackoverflow.com/questions/50848357/what-is-the-purpose-of-providedin-with-the-injectable-decorator-when-generating,306,168815.0,8.0,,,2018-06-14 01:22:51,2023-05-12 12:49:46,2022-01-27 10:04:48,,,angular;typescript;angular6,Stefan Zvonar,4409,3003119,registered,true,50848377,,CC BY-SA 4.0,,481,443,1,0,0,3,true,false,false,true,true,true,102,16,true,0.047,0.0018,3082,2018,6,1,Thursday,false,false,false,false,false,false,false
35110690,ngOnInit not being called when Injectable class is Instantiated,"Why isn't ngOnInit() called when an Injectable class is resolved?
Code
import {Injectable, OnInit} from 'angular2/core';
import { RestApiService, RestRequest } from './rest-api.service';
@Injectable()
export class MovieDbService implements OnInit {
constructor(private _movieDbRest: RestApiService){
window.console.log('FROM constructor()');
}
ngOnInit() {
window.console.log('FROM ngOnInit()');
}
}
Console Output
FROM constructor()
",https://stackoverflow.com/questions/35110690/ngoninit-not-being-called-when-injectable-class-is-instantiated,305,227405.0,5.0,,,2016-01-31 05:33:22,2022-06-02 06:16:12,2017-08-14 19:45:44,,,javascript;angular;typescript,Levi Fuller,16479,2535344,registered,true,35110798,,CC BY-SA 3.0,,606,477,4,0,0,3,true,false,false,true,true,true,63,9,false,0.022,0.0013,3947,2016,1,5,Sunday,true,false,true,false,false,false,false
37502809,What are the "spec.ts" files generated by Angular CLI for?,"I am using Angular CLI to generate and serve projects. It seems to work well – though for my little learning projects, it produces more than I need – but that's to be expected.
I've noticed that it generates spec.ts for each Angular element in a project (Component, Service, Pipe, etc). I've searched around but have not found an explanation of what these files are for.
Are these build files which are normally hidden when using tsc? I wondered because I wanted to change the name of a poorly named Component I'd created and discovered that the name was also referenced in these spec.ts files.
import {
beforeEach,
beforeEachProviders,
describe,
expect,
it,
inject,
} from '@angular/core/testing';
import { ComponentFixture, TestComponentBuilder } from '@angular/compiler/testing';
import { Component } from '@angular/core';
import { By } from '@angular/platform-browser';
import { PovLevelComponent } from './pov-level.component';
describe('Component: PovLevel', () => {
let builder: TestComponentBuilder;
beforeEachProviders(() => [PovLevelComponent]);
beforeEach(inject([TestComponentBuilder], function (tcb: TestComponentBuilder) {
builder = tcb;
}));
it('should inject the component', inject([PovLevelComponent],
(component: PovLevelComponent) => {
expect(component).toBeTruthy();
}));
it('should create the component', inject([], () => {
return builder.createAsync(PovLevelComponentTestController)
.then((fixture: ComponentFixture<any>) => {
let query = fixture.debugElement.query(By.directive(PovLevelComponent));
expect(query).toBeTruthy();
expect(query.componentInstance).toBeTruthy();
});
}));
});
@Component({
selector: 'test',
template: `
<app-pov-level></app-pov-level>
`,
directives: [PovLevelComponent]
})
class PovLevelComponentTestController {
}
",https://stackoverflow.com/questions/37502809/what-are-the-spec-ts-files-generated-by-angular-cli-for,305,248127.0,5.0,,,2016-05-28 19:01:33,2025-12-20 14:47:33,2022-12-29 00:57:29,,,angular;typescript,spring,18637,840992,registered,true,37502922,,CC BY-SA 4.0,2025-12-20 14:52:11,2056,1898,5,1,0,2,true,false,false,true,true,true,68,10,true,0.02,0.0012,3829,2016,5,19,Saturday,true,false,false,false,false,false,false
37699320,Iterating over Typescript Map,"I'm trying to iterate over a typescript map but I keep getting errors and I could not find any solution yet for such a trivial problem.
My code is:
myMap : Map<string, boolean>;
for(let key of myMap.keys()) {
console.log(key);
}
And I get the Error:
Type 'IterableIteratorShim<[string, boolean]>' is not an array type or a string type.
Full Stack Trace:
Error: Typescript found the following errors:
/home/project/tmp/broccoli_type_script_compiler-input_base_path-q4GtzHgb.tmp/0/src/app/project/project-data.service.ts (21, 20): Type 'IterableIteratorShim<[string, boolean]>' is not an array type or a string type.
at BroccoliTypeScriptCompiler._doIncrementalBuild (/home/project/node_modules/angular-cli/lib/broccoli/broccoli-typescript.js:115:19)
at BroccoliTypeScriptCompiler.build (/home/project/node_modules/angular-cli/lib/broccoli/broccoli-typescript.js:43:10)
at /home/project/node_modules/broccoli-caching-writer/index.js:152:21
at lib$rsvp$$internal$$tryCatch (/home/project/node_modules/rsvp/dist/rsvp.js:1036:16)
at lib$rsvp$$internal$$invokeCallback (/home/project/node_modules/rsvp/dist/rsvp.js:1048:17)
at lib$rsvp$$internal$$publish (/home/project/node_modules/rsvp/dist/rsvp.js:1019:11)
at lib$rsvp$asap$$flush (/home/project/node_modules/rsvp/dist/rsvp.js:1198:9)
at _combinedTickCallback (internal/process/next_tick.js:67:7)
at process._tickCallback (internal/process/next_tick.js:98:9)
I'm using angular-cli beta5 and typescript 1.8.10 and my target is es5.
Has anyone had this Problem?
",https://stackoverflow.com/questions/37699320/iterating-over-typescript-map,304,632496.0,15.0,,,2016-06-08 10:01:15,2023-05-02 19:40:54,2023-01-18 01:29:00,,,typescript;dictionary;iterator,mwe,3363,5088381,registered,true,37700588,,CC BY-SA 4.0,,1692,1577,2,0,0,3,true,false,false,true,true,true,29,4,false,0.024,0.0005,3818,2016,6,10,Wednesday,false,false,false,false,false,false,false
32554624,Casting a number to a string in TypeScript,"Which is the the best way (if there is one) to cast from number to string in Typescript?
var page_number:number = 3;
window.location.hash = page_number;
In this case the compiler throws the error:
Type 'number' is not assignable to type 'string'
Because location.hash is a string.
window.location.hash = """"+page_number; //casting using """" literal
window.location.hash = String(number); //casting creating using the String() function
So which method is better?
",https://stackoverflow.com/questions/32554624/casting-a-number-to-a-string-in-typescript,304,654848.0,8.0,,,2015-09-13 21:15:48,2023-12-04 20:25:10,2015-09-13 21:46:52,,,javascript;casting;typescript,Ma Jerez,6245,1316510,registered,true,32607656,,CC BY-SA 3.0,,594,473,3,0,0,3,true,false,false,true,true,true,42,8,false,0.012,0.0005,4087,2015,9,21,Sunday,true,false,true,false,false,false,false
39559296,TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm","I keep getting this error while using TypeScript's Angular2-forms framework:
There is no directive with ""exportAs"" set to ""ngForm""
Here's my code
project dependencies :
""dependencies"": {
""@angular/common"": ""2.0.0-rc.6"",
""@angular/compiler"": ""2.0.0-rc.6"",
""@angular/core"": ""2.0.0-rc.6"",
""@angular/forms"": ""2.0.0-rc.6"",
""@angular/http"": ""2.0.0-rc.6"",
""@angular/platform-browser"": ""2.0.0-rc.6"",
""@angular/platform-browser-dynamic"": ""2.0.0-rc.6"",
""@angular/router"": ""3.0.0-rc.2"",
""ng2-bootstrap"": ""^1.1.1"",
""reflect-metadata"": ""^0.1.8"",
""core-js"": ""^2.4.0"",
""es6-module-loader"": ""^0.17.8"",
""rxjs"": ""5.0.0-beta.11"",
""systemjs"": ""0.19.27"",
""zone.js"": ""0.6.17"",
""jquery"": ""3.0.0"",
}
And this is the Login Template :
<form #loginForm=""ngForm"" (ng-submit)=""authenticate(loginForm.value)"">
</form>
...and the Login Component :
import { Component } from '@angular/core';
import {Http, Headers} from '@angular/http';
@Component({
moduleId: module.id,
selector: 'login-cmp',
templateUrl: 'login.component.html'
})
export class LoginComponent {
constructor($http: Http) {
this.$http = $http;
}
authenticate(data) {
...
}
}
I have this Error :
zone.js?1474211973422:484 Unhandled Promise rejection: Template parse errors:
There is no directive with ""exportAs"" set to ""ngForm"" (""
<form [ERROR ->]#loginForm=""ngForm""
(ngsubmit)=""authenticate(loginForm.value)"">
",https://stackoverflow.com/questions/39559296/typescript-s-angular-framework-error-there-is-no-directive-with-exportas-set,303,342209.0,28.0,,,2016-09-18 15:23:17,2025-02-01 11:20:33,2020-04-13 06:21:54,,,angular;typescript;forms;angular2-forms,Nassim MOUALEK,4874,3252285,registered,true,39559318,,CC BY-SA 4.0,2020-04-15 19:53:27,1690,1498,5,0,0,4,true,false,false,true,true,true,105,14,false,0.082,0.0009,3716,2016,9,15,Sunday,true,false,false,false,false,false,false
45339065,TypeScript empty object for a typed variable,"Say I have:
type User = {
...
}
I want to create a new user but set it to be an empty object:
const user: User = {}; // This fails saying property XX is missing
const user: User = {} as any; // This works but I don't want to use any
How do I do this? I don't want the variable to be null.
",https://stackoverflow.com/questions/45339065/typescript-empty-object-for-a-typed-variable,303,421994.0,12.0,,,2017-07-26 23:37:51,2025-01-13 10:30:15,2021-07-26 09:58:51,,,typescript,Kousha,36827,834045,registered,true,45339463,,CC BY-SA 4.0,,388,293,4,0,0,1,true,false,false,true,true,true,44,7,false,0.028,0.0007,3405,2017,7,23,Wednesday,false,false,false,false,false,false,false
53556409,"flatMap, flat, flatten doesn't exist on type any[]","I'm using Chrome 70 and Chrome does add methods .flatMap, .flatten, .flat. So my code does run as expected. Unfortunately, TypeScript doesn't like it.
// data.flatMap lint error
export const transformData = (data: any[]) => data.flatMap(abc => [
parentObj(abc),
...generateTasks(abc)
]);
The warning I got is TS2339: Property 'flatMap' does not exist on type 'any[]'.
I'm using Angular 6, which uses Typescript ~2.9.2, and I already include import 'core-js/es7/array'; in polyfills.ts.
My guess is that there is no typing for these methods, and I did try to npm run -dev @types/array.prototype.flatmap but still not solve.
",https://stackoverflow.com/questions/53556409/flatmap-flat-flatten-doesnt-exist-on-type-any,301,181662.0,7.0,,,2018-11-30 11:11:24,2022-02-28 17:55:31,2022-02-28 17:23:28,,,angular;typescript,Azriz,3209,3648961,registered,true,53559473,,CC BY-SA 4.0,,779,636,8,0,0,2,true,false,false,true,true,true,54,8,false,0.039,0.0017,2913,2018,11,11,Friday,false,false,false,false,false,false,false
30357634,How do I use namespaces with TypeScript external modules?,"I have some code:
baseTypes.ts
export namespace Living.Things {
export class Animal {
move() { /* ... */ }
}
export class Plant {
photosynthesize() { /* ... */ }
}
}
dog.ts
import b = require('./baseTypes');
export namespace Living.Things {
// Error, can't find name 'Animal', ??
export class Dog extends Animal {
woof() { }
}
}
tree.ts
// Error, can't use the same name twice, ??
import b = require('./baseTypes');
import b = require('./dogs');
namespace Living.Things {
// Why do I have to write b.Living.Things.Plant instead of b.Plant??
class Tree extends b.Living.Things.Plant {
}
}
This is all very confusing. I want to have a bunch of external modules all contribute types to the same namespace, Living.Things. It seems that this doesn't work at all -- I can't see Animal in dogs.ts. I have to write the full namespace name b.Living.Things.Plant in tree.ts. It doesn't work to combine multiple objects in the same namespace across file. How do I do this?
",https://stackoverflow.com/questions/30357634/how-do-i-use-namespaces-with-typescript-external-modules,299,238726.0,10.0,,,2015-05-20 18:27:16,2021-07-30 11:17:48,2019-06-13 18:21:28,,,javascript;module;typescript,Ryan Cavanaugh,223506,1704166,registered,true,30357635,,CC BY-SA 4.0,,1230,1007,8,0,0,3,true,false,false,true,true,true,57,9,true,0.042,0.0013,4203,2015,5,18,Wednesday,false,false,true,false,false,false,false
52801814,"This syntax requires an imported helper but module 'tslib' cannot be found" with ES2015 modules,"I have demo project I'm about to compile to ES5 with ES2015 modules enabled and tslib used for external TS helpers:
package.json
{
""name"": ""foo"",
""scripts"": {
""build"": ""tsc""
},
""dependencies"": {
""tslib"": ""^1.9.3""
},
""devDependencies"": {
""typescript"": ""^3.1.3""
}
}
tsconfig.json
{
""compilerOptions"": {
""target"": ""es5"",
""module"": ""es2015"",
""outDir"": ""./lib"",
""rootDir"": ""./src"",
""importHelpers"": true,
""strict"": true,
""experimentalDecorators"": true
}
}
src/index.ts
function a(target: any) {
return target;
}
@a
export class Foo {}
This results in an error:
src/index.ts:5:1 - error TS2354: This syntax requires an imported helper but module 'tslib' cannot be found.
While lib/index.js is correctly compiled:
import * as tslib_1 from ""tslib"";
function a(target) {
return target;
}
var Foo = /** @class */ (function () {
function Foo() {
}
Foo = tslib_1.__decorate([
a
], Foo);
return Foo;
}());
export { Foo };
How can this problem be solved?
",https://stackoverflow.com/questions/52801814/this-syntax-requires-an-imported-helper-but-module-tslib-cannot-be-found-wit,298,436746.0,25.0,,,2018-10-14 10:42:06,2024-09-07 23:19:31,,,,typescript,Estus Flask,227334,3731501,registered,true,,,CC BY-SA 4.0,2024-02-10 00:29:50,1285,1055,6,0,0,1,false,false,false,true,true,false,114,15,false,0.057,0.0007,2960,2018,10,10,Sunday,true,false,false,false,false,false,false
35688084,How to get query params from url in Angular 2?,"I use angular2.0.0-beta.7. When a component is loaded on a path like /path?query=value1 it is redirected to /path. Why were the GET params removed? How can I preserve the parameters?
I have an error in the routers. If I have a main route like
@RouteConfig([
{
path: '/todos/...',
name: 'TodoMain',
component: TodoMainComponent
}
])
and my child route like
@RouteConfig([
{ path: '/', component: TodoListComponent, name: 'TodoList', useAsDefault:true },
{ path: '/:id', component: TodoDetailComponent, name:'TodoDetail' }
])
then I can't get params in TodoListComponent. I am able to get
params(""/my/path;param1=value1;param2=value2"")
but I want the classic
query params(""/my/path?param1=value1¶m2=value2"")
",https://stackoverflow.com/questions/35688084/how-to-get-query-params-from-url-in-angular-2,298,445494.0,17.0,,,2016-02-28 20:49:31,2023-07-04 08:27:08,2019-02-25 20:36:10,,,typescript;angular,FireGM,3131,3834274,registered,true,39146396,,CC BY-SA 4.0,2019-03-22 06:50:00,911,754,6,0,0,2,true,false,false,true,true,true,46,10,true,0.038,0.0007,3919,2016,2,20,Sunday,true,false,false,false,false,false,false
22885995,How do I initialize a TypeScript object with a JSON object?,"I receive a JSON object from an AJAX call to a REST server. This object has property names that match my TypeScript class (this is a follow-on to How do I cast a JSON object to a TypeScript class?).
What is the best way to initialize it? I don't think Copying AJAX JSON object into existing Object will work because the class (& JSON object) have members that are lists of objects and members that are classes, and those classes have members that are lists and/or classes.
But I'd prefer an approach that looks up the member names and assigns them across, creating lists and instantiating classes as needed, so I don't have to write explicit code for every member in every class (there are a lot).
",https://stackoverflow.com/questions/22885995/how-do-i-initialize-a-typescript-object-with-a-json-object,296,572265.0,19.0,,,2014-04-05 19:52:35,2025-11-28 12:56:29,2025-11-28 12:56:29,,,json;typescript,David Thielen,33986,509627,registered,true,22886730,,CC BY-SA 4.0,,887,702,0,2,0,2,true,false,false,true,true,true,59,11,true,0.033,0.0005,4613,2014,4,19,Saturday,true,false,false,false,false,false,false
56505560,How to fix TS2322: "could be instantiated with a different subtype of constraint 'object'"?,"A have a type-check error in recursive types.
I am trying to write types for react-jss styles object.
type StylesFn<P extends object> = (
props: P
) => CSS.Properties<JssValue<P>> | number | string;
type JssValue<P extends object> =
| string
| number
| Array<string | number>
| StylesFn<P>;
// @ts-ignore
interface StylesObject<K extends string = any, P extends object = {}>
extends Styles {
[x: string]: CSS.Properties<JssValue<P>> | Styles<K, P>;
}
export type Styles<K extends string = any, P extends object = {}> = {
[x in K]: CSS.Properties<JssValue<P>> | StylesObject<any, P> | StylesFn<P>
};
It works fine, but typescript writes an error. I use @ts-ignore, but this is not fancy
ERROR 24:11 typecheck Interface 'StylesObject<K, P>' incorrectly extends interface 'Styles<any, {}>'.
Index signatures are incompatible.
Type 'Properties<JssValue<P>> | Styles<K, P>' is not assignable to type 'StylesFn<{}> | Properties<JssValue<{}>> | StylesObject<any, {}>'.
Type 'Properties<JssValue<P>>' is not assignable to type 'StylesFn<{}> | Properties<JssValue<{}>> | StylesObject<any, {}>'.
Type 'Properties<JssValue<P>>' is not assignable to type 'Properties<JssValue<{}>>'.
Type 'JssValue<P>' is not assignable to type 'JssValue<{}>'.
Type 'StylesFn<P>' is not assignable to type 'JssValue<{}>'.
Type 'StylesFn<P>' is not assignable to type 'StylesFn<{}>'.
Type '{}' is not assignable to type 'P'.
'{}' is assignable to the constraint of type 'P', but 'P' could be instantiated with a different subtype of constraint 'object'.
What does this error mean?
",https://stackoverflow.com/questions/56505560/how-to-fix-ts2322-could-be-instantiated-with-a-different-subtype-of-constraint,295,195736.0,5.0,,,2019-06-08 10:35:11,2024-01-26 06:46:24,2021-02-21 00:10:17,,,typescript;typescript-generics,teux,3060,7908372,registered,true,,,CC BY-SA 4.0,,2069,1906,3,0,0,2,false,false,false,true,true,true,109,14,true,0.026,0.0015,2723,2019,6,10,Saturday,true,false,false,false,false,false,false
43042889,Typescript ReferenceError: exports is not defined,"Trying to implement a module following the official handbook, I get this error message:
Uncaught ReferenceError: exports is not defined
at app.js:2
But nowhere in my code do I ever use the name exports.
How can I fix this?
Files
app.ts
let a = 2;
let b:number = 3;
import Person = require ('./mods/module-1');
module-1.t
export class Person {
constructor(){
console.log('Person Class');
}
}
export default Person;
tsconfig.json
{
""compilerOptions"": {
""module"": ""commonjs"",
""target"": ""es5"",
""noImplicitAny"": false,
""sourceMap"": true,
""outDir"": ""scripts/""
},
""exclude"": [
""node_modules""
]
}
",https://stackoverflow.com/questions/43042889/typescript-referenceerror-exports-is-not-defined,295,683825.0,33.0,,,2017-03-27 09:39:13,2025-02-20 17:18:38,2017-05-16 10:43:32,,,typescript;module,user6600549,,,does_not_exist,true,43999062,,CC BY-SA 3.0,2023-02-17 09:11:07,960,686,4,1,0,2,true,false,false,true,false,true,49,6,false,0.048,0.0004,3526,2017,3,9,Monday,false,false,false,false,false,false,false
30807612,Should I use typescript? or I can just use ES6?,"My daily job is client developer using AngularJS. We are evaluating if we want to go with TypeScript. I did some research on typescript and almost every JavaScript package I need must have definition type files. I found that is not very convenient, especially if I would like to try something new and they don't have the definition for it. Its really frustrating. (Even the current jQuery definition gives me some problems if I want to use typescript 1.5 beta). I started looking at ES6 and it looks similar to TypeScript. Should I just use ES6 instead? Also, I heard angular 2 will have full support for TypeScript, will that be one reason I should stay with it?
",https://stackoverflow.com/questions/30807612/should-i-use-typescript-or-i-can-just-use-es6,294,127585.0,2.0,,,2015-06-12 16:08:07,2020-02-23 00:00:38,2017-01-31 15:33:58,2015-06-12 20:24:42,Opinion-based,angularjs;typescript;ecmascript-6,cjskywalker,3285,1229093,registered,true,30807922,,,,671,664,0,0,0,3,true,true,false,true,true,true,47,10,true,0.016,0.0023,4180,2015,6,16,Friday,false,false,false,false,false,false,false
18961203,'any' vs 'Object',"I am looking at TypeScript code and noticed that they use:
interface Blablabla {
field: Object;
}
What is the benefit of using Object vs any, as in:
interface Blablabla {
field: any;
}
",https://stackoverflow.com/questions/18961203/any-vs-object,294,329642.0,7.0,,,2013-09-23 13:58:58,2022-09-23 12:30:19,2018-09-06 22:41:07,,,typescript,Olivier Refalo,51855,258689,registered,true,18961904,,CC BY-SA 4.0,,287,199,4,0,0,1,true,false,false,true,true,true,33,3,false,0.021,0.0009,4807,2013,9,13,Monday,false,false,false,false,false,false,false
60755711,Is it possible to mark something as deprecated in typescript?,"I'm writing typescript definitions for a Javascript API with a deprecated method. Here's an extract of the documentation (they say API but it's just about this single method):
This API has no effect. It has been maintained for compatibility
purpose.
For compatibility purposes, I would also like to document this method in the definitions file. But if possible, I would like to communicate somehow, that it has been deprecated.
While my current issue is only about deprecation in a definitions file, I would also like to use this feature in other code. So the question is more general: How can I mark something as deprecated in typescript?
",https://stackoverflow.com/questions/60755711/is-it-possible-to-mark-something-as-deprecated-in-typescript,294,164409.0,1.0,,,2020-03-19 10:53:58,2024-05-15 19:15:59,2021-06-28 09:31:59,,,typescript;deprecated;deprecation-warning;typescript-definitions,lhk,30846,497600,registered,true,62991642,,CC BY-SA 4.0,,695,642,0,0,0,4,true,false,false,true,true,true,61,10,true,0.006,0.0018,2438,2020,3,10,Thursday,false,false,false,false,false,false,false
39040108,Import class in definition file (*d.ts),"I want to extend Express Session typings to allow use my custom data in session storage. I have an object req.session.user which is an instance of my class User:
export class User {
public login: string;
public hashedPassword: string;
constructor(login?: string, password?: string) {
this.login = login || """" ;
this.hashedPassword = password ? UserHelper.hashPassword(password) : """";
}
}
So i created my own.d.ts file to merge definition with existing express session typings:
import { User } from ""./models/user"";
declare module Express {
export interface Session {
user: User;
}
}
But it's not working at all - VS Code and tsc don't see it. So I created test definition with simple type:
declare module Express {
export interface Session {
test: string;
}
}
And the test field is working ok, so the import cause problem.
I also tried to add /// <reference path='models/user.ts'/> instead import but the tsc didn't see the User class - how can I use my own class in *d.ts file?
EDIT:
I set tsc to generate definition files on compile and now I have my user.d.ts:
export declare class User {
login: string;
hashedPassword: string;
constructor();
constructor(login: string, password: string);
}
And the own typing file for extending Express Sesion:
import { User } from ""./models/user"";
declare module Express {
export interface Session {
user: User;
uuid: string;
}
}
But still not working when import statement on top. Any ideas?
",https://stackoverflow.com/questions/39040108/import-class-in-definition-file-d-ts,292,210484.0,6.0,,,2016-08-19 13:18:45,2021-07-18 06:50:23,2016-08-20 11:34:38,,,typescript;typescript-typings,Michał Lytek,12337,5472617,registered,true,51114250,,CC BY-SA 3.0,,1805,1560,9,0,0,2,true,false,false,true,true,true,39,6,false,0.029,0.0014,3746,2016,8,13,Friday,false,false,false,false,false,false,false
64933543,Parsing error: Cannot read file '.../tsconfig.json'.eslint,"The error Parsing error: Cannot read file '.../tsconfig.json'.eslint shows in all .ts files in the src folder including index.ts.
I have no idea how to set up configs. The issue just shows a red line and makes the file red. However, everything compiles and run fine. The entire Node project was created using the firebase CLI.
tsconfig.json file:
{
"compilerOptions": {
"module": "commonjs",
"noImplicitReturns": true,
"noUnusedLocals": true,
"outDir": "lib",
"sourceMap": true,
"strict": true,
"target": "es2017"
},
"compileOnSave": true,
"include": [
"src"
]
}
.eslintrc.js file:
module.exports = {
env: {
browser: true,
es6: true,
node: true,
},
extends: [
"plugin:import/errors",
"plugin:import/warnings",
"plugin:import/typescript",
],
parser: "@typescript-eslint/parser",
parserOptions: {
project: "tsconfig.json",
sourceType: "module",
},
plugins: [
"@typescript-eslint",
"import",
],
rules: {
"@typescript-eslint/adjacent-overload-signatures": "error",
"@typescript-eslint/no-empty-function": "error",
"@typescript-eslint/no-empty-interface": "warn",
"@typescript-eslint/no-floating-promises": "error",
"@typescript-eslint/no-namespace": "error",
"@typescript-eslint/no-unnecessary-type-assertion": "error",
"@typescript-eslint/prefer-for-of": "warn",
"@typescript-eslint/triple-slash-reference": "error",
"@typescript-eslint/unified-signatures": "warn",
"comma-dangle": "warn",
"constructor-super": "error",
eqeqeq: ["warn", "always"],
"import/no-deprecated": "warn",
"import/no-extraneous-dependencies": "error",
"import/no-unassigned-import": "warn",
"no-cond-assign": "error",
"no-duplicate-case": "error",
"no-duplicate-imports": "error",
"no-empty": [
"error",
{
allowEmptyCatch: true,
},
],
"no-invalid-this": "error",
"no-new-wrappers": "error",
"no-param-reassign": "error",
"no-redeclare": "error",
"no-sequences": "error",
"no-shadow": [
"error",
{
hoist: "all",
},
],
"no-throw-literal": "error",
"no-unsafe-finally": "error",
"no-unused-labels": "error",
"no-var": "warn",
"no-void": "error",
"prefer-const": "warn",
},
settings: {
jsdoc: {
tagNamePreference: {
returns: "return",
},
},
},
};
I had tried restarting VScode, clearing the cache, and all to no avail. I am guessing I need to change some of the paths but I am not very good at changing the config files so I don't want to accidentally break the entire project.
",https://stackoverflow.com/questions/64933543/parsing-error-cannot-read-file-tsconfig-json-eslint,292,234987.0,16.0,,,2020-11-20 16:51:35,2025-07-12 16:18:33,2020-12-25 02:15:05,,,node.js;typescript;eslint;typescript-eslint,Darren Zou,3863,5632931,registered,true,64940811,,CC BY-SA 4.0,,3764,3527,8,0,0,4,true,false,false,true,true,true,66,6,false,0.068,0.0012,2192,2020,11,16,Friday,false,false,false,false,false,false,false
43100718,TypeScript enum to object array,"I have an enum defined this way:
export enum GoalProgressMeasurements {
Percentage = 1,
Numeric_Target = 2,
Completed_Tasks = 3,
Average_Milestone_Progress = 4,
Not_Measured = 5
}
However, I'd like it to be represented as an object array/list from our API like below:
[{id: 1, name: 'Percentage'},
{id: 2, name: 'Numeric Target'},
{id: 3, name: 'Completed Tasks'},
{id: 4, name: 'Average Milestone Progress'},
{id: 5, name: 'Not Measured'}]
Is there are easy and native way to do this or do I have to build a function that casts the enum to both an int and a string, and build the objects into an array?
",https://stackoverflow.com/questions/43100718/typescript-enum-to-object-array,292,569093.0,33.0,,,2017-03-29 17:53:31,2025-07-31 02:50:37,,,,javascript;arrays;typescript;enums;casting,AnimaSola,7974,940257,registered,true,,,CC BY-SA 3.0,,704,635,2,0,0,5,false,false,false,true,true,false,31,5,false,0.058,0.0005,3524,2017,3,17,Wednesday,false,false,true,false,false,false,false
13252225,Call a global variable inside module,"I have a typescript file called Projects.ts that I want to reference a global variable declared in a bootstrap plugin called bootbox.js.
I want to access a variable called bootbox from within a TypeScript classes.
Is it possible?
",https://stackoverflow.com/questions/13252225/call-a-global-variable-inside-module,290,177070.0,7.0,,,2012-11-06 13:37:47,2021-06-29 20:30:46,2019-09-20 20:19:49,,,typescript,user1027303,2965,1027303,registered,true,,,CC BY-SA 4.0,,292,232,3,0,0,1,false,false,false,true,true,true,36,6,false,0.04,0.0016,5128,2012,11,13,Tuesday,false,false,false,false,false,false,false
13204759,TypeScript or JavaScript type casting,"How does one handle type casting in TypeScript or Javascript?
Say I have the following TypeScript code:
module Symbology {
export class SymbolFactory {
createStyle( symbolInfo : SymbolInfo) : any {
if (symbolInfo == null)
{
return null;
}
if (symbolInfo.symbolShapeType === ""marker"") {
// how to cast to MarkerSymbolInfo
return this.createMarkerStyle((MarkerSymbolInfo) symbolInfo);
}
}
createMarkerStyle(markerSymbol : MarkerSymbolInfo ): any {
throw ""createMarkerStyle not implemented"";
}
}
}
where SymbolInfo is a base class. How do I handle typecasting from SymbolInfo to MarkerSymbolInfo in TypeScript or Javascript?
",https://stackoverflow.com/questions/13204759/typescript-or-javascript-type-casting,287,445959.0,3.0,,,2012-11-03 00:17:05,2021-09-13 07:01:18,2014-01-28 10:56:14,,,casting;typescript,Klaus Nji,19027,187279,registered,true,13206433,,CC BY-SA 3.0,,948,864,4,0,0,2,true,false,false,true,true,true,37,5,false,0.007,0.0006,5131,2012,11,0,Saturday,true,false,false,false,false,false,false
41944650,'this' implicitly has type 'any' because it does not have a type annotation,"When I enable noImplicitThis in tsconfig.json, I get this error for the following code:
'this' implicitly has type 'any' because it does not have a type
annotation.
class Foo implements EventEmitter {
on(name: string, fn: Function) { }
emit(name: string) { }
}
const foo = new Foo();
foo.on('error', function(err: any) {
console.log(err);
this.emit('end'); // error: `this` implicitly has type `any`
});
A workaround is to replace this with the object:
foo.on('error', (err: any) => {
console.log(err);
foo.emit('end');
});
But what is the proper fix for this error?
",https://stackoverflow.com/questions/41944650/this-implicitly-has-type-any-because-it-does-not-have-a-type-annotation,286,362779.0,7.0,,,2017-01-30 20:16:19,2026-04-09 16:22:08,2026-04-09 16:22:08,,,typescript;typescript2.0,tony19,140399,6277151,registered,true,41945742,,CC BY-SA 4.0,,728,588,5,0,0,2,true,false,false,true,true,true,91,13,false,0.019,0.0008,3582,2017,1,20,Monday,false,false,false,false,false,false,false
40510611,typescript interface require one of two properties to exist,"I'm trying to create an interface that could have
export interface MenuItem {
title: string;
component?: any;
click?: any;
icon: string;
}
- Is there a way to require
component or click to be set
- Is there a way to require that both properties can't be set?
",https://stackoverflow.com/questions/40510611/typescript-interface-require-one-of-two-properties-to-exist,285,218504.0,11.0,,,2016-11-09 15:32:21,2025-12-24 17:32:25,,,,typescript,Nix,58915,256793,registered,true,40510700,,CC BY-SA 3.0,,354,270,3,0,0,1,true,false,false,true,true,false,59,9,false,0.05,0.0013,3664,2016,11,15,Wednesday,false,false,false,false,false,false,false
36108110,TypeScript for ... of with index / key?,"As described here TypeScript introduces a foreach loop:
var someArray = [9, 2, 5];
for (var item of someArray) {
console.log(item); // 9,2,5
}
But isn't there any index/key? I would expect something like:
for (var item, key of someArray) { ... }
",https://stackoverflow.com/questions/36108110/typescript-for-of-with-index-key,285,532283.0,5.0,,,2016-03-19 22:43:40,2024-06-20 01:08:10,2023-01-25 12:52:09,,,for-loop;foreach;typescript,Mick,9141,5688490,registered,true,36108402,,CC BY-SA 4.0,,431,252,2,1,0,3,true,false,false,true,true,true,39,8,true,0.009,0.0005,3899,2016,3,22,Saturday,true,false,false,false,false,false,false
13137350,Defining TypeScript callback type,"I've got the following class in TypeScript:
class CallbackTest
{
public myCallback;
public doWork(): void
{
//doing some work...
this.myCallback(); //calling callback
}
}
I am using the class like this:
var test = new CallbackTest();
test.myCallback = () => alert(""done"");
test.doWork();
The code works, so it displays a messagebox as expected.
My question is: Is there any type I can provide for my class field myCallback? Right now, the public field myCallback is of type any as shown above. How can I define the method signature of the callback? Or can I just set the type to some kind of callback-type? Or can I do nether of these? Do I have to use any (implicit/explicit)?
I tried something like this, but it did not work (compile-time error):
public myCallback: ();
// or:
public myCallback: function;
I couldn't find any explanation to this online, so I hope you can help me.
",https://stackoverflow.com/questions/13137350/defining-typescript-callback-type,285,417664.0,12.0,,,2012-10-30 10:46:20,2024-10-13 07:02:54,,,,types;callback;typescript,nikeee,10914,785210,registered,true,13137431,,CC BY-SA 3.0,,1096,930,7,0,0,3,true,false,false,true,true,false,33,4,false,0.029,0.0007,5135,2012,10,10,Tuesday,false,false,false,false,false,false,false
41139763,How to declare a fixed length array in TypeScript?,"When you make a type declaration for an array like this:
position: Array<number>;
it will let you make an array with arbitrary length. However, if you want an array containing numbers with a specific length, e.g. 3 for x, y, z components. Can you make a type with for a fixed length array, something like this?
position: Array<3>
",https://stackoverflow.com/questions/41139763/how-to-declare-a-fixed-length-array-in-typescript,285,345596.0,8.0,,,2016-12-14 10:04:19,2025-02-19 14:38:19,2025-02-02 17:14:02,,,typescript,henryJack,4734,6782278,registered,true,41140074,,CC BY-SA 4.0,,406,344,2,0,0,1,true,false,false,true,true,true,50,9,true,0.023,0.0008,3629,2016,12,10,Wednesday,false,false,false,false,false,false,false
40983055,How to reload the current route with the angular 2 router,"I am using angular 2 with hashlocation strategy.
The component is loaded with that route:
"departments/:id/employees"
So far fine.
After I do a successful batch save of multiple edited table rows I want to reload the current route URL via:
this.router.navigate([`departments/${this.id}/employees`]);
But nothing happens, why?
",https://stackoverflow.com/questions/40983055/how-to-reload-the-current-route-with-the-angular-2-router,283,623785.0,37.0,,,2016-12-05 20:48:15,2024-03-20 09:43:18,2020-12-21 12:07:44,,,angular;typescript,Pascal,12971,401643,registered,true,40983262,,CC BY-SA 4.0,,508,338,3,0,0,2,true,false,false,true,true,true,57,11,false,0.059,0.0005,3638,2016,12,20,Monday,false,false,false,false,false,false,false
40214655,Angular 2 Checkbox Two Way Data Binding,"I´m fairly new to Angular2 and I have a little problem:
In my Login-Component-HTML, I have two checkboxes, which I want to bind in two way data-binding to the Login-Component-TypeScript.
This is the HTML:
<div class=""checkbox"">
<label>
<input #saveUsername [(ngModel)]=""saveUsername.selected"" type=""checkbox"" data-toggle=""toggle"">Save username
</label>
</div>
And this is the Component.ts:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Variables } from '../../services/variables';
@Component({
selector: 'login',
moduleId: module.id,
templateUrl: 'login.component.html',
styleUrls: ['login.component.css']
})
export class LoginComponent implements OnInit {
private saveUsername: boolean = true;
private autoLogin: boolean = true;
constructor(private router: Router, private variables: Variables) { }
ngOnInit() {
this.loginValid = false;
// Get user name from local storage if you want to save
if (window.localStorage.getItem(""username"") === null) {
this.saveUsername = true;
this.autoLogin = true;
console.log(this.saveUsername, this.autoLogin);
} else {
console.log(""init"", window.localStorage.getItem(""username""));
}
}
login(username: string, password: string, saveUsername: boolean, autoLogin: boolean) {
this.variables.setUsername(username);
this.variables.setPassword(password);
this.variables.setIsLoggedIn(true);
console.log(saveUsername, autoLogin);
//this.router.navigate(['dashboard']);
}
If I click an checkbox, I get the correct value in the controller (component).
But if I change the value of for example saveUsername in the component, the checkbox didn't ""get"" the new value.
So I can´t manipulate the checkbox from the Component (like I want to do in the ngOnInit in the component.
Thanks for your help!
",https://stackoverflow.com/questions/40214655/angular-2-checkbox-two-way-data-binding,283,604597.0,15.0,,,2016-10-24 09:12:53,2022-05-09 20:12:10,2018-12-26 00:40:35,,,html;angular;typescript;checkbox;data-binding,Junias,3127,5974174,registered,true,40214714,,CC BY-SA 4.0,,2190,2026,4,0,0,5,true,false,false,true,true,true,39,7,false,0.025,0.0005,3680,2016,10,9,Monday,false,false,false,false,false,false,false
50448272,Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true,"I have a database wrapper class that establishes a connection to some MongoDB instance:
async connect(connectionString: string): Promise<void> {
this.client = await MongoClient.connect(connectionString)
this.db = this.client.db()
}
This gave me a warning:
(node:4833) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
The connect() method accepts a MongoClientOptions instance as second argument. But it doesn't have a property called useNewUrlParser. I also tried to set those property in the connection string like this: mongodb://127.0.0.1/my-db?useNewUrlParser=true but it has no effect on those warning.
So how can I set useNewUrlParser to remove those warning? This is important to me since the script should run as cron and those warnings result in trash-mail spam.
I'm using mongodb driver in version 3.1.0-beta4 with corresponding @types/mongodb package in 3.0.18. Both of them are the latest avaliable using npm install.
Workaround
Using an older version of mongodb driver:
""mongodb"": ""~3.0.8"",
""@types/mongodb"": ""~3.0.18""
",https://stackoverflow.com/questions/50448272/avoid-current-url-string-parser-is-deprecated-warning-by-setting-usenewurlpars,282,356785.0,22.0,,,2018-05-21 11:50:41,2021-05-11 15:08:20,2019-03-07 21:38:28,,,node.js;mongodb;typescript;express;mongoose,Lion,18223,3276634,registered,true,,,CC BY-SA 4.0,2018-08-31 20:53:25,1470,1209,12,0,0,5,false,false,false,true,true,true,100,13,false,0.062,0.0008,3106,2018,5,11,Monday,false,false,false,false,false,false,false
34907682,How to display the app version in Angular?,"How do I display the app version in Angular application? The version should be taken from package.json file.
{
"name": "angular-app",
"version": "0.0.1",
...
}
In Angular 1.x, I have this html:
<p><%=version %></p>
In Angular, this is not rendered as version number, but instead just printed as it is (<%=version %> instead of 0.0.1).
",https://stackoverflow.com/questions/34907682/how-to-display-the-app-version-in-angular,282,200829.0,18.0,,,2016-01-20 18:25:43,2025-11-04 17:12:56,2023-01-24 17:41:24,,,angular;typescript;ionic-framework;version;package.json,Zbynek,5985,2882245,registered,true,48869478,,CC BY-SA 4.0,,515,407,5,0,0,5,true,false,false,true,true,true,42,8,true,0.09,0.0014,3958,2016,1,18,Wednesday,false,false,false,false,false,false,false
40649799,Create component & add it to a specific module with Angular-CLI,"I'm starting to use angular-cli and I've already read a lot to find an answer about what I want to do...no success, so I came here.
Is there a way to create a component to a new module?
e.g.: ng g module newModule
ng g component newComponent (how to add this component to newModule??)
because the angular-cli default behavior is to put all new components inside app.module. I would like to choose where my component will be, so that I can create separated modules and won't have all my components inside app.module . It is possible to do that using angular-cli or do I have to do this manually?
",https://stackoverflow.com/questions/40649799/create-component-add-it-to-a-specific-module-with-angular-cli,280,515980.0,37.0,,,2016-11-17 08:20:23,2024-10-21 09:36:48,2021-04-14 09:51:24,,,angular;typescript;angular-cli,Elmer Dantas,4889,4335507,registered,true,40649834,,CC BY-SA 4.0,2021-11-09 12:06:53,687,600,4,0,0,3,true,false,false,true,true,true,67,11,false,0.072,0.0005,3656,2016,11,8,Thursday,false,false,false,false,false,false,false
56577201,Why is --isolatedModules error fixed by any import?,"In a create-react-app typescript project, I tried to write this just to test some stuff quickly:
// experiment.test.ts
it('experiment', () => {
console.log('test');
});
But it gives me the following error, with a red squiggly beneath it:
All files must be modules when the '--isolatedModules' flag is provided.
However, if I change the file to the following, then everything apparently is fine (except for the unused import of course):
// experiment.test.ts
import { Component} from 'react'; // literally anything, don't even have to use it
it('test', () => {
console.log('test');
});
Why? What is happening here? What does --isolatedModules actually mean/do?
",https://stackoverflow.com/questions/56577201/why-is-isolatedmodules-error-fixed-by-any-import,280,284637.0,10.0,,,2019-06-13 09:15:42,2025-08-14 16:45:46,2019-06-13 09:19:36,,,typescript,Svish,159695,39321,registered,true,56577324,,CC BY-SA 4.0,,891,683,4,0,0,1,true,false,false,true,true,true,51,8,true,0.035,0.001,2718,2019,6,9,Thursday,false,false,false,false,false,false,false
31322525,Confusing "duplicate identifier" Typescript error message,"Why am I getting this and many more errors of this kind? I am adding a link to the repo as well as key code snippets below. I think I have a basic misunderstanding of how the dependency and ""include"" chaining works.
csvproc(master)> tsc
node_modules/typescript/bin/lib.core.d.ts(83,5): error TS2300: Duplicate identifier 'configurable'.
node_modules/typescript/bin/lib.core.d.ts(84,5): error TS2300: Duplicate identifier 'enumerable'.
node_modules/typescript/bin/lib.core.d.ts(85,5): error TS2300: Duplicate identifier 'value'.
node_modules/typescript/bin/lib.core.d.ts(86,5): error TS2300: Duplicate identifier 'writable'.
My tsconfig.json:
{
""compilerOptions"": {
""module"": ""commonjs"",
""noImplicitAny"": false,
""outDir"": ""built/"",
""sourceMap"": true,
""target"": ""es5""
}
}
My tsd.json:
{
""version"": ""v4"",
""repo"": ""borisyankov/DefinitelyTyped"",
""ref"": ""master"",
""path"": ""typings"",
""bundle"": ""typings/tsd.d.ts"",
""installed"": {
""node/node-0.10.d.ts"": {
""commit"": ""6387999eb899d0ba02d37dd8697647718caca230""
},
""should/should.d.ts"": {
""commit"": ""e1182d56ccb192379eade6055d9ba3fb6a0bacc4""
}
}
}
My tsd.d.ts:
{
""version"": ""v4"",
""repo"": ""borisyankov/DefinitelyTyped"",
""ref"": ""master"",
""path"": ""typings"",
""bundle"": ""typings/tsd.d.ts"",
""installed"": {
""node/node-0.10.d.ts"": {
""commit"": ""6387999eb899d0ba02d37dd8697647718caca230""
},
""should/should.d.ts"": {
""commit"": ""e1182d56ccb192379eade6055d9ba3fb6a0bacc4""
}
}
}
",https://stackoverflow.com/questions/31322525/confusing-duplicate-identifier-typescript-error-message,278,391382.0,22.0,,,2015-07-09 15:54:49,2024-08-30 14:03:52,2017-12-29 23:45:34,,,typescript,pitosalas,11068,359219,registered,true,31330272,,CC BY-SA 3.0,2017-07-31 00:11:30,1800,1578,4,1,0,1,true,false,false,true,true,true,67,6,false,0.056,0.0007,4153,2015,7,15,Thursday,false,false,false,false,false,false,false
37688318,Typescript Interface - Possible to make "one or the other" properties required?,"Possibly an odd question, but I'm curious if it's possible to make an interface where one property or the other is required.
So, for example...
interface Message {
text: string;
attachment: Attachment;
timestamp?: number;
// ...etc
}
interface Attachment {...}
In the above case, I'd like to make sure that either text or attachment exists.
This is how I'm doing it right now. Thought it was a bit verbose (typing botkit for slack).
interface Message {
type?: string;
channel?: string;
user?: string;
text?: string;
attachments?: Slack.Attachment[];
ts?: string;
team?: string;
event?: string;
match?: [string, {index: number}, {input: string}];
}
interface AttachmentMessageNoContext extends Message {
channel: string;
attachments: Slack.Attachment[];
}
interface TextMessageNoContext extends Message {
channel: string;
text: string;
}
",https://stackoverflow.com/questions/37688318/typescript-interface-possible-to-make-one-or-the-other-properties-required,276,209029.0,14.0,,,2016-06-07 20:03:46,2023-12-24 12:02:44,2022-01-04 12:48:27,,,typescript,dsifford,3249,3990593,registered,true,37688375,,CC BY-SA 4.0,,1019,911,4,0,0,1,true,false,false,true,true,true,89,12,true,0.067,0.0013,3819,2016,6,20,Tuesday,false,false,false,false,false,false,false
52856496,TypeScript: Object.keys return string[],"When using Object.keys(obj), the return value is a string[], whereas I want a (keyof obj)[].
const v = {
a: 1,
b: 2
}
Object.keys(v).reduce((accumulator, current) => {
accumulator.push(v[current]);
return accumulator;
}, []);
I have the error:
Element implicitly has an 'any' type because type '{ a: number; b: number; }' has no index signature.
TypeScript 3.1 with strict: true. Playground: here, please check all checkboxes in Options to activate strict: true.
",https://stackoverflow.com/questions/52856496/typescript-object-keys-return-string,275,268469.0,10.0,,,2018-10-17 13:48:15,2026-02-23 17:05:52,,,,typescript,jeanpaul62,10781,1935318,registered,true,52856805,,CC BY-SA 4.0,,1004,492,7,1,0,1,true,false,false,true,true,false,39,4,false,0.037,0.001,2957,2018,10,13,Wednesday,false,false,false,false,false,false,false
38548407,Return an empty Observable,"The function more() is supposed to return an Observable from a get request
export class Collection {
public more = (): Observable<Response> => {
if (this.hasMore()) {
return this.fetch();
} else {
// return empty observable
}
};
private fetch = (): Observable<Response> => {
return this.http.get("some-url").map((res) => {
return res.json();
});
};
}
In this case I can only do a request if hasMore() is true, else I get an error on subscribe() function subscribe is not defined, how can I return an empty Observable?
this.collection.more().subscribe(
(res) => {
console.log(res);
}, (err) => {
console.log(err);
}
);
",https://stackoverflow.com/questions/38548407/return-an-empty-observable,274,312879.0,15.0,,,2016-07-24 03:17:31,2022-08-31 12:20:25,2021-12-23 11:38:52,,,javascript;typescript;rxjs;observable,Murhaf Sousli,13442,1015648,registered,true,70465373,,CC BY-SA 4.0,,919,718,7,0,0,4,true,false,false,true,true,true,26,4,false,0.048,0.0009,3772,2016,7,3,Sunday,true,false,true,false,false,false,false
38744159,How to define the type of an async function?,"I tried to define a type of async function, but failed in compilation, see below:
interface SearchFn {
async (subString: string): string;
}
class A {
private Fn: SearchFn
public async do():Promise<string> {
await this.Fn(""fds"") // complain here: cannot invoke an expression whose type lacks a call signature
return ''
}
}
Can anyone help me work this out?
",https://stackoverflow.com/questions/38744159/how-to-define-the-type-of-an-async-function,274,273725.0,4.0,,,2016-08-03 12:48:21,2025-11-04 13:12:50,2025-11-04 13:12:50,,,typescript,Ron,6855,1241464,registered,true,43453106,,CC BY-SA 4.0,,436,398,1,0,0,1,true,false,false,true,true,true,44,9,true,0.015,0.001,3762,2016,8,12,Wednesday,false,false,false,false,false,false,false
63702057,What is the logic behind the TypeScript error "The operand of a 'delete' operator must be optional"?,"This is the new error that is coming in typescript code.
I am not able to realize the logic behind it
Documentation
/*When using the delete operator in strictNullChecks,
the operand must now be any, unknown, never, or be optional
(in that it contains undefined in the type). Otherwise, use of the delete operator is an error.*/
interface Thing {
prop: string;
}
function f(x: Thing) {
delete x.prop; // throws error = The operand of a 'delete' operator must be optional.
}
",https://stackoverflow.com/questions/63702057/what-is-the-logic-behind-the-typescript-error-the-operand-of-a-delete-operato,274,298251.0,8.0,,,2020-09-02 08:54:31,2026-04-27 11:14:17,2021-07-27 17:50:26,,,javascript;typescript,Akshay Vijay Jain,16397,2761641,registered,true,63705211,,CC BY-SA 4.0,,672,482,1,1,0,2,true,false,false,true,true,true,118,17,true,0.027,0.0009,2271,2020,9,8,Wednesday,false,false,true,false,false,false,false
52432191,Auto import in Visual Studio Code only offering absolute path with Lerna subpackages in TypeScript,"For some reason, very recently my Visual Studio Code changed and started only offering absolute imports from the sub-package level with my Lerna packages, for example:
As you can see, the auto import is suggesting the @package/server/src/database path to the file when it should just be ../database as the file being edited is within the same package and is just one folder below the file containing the database variable I'm trying to use.
Is this a bug or configuration issue?
I've set my Import Module Specifiersetting for TypeScript in Visual Studio Code to all three options (auto, relative, and absolute) and none of them seem to make any difference.
",https://stackoverflow.com/questions/52432191/auto-import-in-visual-studio-code-only-offering-absolute-path-with-lerna-subpack,273,169610.0,6.0,,,2018-09-20 19:41:19,2024-11-13 08:27:02,2020-08-12 23:48:03,,,typescript;vs-code;auto-import,Anupheaus,3841,395658,registered,true,53137571,,CC BY-SA 4.0,,875,658,3,1,1,3,true,false,false,true,true,true,98,15,false,0.035,0.0016,2984,2018,9,19,Thursday,false,false,false,false,false,false,false
40382842,Can't import CSS/SCSS modules. TypeScript says "Cannot Find Module","I'm trying to import a theme from a CSS module but TypeScript gives me a ""Cannot Find Module"" error and the theme isn't applied on runtime. I think there's something wrong with my Webpack config but I'm not sure where the problem is.
I'm using the following tools:
""typescript"": ""^2.0.3""
""webpack"": ""2.1.0-beta.25""
""webpack-dev-server"": ""^2.1.0-beta.9""
""react"": ""^15.4.0-rc.4""
""react-toolbox"": ""^1.2.3""
""node-sass"": ""^3.10.1""
""style-loader"": ""^0.13.1""
""css-loader"": ""^0.25.0""
""sass-loader"": ""^4.0.2""
""sass-lint"": ""^1.9.1""
""sasslint-webpack-plugin"": ""^1.0.4""
Here is my webpack.config.js
var path = require('path');
var webpack = require('webpack');
var sassLintPlugin = require('sasslint-webpack-plugin');
module.exports = {
entry: [
'webpack-dev-server/client?http://localhost:8080',
'webpack/hot/dev-server',
'./src/index.tsx',
],
output: {
path: path.resolve(__dirname, 'dist'),
publicPath: 'http://localhost:8080/',
filename: 'dist/bundle.js',
},
devtool: 'source-map',
resolve: {
extensions: ['.webpack.js', '.web.js', '.ts', '.tsx', '.js'],
},
module: {
rules: [{
test: /\.js$/,
loader: 'source-map-loader',
exclude: /node_modules/,
enforce: 'pre',
}, {
test: /\.tsx?$/,
loader: 'tslint-loader',
exclude: /node_modules/,
enforce: 'pre',
}, {
test: /\.tsx?$/,
loaders: [
'react-hot-loader/webpack',
'awesome-typescript-loader',
],
exclude: /node_modules/,
}, {
test: /\.scss$/,
loaders: ['style', 'css', 'sass']
}, {
test: /\.css$/,
loaders: ['style', 'css']
}],
},
externals: {
'react': 'React',
'react-dom': 'ReactDOM'
},
plugins: [
new sassLintPlugin({
glob: 'src/**/*.s?(a|c)ss',
ignoreFiles: ['src/normalize.scss'],
failOnWarning: false, // Do it.
}),
new webpack.HotModuleReplacementPlugin(),
],
devServer: {
contentBase: './'
},
};
and my App.tsx where I'm trying to import:
import * as React from 'react';
import { AppBar } from 'react-toolbox';
import appBarTheme from 'react-toolbox/components/app_bar/theme.scss'
// local ./theme.scss stylesheets aren't found either
interface IAppStateProps {
// No props yet
}
interface IAppDispatchProps {
// No state yet
}
class App extends React.Component<IAppStateProps & IAppDispatchProps, any> {
constructor(props: IAppStateProps & IAppDispatchProps) {
super(props);
}
public render() {
return (
<div className='wrapper'>
<AppBar title='My App Bar' theme={appBarTheme}>
</AppBar>
</div>
);
}
}
export default App;
What else is required to enable typesafe stylesheet module importing?
",https://stackoverflow.com/questions/40382842/cant-import-css-scss-modules-typescript-says-cannot-find-module,273,441884.0,29.0,,,2016-11-02 14:45:40,2026-02-23 07:26:06,,,,typescript;import;sass;webpack;css-modules,zakdances,24203,697190,registered,true,,,CC BY-SA 3.0,,2929,2796,5,0,0,5,false,false,false,true,true,false,81,9,false,0.066,0.0006,3671,2016,11,14,Wednesday,false,false,false,false,false,false,false
35138424,How do I download a file with Angular2 or greater,"I have a WebApi / MVC app for which I am developing an angular2 client (to replace MVC). I am having some troubles understanding how Angular saves a file.
The request is ok (works fine with MVC, and we can log the data received) but I can't figure out how to save the downloaded data (I am mostly following the same logic as in this post). I am sure it is stupidly simple, but so far I am simply not grasping it.
The code of the component function is below. I've tried different alternatives, the blob way should be the way to go as far as I understood, but there is no function createObjectURL in URL. I can't even find the definition of URL in window, but apparently it exists. If I use the FileSaver.js module I get the same error. So I guess this is something that changed recently or is not yet implemented. How can I trigger the file save in A2?
downloadfile(type: string){
let thefile = {};
this.pservice.downloadfile(this.rundata.name, type)
.subscribe(data => thefile = new Blob([data], { type: ""application/octet-stream"" }), //console.log(data),
error => console.log(""Error downloading the file.""),
() => console.log('Completed file download.'));
let url = window.URL.createObjectURL(thefile);
window.open(url);
}
For the sake of completeness, the service that fetches the data is below, but the only thing it does is to issue the request and pass on the data without mapping if it succeeds:
downloadfile(runname: string, type: string){
return this.authHttp.get( this.files_api + this.title +""/""+ runname + ""/?file=""+ type)
.catch(this.logAndPassOn);
}
",https://stackoverflow.com/questions/35138424/how-do-i-download-a-file-with-angular2-or-greater,273,727673.0,32.0,,,2016-02-01 19:15:37,2023-01-23 06:39:36,2020-07-05 10:34:47,,,javascript;angular;typescript;download;fileapi,rll,5615,4974175,registered,true,35210392,,CC BY-SA 4.0,,2072,1662,6,2,0,5,true,false,false,true,true,true,49,10,false,0.044,0.0004,3946,2016,2,19,Monday,false,false,true,false,false,false,false
48011353,How to unwrap the type of a Promise?,"Say I have the following code:
async promiseOne() {
return 1
} // => Promise<number>
const promisedOne = promiseOne()
typeof promisedOne // => Promised<number>
How would I go about extracting the type of the promise result (in this simplified case a number) as its own type?
",https://stackoverflow.com/questions/48011353/how-to-unwrap-the-type-of-a-promise,273,130926.0,8.0,,,2017-12-28 16:57:01,2022-08-23 23:33:38,2021-11-10 23:34:45,,,typescript;promise,fny,34103,390897,registered,true,49889856,,CC BY-SA 4.0,,336,298,1,0,0,2,true,false,false,true,true,true,36,8,true,0.061,0.0021,3250,2017,12,16,Thursday,false,false,false,false,false,false,false
35166168,How to use moment.js library in angular 2 typescript app?,"I tried to use it with typescript bindings:
npm install moment --save
typings install moment --ambient -- save
test.ts:
import {moment} from 'moment/moment';
And without:
npm install moment --save
test.ts:
var moment = require('moment/moment');
But when I call moment.format(), I get an error.
Should be simple, can anybody provide a command line/import combination that would work?
",https://stackoverflow.com/questions/35166168/how-to-use-moment-js-library-in-angular-2-typescript-app,272,381393.0,22.0,,,2016-02-03 00:03:11,2023-10-25 16:08:04,2016-02-03 00:04:20,,,typescript;angular,Sergey Aldoukhov,22894,58463,registered,true,43257938,,CC BY-SA 3.0,2018-12-14 14:58:19,526,395,4,0,0,2,true,false,false,true,true,true,57,10,true,0.058,0.0007,3944,2016,2,0,Wednesday,false,false,false,false,false,false,false
55781559,What does the "as" keyword do?,"if (process.env.NODE_ENV !== 'production') {
(WithUser as any).displayName = wrapDisplayName(Component, 'withUser');
}
I'm not even sure if as is a keyword, but anyway, what does it do in JavaScript?
",https://stackoverflow.com/questions/55781559/what-does-the-as-keyword-do,269,352768.0,6.0,,,2019-04-21 09:35:07,2025-10-18 23:37:34,2022-01-27 15:18:40,,,typescript,Henok Tesfaye,9830,8443899,registered,true,55781571,,CC BY-SA 4.0,,286,205,2,0,0,1,true,false,false,true,true,true,40,6,true,0.017,0.0008,2771,2019,4,9,Sunday,true,false,false,false,false,false,false
46703364,"Why does 'instanceof' in TypeScript give me the error "'Foo' only refers to a type, but is being used as a value here."?","I wrote this code
interface Foo {
abcdef: number;
}
let x: Foo | string;
if (x instanceof Foo) {
// ...
}
But TypeScript gave me this error:
'Foo' only refers to a type, but is being used as a value here.
Why is this happening? I thought that instanceof could check whether my value has a given type, but TypeScript seems not to like this.
",https://stackoverflow.com/questions/46703364/why-does-instanceof-in-typescript-give-me-the-error-foo-only-refers-to-a-ty,269,350733.0,6.0,,,2017-10-12 07:01:41,2024-04-17 14:55:40,2017-10-12 07:05:59,,,javascript;typescript;instanceof,Daniel Rosenwasser,24251,4386952,registered,true,46703380,,CC BY-SA 3.0,,438,356,3,0,0,3,true,false,false,true,true,true,146,23,true,0.017,0.0008,3327,2017,10,7,Thursday,false,false,true,false,false,false,false
45251664,Derive union type from tuple/array values,"Say I have an array:
const list = ['a', 'b', 'c']
Is it possible to derive from this value union type that is 'a' | 'b' | 'c'?
I want this because I want to define type which allows only values from static array, and also need to enumerate these values at runtime, so I use array.
Example how it can be implemented with an indexed object:
const indexed = {a: null, b: null, c: null}
const list = Object.keys(index)
type NeededUnionType = keyof typeof indexed
Is it possible to do it without using an indexed map?
",https://stackoverflow.com/questions/45251664/derive-union-type-from-tuple-array-values,265,100087.0,6.0,,,2017-07-22 06:54:51,2023-11-10 09:55:56,2022-10-03 13:04:08,,,typescript,WHITECOLOR,26370,733596,registered,true,45257357,,CC BY-SA 4.0,,611,515,3,0,0,1,true,false,false,true,true,true,41,6,false,0.06,0.0026,3409,2017,7,6,Saturday,true,false,false,false,false,false,false
28900077,Why is Event.target not Element in Typescript?,"I simply want to do this with my KeyboardEvent
var tag = evt.target.tagName.toLowerCase();
While Event.target is of type EventTarget, it does not inherit from Element. So I have to cast it like this:
var tag = (<Element>evt.target).tagName.toLowerCase();
This is probably due to some browsers not following standards, right? What is the correct browser-agnostic implementation in TypeScript?
P.S. I am using jQuery to capture the KeyboardEvent.
",https://stackoverflow.com/questions/28900077/why-is-event-target-not-element-in-typescript,265,309252.0,12.0,,,2015-03-06 13:43:24,2023-06-13 11:43:40,2021-07-12 07:18:04,,,typescript;event-listener,daniel.sedlacek,8739,487771,registered,true,28900856,,CC BY-SA 4.0,,594,453,7,0,0,2,true,false,false,true,true,true,46,7,true,0.039,0.0009,4278,2015,3,13,Friday,false,false,false,false,false,false,false
39419170,How do I check that a switch block is exhaustive in TypeScript?,"I have some code:
enum Color {
Red,
Green,
Blue
}
function getColorName(c: Color): string {
switch(c) {
case Color.Red:
return 'red';
case Color.Green:
return 'green';
// Forgot about Blue
}
throw new Error('Did not expect to be here');
}
I forgot to handle the Color.Blue case and I'd prefer to have gotten a compile error. How can I structure my code such that TypeScript flags this as an error?
",https://stackoverflow.com/questions/39419170/how-do-i-check-that-a-switch-block-is-exhaustive-in-typescript,263,119429.0,17.0,,,2016-09-09 20:21:18,2026-08-06 17:28:35,,,,typescript,Ryan Cavanaugh,223506,1704166,registered,true,39419171,,CC BY-SA 3.0,,526,475,2,0,0,1,true,false,false,true,true,false,63,12,true,0.142,0.0022,3725,2016,9,20,Friday,false,false,false,false,false,false,false
14980014,How can I calculate the time between 2 Dates in typescript,"This works in Javascript
new Date() - new Date("2013-02-20T12:01:04.753Z")
But in typescript I can't rest two new Dates
Date("2013-02-20T12:01:04.753Z")
Don't work because paremater not match date signature
",https://stackoverflow.com/questions/14980014/how-can-i-calculate-the-time-between-2-dates-in-typescript,263,263476.0,6.0,,,2013-02-20 12:35:25,2023-01-23 22:10:36,2021-07-30 02:39:33,,,date;typescript,user2025288,2671,2025288,registered,true,,,CC BY-SA 4.0,,298,229,2,0,0,2,false,false,false,true,true,true,58,11,false,0.023,0.001,5022,2013,2,12,Wednesday,false,false,false,false,false,false,false
21687907,TypeScript sorting an array,"I've been trying to figure out a very strange issue I ran into with typescript. It was treating an inline Boolean expression as whatever the first value's type was instead of the complete expression.
So if you try something simple like the following:
var numericArray:Array<number> = [2,3,4,1,5,8,11];
var sorrtedArray:Array<number> = numericArray.sort((n1,n2)=> n1 > n2);
You will get an error on your sort method saying the parameters do not match any signature of the call target, because your result is numeric and not Boolean. I guess I'm missing something though cause I'm pretty sure n1>n2 is a Boolean statement.
",https://stackoverflow.com/questions/21687907/typescript-sorting-an-array,262,655601.0,9.0,,,2014-02-10 21:06:28,2023-06-20 17:49:52,,,,typescript,Kent Cooper,4559,2725843,registered,true,21687953,,CC BY-SA 3.0,,955,651,1,1,0,1,true,false,false,true,true,false,27,4,false,0.014,0.0004,4667,2014,2,21,Monday,false,false,false,false,false,false,false
39494689,Is it possible to restrict number to a certain range,"Since typescript 2.0 RC (or even beta?) it is possible to use number literal types, as in type t = 1 | 2;. Is it possible to restrict a type to a number range, e.g. 0-255, without writing out 256 numbers in the type?
In my case, a library accepts color values for a palette from 0-255, and I'd prefer to only name a few but restrict it to 0-255:
const enum paletteColor {
someColor = 25,
someOtherColor = 133
}
declare function libraryFunc(color: paletteColor | 0-255); //would need to use 0|1|2|...
",https://stackoverflow.com/questions/39494689/is-it-possible-to-restrict-number-to-a-certain-range,262,217428.0,20.0,,,2016-09-14 15:45:44,2024-11-25 23:32:30,,,,typescript;types,ASDFGerte,5264,6692606,registered,true,39495173,,CC BY-SA 3.0,,558,507,2,0,0,2,true,false,false,true,true,false,52,10,false,0.092,0.0012,3720,2016,9,15,Wednesday,false,false,false,false,false,false,false
51528780,Typescript: Check "typeof" against custom type,"I have a custom type, let's say
export type Fruit = ""apple"" | ""banana"" | ""grape"";
I would like to determine if a string is part of the Fruit type. How can I accomplish this?
The following doesn't work.
let myfruit = ""pear"";
if (typeof myfruit === ""Fruit"") {
console.log(""My fruit is of type 'Fruit'"");
}
Any thoughts appreciated!
",https://stackoverflow.com/questions/51528780/typescript-check-typeof-against-custom-type,262,380586.0,3.0,,,2018-07-25 22:57:48,2023-08-15 13:29:19,,,,typescript;types,maia,4468,3005925,registered,true,51529486,,CC BY-SA 4.0,,418,342,2,0,0,2,true,false,false,true,true,false,56,6,false,0.008,0.0007,3041,2018,7,22,Wednesday,false,false,false,false,false,false,false
25469244,How can I define an interface for an array of objects?,"I have the following interface and code. I thought I was doing the definitions correctly but I am getting an error:
interface IenumServiceGetOrderBy { id: number; label: string; key: any }[];
and:
getOrderBy = (entity): IenumServiceGetOrderBy => {
var result: IenumServiceGetOrderBy;
switch (entity) {
case ""content"":
result =
[
{ id: 0, label: 'CId', key: 'contentId' },
{ id: 1, label: 'Modified By', key: 'modifiedBy' },
{ id: 2, label: 'Modified Date', key: 'modified' },
{ id: 3, label: 'Status', key: 'contentStatusId' },
{ id: 4, label: 'Status > Type', key: ['contentStatusId', 'contentTypeId'] },
{ id: 5, label: 'Title', key: 'title' },
{ id: 6, label: 'Type', key: 'contentTypeId' },
{ id: 7, label: 'Type > Status', key: ['contentTypeId', 'contentStatusId'] }
];
break;
}
return result;
};
Error:
Error 190 Cannot convert '{}[]' to 'IenumServiceGetOrderBy':
Type '{}[]' is missing property 'id' from type 'IenumServiceGetOrderBy'
",https://stackoverflow.com/questions/25469244/how-can-i-define-an-interface-for-an-array-of-objects,261,592813.0,17.0,,,2014-08-24 06:53:30,2024-06-18 10:07:17,2021-09-25 09:34:32,,,typescript,user1679941,,,does_not_exist,true,25469668,,CC BY-SA 4.0,,1330,1237,3,0,0,1,true,false,false,true,false,true,54,11,true,0.029,0.0004,4472,2014,8,6,Sunday,true,false,false,false,false,false,false
13333489,Declaring abstract method in TypeScript,"I am trying to figure out how to correctly define abstract methods in TypeScript:
Using the original inheritance example:
class Animal {
constructor(public name) { }
makeSound(input : string) : string;
move(meters) {
alert(this.name + "" moved "" + meters + ""m."");
}
}
class Snake extends Animal {
constructor(name) { super(name); }
makeSound(input : string) : string {
return ""sssss""+input;
}
move() {
alert(""Slithering..."");
super.move(5);
}
}
I would like to know how to correctly define method makeSound, so it is typed and possible to overried.
Also, I am not sure how to define correctly protected methods - it seems to be a keyword, but has no effect and the code won't compile.
",https://stackoverflow.com/questions/13333489/declaring-abstract-method-in-typescript,260,269183.0,5.0,,,2012-11-11 17:18:22,2022-09-22 08:31:23,2022-09-22 08:31:23,,,typescript;abstract-class;abstract,Vojtěch,12584,922584,registered,true,13335645,,CC BY-SA 4.0,,823,758,2,0,0,3,true,false,false,true,true,true,39,5,false,0.019,0.001,5123,2012,11,17,Sunday,true,false,false,false,false,false,false
23948348,Where can I find the TypeScript version installed in Visual Studio?,"Maybe it's obvious, but I checked everywhere (besides the right place) and googled it. Nothing.
",https://stackoverflow.com/questions/23948348/where-can-i-find-the-typescript-version-installed-in-visual-studio,258,427518.0,19.0,,,2014-05-30 06:24:04,2024-06-08 04:11:15,,,,visual-studio;typescript,Adrian Rosca,7542,2147704,registered,true,23948960,,CC BY-SA 3.0,,103,96,0,0,0,2,true,false,false,true,true,false,67,11,true,0.044,0.0006,4558,2014,5,6,Friday,false,false,false,false,false,false,false
57132428,Augmentations for the global scope can only be directly nested in external modules or ambient module declarations(2669),"I would like to store my NodeJS config in the global scope.
I tried to follow this => Extending TypeScript Global object in node.js and other solution on stackoverflow,
I made a file called global.d.ts where I have the following code
declare global {
namespace NodeJS {
interface Global {
config: MyConfigType
}
}
}
Augmentations for the global scope can only be directly nested in
external modules or ambient module declarations.ts(2669)
but doing this works fine =>
declare module NodeJS {
interface Global {
config: MyConfigType
}
}
the problem is, I need to import the file MyConfigType to type the config, but the second option do not allow that.
",https://stackoverflow.com/questions/57132428/augmentations-for-the-global-scope-can-only-be-directly-nested-in-external-modul,257,119839.0,3.0,,,2019-07-21 10:44:58,2023-05-12 05:52:22,2022-08-15 22:14:03,,,node.js;typescript;global,Crocsx,7826,3190532,registered,true,59499895,,CC BY-SA 4.0,,951,718,3,1,0,3,true,false,false,true,true,true,119,17,false,0.025,0.0021,2680,2019,7,10,Sunday,true,false,false,false,false,false,false
43176006,TypeError: Class extends value undefined is not a function or null,"I am getting the following error when trying to create these entities.
TypeError: Class extends value undefined is not a function or null
I am assuming this has something to do with circular dependencies, but how is that supposed to be avoided when using table inheritance and one to many relationships?
It is complaining about the following javascript at BaseComic_1.BaseComic.
let Variant = class Variant extends BaseComic_1.BaseComic {
Here is the complete file.
""use strict"";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === ""object"" && typeof Reflect.decorate === ""function"") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === ""object"" && typeof Reflect.metadata === ""function"") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, ""__esModule"", { value: true });
const typeorm_1 = require(""typeorm"");
const Comic_1 = require(""./Comic"");
const BaseComic_1 = require(""./BaseComic"");
let Variant = class Variant extends BaseComic_1.BaseComic {
};
__decorate([
typeorm_1.ManyToOne(type => Comic_1.Comic, comic => comic.variants),
__metadata(""design:type"", Comic_1.Comic)
], Variant.prototype, ""comic"", void 0);
Variant = __decorate([
typeorm_1.ClassEntityChild()
], Variant);
exports.Variant = Variant;
//# sourceMappingURL=Variant.js.map
import {Entity, Column, PrimaryGeneratedColumn, OneToMany} from ""typeorm"";
import {Comic} from ""./Comic"";
@Entity()
export class Series {
@PrimaryGeneratedColumn()
public id: number;
@Column(""text"", {
length: 30
})
public copyright: string;
@Column(""text"", {
length: 100
})
public attributionText: string;
@Column(""text"", {
length: 150
})
public attributionHTML: string;
@Column(""text"", {
length: 50
})
public etag: string;
@Column(""text"", {
length: 200
})
public title: string;
@Column(""text"")
public description: string;
@Column(""number"", {
length: 4
})
public startYear: number;
@Column(""number"", {
length: 4
})
public endYear: number;
@Column(""text"", {
length: 20
})
public rating: string;
@Column(""text"", {
length: 20
})
public type: string;
@Column(""text"")
public thumbnail: string;
@OneToMany(type => Comic, comic => comic.series)
public comics: Array<Comic>;
}
import {Entity, TableInheritance, PrimaryGeneratedColumn, Column, ManyToOne, DiscriminatorColumn} from ""typeorm"";
import {Series} from ""./Series"";
@Entity()
@TableInheritance(""class-table"")
@DiscriminatorColumn({ name: ""type"", type: ""string""})
export class BaseComic {
@PrimaryGeneratedColumn()
public id: number;
@Column(""text"", {
length: 30
})
public copyright: string;
@Column(""text"", {
length: 100
})
public attributionText: string;
@Column(""text"", {
length: 150
})
public attributionHTML: string;
@Column(""text"", {
length: 50
})
public etag: string;
@Column(""text"", {
length: 200
})
public title: string;
@Column(""int"")
public issue: number;
@Column(""text"")
public variantDescription: string;
@Column(""boolean"")
public variant: boolean;
@Column(""text"")
public description: string;
@Column(""int"")
public pageCount: number;
@Column(""date"")
public onSaleDate: Date;
@Column(""date"")
public unlimitedDate: Date;
@Column(""text"")
public thumbnail: string;
@ManyToOne(type => Series, series => series.comics)
public series: Series;
}
import {OneToMany, ClassEntityChild} from ""typeorm"";
import {Variant} from ""./Variant"";
import {BaseComic} from ""./BaseComic"";
@ClassEntityChild()
export class Comic extends BaseComic {
@OneToMany(type => Variant, variant => variant.comic)
public variants: Variant[];
}
import {ManyToOne, ClassEntityChild} from ""typeorm"";
import {Comic} from ""./Comic"";
import {BaseComic} from ""./BaseComic"";
@ClassEntityChild()
export class Variant extends BaseComic {
@ManyToOne(type => Comic, comic => comic.variants)
public comic: Comic;
}
",https://stackoverflow.com/questions/43176006/typeerror-class-extends-value-undefined-is-not-a-function-or-null,257,391415.0,27.0,,,2017-04-03 03:13:51,2025-03-07 11:00:44,,,,javascript;typescript;typeorm,prolink007,34694,427763,registered,true,44727578,,CC BY-SA 3.0,,5002,4768,8,0,0,3,true,false,false,true,true,false,66,11,false,0.069,0.0007,3519,2017,4,3,Monday,false,false,true,false,false,false,false
37652801,When to use Interface and Model in TypeScript / Angular,"I recently watched a Tutorial on Angular 2 with TypeScript, but unsure when to use an Interface and when to use a Model for data structures.
Example of interface:
export interface IProduct {
ProductNumber: number;
ProductName: string;
ProductDescription: string;
}
Example of Model:
export class Product {
constructor(
public ProductNumber: number,
public ProductName: string,
public ProductDescription: string
){}
}
I want to load a JSON data from a URL and bind to the Interface/Model. Sometime I want a single data object, other time I want to hold an array of the object.
Which one should I use and why?
",https://stackoverflow.com/questions/37652801/when-to-use-interface-and-model-in-typescript-angular,257,202043.0,7.0,,,2016-06-06 08:30:13,2023-12-30 01:48:34,2021-02-14 13:47:03,,,angular;typescript;class;interface,I_LIKE_FOO,2874,2834673,registered,true,37652962,,CC BY-SA 4.0,,737,654,2,0,0,4,true,false,false,true,true,true,55,10,false,0.035,0.0013,3820,2016,6,8,Monday,false,false,false,false,false,false,false
35758584,Cannot redeclare block scoped variable,"I'm building a node app, and inside each file in .js used to doing this to require in various packages.
let co = require(""co"");
But getting
etc. So using typescript it seems there can only be one such declaration/require across the whole project?
I'm confused about this as I thought let was scoped to the current file.
I just had a project that was working but after a refactor am now getting these errors all over the place.
Can someone explain?
",https://stackoverflow.com/questions/35758584/cannot-redeclare-block-scoped-variable,256,426581.0,20.0,,,2016-03-02 21:36:34,2023-10-04 01:03:34,2022-04-19 23:09:20,,,typescript;require,dcsan,12475,1146785,registered,true,50913569,,CC BY-SA 4.0,,678,458,2,1,1,2,true,false,false,true,true,true,38,5,false,0.047,0.0006,3916,2016,3,21,Wednesday,false,false,false,false,false,false,false
51040703,What return type should be used for setTimeout in TypeScript?,"Consider following code:
const timer: number = setTimeout(() => '', 1000);
Typescript throws an error: Type 'Timer' is not assignable to type 'number'. Quick lookup tells me that setTimeout returns NodeJS.Timer.
But if I am doing browser-based development, using NodeJS.Timer feels wrong. Which is the correct type definition or return type for making setTimeout work without resorting to any declaration?
",https://stackoverflow.com/questions/51040703/what-return-type-should-be-used-for-settimeout-in-typescript,255,176106.0,9.0,,,2018-06-26 10:31:49,2024-12-15 11:28:37,,,,typescript,Harshal Patil,21678,5723098,registered,true,51040768,,CC BY-SA 4.0,,553,413,7,0,0,1,true,false,false,true,true,false,61,10,true,0.051,0.0014,3070,2018,6,10,Tuesday,false,false,false,false,false,false,false
54139158,Cannot find name 'describe'. Do you need to install type definitions for a test runner?,"When using TypeScript in conjunction with Jest, my specs would fail with error messages like:
test/unit/some.spec.ts:1:1 - error TS2582: Cannot find name 'describe'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`.
test/unit/some.spec.ts:2:3 - error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`.
test/unit/some.spec.ts:3:7 - error TS2304: Cannot find name 'expect'.
test/unit/some.spec.ts:7:1 - error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`.
The types are already installed.
I use:
"@types/jest": "^23.3.12",
"jest": "^23.6.0",
"ts-jest": "^23.10.5",
"typescript": "^3.1.6"
I run tests using jest --forceExit --coverage --verbose
",https://stackoverflow.com/questions/54139158/cannot-find-name-describe-do-you-need-to-install-type-definitions-for-a-test,253,256279.0,38.0,,,2019-01-11 01:21:24,2025-01-13 11:41:36,2022-10-23 19:23:03,,,typescript;jestjs,Ronin,8194,4023065,registered,true,54139175,,CC BY-SA 4.0,2022-07-26 18:59:54,1147,980,3,0,0,2,true,false,false,true,true,true,95,15,true,0.148,0.001,2871,2019,1,1,Friday,false,false,false,false,false,false,false
44243060,Use enum as restricted key type,"Can an enum be used as a key type instead of only number or string? Currently it seems like the only possible declaration is { [key: number]: any }, where key can be of type number or string. Is it possible to make something like in this example:
enum MyEnum
{
First,
Second
}
var layer: { [key: MyEnum]: any };
",https://stackoverflow.com/questions/44243060/use-enum-as-restricted-key-type,253,221208.0,6.0,,,2017-05-29 12:55:45,2024-07-18 06:33:39,2024-07-18 06:33:39,,,typescript,Hivaga,4688,2116361,registered,true,66078799,,CC BY-SA 4.0,,457,322,9,0,0,1,true,false,false,true,true,true,31,6,false,0.027,0.0011,3463,2017,5,12,Monday,false,false,false,false,false,false,false
12736269,How to declare Return Types for Functions in TypeScript,"I checked here https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md which is the TypeScript Language Specifications but I couldn't find how I can declare a return type of the function.
I showed what I was expecting in the code below: greet(name:string): string {}
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet(): string {
return "Hello, " + this.greeting;
}
}
I know I can use (name:string) => any but this is used mostly when passing callback functions around:
function vote(candidate: string, callback: (result: string) => any) {
// ...
}
",https://stackoverflow.com/questions/12736269/how-to-declare-return-types-for-functions-in-typescript,253,535610.0,8.0,,,2012-10-04 21:28:07,2022-12-23 16:32:31,2021-09-29 10:00:29,,,javascript;typescript;oop,Tarik,82411,44852,registered,true,12736331,,CC BY-SA 4.0,,894,642,4,2,0,3,true,false,false,true,true,true,55,9,false,0.015,0.0005,5161,2012,10,21,Thursday,false,false,true,false,false,false,false
35019987,What does 'declare' do in 'export declare class Actions'?,"Why do we need the declare in the statement?
export declare class Actions {
...
}
",https://stackoverflow.com/questions/35019987/what-does-declare-do-in-export-declare-class-actions,252,164939.0,5.0,,,2016-01-26 17:26:29,2023-11-15 09:46:57,2016-09-07 08:04:45,,,typescript,born2net,25155,2040670,registered,true,,,CC BY-SA 3.0,,132,88,2,0,0,1,false,false,false,true,true,true,73,9,true,0.03,0.0015,3952,2016,1,17,Tuesday,false,false,false,false,false,false,false
13955157,How to define static property in TypeScript interface,"I just want to declare a static property in typescript interface? I have not found anywhere regarding this.
interface myInterface {
static Name:string;
}
Is it possible?
",https://stackoverflow.com/questions/13955157/how-to-define-static-property-in-typescript-interface,251,276935.0,22.0,,,2012-12-19 15:02:42,2025-02-26 12:27:51,,,,typescript,Rajagopal 웃,8581,1116467,registered,true,13955591,,CC BY-SA 3.0,,230,175,1,0,0,1,true,false,false,true,true,false,53,8,false,0.079,0.0009,5085,2012,12,15,Wednesday,false,false,false,false,false,false,false
40270393,Specify return type in TypeScript arrow function,"I am using React and Redux and have action types specified as interfaces, so that my reducers can take advantage of tagged union types for improved type safety.
So, I have type declarations that look like this:
interface AddTodoAction {
type: ""ADD_TODO"",
text: string
};
interface DeleteTodoAction {
type: ""DELETE_TODO"",
id: number
}
type TodoAction = AddTodoAction | DeleteTodoAction
I'd like to make helper functions that create these actions, and I tend to use arrow functions for this. If I write this:
export const addTodo1 = (text: string) => ({
type: ""ADD_TODO"",
text
});
The compiler can't provide any help in making sure this is a valid AddTodoAction because the return type isn't specified explicitly. I can specify the return type explicitly by doing this:
export const addTodo2: (text: string) => AddTodoAction = (text: string) => ({
type: ""ADD_TODO"",
text
})
But this requires specifying my function arguments twice, so it's verbose and harder to read.
Is there a way I can specify the return type explicitly when using arrow notation?
I've thought of trying this:
export const addTodo3 = (text: string) => <AddTodoAction>({
type: ""ADD_TODO"",
text
})
In this case, the compiler now infers the return type as AddTodoAction but it's doesn't validate that the object I'm returning has all of the appropriate fields.
I could solve this by switching to a different function syntax:
export const addTodo4 = function(text: string): AddTodoAction {
return {
type: ""ADD_TODO"",
text
}
}
export function addTodo5(text: string): AddTodoAction {
return {
type: ""ADD_TODO"",
text
}
}
Either of these methods will cause the compiler to use the correct return type and enforce that I have set all fields appropriately, but they are also more verbose and they change the way 'this' is handled in a function (which may not be an issue, I suppose.)
Is there any advice about the best way to do this?
",https://stackoverflow.com/questions/40270393/specify-return-type-in-typescript-arrow-function,249,249827.0,5.0,,,2016-10-26 19:12:14,2024-12-12 10:38:49,2018-03-09 22:09:20,,,typescript,Brian Hanechak,2583,7076851,registered,true,40270735,,CC BY-SA 3.0,,2258,2022,8,0,0,1,true,false,false,true,true,true,48,7,false,0.02,0.001,3678,2016,10,19,Wednesday,false,false,false,false,false,false,false
70106880,ERR_IMPORT_ASSERTION_TYPE_MISSING for import of json file,"This code was working fine.
I don't know if it's because I upgraded to Node 17 or what, but now I get
TypeError [ERR_IMPORT_ASSERTION_TYPE_MISSING]:
Module "file:///Users/xxxxx/code/projects/xxxxx/dist/server/data/countries.json"
needs an import assertion of type "json"
In my api.ts I have:
import countryTable from './data/countries.json';
Here's how I start api.ts which is used by server.ts:
NODE_ENV=production node --optimize_for_size --trace-warnings --experimental-json-modules --no-warnings server/server.js
",https://stackoverflow.com/questions/70106880/err-import-assertion-type-missing-for-import-of-json-file,246,219851.0,7.0,,,2021-11-25 06:49:05,2025-12-21 00:32:33,2022-09-16 16:06:05,,,javascript;typescript,PositiveGuy,20740,4694781,registered,true,70106896,,CC BY-SA 4.0,,684,545,6,0,0,2,true,false,false,true,true,true,57,6,false,0.032,0.0011,1822,2021,11,6,Thursday,false,false,true,false,false,false,false
43937387,"If '<selector>' is an Angular component, then verify that it is part of this module","I am new in Angular2. I have tried to create a component but showing an error.
This is the app.component.ts file.
import { Component } from '@angular/core';
import { MyComponentComponent } from './my-component.component';
@Component({
selector: 'my-app',
template: `
<h1>Hello {{name}}</h1>
<h4>Something</h4>
<my-component></my-component>
`,
directives: [MyComponentComponent]
})
export class AppComponent { name = 'Sam' }
This is the component which i want to create.
import { Component } from '@angular/core';
@Component({
selector: 'my-component',
template: `
<p>This is my article</p>
`
})
export class MyComponentComponent {
}
Showing the two errors:
- If
my-component is an Angular component, then verify that it is part of this module.
- If
my-component is a Web Component then add CUSTOM_ELEMENTS_SCHEMA to the @NgModule.schemas of this component to suppress this message.
Please Help.
",https://stackoverflow.com/questions/43937387/if-selector-is-an-angular-component-then-verify-that-it-is-part-of-this-mod,245,561062.0,24.0,,,2017-05-12 12:06:46,2024-06-06 11:33:48,2017-05-12 12:12:21,,,angular;typescript,Vimal,2877,4324301,registered,true,46557638,,CC BY-SA 3.0,,1154,979,7,0,0,2,true,false,false,true,true,true,97,15,false,0.043,0.0004,3480,2017,5,12,Friday,false,false,false,false,false,false,false
22991968,public static const in TypeScript,"Is there such a thing as public static constants in TypeScript? I have a class that looks like:
export class Library {
public static BOOK_SHELF_NONE: string = ""None"";
public static BOOK_SHELF_FULL: string = ""Full"";
}
In that class, I can do Library.BOOK_SHELF_NONE and the tsc doesn't complain. But if I try to use the class Library elsewhere, and try to do the same thing, it doesn't recognize it.
",https://stackoverflow.com/questions/22991968/public-static-const-in-typescript,244,236613.0,8.0,,,2014-04-10 15:08:54,2017-09-05 17:55:31,2017-02-21 11:31:00,,,typescript,Crystal,29828,207524,registered,true,22992267,,CC BY-SA 3.0,,461,410,2,0,0,1,true,false,false,true,true,true,33,5,false,0.034,0.001,4608,2014,4,15,Thursday,false,false,false,false,false,false,false
12687779,How do you produce a .d.ts "typings" definition file from an existing JavaScript library?,"I'm using a lot of libraries both my own and 3rd party. I see the ""typings"" directory contains some for Jquery and WinRT... but how are they created?
",https://stackoverflow.com/questions/12687779/how-do-you-produce-a-d-ts-typings-definition-file-from-an-existing-javascript,242,220964.0,10.0,,,2012-10-02 09:29:02,2023-05-16 19:03:36,2012-10-19 09:01:15,,,typescript;tsc,Hotrodmonkey,3124,752572,registered,true,12695001,,CC BY-SA 3.0,,158,151,0,0,0,2,true,false,false,true,true,true,99,14,true,0.045,0.0011,5163,2012,10,9,Tuesday,false,false,false,false,false,false,false
39668731,What TypeScript version is Visual Studio Code using? How to update it?,"How can I tell what version of TypeScript is being used in Visual Studio Code? In particular, I had been using TypeScript 1.8.10 and VSCode 1.4.0. I first updated VSCode to the latest version, which was 1.5.3. But checking from the command line, I saw that my TypeScript version was still 1.8.10. So I updated TypeScript from the command line, and it is now 2.0.3 .
Is there a way to tell for sure whether Visual Studio Code is using version 2.0.3?
Is there a method for updating Visual Studio Code that will automatically update TypeScript to the latest released version, or does the TypeScript update have to be done independently?
",https://stackoverflow.com/questions/39668731/what-typescript-version-is-visual-studio-code-using-how-to-update-it,241,232798.0,9.0,,,2016-09-23 20:05:01,2023-10-08 08:50:32,2016-09-24 16:49:42,,,typescript;vs-code,Richard Fuhr,3645,111808,registered,true,,,CC BY-SA 3.0,,661,640,0,0,0,2,false,false,false,true,true,true,70,12,true,0.039,0.001,3711,2016,9,20,Friday,false,false,false,false,false,false,false
49295984,Rendering Angular components in Handsontable Cells,"In a project of mine, I try to display Angular Components (like an Autocomplete Dropdown Search) in a table. Because of the requirements I have (like multi-selecting different cells with ctrl+click) I decided to give it a go with handsontable.
I've used the handsontable renderer and add the components dynamically.
The code looks like this
matrix.component.ts
this.hot = new Handsontable(this.handsontable.nativeElement, {
data: this.tableData,
colWidths: [80, 300],
colHeaders: ['Id', 'Custom Component'],
columns: [
{
data: 'id',
},
{
data: 'id',
renderer: (instance: any, td: any, row: any, col: any, prop: any, value: any, cellProperties: any) => {
if (cellProperties.hasOwnProperty('ref')) {
(cellProperties.ref as ComponentRef<CellContainerComponent>).instance.value = row;
} else {
cellProperties.ref = this.loadComponentAtDom(
CellContainerComponent,
td,
((component: any) => {
component.template = this.button4Matrix;
component.value = row;
}));
}
return td;
},
readOnly: true,
},
],
});
private loadComponentAtDom<T>(component: Type<T>, dom: Element, onInit?: (component: T) => void): ComponentRef<T> {
let componentRef;
try {
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(component);
componentRef = componentFactory.create(this.injector, [], dom);
onInit ? onInit(componentRef.instance) : console.log('no init');
this.appRef.attachView(componentRef.hostView);
} catch (e) {
console.error('Unable to load component', component, 'at', dom);
throw e;
}
return componentRef;
}
What's my current issue is the lifecycle of the rendered angular components.
Stuff I tried:
- Do nothing
Tried Solution: Doing nothing and leaving everything to Angular
Problem: Angular never calling the ngOnDestroy of the CellContainer.
- Saving componentRefs
Tried Solution: Saving the componentRef in an Array and after a certain amount of rendering trying to destroy the components I
rendered some time ago. Counting via time, handsontable hooks
(verticalScroll/beforeRender/afterRender), in the render-method
Problem: Destroy of the angular component always throws an error ('cannot read property'nativeNode' of null') or the components get
displayed completely wrong
- Check during rendering if an element is there
Tried Solution: During the render: I checked if there's already a component and if it was I used to recycle the already-there component by adding a new value only.
Problem: The values get completely mixed up during scrolling.
A link to my solution (and an implemented solution #3) is available on github.
Does anyone have an idea of how to handle this in a clean way? If not the application gets slow & unusable after a little bit of scrolling & using the table.
Better refer : https://handsontable.com/docs/8.2.0/tutorial-cell-function.html
",https://stackoverflow.com/questions/49295984/rendering-angular-components-in-handsontable-cells,241,7347.0,2.0,,,2018-03-15 09:42:36,2022-12-31 18:28:09,2021-05-25 08:12:18,,,angular;typescript;dom;dynamic;handsontable,phhbr,2737,5235385,registered,true,,,CC BY-SA 4.0,,3813,3043,1,4,0,5,false,false,false,true,true,true,50,6,false,0.272,0.0328,3173,2018,3,9,Thursday,false,false,false,false,false,false,false
44429996,Angular 2 'component' is not a known element,"I'm trying to use a component I created inside the AppModule in other modules. I get the following error though:
""Uncaught (in promise): Error: Template parse errors:
'contacts-box' is not a known element:
- If 'contacts-box' is an Angular component, then verify that it is part of this module.
- If 'contacts-box' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
My project structure is quite simple:
![]()
I keep my pages in pages directory, where each page is kept in different module (e.g. customers-module) and each module has multiple components (like customers-list-component, customers-add-component and so on). I want to use my ContactBoxComponent inside those components (so inside customers-add-component for example).
As you can see I created the contacts-box component inside the widgets directory so it's basically inside the AppModule. I added the ContactBoxComponent import to app.module.ts and put it in declarations list of AppModule. It didin't work so I googled my problem and added ContactBoxComponent to export list as well. Didn't help. I also tried putting ContactBoxComponent in CustomersAddComponent and then in another one (from different module) but I got an error saying there are multiple declarations.
What am I missing?
",https://stackoverflow.com/questions/44429996/angular-2-component-is-not-a-known-element,240,391952.0,27.0,,,2017-06-08 08:01:32,2024-01-04 10:58:07,,,,angular;typescript;angular-components;angular-module,Danioss,3125,2765341,registered,true,44430230,,CC BY-SA 3.0,,1584,1345,0,1,1,4,true,false,false,true,true,false,52,8,false,0.069,0.0006,3453,2017,6,8,Thursday,false,false,false,false,false,false,false
23790509,Proper use of errors,"I'm using TypeScript for a reasonably large project, and am wondering what the standard is for the use of Errors. For example, say I hand an index out of bounds exception in Java:
throw new IndexOutOfBoundsException();
Would the equivalent statement in TypeScript be:
throw new Error(""Index Out of Bounds"");
What other ways could I accomplish this? What is the accepted standard?
",https://stackoverflow.com/questions/23790509/proper-use-of-errors,240,321692.0,4.0,,,2014-05-21 17:53:58,2023-12-22 07:16:12,2019-02-26 17:25:39,,,exception;typescript,Nathan Bellowe,4982,3653785,registered,true,33122167,,CC BY-SA 4.0,,468,386,3,0,0,2,true,false,false,true,true,true,20,4,false,0.012,0.0007,4567,2014,5,17,Wednesday,false,false,false,false,false,false,false
39713349,Make all properties within a Typescript interface optional,"I have an interface in my application:
interface Asset {
id: string;
internal_id: string;
usage: number;
}
that is part of a post interface:
interface Post {
asset: Asset;
}
I also have an interface that is for a post draft, where the asset object might only be partially constructed
interface PostDraft {
asset: Asset;
}
I want to allow a PostDraft object to have a partial asset object while still checking types on the properties that are there (so I don't want to just swap it out with any).
I basically want a way to be able to generate the following:
interface AssetDraft {
id?: string;
internal_id?: string;
usage?: number;
}
without entirely re-defining the Asset interface. Is there a way to do this? If not, what would the smart way to arrange my types in this situation be?
",https://stackoverflow.com/questions/39713349/make-all-properties-within-a-typescript-interface-optional,239,195303.0,7.0,,,2016-09-26 22:25:21,2024-06-25 16:26:28,,,,typescript,jkjustjoshing,3740,1143987,registered,true,40076355,,CC BY-SA 3.0,,992,815,7,0,0,1,true,false,false,true,true,false,58,8,false,0.036,0.0012,3708,2016,9,22,Monday,false,false,false,false,false,false,false
33332394,Angular and Typescript: Can't find names - Error: cannot find name,"I am using Angular (version 2) with TypeScript (version 1.6) and when I compile the code I get these errors:
Error TS2304: Cannot find name 'Map'.
node_modules/angular2/src/core/change_detection/parser/locals.d.ts(4,42): Error TS2304: Cannot find name 'Map'.
node_modules/angular2/src/core/facade/collection.d.ts(1,25): Error TS2304: Cannot find name 'MapConstructor'.
node_modules/angular2/src/core/facade/collection.d.ts(2,25): Error TS2304: Cannot find name 'SetConstructor'.
node_modules/angular2/src/core/facade/collection.d.ts(4,27): Error TS2304: Cannot find name 'Map'.
node_modules/angular2/src/core/facade/collection.d.ts(4,39): Error TS2304: Cannot find name 'Map'.
node_modules/angular2/src/core/facade/collection.d.ts(7,9): Error TS2304: Cannot find name 'Map'.
node_modules/angular2/src/core/facade/collection.d.ts(8,30): Error TS2304: Cannot find name 'Map'.
node_modules/angular2/src/core/facade/collection.d.ts(11,43): Error TS2304: Cannot find name 'Map'.
node_modules/angular2/src/core/facade/collection.d.ts(12,27): Error TS2304: Cannot find name 'Map'.
node_modules/angular2/src/core/facade/collection.d.ts(14,23): Error TS2304: Cannot find name 'Map'.
node_modules/angular2/src/core/facade/collection.d.ts(15,25): Error TS2304: Cannot find name 'Map'.
node_modules/angular2/src/core/facade/collection.d.ts(94,41): Error TS2304: Cannot find name 'Set'.
node_modules/angular2/src/core/facade/collection.d.ts(95,22): Error TS2304: Cannot find name 'Set'.
node_modules/angular2/src/core/facade/collection.d.ts(96,25): Error TS2304: Cannot find name 'Set'.
node_modules/angular2/src/core/facade/lang.d.ts(1,22): Error TS2304: Cannot find name 'BrowserNodeGlobal'.
node_modules/angular2/src/core/facade/lang.d.ts(33,59): Error TS2304: Cannot find name 'Map'.
node_modules/angular2/src/core/facade/promise.d.ts(1,10): Error TS2304: Cannot find name 'Promise'.
node_modules/angular2/src/core/facade/promise.d.ts(3,14): Error TS2304: Cannot find name 'Promise'.
node_modules/angular2/src/core/facade/promise.d.ts(8,32): Error TS2304: Cannot find name 'Promise'.
node_modules/angular2/src/core/facade/promise.d.ts(9,38): Error TS2304: Cannot find name 'Promise'.
node_modules/angular2/src/core/facade/promise.d.ts(10,35): Error TS2304: Cannot find name 'Promise'.
node_modules/angular2/src/core/facade/promise.d.ts(10,93): Error TS2304: Cannot find name 'Promise'.
node_modules/angular2/src/core/facade/promise.d.ts(11,34): Error TS2304: Cannot find name 'Promise'.
node_modules/angular2/src/core/facade/promise.d.ts(12,32): Error TS2304: Cannot find name 'Promise'.
node_modules/angular2/src/core/facade/promise.d.ts(12,149): Error TS2304: Cannot find name 'Promise'.
node_modules/angular2/src/core/facade/promise.d.ts(13,43): Error TS2304: Cannot find name 'Promise'.
node_modules/angular2/src/core/linker/element_injector.d.ts(72,32): Error TS2304: Cannot find name 'Map'.
node_modules/angular2/src/core/linker/element_injector.d.ts(74,17): Error TS2304: Cannot find name 'Map'.
node_modules/angular2/src/core/linker/element_injector.d.ts(78,184): Error TS2304: Cannot find name 'Map'.
node_modules/angular2/src/core/linker/element_injector.d.ts(83,182): Error TS2304: Cannot find name 'Map'.
node_modules/angular2/src/core/linker/element_injector.d.ts(107,37): Error TS2304: Cannot find name 'Map'.
node_modules/angular2/src/core/linker/proto_view_factory.d.ts(27,146): Error TS2304: Cannot find name 'Map'.
node_modules/angular2/src/core/linker/view.d.ts(52,144): Error TS2304: Cannot find name 'Map'.
node_modules/angular2/src/core/linker/view.d.ts(76,79): Error TS2304: Cannot find name 'Map'.
node_modules/angular2/src/core/linker/view.d.ts(77,73): Error TS2304: Cannot find name 'Map'.
node_modules/angular2/src/core/linker/view.d.ts(94,31): Error TS2304: Cannot find name 'Map'.
node_modules/angular2/src/core/linker/view.d.ts(97,18): Error TS2304: Cannot find name 'Map'.
node_modules/angular2/src/core/linker/view.d.ts(100,24): Error TS2304: Cannot find name 'Map'.
node_modules/angular2/src/core/linker/view.d.ts(103,142): Error TS2304: Cannot find name 'Map'.
node_modules/angular2/src/core/linker/view.d.ts(104,160): Error TS2304: Cannot find name 'Map'.
node_modules/angular2/src/core/render/api.d.ts(281,74): Error TS2304: Cannot find name 'Map'.
node_modules/angular2/src/core/zone/ng_zone.d.ts(1,37): Error TS2304: Cannot find name 'Zone'.
This is the code:
import 'reflect-metadata';
import {bootstrap, Component, CORE_DIRECTIVES, FORM_DIRECTIVES} from 'angular2/core';
@Component({
selector: 'my-app',
template: '<input type=""text"" [(ng-model)]=""title"" /><h1>{{title}}</h1>',
directives: [ CORE_DIRECTIVES ]
})
class AppComponent {
title :string;
constructor() {
this.title = 'hello angular 2';
}
}
bootstrap(AppComponent);
",https://stackoverflow.com/questions/33332394/angular-and-typescript-cant-find-names-error-cannot-find-name,239,425017.0,25.0,,,2015-10-25 16:58:48,2022-03-25 14:23:07,2020-07-01 16:13:39,,,angular;typescript,user233232,6227,4997649,registered,true,33359873,,CC BY-SA 4.0,2017-11-09 11:32:23,5027,4965,2,0,0,2,true,false,false,true,true,true,70,11,false,0.059,0.0006,4045,2015,10,16,Sunday,true,false,false,false,false,false,false
43241193,'Found the synthetic property @panelState. Please include either "BrowserAnimationsModule" or "NoopAnimationsModule" in your application.',"I upgraded an Angular 4 project using angular-seed and now get the error
Found the synthetic property @panelState. Please include either ""BrowserAnimationsModule"" or ""NoopAnimationsModule"" in your application.
How can I fix this? What exactly is the error message telling me?
",https://stackoverflow.com/questions/43241193/found-the-synthetic-property-panelstate-please-include-either-browseranimati,237,260871.0,22.0,,,2017-04-05 20:38:41,2024-12-18 19:09:59,2020-01-11 11:56:44,,,angular;typescript;angular-animations,Aravind,41783,3858469,registered,true,43241908,,CC BY-SA 4.0,,470,285,0,1,1,3,true,false,false,true,true,true,166,14,false,0.084,0.0009,3517,2017,4,20,Wednesday,false,false,false,false,false,false,false
39020022,Angular 2 Unit Tests: Cannot find name 'describe',"I'm following this tutorial from angular.io
As they said, I've created hero.spec.ts file to create unit tests:
import { Hero } from './hero';
describe('Hero', () => {
it('has name', () => {
let hero: Hero = {id: 1, name: 'Super Cat'};
expect(hero.name).toEqual('Super Cat');
});
it('has id', () => {
let hero: Hero = {id: 1, name: 'Super Cat'};
expect(hero.id).toEqual(1);
});
});
Unit Tests work like a charm. The problem is: I see some errors, which are mentioned in tutorial:
Our editor and the compiler may complain that they don’t know what it
and expect are because they lack the typing files that describe
Jasmine. We can ignore those annoying complaints for now as they are
harmless.
And they indeed ignored it. Even though those errors are harmless, it doesn't look good in my output console when I receive bunch of them.
Example of what I get:
Cannot find name 'describe'.
Cannot find name 'it'.
Cannot find name 'expect'.
What can I do to fix it?
",https://stackoverflow.com/questions/39020022/angular-2-unit-tests-cannot-find-name-describe,237,180103.0,17.0,,,2016-08-18 13:51:46,2023-01-17 08:09:53,2020-06-20 09:12:55,,,unit-testing;angular;typescript;jasmine,Piotrek,11289,1804027,registered,true,39945169,,CC BY-SA 4.0,,1264,996,3,1,0,4,true,false,false,true,true,true,57,8,false,0.094,0.0013,3747,2016,8,13,Thursday,false,false,false,false,false,false,false
38906359,Create a global variable in TypeScript,"In JavaScript I can just do this:
something = 'testing';
And then in another file:
if (something === 'testing')
and it will have something be defined (as long as they were called in the correct order).
I can't seem to figure out how to do that in TypeScript.
This is what I have tried.
In a .d.ts file:
interface Window { something: string; }
Then in my main.ts file:
window.something = 'testing';
then in another file:
if (window.something === 'testing')
And this works. But I want to be able to lose the window. part of it and just have my something be global. Is there a way to do that in TypeScript?
(In case someone is interested, I am really trying to setup my logging for my application. I want to be able to call log.Debug from any file without having to import and create objects.)
",https://stackoverflow.com/questions/38906359/create-a-global-variable-in-typescript,236,488023.0,20.0,,,2016-08-11 21:22:27,2025-07-23 01:12:34,2018-03-26 15:38:51,,,typescript,Vaccano,83670,16241,registered,true,40679225,,CC BY-SA 3.0,,1078,819,9,0,0,1,true,false,false,true,true,true,38,6,false,0.041,0.0005,3754,2016,8,21,Thursday,false,false,false,false,false,false,false
34489916,How to load external scripts dynamically in Angular?,"I have this module which componentize the external library together with additional logic without adding the <script> tag directly into the index.html:
import 'http://external.com/path/file.js'
//import '../js/file.js'
@Component({
selector: 'my-app',
template: `
<script src=""http://iknow.com/this/does/not/work/either/file.js""></script>
<div>Template</div>`
})
export class MyAppComponent {...}
I notice the import by ES6 spec is static and resolved during TypeScript transpiling rather than at runtime.
Anyway to make it configurable so the file.js will be loading either from CDN or local folder?
How to tell Angular 2 to load a script dynamically?
",https://stackoverflow.com/questions/34489916/how-to-load-external-scripts-dynamically-in-angular,235,366223.0,23.0,,,2015-12-28 08:14:05,2023-02-23 18:19:52,2018-02-09 11:13:24,,,javascript;angular;typescript;ecmascript-6,CallMeLaNN,8628,186334,registered,true,34489991,,CC BY-SA 3.0,2019-07-13 20:11:07,783,712,3,0,0,4,true,false,false,true,true,true,52,8,true,0.063,0.0006,3981,2015,12,8,Monday,false,false,true,false,false,false,false
29775830,How to implement a typescript decorator?,"TypeScript 1.5 now has decorators.
Could someone provide a simple example demonstrating the proper way to implement a decorator and describe what the arguments in the possible valid decorator signatures mean?
declare type ClassDecorator = <TFunction extends Function>(target: TFunction) => TFunction | void;
declare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void;
declare type MethodDecorator = <T>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => TypedPropertyDescriptor<T> | void;
declare type ParameterDecorator = (target: Function, propertyKey: string | symbol, parameterIndex: number) => void;
Additionally, are there any best practice considerations that should be kept in mind while implementing a decorator?
",https://stackoverflow.com/questions/29775830/how-to-implement-a-typescript-decorator,235,102927.0,5.0,,,2015-04-21 14:55:55,2020-08-27 03:57:47,2015-04-21 15:02:08,,,typescript;decorator,David Sherret,107960,188246,registered,true,29837695,,CC BY-SA 3.0,,1041,829,1,2,0,2,true,false,false,true,true,true,40,6,true,0.049,0.0023,4232,2015,4,14,Tuesday,false,false,false,false,false,false,false
40177331,What is the shortcut in Visual Studio Code for console.log,"I want to know what is the shortcut for console.log in Visual Studio Code?
",https://stackoverflow.com/questions/40177331/what-is-the-shortcut-in-visual-studio-code-for-console-log,234,217034.0,27.0,,,2016-10-21 12:59:30,2025-03-08 22:55:33,2023-04-22 05:32:54,,,javascript;typescript;vs-code;keyboard-shortcuts,Petko Kamenov,2456,6300862,registered,true,40177800,,CC BY-SA 4.0,,95,75,1,0,0,4,true,false,false,true,true,true,58,10,false,0.124,0.0011,3683,2016,10,12,Friday,false,false,true,false,false,false,false
40275832,"Typescript has unions, so are enums redundant?","Ever since TypeScript introduced unions types, I wonder if there is any reason to declare an enum type. Consider the following enum type declaration:
enum X { A, B, C }
var x: X = X.A;
and a similar union type declaration:
type X: "A" | "B" | "C"
var x: X = "A";
If they basically serve the same purpose, and unions are more powerful and expressive, then why are enums necessary?
",https://stackoverflow.com/questions/40275832/typescript-has-unions-so-are-enums-redundant,234,116781.0,5.0,,,2016-10-27 03:53:11,2021-11-23 20:00:29,2021-11-23 20:00:29,,,typescript;enums;unions,prmph,8504,761861,registered,true,60041791,,CC BY-SA 4.0,,491,422,2,0,0,3,true,false,false,true,true,true,46,7,true,0.043,0.002,3677,2016,10,3,Thursday,false,false,false,false,false,false,false
48759035,Mock dependency in Jest with TypeScript,"When testing a module that has a dependency in a different file and assigning that module to be a jest.mock, TypeScript gives an error that the method mockReturnThisOnce (or any other jest.mock method) does not exist on the dependency, this is because it is previously typed.
What is the proper way to get TypeScript to inherit the types from jest.mock?
Here is a quick example.
Dependency
const myDep = (name: string) => name;
export default myDep;
test.ts
import * as dep from '../dependency';
jest.mock('../dependency');
it('should do what I need', () => {
//this throws ts error
// Property mockReturnValueOnce does not exist on type (name: string)....
dep.default.mockReturnValueOnce('return')
}
I feel like this is a very common use case and not sure how to properly type this.
",https://stackoverflow.com/questions/48759035/mock-dependency-in-jest-with-typescript,233,241069.0,15.0,,,2018-02-13 03:39:12,2024-02-26 16:15:38,2024-02-26 16:09:38,,,javascript;unit-testing;typescript;jestjs,Philip Chmalts,2508,4935009,registered,true,,,CC BY-SA 4.0,,941,799,6,0,0,4,false,false,false,true,true,true,39,6,false,0.062,0.001,3203,2018,2,3,Tuesday,false,false,true,false,false,false,false
44517737,'router-outlet' is not a known element,"I have a mvc 5 project with a angular frontend . I wanted to add routing as described in this tutorial https://angular.io/guide/router. So in my _Layout.cshtml I added a
<base href=""/"">
and created my routing in my app.module. But when I run this I get the following error:
Error: Template parse errors:
'router-outlet' is not a known element:
1. If 'router-outlet' is an Angular component, then verify that it is part of this module.
2. If 'router-outlet' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. (""
<a routerLink=""/dashboard"">dashboard</a>
</nav>
[ERROR ->]<router-outlet></router-outlet>
""): ng:///AppModule/AppComponent.html@5:0
In my app.component the line
<router-outlet></router-outlet>
gives an error telling me that Visual studio cannot resolve the tag 'router-outlet'. Any suggestions how I can fix this error? Am I missing a reference or a import or just overlooking something?
Below are my package.json ,app.component and app.module
package.json:
{
""version"": ""1.0.0"",
""name"": ""app"",
""private"": true,
""scripts"": {},
""dependencies"": {
""@angular/common"": ""^4.2.2"",
""@angular/compiler"": ""^4.2.2"",
""@angular/core"": ""^4.2.2"",
""@angular/forms"": ""^4.2.2"",
""@angular/http"": ""^4.2.2"",
""@angular/platform-browser"": ""^4.2.2"",
""@angular/platform-browser-dynamic"": ""^4.2.2"",
""@angular/router"": ""^4.2.2"",
""@types/core-js"": ""^0.9.41"",
""angular-in-memory-web-api"": ""^0.3.2"",
""bootstrap"": ""^3.3.7"",
""core-js"": ""^2.4.1"",
""graceful-fs"": ""^4.0.0"",
""ie-shim"": ""^0.1.0"",
""minimatch"": ""^3.0.4"",
""reflect-metadata"": ""^0.1.10"",
""rxjs"": ""^5.0.1"",
""systemjs"": ""^0.20.12"",
""zone.js"": ""^0.8.12""
},
""devDependencies"": {
""gulp"": ""^3.9.1"",
""gulp-clean"": ""^0.3.2"",
""gulp-concat"": ""^2.6.1"",
""gulp-tsc"": ""^1.3.2"",
""gulp-typescript"": ""^3.1.7"",
""path"": ""^0.12.7"",
""typescript"": ""^2.3.3""
}
}
app.module.ts:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
import {DashboardComponent} from ""./dashboard/dashboard.component""
const appRoutes: Routes = [
{
path: '',
redirectTo: '/dashboard',
pathMatch: 'full',
component: DashboardComponent
},
{
path: 'dashboard',
component: DashboardComponent
}
];
@NgModule({
imports: [
RouterModule.forRoot(appRoutes),
BrowserModule,
FormsModule
],
exports: [RouterModule],
declarations: [
AppComponent,
DashboardComponent
],
bootstrap: [AppComponent]
})
export class AppModule {
}
app.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<h1>{{title}}</h1>
<nav>
<a routerLink=""/dashboard"">dashboard</a>
</nav>
<router-outlet></router-outlet>
`
})
export class AppComponent {
title = 'app Loaded';
}
",https://stackoverflow.com/questions/44517737/router-outlet-is-not-a-known-element,232,558673.0,27.0,,,2017-06-13 09:39:19,2024-10-15 09:19:37,2019-12-15 07:38:20,,,angular;typescript;asp.net-mvc-5;angular2-routing,Molo,2343,5359808,registered,true,44517948,,CC BY-SA 4.0,2019-09-23 17:15:55,3746,3279,10,1,0,4,true,false,false,true,true,true,46,6,false,0.048,0.0004,3448,2017,6,9,Tuesday,false,false,false,false,false,false,false
12686927,How to assert a type of an HTMLElement in TypeScript?,"I'm trying to do this:
var script:HTMLScriptElement = document.getElementsByName("script")[0];
alert(script.type);
but it's giving me an error:
Cannot convert 'Node' to 'HTMLScriptElement': Type 'Node' is missing property 'defer' from type 'HTMLScriptElement'
(elementName: string) => NodeList
I can't access the 'type' member of the script element unless I cast it to the correct type, but I don't know how to do this. I searched the docs & samples, but I couldn't find anything.
",https://stackoverflow.com/questions/12686927/how-to-assert-a-type-of-an-htmlelement-in-typescript,232,278905.0,14.0,,,2012-10-02 08:33:05,2021-05-15 23:42:06,2021-05-15 22:45:26,,,typescript;type-assertion;typescript-types;typescript-lib-dom,Spongman,9921,204555,registered,true,12687137,,CC BY-SA 4.0,,569,500,2,0,0,4,true,false,false,true,true,true,53,10,true,0.05,0.0008,5163,2012,10,8,Tuesday,false,false,false,false,false,false,false
55012174,Why doesn't Object.keys return a keyof type in TypeScript?,"Title says it all - why doesn't Object.keys(x) in TypeScript return the type Array<keyof typeof x>? That's what Object.keys does, so it seems like an obvious oversight on the part of the TypeScript definition file authors to not make the return type simply be keyof T.
Should I log a bug on their GitHub repo, or just go ahead and send a PR to fix it for them?
",https://stackoverflow.com/questions/55012174/why-doesnt-object-keys-return-a-keyof-type-in-typescript,232,89981.0,8.0,,,2019-03-05 21:52:33,2026-10-19 14:32:27,,,,typescript,Ryan Cavanaugh,223506,1704166,registered,true,55012175,,CC BY-SA 4.0,,434,368,4,0,0,1,true,false,false,true,true,false,62,9,true,0.089,0.0026,2818,2019,3,21,Tuesday,false,false,false,false,false,false,false
43159887,Make a single property optional in TypeScript,"In TypeScript, 2.2...
Let's say I have a Person type:
interface Person {
name: string;
hometown: string;
nickname: string;
}
And I'd like to create a function that returns a Person, but doesn't require a nickname:
function makePerson(input: ???): Person {
return {...input, nickname: input.nickname || input.name};
}
What should be the type of input? I'm looking for a dynamic way to specify a type that is identical to Person except that nickname is optional (nickname?: string | undefined). The closest thing I've figured out so far is this:
type MakePersonInput = Partial<Person> & {
name: string;
hometown: string;
}
but that's not quite what I'm looking for, since I have to specify all the types that are required instead of the ones that are optional.
",https://stackoverflow.com/questions/43159887/make-a-single-property-optional-in-typescript,230,190274.0,10.0,,,2017-04-01 17:24:06,2025-06-21 18:18:44,,,,typescript,DallonF,3436,627544,registered,true,54178819,,CC BY-SA 3.0,,959,791,7,0,0,1,true,false,false,true,true,false,45,7,false,0.053,0.0012,3521,2017,4,17,Saturday,true,false,false,false,false,false,false
63616486,Property 'replaceAll' does not exist on type 'string',"I want to use replaceAll in typescript and angular 10.
But I get this error: Property 'replaceAll' does not exist on type 'string'.
This is my code:
let date="1399/06/08"
console.log(date.replaceAll('/', '_'))
Output: 13990608
How can fix my typescript to show me this function?
",https://stackoverflow.com/questions/63616486/property-replaceall-does-not-exist-on-type-string,230,196719.0,15.0,,,2020-08-27 12:57:02,2025-10-24 06:18:43,2021-04-18 13:50:17,,,angular;typescript;angular10,behroozbc,2908,5360463,registered,true,67227887,,CC BY-SA 4.0,,379,290,2,0,0,3,true,false,false,true,true,true,69,8,false,0.076,0.0012,2277,2020,8,12,Thursday,false,false,false,false,false,false,false
17382143,Create a new object from type parameter in generic class,"I'm trying to create a new object of a type parameter in my generic class.
In my class View, I have 2 lists of objects of generic type passed as type parameters, but when I try to make new TGridView(), TypeScript says:
Could not find symbol 'TGridView
This is the code:
module AppFW {
// Represents a view
export class View<TFormView extends FormView, TGridView extends GridView> {
// The list of forms
public Forms: { [idForm: string]: TFormView; } = {};
// The list of grids
public Grids: { [idForm: string]: TGridView; } = {};
public AddForm(formElement: HTMLFormElement, dataModel: any, submitFunction?: (e: SubmitFormViewEvent) => boolean): FormView {
var newForm: TFormView = new TFormView(formElement, dataModel, submitFunction);
this.Forms[formElement.id] = newForm;
return newForm;
}
public AddGrid(element: HTMLDivElement, gridOptions: any): GridView {
var newGrid: TGridView = new TGridView(element, gridOptions);
this.Grids[element.id] = newGrid;
return newGrid;
}
}
}
Can I create objects from a generic type?
",https://stackoverflow.com/questions/17382143/create-a-new-object-from-type-parameter-in-generic-class,230,307655.0,13.0,,,2013-06-29 16:10:52,2024-09-27 02:31:39,2018-10-03 16:50:36,,,typescript;generics,Javier Ros,3731,1274509,registered,true,17383858,,CC BY-SA 4.0,,1296,1193,3,0,0,2,true,false,false,true,true,true,56,10,false,0.042,0.0007,4893,2013,6,16,Saturday,true,false,false,false,false,false,false
35539622,How do you deploy Angular apps?,"How do you deploy Angular apps once they reach the production phase?
All the guides I've seen so far (even on angular.io) are counting on a lite-server for serving and browserSync to reflect changes - but when you finish with development, how can you publish the app?
Do I import all the compiled .js files on the index.html page or do I minify them using gulp? Will they work? Do I need SystemJS at all in the production version?
",https://stackoverflow.com/questions/35539622/how-do-you-deploy-angular-apps,230,263422.0,19.0,,,2016-02-21 17:47:34,2023-01-29 09:44:55,2017-12-20 20:52:48,,,typescript;angular;production;systemjs,Joseph Girgis,3183,1362355,registered,true,35563542,,CC BY-SA 3.0,,535,437,2,1,0,4,true,false,false,true,true,true,31,6,true,0.072,0.0009,3926,2016,2,17,Sunday,true,false,false,false,false,false,false
49102724,Angular 5 - Copy to clipboard,"I am trying to implement an icon that when clicked will save a variable to the user's clipboard. I have currently tried several libraries and none of them have been able to do so.
How do I properly copy a variable to the user's clipboard in Angular 5?
",https://stackoverflow.com/questions/49102724/angular-5-copy-to-clipboard,229,270951.0,20.0,,,2018-03-05 02:40:49,2023-05-08 06:33:14,2019-05-21 23:49:46,,,angular;typescript;angular5,anonymous-dev,2486,8021125,registered,true,49121680,,CC BY-SA 4.0,,268,254,0,0,0,3,true,false,false,true,true,true,29,6,false,0.074,0.0008,3183,2018,3,2,Monday,false,false,false,false,false,false,false
39787038,How to manage Angular2 "expression has changed after it was checked" exception when a component property depends on current datetime,"My component has styles that depend on current datetime. In my component I've got the following function.
private fontColor( dto : Dto ) : string {
// date d'exécution du dto
let dtoDate : Date = new Date( dto.LastExecution );
(...)
let color = ""hsl( "" + hue + "", 80%, "" + (maxLigness - lightnessAmp) + ""%)"";
return color;
}
lightnessAmp is calculated from the current datetime. The color changes if dtoDate is in the last 24 hours.
The exact error is the following:
Expression has changed after it was checked. Previous value: 'hsl( 123, 80%, 49%)'. Current value: 'hsl( 123, 80%, 48%)'
I know the exception appear in development mode only at the moment the value is checked. If the checked value is different of the updated value, the exception is thrown.
So I tried to update the current datetime at each lifecycle in the following hook method to prevent the exception:
ngAfterViewChecked()
{
console.log( ""! changement de la date du composant !"" );
this.dateNow = new Date();
}
...but without success.
",https://stackoverflow.com/questions/39787038/how-to-manage-angular2-expression-has-changed-after-it-was-checked-exception-w,229,277459.0,13.0,,,2016-09-30 08:31:52,2022-12-21 10:42:09,2018-12-27 17:49:46,,,angular;typescript;time;styles;components,Anthony Brenelière,63860,3433751,registered,true,39787056,,CC BY-SA 4.0,,1210,1062,4,0,0,5,true,false,false,true,true,true,142,20,false,0.047,0.0008,3704,2016,9,8,Friday,false,false,false,false,false,false,false
30174078,How to define Singleton in TypeScript,"What is the best and most convenient way to implement a Singleton pattern for a class in TypeScript? (Both with and without lazy initialisation).
",https://stackoverflow.com/questions/30174078/how-to-define-singleton-in-typescript,229,237621.0,25.0,,,2015-05-11 17:35:08,2025-11-29 05:26:49,,,,singleton;typescript,maja,18202,2224996,registered,true,30174360,,CC BY-SA 3.0,2022-08-08 07:51:39,153,146,0,0,0,2,true,false,false,true,true,false,37,6,false,0.105,0.001,4212,2015,5,17,Monday,false,false,false,false,false,false,false
13407036,How does interfaces with construct signatures work?,"I am having some trouble working out how defining constructors in interfaces work. I might be totally misunderstanding something. But I have searched for answers for a good while and I can not find anything related to this.
How do I implement the following interface in a TypeScript class:
interface MyInterface {
new ( ... ) : MyInterface;
}
Anders Hejlsberg creates an interface containing something similar to this in this video (at around 14 minutes). But for the life of me I can not implement this in a class.
I am probably misunderstanding something, what am I not getting?
EDIT:
To clarify. With ""new ( ... )"" I meant ""anything"". My problem is that I can not get even the most basic version of this working:
interface MyInterface {
new () : MyInterface;
}
class test implements MyInterface {
constructor () { }
}
This is not compiling for me I get ""Class 'test' declares interface 'MyInterface' but does not implement it: Type 'MyInterface' requires a construct signature, but Type 'test' lacks one"" when trying to compile it.
EDIT:
So after researching this a bit more given the feedback.
interface MyInterface {
new () : MyInterface;
}
class test implements MyInterface {
constructor () => test { return this; }
}
Is not valid TypeScript and this does not solve the problem. You can not define the return type of the constructor. It will return ""test"". The signature of the following:
class test {
constructor () { }
}
Seems to be ""new () => test"" (obtained by hovering over ""class"" in the online editor with just that code pasted in). And this is what we would want and what i thought it would be.
Can anyone provide an example of this or something similar where it is actually compiling?
EDIT (again...):
So I might have come up with an idea as to why it is possible to define this in an interface but not possible to implement in a TypeScript class.The following works:
var MyClass = (function () {
function MyClass() { }
return MyClass;
})();
interface MyInterface {
new () : MyInterface;
}
var testFunction = (foo: MyInterface) : void => { }
var bar = new MyClass();
testFunction(bar);
So is this only a feature of TypeScript that lets you interface javascript? Or is it possible to implement it in TypeScript without having to implement the class using javascript?
",https://stackoverflow.com/questions/13407036/how-does-interfaces-with-construct-signatures-work,229,164412.0,8.0,,,2012-11-15 22:03:36,2022-08-10 12:32:34,2019-02-13 20:32:52,,,typescript;constructor;interface,Nypan,7246,1827926,registered,true,13408029,,CC BY-SA 4.0,,2677,2374,4,1,0,3,true,false,false,true,true,true,51,7,true,0.049,0.0014,5119,2012,11,22,Thursday,false,false,false,false,false,false,false
62619058,Appending .js extension on relative import statements during Typescript compilation (ES6 modules),"This seems to be a trivial problem, but it is not very obvious what settings/configurations need to be used to solve this issue.
Here are the Hello World program directory structure and the source code:
Directory Structure:
| -- HelloWorldProgram
| -- HelloWorld.ts
| -- index.ts
| -- package.json
| -- tsconfig.json
index.ts:
import {HelloWorld} from "./HelloWorld";
let world = new HelloWorld();
HelloWorld.ts:
export class HelloWorld {
constructor(){
console.log("Hello World!");
}
}
package.json:
{
"type": "module",
"scripts": {
"start": "tsc && node index.js"
}
}
Now, execution of the command tsc && node index.js results in the following error:
internal/modules/run_main.js:54
internalBinding('errors').triggerUncaughtException(
^
Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'HelloWorld' imported from HelloWorld\index.js
Did you mean to import ../HelloWorld.js?
at finalizeResolution (internal/modules/esm/resolve.js:284:11)
at moduleResolve (internal/modules/esm/resolve.js:662:10)
at Loader.defaultResolve [as _resolve] (internal/modules/esm/resolve.js:752:11)
at Loader.resolve (internal/modules/esm/loader.js:97:40)
at Loader.getModuleJob (internal/modules/esm/loader.js:242:28)
at ModuleWrap.<anonymous> (internal/modules/esm/module_job.js:50:40)
at link (internal/modules/esm/module_job.js:49:36) {
code: 'ERR_MODULE_NOT_FOUND'
}
It is obvious that the problem seems to have been originated from the fact that in index.ts Typescript file there is no .js extension in the import statement (import {HelloWorld} from "./HelloWorld";). Typescript didn't throw any error during compilation. However, during runtime Node (v14.4.0) wants the .js extension.
Hope the context is clear.
Now, how to change the compiler output setting (tsconfig.json or any flags) so that local relative path imports such as import {HelloWorld} from ./Helloworld; will get replaced by import {HelloWorld} from ./Helloworld.js; during Typescript to Javascript compilation in the index.js file?
Note:
It is possible to directly use the .js extension while importing inside typescript file. However, it doesn't help much while working with hundreds of old typescript modules, because then we have to go back and manually add .js extension. Rather than that for us better solution is to batch rename and remove all the .js extension from all the generated .js filenames at last.
",https://stackoverflow.com/questions/62619058/appending-js-extension-on-relative-import-statements-during-typescript-compilat,229,87757.0,24.0,,,2020-06-28 06:34:13,2026-02-09 23:09:00,2020-06-28 07:13:43,,,javascript;node.js;typescript;npm;node-modules,user3330840,7591,3330840,registered,true,62626938,,CC BY-SA 4.0,,2903,2589,14,0,0,5,true,false,false,true,true,true,97,12,false,0.273,0.0026,2337,2020,6,6,Sunday,true,false,true,false,false,false,false
38888008,How can I use/create dynamic template to compile dynamic Component with Angular 2.0?,"I want to dynamically create a template. This should be used to build a ComponentType at runtime and place (even replace) it somewhere inside of the hosting Component.
Until RC4 I was using ComponentResolver, but with RC5 I get the following message:
ComponentResolver is deprecated for dynamic compilation.
Use ComponentFactoryResolver together with @NgModule/@Component.entryComponents or ANALYZE_FOR_ENTRY_COMPONENTS provider instead.
For runtime compile only, you can also use Compiler.compileComponentSync/Async.
I found this document (Angular 2 Synchronous Dynamic Component Creation)
And understand that I can use either
- Kind of dynamic
ngIf with ComponentFactoryResolver. If I pass known components inside of @Component({entryComponents: [comp1, comp2], ...}) - I can use .resolveComponentFactory(componentToRender);
- Real runtime compilation, with
Compiler...
But the question is how to use that Compiler? The note above says that I should call: Compiler.compileComponentSync/Async - so how?
For example. I want to create (based on some configuration conditions) this kind of template for one kind of settings
<form>
<string-editor
[propertyName]=""'code'""
[entity]=""entity""
></string-editor>
<string-editor
[propertyName]=""'description'""
[entity]=""entity""
></string-editor>
...
and in another case this one (string-editor is replaced with text-editor)
<form>
<text-editor
[propertyName]=""'code'""
[entity]=""entity""
></text-editor>
...
And so on (different number/date/reference editors by property types, skipped some properties for some users...). i.e. this is an example, the real configuration could generate much more different and complex templates.
The template is changing, so I cannot use ComponentFactoryResolver and pass existing ones... I need a solution with the Compiler.
",https://stackoverflow.com/questions/38888008/how-can-i-use-create-dynamic-template-to-compile-dynamic-component-with-angular,228,197206.0,16.0,,,2016-08-11 05:37:07,2024-08-29 14:27:06,2019-12-27 16:50:15,,,angular;typescript;compilation;angular2-compiler,Radim Köhler,124091,1679310,registered,true,38888009,,CC BY-SA 4.0,2022-08-12 02:03:44,2539,1914,17,1,0,4,true,false,false,true,true,true,84,13,true,0.081,0.0012,3754,2016,8,5,Thursday,false,false,false,false,false,false,false
48859169,Error: 'types' can only be used in a .ts file - Visual Studio Code using @ts-check,"I am starting to use TypeScript in a Node project I am working on in Visual Studio Code. I wanted to follow the ""opt-in"" strategy, similar to Flow. Therefore I put // @ts-check at the top of my .js file in hope to enable TS for that file. Ultimately I want the same experience of ""linting"" as Flow, therefore I installed the plugin TSLint so I could see Intellisense warnings/errors.
But with my file looking like:
// @ts-check
module.exports = {
someMethod: (param: string): string => {
return param;
},
};
and my tsconfig.json file looking like...
{
""compilerOptions"": {
""target"": ""es2016"",
""module"": ""commonjs"",
""allowJs"": true
}
}
I get this error: [js] 'types' can only be used in a .ts file. as shown below in the image.
I saw this question which recommended disabling javascript validation in vscode but then that doesn't show me any TypeScript Intellisense info.
I tried setting tslint.jsEnable to true in my vscode settings as mentioned in the TSLint extension docs but no luck there.
What is the correct setup in order to use .js files with TypeScript and get Intellisense so I know what the errors in my code are before I run any TS commands?
",https://stackoverflow.com/questions/48859169/error-types-can-only-be-used-in-a-ts-file-visual-studio-code-using-ts-che,227,356396.0,15.0,,,2018-02-19 03:28:53,2025-01-17 17:59:24,2022-03-01 19:29:50,,,javascript;typescript;vs-code,james,5276,1554860,registered,true,50385231,,CC BY-SA 4.0,,1759,1200,9,3,1,3,true,false,false,true,true,true,90,16,false,0.042,0.0006,3197,2018,2,3,Monday,false,false,true,false,false,false,false
46915002,Argument of type 'string | null' is not assignable to parameter of type 'string'. Type 'null' is not assignable to type 'string',"I have a dotnetcore 20 and angular4 project that I am trying to create a userService and get the user to my home component. The backend works just fine but the service doesn't. The problem is on localStorage. The error message that I have is :
Argument of type 'string | null' is not assignable to parameter of type 'string'.
Type 'null' is not assignable to type 'string'.
And my userService
import { User } from './../models/users';
import { AppConfig } from './../../app.config';
import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
@Injectable()
export class UserService {
constructor(private http: Http, private config: AppConfig) { }
getAll() {
return this.http.get(this.config.apiUrl + '/users', this.jwt()).map((response: Response) => response.json());
}
getById(_id: string) {
return this.http.get(this.config.apiUrl + '/users/' + _id, this.jwt()).map((response: Response) => response.json());
}
create(user: User) {
return this.http.post(this.config.apiUrl + '/users/register', user, this.jwt());
}
update(user: User) {
return this.http.put(this.config.apiUrl + '/users/' + user.id, user, this.jwt());
}
delete(_id: string) {
return this.http.delete(this.config.apiUrl + '/users/' + _id, this.jwt());
}
// private helper methods
private jwt() {
// create authorization header with jwt token
let currentUser = JSON.parse(localStorage.getItem('currentUser'));
if (currentUser && currentUser.token) {
let headers = new Headers({ 'Authorization': 'Bearer ' + currentUser.token });
return new RequestOptions({ headers: headers });
}
}
And my home.component.ts is
import { UserService } from './../services/user.service';
import { User } from './../models/users';
import { Component, OnInit } from '@angular/core';
@Component({
moduleId: module.id,
templateUrl: 'home.component.html'
})
export class HomeComponent implements OnInit {
currentUser: User;
users: User[] = [];
constructor(private userService: UserService) {
this.currentUser = JSON.parse(localStorage.getItem('currentUser'));
}
ngOnInit() {
this.loadAllUsers();
}
deleteUser(_id: string) {
this.userService.delete(_id).subscribe(() => { this.loadAllUsers() });
}
private loadAllUsers() {
this.userService.getAll().subscribe(users => { this.users = users; });
}
The error is on JSON.parse(localStorage.getItem('currentUser'));
",https://stackoverflow.com/questions/46915002/argument-of-type-string-null-is-not-assignable-to-parameter-of-type-string,227,501044.0,14.0,,,2017-10-24 15:55:39,2024-10-29 10:11:12,2021-05-23 14:35:34,,,angular;typescript,GoGo,3097,3450163,registered,true,46915314,,CC BY-SA 4.0,,2613,2475,3,0,0,2,true,false,false,true,true,true,160,22,false,0.028,0.0005,3315,2017,10,15,Tuesday,false,false,false,false,false,false,false
56833469,Typescript error: TS7053 Element implicitly has an 'any' type,"this is part of my code:
const myObj: object = {}
const propname = 'propname'
myObj[propname] = 'string'
but I got error:
ERROR in path/to/file.ts(4,1)
TS7053: Element implicitly has an 'any' type because expression of type '""propname""' can't be used to index type '{}'.
Property 'propname' does not exist on type '{}'.
What is wrong here, and how can I fix it?
",https://stackoverflow.com/questions/56833469/typescript-error-ts7053-element-implicitly-has-an-any-type,227,192617.0,9.0,,,2019-07-01 09:49:53,2025-04-06 20:20:07,,,,typescript,Cichy,5402,1842159,registered,true,56833507,,CC BY-SA 4.0,,514,371,2,0,0,1,true,false,false,true,true,false,69,9,false,0.047,0.0012,2700,2019,7,9,Monday,false,false,false,false,false,false,false
33571605,Angular 2 - How do I navigate to another route using this.router.parent.navigate('/about')?,"Angular 2 - How do I navigate to another route using this.router.parent.navigate('/about')?
It doesn't seem to work.
I tried location.go("/about"); as that didn't work.
Basically, once a user has logged in I want to redirect them to another page.
Here is my code below:
import {Component} from 'angular2/angular2';
import {CORE_DIRECTIVES, FORM_DIRECTIVES} from 'angular2/angular2';
import {Router} from 'angular2/router';
import {AuthService} from '../../authService';
//Model
class User {
constructor(public email: string, public password: string) {}
}
@Component({
templateUrl:'src/app/components/todo/todo.html',
directives: [CORE_DIRECTIVES, FORM_DIRECTIVES]
})
export class Todo {
model = new User('Mark@gmail.com', 'Password');
authService:AuthService;
router: Router;
constructor(_router: Router, _authService: AuthService){
this.authService = _authService;
this.router = _router;
}
onLogin = () => {
this.authService.logUserIn(this.model).then((success) => {
//This is where its broke - below:
this.router.parent.navigate('/about');
});
}
}
",https://stackoverflow.com/questions/33571605/angular-2-how-do-i-navigate-to-another-route-using-this-router-parent-navigate,227,408460.0,5.0,,,2015-11-06 16:45:20,2022-08-14 15:00:38,2021-03-17 21:55:41,,,angular;typescript;angular2-routing,AngularM,16700,1590389,registered,true,37622179,,CC BY-SA 4.0,,1271,1193,3,0,0,3,true,false,false,true,true,true,99,12,true,0.012,0.0006,4033,2015,11,16,Friday,false,false,false,false,false,false,false
32050645,How to use jQuery with TypeScript,"I am trying
$(function(){
alert('Hello');
});
Its showing this error in Visual Studio: (TS) Cannot find name '$'.. How can I use jQuery with TypeScript ?
",https://stackoverflow.com/questions/32050645/how-to-use-jquery-with-typescript,227,388086.0,18.0,,,2015-08-17 12:38:39,2026-07-05 05:15:11,2018-03-30 03:39:31,,,typescript,JavaScript Linq,2845,5230527,registered,true,,,CC BY-SA 3.0,,215,164,2,0,0,1,false,false,false,true,true,true,33,6,false,0.046,0.0006,4114,2015,8,12,Monday,false,false,false,false,false,false,false
39256682,How to define an interface for objects with dynamic keys?,"I have an Object like this that is created by underscore's _.groupBy() method.
myObject = {
""key"" : [{Object},{Object2},{Object3}],
""key2"" : [{Object4},{Object5},{Object6}],
...
}
How would I define that as an Interface with TypeScript?
i don't want to simply define it as myObject:Object = { ... but rather have an own type for it.
",https://stackoverflow.com/questions/39256682/how-to-define-an-interface-for-objects-with-dynamic-keys,226,279278.0,6.0,,,2016-08-31 18:33:52,2021-07-23 11:17:52,2021-07-23 11:17:52,,,typescript,Manuel Schiller,3247,6632579,registered,true,39257653,,CC BY-SA 4.0,,406,342,3,0,0,1,true,false,false,true,true,true,57,10,true,0.021,0.0008,3734,2016,8,18,Wednesday,false,false,false,false,false,false,false
35163009,Angular 2 Show and Hide an element,"I'm having a problem hiding and showing an element depending of a boolean variable in Angular 2.
this is the code for the div to show and hide:
<div *ngIf=""edited==true"" class=""alert alert-success alert-dismissible fade in"" role=""alert"">
<strong>List Saved!</strong> Your changes has been saved.
</div>
the variable is ""edited"" and it's stored in my component:
export class AppComponent implements OnInit{
(...)
public edited = false;
(...)
saveTodos(): void {
//show box msg
this.edited = true;
//wait 3 Seconds and hide
setTimeout(function() {
this.edited = false;
console.log(this.edited);
}, 3000);
}
}
The element is hidden, when saveTodos function starts, the element is shown, but after 3 seconds, even if the variable come back to be false, the element does not hide. Why?
",https://stackoverflow.com/questions/35163009/angular-2-show-and-hide-an-element,225,684298.0,11.0,,,2016-02-02 20:16:40,2023-02-16 08:08:09,2016-02-02 20:56:18,,,typescript;angular,user4956851,,,does_not_exist,true,35163037,,CC BY-SA 3.0,,973,860,2,0,0,2,true,false,false,true,false,true,34,7,false,0.016,0.0003,3945,2016,2,20,Tuesday,false,false,false,false,false,false,false
37525094,How can I make a generic type optional?,"I have the following logging method:
private logData<T, S>(operation: string, responseData: T, requestData?: S) {
this.logger.log(operation + ' ' + this.url);
if (requestData) {
this.logger.log('SENT');
this.logger.log(requestData);
}
this.logger.log('RECEIVED');
this.logger.log(responseData);
return responseData;
}
The requestData is optional. I want to be able to call logData without having to specify the S type when I don't send the requestData to the method: instead of: this.logData<T, any>('GET', data), I want to call this.logData<T>('GET', data).
Is there a way to achieve this?
",https://stackoverflow.com/questions/37525094/how-can-i-make-a-generic-type-optional,225,229911.0,7.0,,,2016-05-30 11:56:00,2023-07-02 09:19:10,2022-12-21 16:20:42,,,generics;typescript,Marius,3753,595136,registered,true,43543295,,CC BY-SA 4.0,,810,650,7,0,0,2,true,false,false,true,true,true,39,8,true,0.03,0.001,3827,2016,5,11,Monday,false,false,false,false,false,false,false
58273824,Typescript: Cannot use import statement outside a module,"I have a .ts file in node js (latest version of node.js for 07.10.19) app with importing node-module without default export. I use this construction: import { Class } from 'abc'; When i run the code, i have this error: Cannot use import statement outside a module.
In the network i see many solutions for this problem (for .js), but it not helps to me, maybe because i have typescript file. Here's my code:
import { Class } from 'abc';
module.exports = { ...
execute(a : Class ,args : Array<string>){ ...
Here's my tsconfig.json:
{
""compilerOptions"": {
""target"": ""es6"",
""module"": ""commonjs"",
""strict"": true
}
}
",https://stackoverflow.com/questions/58273824/typescript-cannot-use-import-statement-outside-a-module,225,409599.0,11.0,,,2019-10-07 16:43:06,2025-04-13 19:41:58,2019-11-24 20:04:56,,,typescript;ecmascript-6,Zerumi,2413,10739437,registered,true,60225870,,CC BY-SA 4.0,,739,644,4,0,0,2,true,false,false,true,true,true,56,8,false,0.027,0.0005,2602,2019,10,16,Monday,false,false,false,false,false,false,false
13212521,TypeScript static classes,"I wanted to move to TypeScript from traditional JS because I like the C#-like syntax.
My problem is that I can't find out how to declare static classes in TypeScript.
In C#, I often use static classes to organize variables and methods, putting them together in a named class, without needing to instatiate an object.
In vanilla JS, I used to do this with a simple JS object:
var myStaticClass = {
property: 10,
method: function(){}
}
In TypeScript, I would rather go for my C-sharpy approach, but it seems that static classes don't exist in TS.
What is the appropriate solution for this problem ?
",https://stackoverflow.com/questions/13212521/typescript-static-classes,224,311379.0,15.0,,,2012-11-03 19:08:38,2022-04-19 20:22:59,2017-07-12 15:30:49,,,javascript;class;static;typescript,Rayjax,7844,1397271,registered,true,13212648,,CC BY-SA 3.0,,655,610,1,0,0,4,true,false,false,true,true,true,25,3,false,0.048,0.0007,5131,2012,11,19,Saturday,true,false,true,false,false,false,false
44053227,How to emit an event from parent to child?,"I am currently using Angular 2. Usually we use @Output() addTab = new EventEmitter<any>(); and then addTab.emit() to emit an event to parent component.
Is there any way we can do it vice cersa, from parent to child?
",https://stackoverflow.com/questions/44053227/how-to-emit-an-event-from-parent-to-child,223,254784.0,7.0,,,2017-05-18 16:26:45,2022-08-02 08:10:06,2019-06-06 20:12:33,,,angular;typescript,code1,9209,7679343,registered,true,,,CC BY-SA 4.0,,263,223,2,0,0,2,false,false,false,true,true,true,42,9,true,0.027,0.0009,3474,2017,5,16,Thursday,false,false,false,false,false,false,false
46408537,Angular HttpClient "Http failure during parsing","I try to send an POST request from Angular 4 to my Laravel backend.
My LoginService has this method:
login(email: string, password: string) {
return this.http.post(`http://10.0.1.19/login`, { email, password })
}
I subscribe to this method in my LoginComponent:
.subscribe(
(response: any) => {
console.log(response)
location.reload()
},
(error: any) => {
console.log(error)
})
And this is my Laravel backend method:
...
if($this->auth->attempt(['email' => $email, 'password' => $password], true)) {
return response('Success', 200);
}
return response('Unauthorized', 401);
My Chrome dev tools says that my request was a success with 200 status code. But my Angular code triggers the error block and gives me this message:
Http failure during parsing for http://10.0.1.19/api/login
If I return an empty array from my backend, it works... So Angular is trying to parse my response as JSON? How can i disable this?
",https://stackoverflow.com/questions/46408537/angular-httpclient-http-failure-during-parsing,223,393347.0,13.0,,,2017-09-25 15:08:08,2023-10-27 19:29:46,2019-01-22 09:45:25,,,angular;typescript;angular-httpclient,nutzt,2943,4237070,registered,true,46408622,,CC BY-SA 4.0,2023-01-25 10:37:32,1212,995,4,1,0,3,true,false,false,true,true,true,58,6,false,0.033,0.0006,3344,2017,9,15,Monday,false,false,false,false,false,false,false
42677096,What does Angular 2 hashtags in template mean?,"I am working with angular 2 and I have found something like
<input #searchBox (keyup)=""search(searchBox.value)""
and it works.
However, I don't understand the meaning of #searchBox. I haven't found anything clear neither in the doc.
Could anyone explain to me how it works?
",https://stackoverflow.com/questions/42677096/what-does-angular-2-hashtags-in-template-mean,223,108203.0,4.0,,,2017-03-08 16:45:52,2024-12-31 02:06:01,2020-01-09 18:03:58,,,javascript;html;angular;typescript,ackuser,5959,3029263,registered,true,,,CC BY-SA 4.0,,352,283,1,0,0,4,false,false,false,true,true,true,46,8,true,0.037,0.0021,3545,2017,3,16,Wednesday,false,false,true,false,false,false,false
44480644,String Union to string Array,"I have a string union type like so:
type Suit = 'hearts' | 'diamonds' | 'spades' | 'clubs';
I want a type-safe way to get all the possible values that can be used in this string union. But because interfaces are largely a design-time construct, the best I can do is this:
export const ALL_SUITS = getAllStringUnionValues<Suit>({
hearts: 0,
diamonds: 0,
spades: 0,
clubs: 0
});
export function getAllStringUnionValues<TStringUnion extends string>(valuesAsKeys: { [K in TStringUnion]: 0 }): TStringUnion[] {
const result = Object.getOwnPropertyNames(valuesAsKeys);
return result as any;
}
This works okay, the function ensures I always pass an object where each key is an element in the string union and that every element is included, and returns a string array of all the elements. So if the string union ever changes, the call to this function will error at compile time if not also updated.
However the problem is the type signature for the constant ALL_SUITS is ('hearts' | 'diamonds' | 'spades' | 'clubs')[]. In other words, TypeScript thinks it is an array containing none or more of these values possibly with duplicates, rather than an array containing all the values just once, e.g. ['hearts', 'diamonds', 'spades', 'clubs'].
What I'd really like is a way for my generic getAllStringUnionValues function to specify that it returns ['hearts', 'diamonds', 'spades', 'clubs'].
How can I achieve this generically while being as DRY as possible?
",https://stackoverflow.com/questions/44480644/string-union-to-string-array,222,181296.0,8.0,,,2017-06-11 05:23:45,2025-02-26 22:51:02,2020-11-23 21:13:30,,,typescript,CodeAndCats,8084,26335,registered,true,45486495,,CC BY-SA 4.0,,1787,1495,7,1,0,1,true,false,false,true,true,true,28,5,false,0.044,0.0012,3450,2017,6,5,Sunday,true,false,false,false,false,false,false
43716263,How to check undefined in TypeScript,"I am using this code to check whether a variable is undefined, but it's not working.
var uemail = localStorage.getItem(""useremail"");
if (typeof uemail === ""undefined"")
{
alert('undefined');
}
else
{
alert('defined');
}
",https://stackoverflow.com/questions/43716263/how-to-check-undefined-in-typescript,222,673078.0,14.0,,,2017-05-01 08:19:36,2025-09-23 18:48:51,2023-02-24 19:12:20,,,typescript,pushp,2560,5291499,registered,true,,,CC BY-SA 4.0,,460,238,1,0,0,1,false,false,false,true,true,true,36,6,false,0.021,0.0003,3491,2017,5,8,Monday,false,false,false,false,false,false,false
39610294,Import two exported classes with the same name,"In typescript, using Angular 2, I need to import two classes with the same name, but lying in different paths.
The project is quite too big that I find it hard to change the exported class names.
Is there any way to alias the imported classes,
import {Class1} from '../location1/class1'
import {Class1} from '../location2/class1'
",https://stackoverflow.com/questions/39610294/import-two-exported-classes-with-the-same-name,221,103307.0,1.0,,,2016-09-21 07:38:56,2019-07-21 15:33:46,,,,angular;typescript;ionic2,Rizan Zaky,4702,4294275,registered,true,39610348,,CC BY-SA 3.0,,379,334,1,0,0,3,true,false,false,true,true,false,46,8,false,0.01,0.0021,3713,2016,9,7,Wednesday,false,false,false,false,false,false,false
24454371,How can I get the Typescript compiler to output the compiled js to a different directory?,"I'm fairly new to TypeScript, and right now I have .ts files in several places throughought my project structure:
app/
|-scripts/
|-app.ts
|
|-classes/
| |-classA.ts
| |-classB.ts
|
|-controllers/
| |-controllerA.ts
| |-controllerB.ts
|
|-otherStuff/
|-otherstuffA.ts
Right now, when my files are compiled, they are compiled to the same directory that the .ts fles are in:
app/
|-scripts/
|-app.ts
|-app.js
|
|-classes/
| |-classA.ts
| |-classB.ts
| |-classA.js
| |-classB.js
|
|-controllers/
| |-controllerA.ts
| |-controllerB.ts
| |-controllerA.js
| |-controllerB.js
|
|-otherStuff/
|-otherstuffA.ts
|-otherStuffA.js
While I like the way that the .js files keep the same directory structure as the .ts files, I don't want to track the .js files in my VCS, so I'd like to keep all of my JavaScript files in a separate directory tree (that I can then add to .gitignore), like so:
app/
|-scripts/
| |-app.ts
| |
| |-classes/
| | |-classA.ts
| | |-classB.ts
| |
| |-controllers/
| | |-controllerA.ts
| | |-controllerB.ts
| |
| |-otherStuff/
| |-otherstuffA.ts
|
|-js/
|-app.js
|
|-classes/
| |-classA.js
| |-classB.js
|
|-controllers/
| |-controllerA.js
| |-controllerB.js
|
|-otherStuff/
|-otherstuffA.js
Is there a setting or option somewhere that will tell the TypeScript compiler to do this? Also, I'm not sure if it's relevant, but I am using WebStorm.
",https://stackoverflow.com/questions/24454371/how-can-i-get-the-typescript-compiler-to-output-the-compiled-js-to-a-different-d,220,186429.0,10.0,,,2014-06-27 14:31:47,2024-07-15 07:56:30,2020-04-29 13:04:58,,,javascript;typescript;tsc,TheGuyWithTheFace,2845,3392912,registered,true,24454551,,CC BY-SA 4.0,,1710,1610,3,0,0,3,true,false,false,true,true,true,89,16,true,0.054,0.0012,4530,2014,6,14,Friday,false,false,true,false,false,false,false
32805559,TypeScript ES6 import module "File is not a module error","I am using TypeScript 1.6 with ES6 modules syntax.
My files are:
test.ts:
module App {
export class SomeClass {
getName(): string {
return 'name';
}
}
}
main.ts:
import App from './test';
var a = new App.SomeClass();
When I am trying to compile the main.ts file I get this error:
Error TS2306: File 'test.ts' is not a module.
How can I accomplish that?
",https://stackoverflow.com/questions/32805559/typescript-es6-import-module-file-is-not-a-module-error,219,390900.0,10.0,,,2015-09-27 07:24:55,2024-12-14 06:14:41,2022-02-13 01:38:03,,,javascript;typescript;ecmascript-6,Bazinga,11294,4159572,registered,true,32805764,,CC BY-SA 4.0,2023-02-19 14:58:05,562,376,3,0,0,3,true,false,false,true,true,true,67,10,false,0.026,0.0006,4073,2015,9,7,Sunday,true,false,true,false,false,false,false
53662208,Types from both keys and values of object in Typescript,"I have two sets of string values that I want to map from one to the other as a constant object. I want to generate two types from that mapping: one for keys and one for values.
const KeyToVal = {
MyKey1: 'myValue1',
MyKey2: 'myValue2',
};
The keys are easy enough:
type Keys = keyof typeof KeyToVal;
I'm having trouble getting a compile-time type for the values. I thought maybe one of these would work:
type Values = typeof KeyToVal[Keys];
type Values<K> = K extends Keys ? (typeof KeyToVal)[K] : never;
type Prefix<
K extends Keys = Keys,
U extends { [name: string]: K } = { [name: string]: K }
> = {[V in keyof U]: V}[K];
All of these just made Values to be string. I also tried adapting the two answers to How to infer typed mapValues using lookups in typescript?, but either I got my adaptations wrong, or the answers didn't fit my scenario in the first place.
",https://stackoverflow.com/questions/53662208/types-from-both-keys-and-values-of-object-in-typescript,218,276239.0,6.0,,,2018-12-07 01:56:17,2025-04-08 13:29:46,,,,typescript;typescript-typings,dx_over_dt,14550,3120446,registered,true,69902027,,CC BY-SA 4.0,,1271,909,5,1,0,2,true,false,false,true,true,false,55,10,false,0.022,0.0008,2906,2018,12,1,Friday,false,false,false,false,false,false,false
40238144,Safe navigation operator (?.) or (!.) and null property paths,"In Angular 2 templates safe operator ?. works, but not in component.ts using TypeScript 2.0. Also, safe navigation operator (!.) doesn't work.
For example:
This TypeScript
if (a!.b!.c) { }
compiles to this JavaScript
if (a.b.c) { }
But when I run it, I get the follow error:
Cannot read property 'b' of undefined
Is there any alternative to the following?
if (a && a.b && a.b.c) { }
",https://stackoverflow.com/questions/40238144/safe-navigation-operator-or-and-null-property-paths,218,291421.0,7.0,,,2016-10-25 10:57:42,2021-10-01 11:16:23,2020-10-29 20:15:37,,,typescript,Emerceen,2885,6081464,registered,true,58762171,,CC BY-SA 4.0,,589,404,6,0,0,1,true,false,false,true,true,true,61,10,false,0.024,0.0007,3679,2016,10,10,Tuesday,false,false,false,false,false,false,false
23130292,Test for array of string type in TypeScript,"How can I test if a variable is an array of string in TypeScript? Something like this:
function f(): string {
var a: string[] = [""A"", ""B"", ""C""];
if (typeof a === ""string[]"") {
return ""Yes""
}
else {
// returns no as it's 'object'
return ""No""
}
};
TypeScript.io here: http://typescript.io/k0ZiJzso0Qg/2
Edit: I've updated the text to ask for a test for string[]. This was only in the code example previously.
",https://stackoverflow.com/questions/23130292/test-for-array-of-string-type-in-typescript,218,377022.0,8.0,,,2014-04-17 10:11:30,2022-08-26 12:27:17,2014-04-17 11:22:52,,,typescript,Sean Kearon,11457,2608,registered,true,23133681,,CC BY-SA 3.0,,554,460,1,1,0,1,true,false,false,true,true,true,43,8,false,0.021,0.0006,4601,2014,4,10,Thursday,false,false,false,false,false,false,false
42233987,How to configure custom global interfaces (.d.ts files) for TypeScript?,"I'm currently working on a ReactJS project which uses Webpack2 and TypeScript. Everything works perfectly apart from one thing - I can't a find a way to move interfaces that I've written myself into separate files so that they are visible to the whole application.
For prototyping purposes I initially had interfaces defined in files that use them but eventually I started adding some that were needed in multiple classes and that's when all the problems started. No matter what changes I make to my tsconfig.json and no matter where I put the files my IDE and Webpack both complain about not being able to find names ("Could not find name 'IMyInterface'").
Here's my current tsconfig.json file:
{
"compilerOptions": {
"baseUrl": "src",
"outDir": "build/dist",
"module": "commonjs",
"target": "es5",
"lib": [
"es6",
"dom"
],
"typeRoots": [
"./node_modules/@types",
"./typings"
],
"sourceMap": true,
"allowJs": true,
"jsx": "react",
"moduleResolution": "node",
"rootDir": "src",
"forceConsistentCasingInFileNames": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noImplicitAny": false,
"strictNullChecks": true,
"suppressImplicitAnyIndexErrors": true,
"noUnusedLocals": true
},
"exclude": [
"node_modules",
"build",
"scripts",
"acceptance-tests",
"webpack",
"jest",
"src/setupTests.ts"
],
"types": [
"typePatches"
]
}
As you can see, my tsconfig.json is in the root of the project directory, all source is in ./src, I placed my custom .d.ts files in ./typings and included it in typeRoots.
I tested it with TypeScript 2.1.6 and 2.2.0 and neither works.
One way of getting it all to work is to move my typings directory into src and then import {IMyInterface} from 'typings/blah' but that doesn't feel right to me as it's not something I need to use. I want those interfaces to just be 'magically' available throughout my application.
Here's a sample app.d.ts file:
interface IAppStateProps {}
interface IAppDispatchProps {}
interface IAppProps extends IAppStateProps, IAppDispatchProps {}
Do I need to export them or maybe declare? I hope I don't have to wrap them in a namespace?!
Update (October 2020)
Seeing how this question is still surprisingly popular I wanted to explain the solution in more detail.
Firstly, what could and should be confusing to people is that the interface example I gave at the end of my question actually doesn't have any export keywords even though I'm almost certain I did have them in my files at the time of asking the question. I believe I didn't include them in the question thinking they didn't make any difference, whether they were there or not. Well, it turns out that it's not true and the export keyword is exactly what makes or breaks you being able to just "use" the interfaces versus having to explicitly import them.
So, the way it works in TypeScript is as follows:
If you want an interface/type that you can simply use without having to import it in the consuming module said interface must reside in a .ts or ideally a .d.ts file without any imports or exports being present in the same file. This is of utmost importance because as soon as you are exporting at least one thing from the same file it becomes a module and everything that is in that module must be subsequently imported by consumers.
To give you an example let's assume you want to have a type called Dictionary that you want to be able to use without importing. The way to declare it would be as follows:
// types.d.ts
interface Dictionary {}
interface Foo {}
interface Bar {}
To use it you simply do:
// consumer.ts
const dict: Dictionary = {};
However, it will no longer work if for some reason any of the interfaces/types in that file are exported, e.g.:
// types.d.ts
interface Dictionary {}
interface Foo {}
export interface Bar {}
It will also not work if there are imports in that file:
// types.d.ts
import { OtherType } from 'other-library';
interface Dictionary {}
interface Foo extends OtherType {}
interface Bar {}
If that is the case the only way to be able to use the Dictionary type would be to also export it and then import it in the consumer:
// types.d.ts
export interface Dictionary {}
interface Foo {}
export interface Bar {}
// consumer.ts
import { Dictionary } from './types';
const dict: Dictionary = {};
--isolatedModules
There is an additional quirk to keep in mind when using the isolatedModules modules flag in TypeScript, which, importantly, is enabled by default (and cannot be disabled) when using Create React App - .ts files MUST export at least one thing as otherwise you will be getting the "All files must be modules when the '--isolatedModules' flag is provided." error. That means that putting the Dictionary interface in a types.ts files without the export keyword won't work. It must either be an export from a .ts file of be a declaration without the export in a .d.ts file:
// types.d.ts
interface Dictionary {} // works
export interface Dictionary {} // works
// types.ts
interface Dictionary {} // doesn't work with --isolatedModules enabled
export interface Dictionary {} // works
N.B.
As @dtabuenc mentions in his answer ambient modules (.d.ts files) are discoraged and my correction shouldn't be taken as advice. It's just an attempt at explaining how normal modules and ambient modules work in TypeScript.
",https://stackoverflow.com/questions/42233987/how-to-configure-custom-global-interfaces-d-ts-files-for-typescript,218,177917.0,2.0,,,2017-02-14 18:50:22,2023-12-28 19:45:15,2020-10-19 11:16:28,,,typescript;typescript-typings;typescript2.0;typescript1.8,Andris,6133,1288418,registered,true,42257742,,CC BY-SA 4.0,,6936,5882,36,0,0,4,true,false,false,true,true,true,71,10,true,0.011,0.0012,3567,2017,2,18,Tuesday,false,false,false,false,false,false,false
36475626,How to extend / inherit components?,"I would like to create extensions for some components already deployed in Angular 2, without having to rewrite them almost completely, as the base component could undergo changes and wish these changes were also reflected in its derived components.
I created this simple example to try to explain better my questions:
With the following base component app/base-panel.component.ts:
import {Component, Input} from 'angular2/core';
@Component({
selector: 'base-panel',
template: '<div class=""panel"" [style.background-color]=""color"" (click)=""onClick($event)"">{{content}}</div>',
styles: [`
.panel{
padding: 50px;
}
`]
})
export class BasePanelComponent {
@Input() content: string;
color: string = ""red"";
onClick(event){
console.log(""Click color: "" + this.color);
}
}
Would you like to create another derivative component only alter, for example, a basic component behavior in the case of the example color, app/my-panel.component.ts:
import {Component} from 'angular2/core';
import {BasePanelComponent} from './base-panel.component'
@Component({
selector: 'my-panel',
template: '<div class=""panel"" [style.background-color]=""color"" (click)=""onClick($event)"">{{content}}</div>',
styles: [`
.panel{
padding: 50px;
}
`]
})
export class MyPanelComponent extends BasePanelComponent{
constructor() {
super();
this.color = ""blue"";
}
}
Complete working example in Plunker
Note: Obviously this example is simple and could be solved otherwise no need to use inheritance, but it is intended only to illustrate the real problem.
As you can see in the implementation of the derivative component app/my-panel.component.ts, much of the implementation was repeated, and the single part really inherited was the class BasePanelComponent, but the @Component had to basically be completely repeated, not just the changed portions, as the selector: 'my-panel'.
Is there some way to make a literally full inheritance of a component Angular2, inheriting the class definition of the markings/annotations, as for example @Component?
Edit 1 - Feature Request
Feature request angular2 added to the project on GitHub: Extend/Inherit angular2 components annotations #7968
Edit 2 - Closed Request
The request was closed, for this reason, that briefly would not know how to merge the decorator will be made. Leaving us with no options. So my opinion is is quoted in the Issue.
",https://stackoverflow.com/questions/36475626/how-to-extend-inherit-components,216,243429.0,10.0,,,2016-04-07 12:03:20,2022-03-23 19:07:02,2020-06-29 09:38:58,,,angular;typescript;inheritance;angular-directive,Fernando Leal,10205,2290538,registered,true,,,CC BY-SA 4.0,,3193,2472,11,4,0,4,false,false,false,true,true,true,35,6,true,0.041,0.0009,3880,2016,4,12,Thursday,false,false,false,false,false,false,false
16047306,How is Docker different from a virtual machine?,"I keep rereading the Docker documentation to try to understand the difference between Docker and a full VM. How does it manage to provide a full filesystem, isolated networking environment, etc. without being as heavy?
Why is deploying software to a Docker image (if that's the right term) easier than simply deploying to a consistent production environment?
",https://stackoverflow.com/questions/16047306/how-is-docker-different-from-a-virtual-machine,4502,966201.0,26.0,,,2013-04-16 21:19:47,2026-10-29 14:34:13,2022-03-27 15:13:00,,,docker;virtual-machine,zslayton,53133,109549,registered,true,16048358,,CC BY-SA 4.0,2014-09-03 22:48:37,430,360,0,1,0,2,true,false,false,true,true,true,47,8,true,0.027,0.0047,4967,2013,4,21,Tuesday,false,false,false,false,false,false,false
24319662,"From inside of a Docker container, how do I connect to the localhost of the machine?","I have an Nginx instance running inside a Docker container. I have a MySQL running on the host system. I want to connect to the MySQL from within my container. MySQL is only binding to the localhost device.
Is there a way to connect to this MySQL or any other program on localhost from within this docker container?
This question is different from "How to get the IP address of the Docker host from inside a Docker container" due to the fact that the IP address of the Docker host could be the public IP address or the private IP address in the network which may or may not be reachable from within the Docker container (I mean public IP address if hosted at AWS or something).
Even if you have the IP address of the Docker host, it does not mean you can connect to the Docker host from within the container, given that IP address as your Docker network may be overlay, host, bridge, macvlan, none. etc., which restricts the reachability of that IP address.
",https://stackoverflow.com/questions/24319662/from-inside-of-a-docker-container-how-do-i-connect-to-the-localhost-of-the-mach,3568,2928910.0,45.0,,,2014-06-20 03:54:16,2026-08-09 14:00:05,2025-04-11 22:59:30,,,docker;nginx;docker-container;docker-network,Phil,51084,78000,registered,true,24326540,,CC BY-SA 4.0,2020-08-13 07:09:35,1148,968,0,2,0,4,true,false,false,true,true,true,84,16,true,0.015,0.0012,4537,2014,6,3,Friday,false,false,false,false,false,false,false
24958140,What is the difference between the 'COPY' and 'ADD' commands in a Dockerfile?,"What is the difference between the COPY and ADD commands in a Dockerfile, and when would I use one over the other?
COPY <src> <dest>
The COPY instruction will copy new files from <src> and add them to the container's filesystem at path <dest>
ADD <src> <dest>
The ADD instruction will copy new files from <src> and add them to the container's filesystem at path <dest>.
",https://stackoverflow.com/questions/24958140/what-is-the-difference-between-the-copy-and-add-commands-in-a-dockerfile,3144,1141007.0,17.0,,,2014-07-25 14:31:20,2026-01-02 02:08:29,2019-09-16 05:12:49,,,docker;dockerfile,Steve,55843,131640,registered,true,24958548,,CC BY-SA 4.0,,629,432,8,0,0,2,true,false,false,true,true,true,93,13,true,0.015,0.0028,4502,2014,7,14,Friday,false,false,false,false,false,false,false
22049212,Copying files from Docker container to host,"I'm thinking of using Docker to build my dependencies on a Continuous Integration (CI) server, so that I don't have to install all the runtimes and libraries on the agents themselves.
To achieve this I would need to copy the build artifacts that are built inside the container back into the host. Is that possible?
",https://stackoverflow.com/questions/22049212/copying-files-from-docker-container-to-host,3043,2162699.0,29.0,,,2014-02-26 17:46:52,2026-10-21 18:37:21,2023-05-10 16:18:03,,,docker;docker-container;file-copying,user2668128,43118,2668128,registered,true,22050116,,CC BY-SA 4.0,2023-02-17 09:32:09,331,317,0,0,0,3,true,false,false,true,true,true,43,7,false,0.013,0.0014,4651,2014,2,17,Wednesday,false,false,false,false,false,false,false
21553353,What is the difference between CMD and ENTRYPOINT in a Dockerfile?,"In Dockerfiles there are two commands that look similar to me: CMD and ENTRYPOINT. But I guess that there is a (subtle?) difference between them - otherwise it would not make any sense to have two commands for the very same thing.
The documentation states for CMD-
The main purpose of a CMD is to provide defaults for an executing container.
and for ENTRYPOINT:
An ENTRYPOINT helps you to configure a container that you can run as an executable.
So, what's the difference between those two commands?
",https://stackoverflow.com/questions/21553353/what-is-the-difference-between-cmd-and-entrypoint-in-a-dockerfile,2905,1104994.0,19.0,,,2014-02-04 13:04:23,2026-03-22 05:03:12,2024-04-15 01:54:40,,,docker;docker-entrypoint;docker-cmd,Golo Roden,153081,1333873,registered,true,21564990,,CC BY-SA 4.0,2020-02-11 00:05:01,648,504,4,0,0,3,true,false,false,true,true,true,66,11,true,0.017,0.0026,4673,2014,2,13,Tuesday,false,false,false,false,false,false,false
22907231,How can I copy files from a host to a Docker container?,"I am trying to build a backup-and-restore solution for the Docker containers that we work with.
I have a Docker base image that I have created, ubuntu:base, and do not want have to rebuild it each time with a Docker file to add files to it.
I want to create a script that runs from the host machine and creates a new container using the ubuntu:base Docker image and then copies files into that container.
How can I copy files from the host to the container?
",https://stackoverflow.com/questions/22907231/how-can-i-copy-files-from-a-host-to-a-docker-container,2584,2619497.0,54.0,,,2014-04-07 08:28:55,2026-08-24 22:18:05,2026-01-01 18:56:33,,,docker;docker-container,user3001829,26250,3001829,registered,true,31971697,,CC BY-SA 4.0,2019-07-10 19:25:50,512,458,2,0,0,2,true,false,false,true,true,true,55,12,true,0.021,0.001,4611,2014,4,8,Monday,false,false,false,false,false,false,false
30172605,How do I get a console-like connection into a Docker container's shell?,"I'm trying to SSH into one of my Docker containers running the WordPress base image to inspect the files/directories that were created during the initial build.
I tried to run docker-compose run containername ls -la, but that didn't do anything.
Even if it did, I'd rather have a console where I can traverse the directory structure, rather than run a single command.
Is something like this possible with Docker, and if so, how?
",https://stackoverflow.com/questions/30172605/how-do-i-get-a-console-like-connection-into-a-docker-containers-shell,2517,3923189.0,32.0,,,2015-05-11 16:12:30,2026-01-04 21:03:58,2025-11-07 20:24:12,2025-08-14 07:59:11,Not suitable for this site,docker;docker-container,Andrew,241827,48523,registered,true,30173220,,,2018-07-26 13:10:42,470,429,1,0,0,2,true,true,false,true,true,true,75,12,true,0.008,0.0006,4212,2015,5,16,Monday,false,false,false,false,false,false,false
23935141,How to copy Docker images from one host to another without using a repository,"How do I transfer a Docker image from one machine to another one without using a repository, no matter private or public?
I create my own image in VirtualBox, and when it is finished I try to deploy to other machines to have real usage.
Since it is based on my own base image (like Red Hat Linux), it cannot be recreated from a Dockerfile. My Dockerfile isn't easily portable.
Are there simple commands I can use? Or another solution?
",https://stackoverflow.com/questions/23935141/how-to-copy-docker-images-from-one-host-to-another-without-using-a-repository,2450,1571673.0,26.0,,,2014-05-29 13:57:18,2026-01-09 18:05:47,2025-05-31 22:50:59,,,docker,Larry Cai,61163,308174,registered,true,23938978,,CC BY-SA 4.0,2018-04-25 21:38:30,463,435,0,0,0,1,true,false,false,true,true,true,77,14,false,0.017,0.0016,4559,2014,5,13,Thursday,false,false,false,false,false,false,false
17157721,How to get a Docker container's IP address from the host,"Is there a command I can run to get the container's IP address right from the host after a new container is created?
Basically, once Docker creates the container, I want to roll my own code deployment and container configuration scripts.
",https://stackoverflow.com/questions/17157721/how-to-get-a-docker-containers-ip-address-from-the-host,2261,2841901.0,56.0,,,2013-06-17 22:10:22,2024-03-28 09:48:00,2021-04-08 13:32:36,,,docker;ip-address,Murali Allada,23146,1131518,registered,true,20686101,,CC BY-SA 4.0,2018-05-09 15:15:29,253,239,0,0,0,2,true,false,false,true,true,true,60,11,false,0.02,0.0008,4905,2013,6,22,Monday,false,false,false,false,false,false,false
16647069,Should I use Vagrant or Docker for creating an isolated environment?,"I use Ubuntu for development and deployment and have a need for creating an isolated environment.
I am considering either Vagrant or Docker for this purpose. What are the pros and cons, or how do these solutions compare?
",https://stackoverflow.com/questions/16647069/should-i-use-vagrant-or-docker-for-creating-an-isolated-environment,2209,432982.0,10.0,,,2013-05-20 10:05:25,2025-10-07 06:33:12,2016-12-24 22:57:52,2017-05-11 07:20:10,Needs more focus,vagrant;docker,murtaza52,47541,780799,registered,true,16761439,,,2014-07-30 12:12:26,237,223,0,0,0,2,true,true,false,true,true,true,68,11,true,0.023,0.0051,4933,2013,5,10,Monday,false,false,false,false,false,false,false
35594987,How to force Docker for a clean build of an image,"I have build a Docker image from a Docker file using the below command.
$ docker build -t u12_core -f u12_core .
When I am trying to rebuild it with the same command, it's using the build cache like:
Step 1 : FROM ubuntu:12.04
---> eb965dfb09d2
Step 2 : MAINTAINER Pavan Gupta <pavan.gupta@gmail.com>
---> Using cache
---> 4354ccf9dcd8
Step 3 : RUN apt-get update
---> Using cache
---> bcbca2fcf204
Step 4 : RUN apt-get install -y openjdk-7-jdk
---> Using cache
---> 103f1a261d44
Step 5 : RUN apt-get install -y openssh-server
---> Using cache
---> dde41f8d0904
Step 6 : RUN apt-get install -y git-core
---> Using cache
---> 9be002f08b6a
Step 7 : RUN apt-get install -y build-essential
---> Using cache
---> a752fd73a698
Step 8 : RUN apt-get install -y logrotate
---> Using cache
---> 93bca09b509d
Step 9 : RUN apt-get install -y lsb-release
---> Using cache
---> fd4d10cf18bc
Step 10 : RUN mkdir /var/run/sshd
---> Using cache
---> 63b4ecc39ff0
Step 11 : RUN echo 'root:root' | chpasswd
---> Using cache
---> 9532e31518a6
Step 12 : RUN sed -i 's/PermitRootLogin without-password/PermitRootLogin yes/' /etc/ssh/sshd_config
---> Using cache
---> 47d1660bd544
Step 13 : RUN sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd
---> Using cache
---> d1f97f1c52f7
Step 14 : RUN wget -O aerospike.tgz 'http://aerospike.com/download/server/latest/artifact/ubuntu12'
---> Using cache
---> bd7dde7a98b9
Step 15 : RUN tar -xvf aerospike.tgz
---> Using cache
---> 54adaa09921f
Step 16 : RUN dpkg -i aerospike-server-community-*/*.deb
---> Using cache
---> 11aba013eea5
Step 17 : EXPOSE 22 3000 3001 3002 3003
---> Using cache
---> e33aaa78a931
Step 18 : CMD /usr/sbin/sshd -D
---> Using cache
---> 25f5fe70fa84
Successfully built 25f5fe70fa84
The cache shows that aerospike is installed. However, I don't find it inside containers spawn from this image, so I want to rebuild this image without using the cache. How can I force Docker to rebuild a clean image without the cache?
",https://stackoverflow.com/questions/35594987/how-to-force-docker-for-a-clean-build-of-an-image,1708,1746700.0,10.0,,,2016-02-24 06:37:48,2025-09-30 01:38:55,2021-12-16 09:03:04,,,docker,Pavan Gupta,19543,2710873,registered,true,35595021,,CC BY-SA 4.0,,2235,2166,2,0,0,1,true,false,false,true,true,true,49,11,false,0.006,0.001,3923,2016,2,6,Wednesday,false,false,false,false,false,false,false
30494050,How do I pass environment variables to Docker containers?,"How can one access an external database from a container? Is the best way to hard code in the connection string?
# Dockerfile
ENV DATABASE_URL amazon:rds/connection?string
",https://stackoverflow.com/questions/30494050/how-do-i-pass-environment-variables-to-docker-containers,1533,2397281.0,21.0,,,2015-05-27 22:17:09,2025-10-10 13:09:20,2022-12-29 01:50:13,,,docker;environment-variables;dockerfile,AJcodez,34606,824377,registered,true,30494145,,CC BY-SA 4.0,,204,173,1,0,0,3,true,false,false,true,true,true,57,9,true,0.009,0.0006,4196,2015,5,22,Wednesday,false,false,false,false,false,false,false
17236796,How to remove old Docker containers,"This question is related to Should I be concerned about excess, non-running, Docker containers?.
I'm wondering how to remove old containers. The docker rm 3e552code34a lets you remove a single one, but I have lots already. docker rm --help doesn't give a selection option (like all, or by image name).
Maybe there is a directory in which these containers are stored where I can delete them easily manually?
",https://stackoverflow.com/questions/17236796/how-to-remove-old-docker-containers,1505,979807.0,68.0,,,2013-06-21 13:41:42,2026-03-11 13:24:37,2017-05-23 11:55:19,,,docker,qkrijger,27436,1449361,registered,true,17237701,,CC BY-SA 3.0,2017-08-25 20:22:38,589,409,2,1,0,1,true,false,false,true,true,true,35,6,false,0.069,0.0015,4901,2013,6,13,Friday,false,false,false,false,false,false,false
48957195,How to fix Docker: Permission denied,"I installed Docker on my Ubuntu machine.
When I run
sudo docker run hello-world
it works.
But if I write the command without sudo
docker run hello-world
it displays the following:
docker: Got permission denied while trying to connect
to the Docker daemon socket at unix:///var/run/docker.sock:
Post http://%2Fvar%2Frun%2Fdocker.sock/v1.35/containers/create:
dial unix /var/run/docker.sock: connect: permission denied.
See 'docker run --help'.
The same happens when I try to run:
docker-compose up
How can I resolve this?
",https://stackoverflow.com/questions/48957195/how-to-fix-docker-permission-denied,1420,1947257.0,29.0,,,2018-02-23 22:38:58,2025-04-27 03:33:16,2025-04-27 03:33:16,,,docker;docker-compose,Carlos Andres,16705,7288685,registered,true,48957722,,CC BY-SA 4.0,2021-04-04 18:24:49,804,529,5,0,0,2,true,false,false,true,true,true,36,6,false,0.015,0.0007,3193,2018,2,22,Friday,false,false,false,false,false,false,false
23735149,What is the difference between a Docker image and a container?,"When using Docker, we start with a base image. We boot it up, create changes and those changes are saved in layers forming another image.
So eventually I have an image for my PostgreSQL instance and an image for my web application, changes to which keep on being persisted.
What is a container?
",https://stackoverflow.com/questions/23735149/what-is-the-difference-between-a-docker-image-and-a-container,1260,463690.0,32.0,,,2014-05-19 10:15:27,2025-01-06 00:32:59,2019-11-11 14:17:24,2025-02-11 21:41:56,Not suitable for this site,docker;docker-container;docker-image,Bibek Shrestha,35764,84143,registered,true,23736802,,,2022-03-01 16:12:27,318,297,0,0,0,3,true,true,false,true,true,true,62,11,true,0.069,0.0027,4569,2014,5,10,Monday,false,false,false,false,false,false,false
32723111,How can I remove old and unused Docker images?,"How can I remove all unused Docker images at once safely? I also want to remove images pulled months ago which have a certain tag.
I'm not asking about removing untagged images only. I want to remove general unused images, which includes both untagged and other images such as those pulled months ago with a specific tag.
",https://stackoverflow.com/questions/32723111/how-can-i-remove-old-and-unused-docker-images,1187,958047.0,31.0,,,2015-09-22 17:23:37,2025-07-19 18:26:53,2025-07-18 17:39:39,2025-07-22 09:46:29,Not suitable for this site,docker;docker-image,Quanlong,25888,622662,registered,true,32723127,,,2018-08-24 17:56:55,336,322,0,0,0,2,true,true,false,true,true,true,46,9,true,0.032,0.0012,4078,2015,9,17,Tuesday,false,false,false,false,false,false,false
44785585,How can I delete all local Docker images?,"I recently started using Docker and never realized that I should use docker-compose down instead of ctrl-c or docker-compose stop to get rid of my experiments. I now have a large number of unneeded docker images locally.
Is there an option to delete all the local Docker images and containers?
Something like docker rmi --all --force?
The --all option does not exist but I am looking for something to that effect.
",https://stackoverflow.com/questions/44785585/how-can-i-delete-all-local-docker-images,1180,1612121.0,28.0,,,2017-06-27 16:36:53,2026-11-04 16:55:20,2025-12-20 09:14:15,,,docker;docker-compose,Kimmo Hintikka,16240,2335820,registered,true,44785784,,CC BY-SA 4.0,,507,414,5,0,0,2,true,false,false,true,true,true,41,8,true,0.017,0.0007,3434,2017,6,16,Tuesday,false,false,false,false,false,false,false
20813486,Exploring Docker container's file system,"I've noticed with docker that I need to understand what's happening inside a container or what files exist in there. One example is downloading images from the docker index - you don't have a clue what the image contains so it's impossible to start the application.
What would be ideal is to be able to ssh into them or equivalent. Is there a tool to do this, or is my conceptualisation of docker wrong in thinking I should be able to do this.
",https://stackoverflow.com/questions/20813486/exploring-docker-containers-file-system,1144,1475861.0,34.0,,,2013-12-28 10:29:02,2026-01-04 21:07:35,2017-06-30 23:03:53,2026-01-15 01:07:28,Not suitable for this site,linux;docker;filesystems,user2668128,43118,2668128,registered,true,20816397,,,2022-05-30 20:00:46,459,445,0,0,0,3,true,true,false,true,true,true,44,5,false,0.023,0.0008,4711,2013,12,10,Saturday,true,false,false,false,false,false,false
18496940,How to deal with persistent storage (e.g. databases) in Docker,"How do people deal with persistent storage for your Docker containers?
I am currently using this approach: build the image, e.g. for PostgreSQL, and then start the container with
docker run --volumes-from c0dbc34fd631 -d app_name/postgres
IMHO, that has the drawback, that I must not ever (by accident) delete container ""c0dbc34fd631"".
Another idea would be to mount host volumes ""-v"" into the container, however, the userid within the container does not necessarily match the userid from the host, and then permissions might be messed up.
Note: Instead of --volumes-from 'cryptic_id' you can also use --volumes-from my-data-container where my-data-container is a name you assigned to a data-only container, e.g. docker run --name my-data-container ... (see the accepted answer)
",https://stackoverflow.com/questions/18496940/how-to-deal-with-persistent-storage-e-g-databases-in-docker,1074,323326.0,15.0,,,2013-08-28 19:45:44,2024-11-02 04:55:34,2024-11-02 04:55:34,,,docker;docker-volume;docker-container,juwalter,11572,226743,registered,true,20652410,,CC BY-SA 4.0,2017-08-31 11:55:44,930,785,5,0,0,3,true,false,false,true,true,true,62,10,false,0.046,0.0033,4833,2013,8,19,Wednesday,false,false,false,false,false,false,false
19234831,Where are Docker images stored on the host machine?,"I managed to find the containers under directory /var/lib/docker/containers, but I can't find the images.
What are the directories and files under /var/lib/docker?
",https://stackoverflow.com/questions/19234831/where-are-docker-images-stored-on-the-host-machine,1067,1216298.0,31.0,,,2013-10-07 21:08:48,2022-07-17 14:01:01,2017-03-29 16:26:02,,,docker;docker-image,nemo,12918,714179,registered,true,25978888,,CC BY-SA 3.0,2018-11-07 05:35:43,205,165,2,0,0,2,true,false,false,true,true,true,51,9,true,0.025,0.0009,4793,2013,10,21,Monday,false,false,false,false,false,false,false
40801772,What is the difference between ports and expose in docker-compose?,"What is the difference between ports and expose options in docker-compose.yml?
",https://stackoverflow.com/questions/40801772/what-is-the-difference-between-ports-and-expose-in-docker-compose,1052,776984.0,5.0,,,2016-11-25 09:39:10,2024-04-19 23:06:45,2022-10-21 11:26:46,,,docker;docker-compose,Bibek Shrestha,35764,84143,registered,true,,,CC BY-SA 4.0,,125,79,3,0,0,2,false,false,false,true,true,true,66,10,true,0.006,0.0014,3648,2016,11,9,Friday,false,false,false,false,false,false,false
30063907,How to execute multiple commands with Docker Compose?,"I want to do something like this where I can run multiple commands in the following code:
db:
image: postgres
web:
build: .
command: python manage.py migrate
command: python manage.py runserver 0.0.0.0:8000
volumes:
- .:/code
ports:
- "8000:8000"
links:
- db
How can I execute multiple commands?
",https://stackoverflow.com/questions/30063907/how-to-execute-multiple-commands-with-docker-compose,1035,1351065.0,25.0,,,2015-05-05 21:53:37,2026-03-16 07:51:33,2026-03-16 07:51:33,2026-03-16 22:01:49,Not suitable for this site,docker;docker-compose,RustyShackleford,27708,2587797,registered,true,30064175,,,2020-08-20 19:58:04,410,333,1,0,0,2,true,true,false,true,true,true,53,8,true,0.019,0.0008,4218,2015,5,21,Tuesday,false,false,false,false,false,false,false
43099116,Error "The input device is not a TTY","I am running the following command from my Jenkinsfile. However, I get the error ""The input device is not a TTY"".
docker run -v $PWD:/foobar -it cloudfoundry/cflinuxfs2 /foobar/script.sh
Is there a way to run the script from the Jenkinsfile without doing interactive mode?
I basically have a file called script.sh that I would like to run inside the Docker container.
",https://stackoverflow.com/questions/43099116/error-the-input-device-is-not-a-tty,1013,808245.0,18.0,,,2017-03-29 16:26:14,2024-07-22 02:24:29,2018-07-21 18:43:14,,,docker;jenkins;jenkins-pipeline,Anthony,36462,654203,registered,true,43099210,,CC BY-SA 4.0,,465,372,4,0,0,3,true,false,false,true,true,true,47,8,false,0.022,0.0013,3524,2017,3,16,Wednesday,false,false,false,false,false,false,false
25211198,Docker how to change repository name or rename image?,"I'm trying to change repository name of the image:
REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE
server latest d583c3ac45fd 26 minutes ago 685.5 MB
Hence I want to change the name server to something like myname/server:
REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE
myname/server latest d583c3ac45fd 26 minutes ago 685.5 MB
How can I do this?
",https://stackoverflow.com/questions/25211198/docker-how-to-change-repository-name-or-rename-image,994,894601.0,15.0,,,2014-08-08 19:48:36,2025-10-28 22:25:31,2025-07-06 20:01:47,,,docker,Timur Fayzrakhmanov,20117,1349754,registered,true,25214186,,CC BY-SA 4.0,2023-01-23 16:29:55,607,512,4,0,0,1,true,false,false,true,true,true,53,9,true,0.017,0.0011,4488,2014,8,19,Friday,false,false,false,false,false,false,false
44769315,How to see docker image contents,"I did a docker pull and can list the image that's downloaded. I want to see the contents of this image. Did a search on the net but no straight answer.
",https://stackoverflow.com/questions/44769315/how-to-see-docker-image-contents,974,940394.0,17.0,,,2017-06-26 22:01:49,2026-01-06 08:13:54,2019-10-02 10:39:41,2026-01-14 19:41:23,Not suitable for this site,docker,pylearn,9935,7865278,registered,true,44769468,,,,159,152,0,0,0,1,true,true,false,true,true,true,32,6,false,0.018,0.001,3435,2017,6,22,Monday,false,false,false,false,false,false,false
44678725,Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running?,"I have applied every solution available on internet but still I cannot run Docker.
I want to use Scrapy Splash on my server.
Here is history of commands I ran.
docker run -p 8050:8050 scrapinghub/splash
sudo docker run -p 8050:8050 scrapinghub/splash
sudo usermod -aG docker $(whoami)
sudo docker run -p 8050:8050 scrapinghub/splash
newgrp docker
sudo docker run -p 8050:8050 scrapinghub/splash
reboot
sudo docker run -p 8050:8050 scrapinghub/splash
docker run -p 8050:8050 scrapinghub/splash
You can see I tried to restart my server as well, but it didnt help.
see output of ps -aux | grep docker
root@mani:/var/www/html# ps aux | grep docker
root 8524 0.0 0.8 127904 13964 ? Ssl 17:21 0:00 /usr/bin/dockerd --raw-logs
root 8534 0.0 0.3 90588 5012 ? Ssl 17:21 0:00 docker-containerd -l unix:///var/run/docker/libcontainerd/docker-containerd.sock --metrics-interval=0 --start-timeout 2m --state-dir /var/run/docker/libcontainerd/containerd --shim docker-containerd-shim --runtime docker-runc
root 8543 0.0 0.0 8812 764 pts/1 S+ 17:21 0:00 grep --color=auto docker
root 16356 0.0 0.0 17200 964 pts/1 S 17:14 0:00 newgrp docker
root 20080 0.0 0.0 17200 964 pts/1 S 17:06 0:00 newgrp docker
root 30221 0.0 0.0 17200 964 pts/1 S 17:09 0:00 newgrp docker
but it gives the error:
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?.
",https://stackoverflow.com/questions/44678725/cannot-connect-to-the-docker-daemon-at-unix-var-run-docker-sock-is-the-docker,966,3303820.0,79.0,,,2017-06-21 14:18:53,2025-08-26 08:24:23,2022-05-23 19:10:50,2025-07-18 08:13:20,Not suitable for this site,linux;ubuntu;docker;ubuntu-14.04,Umair Ayub,21685,4094231,registered,true,,,,2019-06-12 19:12:35,1643,1482,5,0,0,4,false,true,false,true,true,true,95,13,true,0.024,0.0003,3440,2017,6,14,Wednesday,false,false,false,false,false,false,false
16840409,How to list containers in Docker,"There's a command to list images, docker images, but there doesn't seem to be a corresponding docker containers.
Other than becoming root and looking into /var/lib/docker there doesn't seem a way to do that. Am I missing something? Is that something one isn't supposed to do?
",https://stackoverflow.com/questions/16840409/how-to-list-containers-in-docker,964,1130431.0,14.0,,,2013-05-30 15:41:46,2025-02-05 11:36:52,2018-06-21 19:58:23,,,docker,w00t,18341,124416,registered,true,16842203,,CC BY-SA 4.0,2020-04-10 06:59:20,330,277,3,0,0,1,true,false,false,true,true,true,32,6,false,0.012,0.0009,4923,2013,5,15,Thursday,false,false,false,false,false,false,false
23439126,How to mount a host directory in a Docker container,"I am trying to mount a host directory into a Docker container so that any updates done on the host is reflected into the Docker containers.
Where am I doing something wrong. Here is what I did:
kishore$ cat Dockerfile
FROM ubuntu:trusty
RUN apt-get update
RUN apt-get -y install git curl vim
CMD [""/bin/bash""]
WORKDIR /test_container
VOLUME [""/test_container""]
kishore$ tree
.
├── Dockerfile
└── main_folder
├── tfile1.txt
├── tfile2.txt
├── tfile3.txt
└── tfile4.txt
1 directory, 5 files
kishore$ pwd
/Users/kishore/tdock
kishore$ docker build --tag=k3_s3:latest .
Uploading context 7.168 kB
Uploading context
Step 0 : FROM ubuntu:trusty
---> 99ec81b80c55
Step 1 : RUN apt-get update
---> Using cache
---> 1c7282005040
Step 2 : RUN apt-get -y install git curl vim
---> Using cache
---> aed48634e300
Step 3 : CMD [""/bin/bash""]
---> Running in d081b576878d
---> 65db8df48595
Step 4 : WORKDIR /test_container
---> Running in 5b8d2ccd719d
---> 250369b30e1f
Step 5 : VOLUME [""/test_container""]
---> Running in 72ca332d9809
---> 163deb2b1bc5
Successfully built 163deb2b1bc5
Removing intermediate container b8bfcb071441
Removing intermediate container d081b576878d
Removing intermediate container 5b8d2ccd719d
Removing intermediate container 72ca332d9809
kishore$ docker run -d -v /Users/kishore/main_folder:/test_container k3_s3:latest
c9f9a7e09c54ee1c2cc966f15c963b4af320b5203b8c46689033c1ab8872a0ea
kishore$ docker run -i -t k3_s3:latest /bin/bash
root@0f17e2313a46:/test_container# ls -al
total 8
drwx------ 2 root root 4096 Apr 29 05:15 .
drwxr-xr-x 66 root root 4096 Apr 29 05:15 ..
root@0f17e2313a46:/test_container# exit
exit
kishore$ docker -v
Docker version 0.9.1, build 867b2a9
- I don't know how to check boot2docker version
Questions, issues facing:
- How do I need to link the main_folder to the test_container folder present inside the docker container?
- I need to make this automatically. How do I to do that without really using the
run -d -v command?
- What happens if the boot2docker crashes? Where are the Docker files stored (apart from Dockerfile)?
",https://stackoverflow.com/questions/23439126/how-to-mount-a-host-directory-in-a-docker-container,945,1785224.0,27.0,,,2014-05-03 01:12:14,2026-03-11 02:03:44,2022-03-15 11:42:56,,,bash;docker;mount;boot2docker,Kishore,9754,2171928,registered,true,,,CC BY-SA 4.0,2020-09-24 13:14:18,2433,2136,9,0,0,4,false,false,false,true,true,true,51,10,false,0.015,0.0005,4585,2014,5,1,Saturday,true,false,false,false,false,false,false
27068596,How to include files outside of Docker's build context?,"How can I include files from outside of Docker's build context using the ""ADD"" command in the Docker file?
From the Docker documentation:
The path must be inside the context of the build; you cannot ADD
../something/something, because the first step of a docker build is to
send the context directory (and subdirectories) to the docker daemon.
I do not want to restructure my whole project just to accommodate Docker in this matter. I want to keep all my Docker files in the same sub-directory.
Also, it appears Docker does not yet (and may not ever) support symlinks: Dockerfile ADD command does not follow symlinks on host #1676.
The only other thing I can think of is to include a pre-build step to copy the files into the Docker build context (and configure my version control to ignore those files). Is there a better workaround for than that?
",https://stackoverflow.com/questions/27068596/how-to-include-files-outside-of-dockers-build-context,913,629210.0,22.0,,,2014-11-21 19:11:28,2024-04-12 17:44:25,2018-08-12 16:34:56,,,docker,ben_frankly,10080,2048879,registered,true,34392052,,CC BY-SA 4.0,,1007,864,0,1,0,1,true,false,false,true,true,true,59,9,true,0.035,0.0015,4383,2014,11,19,Friday,false,false,false,false,false,false,false
17665283,How does one remove a Docker image?,"I'm running Docker under Vagrant under OS X 10.8.4 (Mountain Lion), and whenever I try to delete a saved image, I get an error:
$ docker rmi some-image-id
2013/07/15 hh:mm:ss unexpected JSON input
According to the rmi help, the proper syntax is docker rmi IMAGE [IMAGE...], and I'm not sure what to make of that.
How can I delete an image?
$ docker version
Client version: 0.4.8
Server version: 0.4.8
Go version: go1.1
$docker info
Containers: 1
Images: 3
Interestingly, when I run docker ps, no containers show up at all. Running docker images shows four (4) base images and one (1) node image.
",https://stackoverflow.com/questions/17665283/how-does-one-remove-a-docker-image,893,748862.0,20.0,,,2013-07-15 22:56:02,2025-04-24 18:37:31,2021-01-24 22:00:30,,,docker,Jules,14609,1033027,registered,true,17870293,,CC BY-SA 4.0,2015-07-18 16:11:01,794,609,9,0,0,1,true,false,false,true,true,true,35,7,true,0.027,0.0012,4877,2013,7,22,Monday,false,false,false,false,false,false,false
30853247,How do I edit a file after I shell to a Docker container?,"I successfully shelled to a Docker container using:
docker exec -i -t 69f1711a205e bash
Now I need to edit file and I don't have any editors inside:
root@69f1711a205e:/# nano
bash: nano: command not found
root@69f1711a205e:/# pico
bash: pico: command not found
root@69f1711a205e:/# vi
bash: vi: command not found
root@69f1711a205e:/# vim
bash: vim: command not found
root@69f1711a205e:/# emacs
bash: emacs: command not found
root@69f1711a205e:/#
How do I edit files?
",https://stackoverflow.com/questions/30853247/how-do-i-edit-a-file-after-i-shell-to-a-docker-container,879,966505.0,27.0,,,2015-06-15 19:15:56,2024-11-22 17:58:39,2024-01-19 17:52:29,,,docker;command-line-interface;editor,Igor Barinov,26360,1268964,registered,true,30859601,,CC BY-SA 4.0,,542,473,2,0,0,3,true,false,false,true,true,true,57,13,true,0.028,0.0009,4177,2015,6,19,Monday,false,false,false,false,false,false,false
41984399,docker push error: denied: requested access to the resource is denied,"I have successfully logged into Docker and I followed documentation to create my first Docker image which went successfully. Now I am trying to push this image into my Docker repository following these instructions. But whenever I am trying to push this image into repository, I got this type of error:
denied: requested access to the resource is denied
",https://stackoverflow.com/questions/41984399/docker-push-error-denied-requested-access-to-the-resource-is-denied,844,998691.0,79.0,,,2017-02-01 16:08:53,2026-06-29 21:56:54,2026-06-29 21:56:54,2026-01-11 11:20:51,Not suitable for this site,docker,Keyur Shah,11615,2693841,registered,true,41984666,,,2019-01-15 18:54:49,711,357,0,3,1,1,true,true,false,true,true,true,69,11,false,0.079,0.0008,3580,2017,2,16,Wednesday,false,false,false,false,false,false,false
18497688,Run a Docker image as a container,"After building a Docker image from a dockerfile, I see the image was built successfully, but what do I do with it? Shouldn't i be able to run it as a container?
",https://stackoverflow.com/questions/18497688/run-a-docker-image-as-a-container,830,1697278.0,12.0,,,2013-08-28 20:34:51,2023-12-02 13:50:13,2020-08-26 08:50:44,,,docker;docker-image,boom,11886,949845,registered,true,18498313,,CC BY-SA 4.0,2022-03-11 12:00:58,181,161,1,0,0,2,true,false,false,true,true,true,33,7,false,0.007,0.0005,4833,2013,8,20,Wednesday,false,false,false,false,false,false,false
39901311,Docker - Ubuntu - bash: ping: command not found,"I've got a Docker container running Ubuntu which I did as follows:
docker run -it ubuntu /bin/bash
however it doesn't seem to have ping. E.g.
bash: ping: command not found
Do I need to install that?
Seems a pretty basic command to be missing. I tried whereis ping which doesn't report anything.
",https://stackoverflow.com/questions/39901311/docker-ubuntu-bash-ping-command-not-found,822,1480553.0,9.0,,,2016-10-06 16:33:07,2025-03-21 02:26:45,,2025-03-23 08:29:38,Not suitable for this site,ubuntu;docker;ping,Snowcrash,87573,343204,registered,true,39901446,,,,404,302,4,0,0,3,true,true,false,true,true,false,47,9,false,0.006,0.0006,3698,2016,10,16,Thursday,false,false,false,false,false,false,false
19335444,How do I assign a port mapping to an existing Docker container?,"I'm not sure if I've misunderstood something here, but it seems like it's only possible to set port mappings by creating a new container from an image. Is there a way to assign a port mapping to an existing Docker container?
",https://stackoverflow.com/questions/19335444/how-do-i-assign-a-port-mapping-to-an-existing-docker-container,820,1211343.0,17.0,,,2013-10-12 14:46:18,2025-08-25 22:54:07,2017-03-12 13:28:26,,,docker;port;lxc;linux-containers,thasmo,10057,455988,registered,true,38783433,,CC BY-SA 3.0,2022-08-16 21:10:53,232,225,0,0,0,4,true,false,false,true,true,true,63,12,true,0.014,0.0007,4788,2013,10,14,Saturday,true,false,false,false,false,false,false
21889053,What is the runtime performance cost of a Docker container?,"I'd like to comprehensively understand the run-time performance cost of a Docker container. I've found references to networking anecdotally being ~100µs slower.
I've also found references to the run-time cost being ""negligible"" and ""close to zero"" but I'd like to know more precisely what those costs are. Ideally I'd like to know what Docker is abstracting with a performance cost and things that are abstracted without a performance cost. Networking, CPU, memory, etc.
Furthermore, if there are abstraction costs, are there ways to get around the abstraction cost. For example, perhaps I can mount a disk directly vs. virtually in Docker.
",https://stackoverflow.com/questions/21889053/what-is-the-runtime-performance-cost-of-a-docker-container,815,316855.0,4.0,,,2014-02-19 18:19:45,2026-06-17 19:33:20,2021-05-12 23:06:50,,,linux;docker;performance;virtual-machine;containerd,Luke Hoersten,9055,251630,registered,true,26149994,,CC BY-SA 4.0,2016-12-19 01:42:37,792,643,0,1,0,5,true,false,false,true,true,true,59,10,true,0.013,0.0026,4658,2014,2,18,Wednesday,false,false,false,false,false,false,false
31324981,How to access host port from docker container,"I have a docker container running jenkins. As part of the build process, I need to access a web server that is run locally on the host machine. Is there a way the host web server (which can be configured to run on a port) can be exposed to the jenkins container?
I'm running docker natively on a Linux machine.
UPDATE:
In addition to @larsks answer below, to get the IP address of the Host IP from the host machine, I do the following:
ip addr show docker0 | grep -Po 'inet \K[\d.]+'
",https://stackoverflow.com/questions/31324981/how-to-access-host-port-from-docker-container,812,1016996.0,17.0,,,2015-07-09 18:01:28,2025-02-14 13:55:16,2022-03-14 09:52:04,2022-03-14 09:52:18,Duplicate,docker;docker-container,Tri Nguyen,11388,1368032,registered,true,31328031,,,,537,485,1,0,0,2,true,true,false,true,true,true,45,8,false,0.017,0.0008,4153,2015,7,18,Thursday,false,false,false,false,false,false,false
27093612,"In a Dockerfile, How to update PATH environment variable?","I have a dockerfile that download and builds GTK from source, but the following line is not updating my image's environment variable:
RUN PATH=""/opt/gtk/bin:$PATH""
RUN export PATH
I read that that I should be using ENV to set environment values, but the following instruction doesn't seem to work either:
ENV PATH /opt/gtk/bin:$PATH
This is my entire Dockerfile:
FROM ubuntu
RUN apt-get update
RUN apt-get install -y golang gcc make wget git libxml2-utils libwebkit2gtk-3.0-dev libcairo2 libcairo2-dev libcairo-gobject2 shared-mime-info libgdk-pixbuf2.0-* libglib2-* libatk1.0-* libpango1.0-* xserver-xorg xvfb
# Downloading GTKcd
RUN wget http://ftp.gnome.org/pub/gnome/sources/gtk+/3.12/gtk+-3.12.2.tar.xz
RUN tar xf gtk+-3.12.2.tar.xz
RUN cd gtk+-3.12.2
# Setting environment variables before running configure
RUN CPPFLAGS=""-I/opt/gtk/include""
RUN LDFLAGS=""-L/opt/gtk/lib""
RUN PKG_CONFIG_PATH=""/opt/gtk/lib/pkgconfig""
RUN export CPPFLAGS LDFLAGS PKG_CONFIG_PATH
RUN ./configure --prefix=/opt/gtk
RUN make
RUN make install
# running ldconfig after make install so that the newly installed libraries are found.
RUN ldconfig
# Setting the LD_LIBRARY_PATH environment variable so the systems dynamic linker can find the newly installed libraries.
RUN LD_LIBRARY_PATH=""/opt/gtk/lib""
# Updating PATH environment program so that utility binaries installed by the various libraries will be found.
RUN PATH=""/opt/gtk/bin:$PATH""
RUN export LD_LIBRARY_PATH PATH
# Collecting garbage
RUN rm -rf gtk+-3.12.2.tar.xz
# creating go code root
RUN mkdir gocode
RUN mkdir gocode/src
RUN mkdir gocode/bin
RUN mkdir gocode/pkg
# Setting the GOROOT and GOPATH enviornment variables, any commands created are automatically added to PATH
RUN GOROOT=/usr/lib/go
RUN GOPATH=/root/gocode
RUN PATH=$GOPATH/bin:$PATH
RUN export GOROOT GOPATH PATH
",https://stackoverflow.com/questions/27093612/in-a-dockerfile-how-to-update-path-environment-variable,812,621798.0,5.0,,,2014-11-23 19:58:33,2025-08-21 08:15:17,2023-03-01 15:34:54,2025-08-22 10:21:57,Not suitable for this site,docker;environment-variables,ILikeTacos,18944,1315565,registered,true,38742545,,,2018-11-23 16:12:54,1926,1837,3,0,0,2,true,true,false,true,true,true,57,9,true,0.008,0.0013,4381,2014,11,19,Sunday,true,false,false,false,false,false,false
22111060,What is the difference between "expose" and "publish" in Docker?,"I'm experimenting with Dockerfiles, and I think I understand most of the logic. However, I don't see the difference between ""exposing"" and ""publishing"" a port in this context.
All the tutorials I have seen first include the EXPOSE command in the Dockerfile:
...
EXPOSE 8080
...
They then build an image from this Dockerfile:
$ docker build -t an_image - < Dockerfile
And then publish the same port as above when running the image:
$ docker run -d -p 8080 an_image
or publish all ports using
$ docker run -d -P an_image
What is the point of exposing a port in the Dockerfile, if it will be published anyway? Would there ever be a need to expose a port first, and not publish it later? Effectively, I would like to specify all the ports that I will use in the Dockerfile when creating the image, and then not bother with them again, running them simply with:
$ docker run -d an_image
Is this possible?
",https://stackoverflow.com/questions/22111060/what-is-the-difference-between-expose-and-publish-in-docker,783,342786.0,8.0,,,2014-03-01 06:35:53,2023-05-16 06:06:20,2022-08-17 18:19:54,,,docker;port;publish;docker-run,user1496984,11705,1496984,registered,true,22150099,,CC BY-SA 4.0,,1119,919,6,0,0,4,true,false,false,true,true,true,84,10,true,0.023,0.0023,4648,2014,3,6,Saturday,true,false,false,false,false,false,false
30604846,"Docker complains about "no space left on device", how to clean up?","I installed docker on a Debian 7 machine in the following way
$ echo deb http://get.docker.io/ubuntu docker main > /etc/apt/sources.list.d/docker.list
$ sudo apt-get update
$ curl -sSL https://get.docker.com/ubuntu/ | sudo sh
After that when I first tried creating an Image it failed with the following error
time="2015-06-02T14:26:37-04:00" level=info msg="[8] System error: write /sys/fs/cgroup/docker/01f5670fbee1f6687f58f3a943b1e1bdaec2630197fa4da1b19cc3db7e3d3883/cgroup.procs: no space left on device"
Here is the docker info
Containers: 2
Images: 21
Storage Driver: aufs
Root Dir: /var/lib/docker/aufs
Backing Filesystem: extfs
Dirs: 25
Dirperm1 Supported: true
Execution Driver: native-0.2
Kernel Version: 3.16.0-0.bpo.4-amd64
Operating System: Debian GNU/Linux 7 (wheezy)
CPUs: 2
Total Memory: 15.7 GiB
WARNING: No memory limit support
WARNING: No swap limit support
How can I increase the memory? Where are the system configurations stored?
From Kal's suggestions:
When I got rid of all the images and containers it did free some space and the image build ran longer before failing with the same error. So the question is, which space is this referring to and how do I configure it?
",https://stackoverflow.com/questions/30604846/docker-complains-about-no-space-left-on-device-how-to-clean-up,763,770487.0,35.0,,,2015-06-02 19:23:55,2025-08-14 12:22:39,2025-01-23 11:22:54,,,docker;ubuntu;memory;temporary-files,user_mda,19708,3987161,registered,true,,,CC BY-SA 4.0,2022-10-18 08:08:34,1338,1224,3,0,0,4,false,false,false,true,true,true,76,12,true,0.045,0.001,4190,2015,6,19,Tuesday,false,false,false,false,false,false,false
20845056,How can I expose more than 1 port with Docker?,"So I have 3 ports that should be exposed to the machine's interface. Is it possible to do this with a Docker container?
",https://stackoverflow.com/questions/20845056/how-can-i-expose-more-than-1-port-with-docker,760,643674.0,7.0,,,2013-12-30 18:13:44,2023-10-30 11:32:46,2017-10-09 15:58:55,,,docker;docker-network,nubela,17402,118644,registered,true,20851484,,CC BY-SA 3.0,,127,120,0,0,0,2,true,false,false,true,true,true,46,10,true,0.011,0.0012,4709,2013,12,18,Monday,false,false,false,false,false,false,false
31697828,Docker - Name is already in use by container,"Running the docker registry with below command always throws an error:
dev:tmp me$ docker run \
-d --name registry-v1 \
-e SETTINGS_FLAVOR=local \
-e STORAGE_PATH=/registry \
-e SEARCH_BACKEND=sqlalchemy \
-e LOGLEVEL=DEBUG \
-p 5000:5000 \
registry:0.9.1
Error response from daemon: Conflict. The name "registry-v1" is already in use by container f9e5798a82e0. You have to delete (or rename) that container to be able to reuse that name.
How can I prevent this error ?
",https://stackoverflow.com/questions/31697828/docker-name-is-already-in-use-by-container,747,832717.0,22.0,,,2015-07-29 10:26:10,2023-11-22 14:52:32,2022-08-09 18:49:59,,,docker;docker-run,Rubytastic,15599,355281,registered,true,,,CC BY-SA 4.0,,584,516,2,0,0,2,false,false,false,true,true,true,44,9,false,0.026,0.0009,4133,2015,7,10,Wednesday,false,false,false,false,false,false,false
28349392,How to push a docker image to a private repository,"I have a docker image tagged as me/my-image, and I have a private repo on the dockerhub named me-private.
When I push my me/my-image, I end up always hitting the public repo.
What is the exact syntax to specifically push my image to my private repo?
",https://stackoverflow.com/questions/28349392/how-to-push-a-docker-image-to-a-private-repository,734,1025664.0,14.0,,,2015-02-05 16:42:49,2022-06-24 16:53:06,2020-04-29 17:40:52,,,docker;docker-registry,Eugene Goldberg,15702,518012,registered,true,28349540,,CC BY-SA 4.0,2021-01-09 23:42:26,309,252,3,0,0,2,true,false,false,true,true,true,50,10,false,0.014,0.0007,4307,2015,2,16,Thursday,false,false,false,false,false,false,false
37461868,Difference between RUN and CMD in a Dockerfile,"I'm confused about when should I use CMD vs RUN. For example, to execute bash/shell commands (i.e. ls -la) I would always use CMD or is there a situation where I would use RUN? Trying to understand the best practices about these two similar Dockerfile directives.
",https://stackoverflow.com/questions/37461868/difference-between-run-and-cmd-in-a-dockerfile,725,412650.0,10.0,,,2016-05-26 13:11:20,2024-04-16 20:32:33,2024-04-16 20:32:33,,,docker;dockerfile;docker-run;docker-cmd,TakeSoUp,8227,6386350,registered,true,37462208,,CC BY-SA 4.0,,349,264,6,0,0,4,true,false,false,true,true,true,46,8,false,0.024,0.0018,3831,2016,5,13,Thursday,false,false,false,false,false,false,false
36884991,How to rebuild docker container in docker-compose.yml?,"There are scope of services which are defined in docker-compose.yml. These services have been started. I need to rebuild only one of these and start it without up other services.
I run the following commands:
docker-compose up -d # run all services
docker-compose stop nginx # stop only one. but it is still running !!!
docker-compose build --no-cache nginx
docker-compose up -d --no-deps # link nginx to other services
At the end I get the old nginx container.
Docker-compose doesn't kill all running containers!
",https://stackoverflow.com/questions/36884991/how-to-rebuild-docker-container-in-docker-compose-yml,712,1342317.0,15.0,,,2016-04-27 08:57:50,2024-11-29 04:29:43,2022-10-18 19:39:07,2025-08-14 06:14:05,Not suitable for this site,docker;docker-compose;docker-container,yuklia,8071,2207007,registered,true,,,,,554,516,1,0,0,3,false,true,false,true,true,true,54,7,true,0.011,0.0005,3860,2016,4,8,Wednesday,false,false,false,false,false,false,false
38088279,Communication between multiple docker-compose projects,"I have two separate docker-compose.yml files in two different folders:
~/front/docker-compose.yml
~/api/docker-compose.yml
How can I make sure that a container in front can send requests to a container in api?
I know that --default-gateway option can be set using docker run for an individual container, so that a specific IP address can be assigned to this container, but it seems that this option is not available when using docker-compose.
Currently I end up doing a docker inspect my_api_container_id and look at the gateway in the output. It works but the problem is that this IP is randomly attributed, so I can't rely on it.
Another form of this question might thus be:
- Can I attribute a fixed IP address to a particular container using docker-compose?
But in the end what I'm looking after is:
- How can two different docker-compose projects communicate with each other?
",https://stackoverflow.com/questions/38088279/communication-between-multiple-docker-compose-projects,707,669972.0,23.0,,,2016-06-29 00:13:57,2025-08-25 15:00:58,2022-03-01 11:54:59,,,docker;docker-compose,Jivan,23438,2091169,registered,true,38089080,,CC BY-SA 4.0,,1113,891,9,0,0,2,true,false,false,true,true,true,54,5,false,0.034,0.0011,3797,2016,6,0,Wednesday,false,false,false,false,false,false,false
20932357,How to enter in a Docker container already running with a new TTY,"I have a container that is running the Apache service in the foreground. I would like to be able to access the container from another shell in order to ""poke around"" inside it and examine the files. At the moment, if I attach to the container, I am left looking at the Apache daemon and cannot run any commands.
Is it possible to attach another tty to a running container? Possibly, I can take advantage of the fact that Docker is actually just wrapping around LXC containers? I have tried sudo lxc-console -n [container-id] -t [1-4] but it appears that only one tty is made available and that is the one running the apache daemon. Perhaps there is a way to enable multiple lxc consoles during the build?
I would rather not configure and build the container with an openssh service if possible.
",https://stackoverflow.com/questions/20932357/how-to-enter-in-a-docker-container-already-running-with-a-new-tty,705,694355.0,12.0,,,2014-01-05 10:13:41,2026-02-24 06:04:27,2018-04-20 01:42:17,,,docker;tty,Programster,13044,1385833,registered,true,26496854,,CC BY-SA 3.0,,848,797,1,0,0,2,true,false,false,true,true,true,65,13,false,0.017,0.001,4703,2014,1,10,Sunday,true,false,false,false,false,false,false
42564058,How can I use local Docker images with Minikube?,"I have several Docker images that I want to use with Minikube. I don't want to first have to upload and then download the same image instead of just using the local image directly. How do I do this?
Stuff I tried:
1. I tried running these commands (separately, deleting the instances of Minikube both times and starting fresh)
kubectl run hdfs --image=fluxcapacitor/hdfs:latest --port=8989
kubectl run hdfs --image=fluxcapacitor/hdfs:latest --port=8989 imagePullPolicy=Never
Output:
NAME READY STATUS RESTARTS AGE
hdfs-2425930030-q0sdl 0/1 ContainerCreating 0 10m
It just gets stuck on some status but never reaches the ready state.
2. I tried creating a registry and then putting images into it, but that didn't work either. I might've done that incorrectly but I can't find proper instructions to do this task.
Please provide instructions to use local Docker images in a local Kubernetes instance.
OS: Ubuntu 16.04 (Xenial Xerus)
Docker: Docker version 1.13.1, build 092cba3
Kubernetes:
Client Version: version.Info{Major:"1", Minor:"5", GitVersion:"v1.5.3", GitCommit:"029c3a408176b55c30846f0faedf56aae5992e9b", GitTreeState:"clean", BuildDate:"2017-02-15T06:40:50Z", GoVersion:"go1.7.4", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"5", GitVersion:"v1.5.2", GitCommit:"08e099554f3c31f6e6f07b448ab3ed78d0520507", GitTreeState:"clean", BuildDate:"1970-01-01T00:00:00Z", GoVersion:"go1.7.1", Compiler:"gc", Platform:"linux/amd64"}
What is a solution that uses docker-compose to do this?
Images loaded in eval $(minikube docker-env):
REPOSITORY TAG IMAGE ID CREATED SIZE
fluxcapacitor/jupyterhub latest e5175fb26522 4 weeks ago 9.59 GB
fluxcapacitor/zeppelin latest fe4bc823e57d 4 weeks ago 4.12 GB
fluxcapacitor/prediction-pmml latest cae5b2d9835b 4 weeks ago 973 MB
fluxcapacitor/scheduler-airflow latest 95adfd56f656 4 weeks ago 8.89 GB
fluxcapacitor/loadtest latest 6a777ab6167c 5 weeks ago 899 MB
fluxcapacitor/hdfs latest 00fa0ed0064b 6 weeks ago 1.16 GB
fluxcapacitor/sql-mysql latest 804137671a8c 7 weeks ago 679 MB
fluxcapacitor/metastore-1.2.1 latest ea7ce8c5048f 7 weeks ago 1.35 GB
fluxcapacitor/cassandra latest 3cb5ff117283 7 weeks ago 953 MB
fluxcapacitor/apachespark-worker-2.0.1 latest 14ee3e4e337c 7 weeks ago 3.74 GB
fluxcapacitor/apachespark-master-2.0.1 latest fe60b42d54e5 7 weeks ago 3.72 GB
fluxcapacitor/package-java-openjdk-1.8 latest 1db08965289d 7 weeks ago 841 MB
gcr.io/google_containers/kubernetes-dashboard-amd64 v1.5.1 1180413103fd 7 weeks ago 104 MB
fluxcapacitor/stream-kafka-0.10 latest f67750239f4d 2 months ago 1.14 GB
fluxcapacitor/pipeline latest f6afd6c5745b 2 months ago 11.2 GB
gcr.io/google-containers/kube-addon-manager v6.1 59e1315aa5ff 3 months ago 59.4 MB
gcr.io/google_containers/kubedns-amd64 1.9 26cf1ed9b144 3 months ago 47 MB
gcr.io/google_containers/kube-dnsmasq-amd64 1.4 3ec65756a89b 5 months ago 5.13 MB
gcr.io/google_containers/exechealthz-amd64 1.2 93a43bfb39bf 5 months ago 8.37 MB
gcr.io/google_containers/pause-amd64
",https://stackoverflow.com/questions/42564058/how-can-i-use-local-docker-images-with-minikube,690,478740.0,36.0,,,2017-03-02 19:16:34,2025-11-05 06:26:46,2024-06-05 14:57:31,,,linux;docker;kubernetes;docker-compose;minikube,Kapil Gupta,7881,6930923,registered,true,42564211,,CC BY-SA 4.0,2022-12-15 17:28:08,4347,3784,5,2,0,5,true,false,false,true,true,true,48,9,true,0.075,0.0014,3551,2017,3,19,Thursday,false,false,false,false,false,false,false
29480099,What's the difference between Docker Compose vs. Dockerfile,"I have been reading up and learning about Docker, and am trying to correctly choose the Django setup to use. So far there is either:
I understand that Dockerfiles are used in Docker Compose, but I am not sure if it is good practice to put everything in one large Dockerfile with multiple FROM commands for the different images?
I want to use several different images that include:
uwsgi
nginx
postgres
redis
rabbitmq
celery with cron
Please advise on what are best practices in setting up this type of environment using Docker.
If it helps, I am on a Mac, so using boot2docker.
Some issues I've had:
- Docker Compose is not compatible with Python3
- I want to containerize my project, so if one large Dockerfile
is not ideal, then I feel I'd need to break it up using Docker Compose
- I am OK to make the project Py2 & Py3 compatible, so am leaning towards django-compose
",https://stackoverflow.com/questions/29480099/whats-the-difference-between-docker-compose-vs-dockerfile,686,375710.0,13.0,,,2015-04-06 21:36:43,2025-05-25 16:45:47,2022-05-07 09:32:31,2025-12-29 07:30:17,Not suitable for this site,docker;docker-compose;dockerfile;development-environment;boot2docker,Aaron Lelevier,21098,1913888,registered,true,29487120,,,,1314,902,2,4,0,5,true,true,false,true,true,true,63,8,false,0.035,0.0018,4247,2015,4,21,Monday,false,false,false,false,false,false,false
43747776,COPY with docker but with exclusion,"In a Dockerfile, I have
COPY . .
I want to exclude an entire directory, in my case, node_modules directory.
Something like this:
COPY [all but **/node_modules/**] .
Is this possible with Docker?
",https://stackoverflow.com/questions/43747776/copy-with-docker-but-with-exclusion,686,517472.0,11.0,,,2017-05-02 21:48:02,2025-01-14 23:24:54,,,,docker;dockerfile;docker-copy,Alexander Mills,102786,1223975,registered,true,43747867,,CC BY-SA 3.0,,281,205,2,0,0,3,true,false,false,true,true,false,35,6,false,0.021,0.0013,3490,2017,5,21,Tuesday,false,false,false,false,false,false,false
31746182,Docker Compose wait for container X before starting Y,"I am using rabbitmq and a simple python sample from here
together with docker-compose. My problem is that I need to wait for rabbitmq to be fully started. From what I searched so far, I don't know how to wait with container x (in my case worker) until y (rabbitmq) is started.
I found this blog post where he checks if the other host is online.
I also found this docker command:
wait
Usage: docker wait CONTAINER [CONTAINER...]
Block until a container stops, then print its exit code.
Waiting for a container to stop is maybe not what I am looking for but if
it is, is it possible to use that command inside the docker-compose.yml?
My solution so far is to wait some seconds and check the port, but is this the way to achieve this? If I don't wait, I get an error.
docker-compose.yml
worker:
build: myapp/.
volumes:
- myapp/.:/usr/src/app:ro
links:
- rabbitmq
rabbitmq:
image: rabbitmq:3-management
python hello sample (rabbit.py):
import pika
import time
import socket
pingcounter = 0
isreachable = False
while isreachable is False and pingcounter < 5:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect(('rabbitmq', 5672))
isreachable = True
except socket.error as e:
time.sleep(2)
pingcounter += 1
s.close()
if isreachable:
connection = pika.BlockingConnection(pika.ConnectionParameters(
host="rabbitmq"))
channel = connection.channel()
channel.queue_declare(queue='hello')
channel.basic_publish(exchange='',
routing_key='hello',
body='Hello World!')
print (" [x] Sent 'Hello World!'")
connection.close()
Dockerfile for worker:
FROM python:2-onbuild
RUN ["pip", "install", "pika"]
CMD ["python","rabbit.py"]
Update Nov 2015:
A shell script or waiting inside your program is maybe a possible solution. But after seeing this Issue I am looking for a command or feature of docker/docker-compose itself.
They mention a solution for implementing a health check, which may be the best option. A open tcp connection does not mean your service is ready or may remain ready. In addition to that I need to change my entrypoint in my dockerfile.
So I am hoping for an answer with docker-compose on board commands, which will hopefully the case if they finish this issue.
Update March 2016
There is a proposal for providing a built-in way to determine if a container is "alive". So docker-compose can maybe make use of it in near future.
Update June 2016
It seems that the healthcheck will be integrated into docker in Version 1.12.0
Update January 2017
I found a docker-compose solution see:
Docker Compose wait for container X before starting Y
",https://stackoverflow.com/questions/31746182/docker-compose-wait-for-container-x-before-starting-y,681,734955.0,21.0,,,2015-07-31 12:25:23,2024-12-19 18:02:50,2022-03-01 10:42:59,,,docker;docker-compose,svenhornberg,16036,1584115,registered,true,41854997,,CC BY-SA 4.0,2019-01-16 00:18:09,3918,2812,3,7,0,2,true,false,false,true,true,true,53,9,false,0.029,0.0009,4131,2015,7,12,Friday,false,false,false,false,false,false,false
26734402,How to upgrade docker container after its image changed,"Let's say I have pulled the official mysql:5.6.21 image.
I have deployed this image by creating several docker containers.
These containers have been running for some time until MySQL 5.6.22 is released. The official image of mysql:5.6 gets updated with the new release, but my containers still run 5.6.21.
How do I propagate the changes in the image (i.e. upgrade MySQL distro) to all my existing containers? What is the proper Docker way of doing this?
",https://stackoverflow.com/questions/26734402/how-to-upgrade-docker-container-after-its-image-changed,676,649270.0,14.0,,,2014-11-04 11:48:22,2022-05-30 08:30:51,2016-09-27 22:15:43,,,docker,Yaroslav Stavnichiy,21544,697313,registered,true,,,CC BY-SA 3.0,,559,459,0,1,0,1,false,false,false,true,true,true,55,9,false,0.022,0.001,4400,2014,11,11,Tuesday,false,false,false,false,false,false,false
38986057,How can I set an image name in a Dockerfile?,"You can set the image name when building a custom image, like this:
docker build -t dude/man:v2 . # Will be named dude/man:v2
Is there a way to define the name of the image in the Dockerfile, so I don't have to mention it in the docker build command?
",https://stackoverflow.com/questions/38986057/how-can-i-set-an-image-name-in-a-dockerfile,674,922946.0,7.0,,,2016-08-16 23:37:34,2025-12-17 19:46:46,2025-12-17 19:20:35,,,docker;tags,gvlasov,20395,1542343,registered,true,38986676,,CC BY-SA 4.0,,342,252,2,0,0,2,true,false,false,true,true,true,44,10,true,0.008,0.0007,3749,2016,8,23,Tuesday,false,false,false,false,false,false,false
36249744,Interactive shell using Docker Compose,"Is there any way to start an interactive shell in a container using Docker Compose only? I've tried something like this, in my docker-compose.yml:
myapp:
image: alpine:latest
entrypoint: /bin/sh
When I start this container using docker-compose up it's exited immediately. Are there any flags I can add to the entrypoint command, or as an additional option to myapp, to start an interactive shell?
I know there are native docker command options to achieve this, just curious if it's possible using only Docker Compose, too.
",https://stackoverflow.com/questions/36249744/interactive-shell-using-docker-compose,673,823775.0,14.0,,,2016-03-27 16:25:57,2026-09-01 01:01:21,2021-02-15 08:23:40,,,shell;docker;interactive;docker-compose,drubb,16101,4042051,registered,true,,,CC BY-SA 4.0,2024-01-04 20:00:43,599,528,3,0,0,4,false,false,false,true,true,true,38,5,false,0.017,0.0008,3891,2016,3,16,Sunday,true,false,false,false,false,false,false
36710459,How do I make a comment in a Dockerfile?,"I am writing a Dockerfile. Is there a way to make comments in this file?
Does Docker have a comment option that takes the rest of a line and ignores it?
",https://stackoverflow.com/questions/36710459/how-do-i-make-a-comment-in-a-dockerfile,672,342857.0,7.0,,,2016-04-19 06:42:05,2025-07-26 09:21:32,2019-04-02 20:59:50,,,docker;dockerfile,kpie,11282,2334254,registered,true,36710513,,CC BY-SA 4.0,,168,154,0,0,0,2,true,false,false,true,true,true,40,9,true,0.02,0.002,3868,2016,4,6,Tuesday,false,false,false,false,false,false,false
26982274,ps command doesn't work in docker container,"I want to do a ps command in a docker container derived from Debian official Docker hub repository:
$ docker run -ti debian:wheezy /bin/bash
root@51afd6b09af8:/# ps
bash: ps: command not found
",https://stackoverflow.com/questions/26982274/ps-command-doesnt-work-in-docker-container,666,656434.0,7.0,,,2014-11-17 21:26:14,2023-02-09 08:49:46,2017-04-16 04:33:09,,,debian;docker,Yves Nicolas,8181,2763877,registered,true,26982502,,CC BY-SA 3.0,,226,195,1,0,0,2,true,false,false,true,true,true,47,7,false,0.011,0.001,4387,2014,11,21,Monday,false,false,false,false,false,false,false
26153686,How do I run a command on an already existing Docker container?,"I created a container with -d so it's not interactive.
docker run -d shykes/pybuilder bin/bash
I see that the container has exited:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
d6c45e8cc5f0 shykes/pybuilder:latest ""bin/bash"" 41 minutes ago Exited (0) 2 seconds ago clever_bardeen
Now I would like to run occasional commands on the machine and exit. Just to get the response.
I tried to start the machine. I tried attaching. I thought I could call run with a container, but that does not seem to be allowed. Using start just seems to run and then exist quickly.
I'd like to get back into interactive mode after exiting.
I tried:
docker attach d6c45e8cc5f0
But I get:
2014/10/01 22:33:34 You cannot attach to a stopped container, start it first
But if I start it, it exits anyway. Catch 22. I can't win.
",https://stackoverflow.com/questions/26153686/how-do-i-run-a-command-on-an-already-existing-docker-container,651,821471.0,21.0,,,2014-10-02 02:34:25,2025-02-27 06:41:13,2017-03-13 19:10:24,,,docker,Johnston,21114,974407,registered,true,27708039,,CC BY-SA 3.0,,1149,958,7,0,0,1,true,false,false,true,true,true,63,12,true,0.026,0.0008,4433,2014,10,2,Thursday,false,false,false,false,false,false,false
21871479,Docker can't connect to docker daemon,"After I update my Docker version to 0.8.0, I get an error message while entering sudo docker version:
Client version: 0.8.0
Go version (client): go1.2
Git commit (client): cc3a8c8
2014/02/19 12:54:16 Can't connect to docker daemon. Is 'docker -d' running on this host?
And I've followed the instructions and entered command sudo docker -d, and I got this:
[/var/lib/docker|2462000b] +job initserver()
[/var/lib/docker|2462000b.initserver()] Creating server
open /var/lib/docker/aufs/layers/cf2414da53f9bcfaa48bc3d58360d7f1cfd3784e4fe51fbef95197709dfc285d: no such file or directory[/var/lib/docker|2462000b] -job initserver() = ERR (1)
2014/02/19 12:55:57 initserver: open /var/lib/docker/aufs/layers/cf2414da53f9bcfaa48bc3d58360d7f1cfd3784e4fe51fbef95197709dfc285d: no such file or directory
How do I solve the problem?
",https://stackoverflow.com/questions/21871479/docker-cant-connect-to-docker-daemon,645,1161139.0,49.0,,,2014-02-19 05:02:22,2025-04-22 10:28:31,2017-03-11 16:38:52,,,linux;docker,LiJung,8039,1497484,registered,true,,,CC BY-SA 3.0,2017-07-21 17:09:39,935,827,5,0,0,2,false,false,false,true,true,true,41,6,false,0.042,0.0006,4658,2014,2,5,Wednesday,false,false,false,false,false,false,false
47854463,Docker: Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock,"I am new to docker. I just tried to use docker in my local machine(Ubuntu 16.04) with Jenkins.
I configured a new job with below pipeline script.
node {
stage('Build') {
docker.image('maven:3.3.3').inside {
sh 'mvn --version'
}
}
}
But it fails with this error:
Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock
",https://stackoverflow.com/questions/47854463/docker-got-permission-denied-while-trying-to-connect-to-the-docker-daemon-socke,642,965317.0,46.0,,,2017-12-17 11:08:22,2026-01-19 16:40:16,2022-09-15 19:25:58,,,docker;jenkins;jenkins-pipeline,Ponsuyambu,9354,1294150,registered,true,48450294,,CC BY-SA 4.0,2019-06-12 19:38:02,667,399,1,1,1,3,true,false,false,true,true,true,112,15,false,0.048,0.0007,3261,2017,12,11,Sunday,true,false,false,false,false,false,false
31466428,How to restart a single container with docker-compose,"I have a docker-compose.yml file that contains 4 containers: redis, postgres, api and worker.
During the development of the worker container, I often need to restart it in order to apply changes. Is there any good way to restart a single container (e.g. worker) without restarting the others?
",https://stackoverflow.com/questions/31466428/how-to-restart-a-single-container-with-docker-compose,631,559273.0,14.0,,,2015-07-16 23:55:01,2026-02-04 14:26:35,2021-06-20 11:17:03,,,docker;docker-compose,Bryan Chen,46816,642626,registered,true,31485685,,CC BY-SA 4.0,,398,293,7,0,0,2,true,false,false,true,true,true,53,8,false,0.025,0.0011,4146,2015,7,23,Thursday,false,false,false,false,false,false,false
42248198,How to mount a single file in a volume,"I am trying to dockerize a PHP application. In the dockerfile, I download the archive, extract it, etc.
Everything works fine. However, if a new version gets released and I update the dockerfile, I have to reinstall the application, because the config.php gets overwritten.
So I thought I can mount the file as a volume, like I do with the database.
I tried it two ways, with a volume and a direct path.
docker-compose:
version: '2'
services:
app:
build: src
ports:
- "8080:80"
depends_on:
- mysql
volumes:
- app-conf:/var/www/html/upload
- app-conf:/var/www/html/config.php
environment:
DB_TYPE: mysql
DB_MANAGER: MysqlManager
mysql:
image: mysql:5.6
container_name: mysql
volumes:
- mysqldata:/var/lib/mysql
ports:
- 3306:3306
environment:
MYSQL_ROOT_PASSWORD:
MYSQL_DATABASE:
MYSQL_USER:
MYSQL_PASSWORD:
volumes:
mysqldata:
app-conf:
Which results in the error:
And I tried it with a given path, as a mounted volume.
/src/docker/myapp/upload:/var/www/html/upload
/src/docker/myapp/upload:/var/www/html/config.php
However, both ways are not working. With the mounted volume, I see that upload gets created.
But then it fails with:
/var/www/html/config.php\" caused \"not a directory\"""
If I try it with
/src/docker/myapp/upload/config.php:/var/www/html/config.php
Docker creates the upload folder and then a config.php folder. Not a file.
Or is there another way to persist the config?
",https://stackoverflow.com/questions/42248198/how-to-mount-a-single-file-in-a-volume,627,961079.0,22.0,,,2017-02-15 11:33:27,2025-09-15 23:44:17,2020-10-06 00:19:11,,,docker;docker-compose,Hasu,8155,3791380,registered,true,42260979,,CC BY-SA 4.0,2018-07-27 13:57:29,1780,1553,3,0,0,2,true,false,false,true,true,true,38,9,false,0.023,0.0007,3566,2017,2,11,Wednesday,false,false,false,false,false,false,false
26504846,Copy directory to another directory using ADD command,"I have read http://docs.docker.com/engine/reference/builder/#add however I met a problem. I want to copy the local directory go to docker /user/local/
I tried:
ADD go /usr/local/
and:
ADD /go/ /usr/local/
also:
RUN chmod 0755 /usr/local/go/src/make.bash
However, I see the following error message:
/usr/local/go/src/make.bash: No such file or directory
but the local go directory does contain make.bash.
",https://stackoverflow.com/questions/26504846/copy-directory-to-another-directory-using-add-command,618,1185541.0,6.0,,,2014-10-22 09:56:24,2023-10-07 21:56:42,2021-01-28 23:38:30,,,docker,pengwang,20036,233618,registered,true,26504961,,CC BY-SA 4.0,2021-01-28 23:31:05,683,409,8,1,0,1,true,false,false,true,true,true,53,8,false,0.005,0.0005,4413,2014,10,9,Wednesday,false,false,false,false,false,false,false
37694987,Connecting to Postgresql in a docker container from outside,"I have Postgresql on a server in a docker container. How can I connect to it from the outside, that is, from my local computer? What setting should I apply to allow that?
",https://stackoverflow.com/questions/37694987/connecting-to-postgresql-in-a-docker-container-from-outside,618,987473.0,22.0,,,2016-06-08 06:39:44,2025-11-04 07:21:33,2025-01-10 23:25:54,,,postgresql;docker,Sojo,6383,6250601,registered,true,,,CC BY-SA 4.0,2025-01-10 23:25:44,178,171,0,0,0,2,false,false,false,true,true,true,59,9,false,0.022,0.0006,3818,2016,6,6,Wednesday,false,false,false,false,false,false,false
42510002,Docker: How to clear the logs properly for a Docker container?,"I use docker logs [container-name] to see the logs of a specific container.
Is there an elegant way to clear these logs?
",https://stackoverflow.com/questions/42510002/docker-how-to-clear-the-logs-properly-for-a-docker-container,611,961739.0,26.0,,,2017-02-28 13:25:28,2025-10-10 14:54:46,2021-07-14 12:07:45,2025-10-11 05:57:39,Not suitable for this site,docker;docker-compose;boot2docker;docker-machine,Youssouf Maiga,7991,6288254,registered,true,42510314,,,,149,122,1,0,0,4,true,true,false,true,true,true,62,11,true,0.027,0.0006,3553,2017,2,13,Tuesday,false,false,false,false,false,false,false
44084846,Cannot connect to the Docker daemon on macOS,"I normally prefer to manage my apps on my OSX with brew
I am able to install docker, docker-compose and docker-machine
docker --version
Docker version 17.05.0-ce, build 89658be
docker-compose --version
docker-compose version 1.13.0, build unknown
docker-machine --version
docker-machine version 0.11.0, build 5b27455
I did not download and run 'Docker for Mac' app.
However when I try to run
> docker run -d -p 80:80 --name webserver nginx
docker: Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?.
See 'docker run --help'.
I have already checked the sock file
ls -lah /var/run/docker.sock /var/tmp/docker.sock
ls: /var/run/docker.sock: No such file or directory
ls: /var/tmp/docker.sock: No such file or directory
I have also tried this proposed solution: Mac OS X sudo docker Cannot connect to the Docker daemon. Is the docker daemon running on this host?
But I got this error message:
$ eval $(docker-machine env default)
Host does not exist: ""default""
Is it possible to get a docker service to run by command line tools?
",https://stackoverflow.com/questions/44084846/cannot-connect-to-the-docker-daemon-on-macos,609,847210.0,34.0,,,2017-05-20 10:36:15,2025-10-28 18:38:47,2017-05-23 12:18:24,2025-10-28 18:34:12,Not suitable for this site,macos;docker;macos-sierra,Anthony Kong,41523,58129,registered,true,44719239,,,2019-06-12 19:21:04,1382,1091,4,1,0,3,true,true,false,true,true,true,44,8,false,0.04,0.0007,3472,2017,5,10,Saturday,true,false,false,false,false,false,false
30215830,Dockerfile copy keep subdirectory structure,"I'm trying to copy a number of files and folders to a docker image build from my localhost.
The files are like this:
folder1/
file1
file2
folder2/
file1
file2
I'm trying to make the copy like this:
COPY files/* /files/
However, all of the files from folder1/ and folder2/ are placed in /files/ directly, without their folders:
files/
file1
file2
Is there a way in Docker to keep the subdirectory structure as well as copying the files into their directories? Like this:
files/
folder1/
file1
file2
folder2/
file1
file2
",https://stackoverflow.com/questions/30215830/dockerfile-copy-keep-subdirectory-structure,609,685672.0,7.0,,,2015-05-13 13:09:42,2025-02-28 19:39:39,2022-11-01 01:38:09,,,copy;docker;dockerfile,user1220022,12375,1220022,registered,true,30220096,,CC BY-SA 4.0,,757,587,7,0,0,3,true,false,false,true,true,true,43,5,false,0.01,0.0009,4210,2015,5,13,Wednesday,false,false,false,false,false,false,false
28302178,How can I add a volume to an existing Docker container?,"I have a Docker container that I've created simply by installing Docker on Ubuntu and doing:
sudo docker run -i -t ubuntu /bin/bash
I immediately started installing Java and some other tools, spent some time with it, and stopped the container by
exit
Then I wanted to add a volume and realised that this is not as straightforward as I thought it would be. If I use sudo docker -v /somedir run ... then I end up with a fresh new container, so I'd have to install Java and do what I've already done before just to arrive at a container with a mounted volume.
All the documentation about mounting a folder from the host seems to imply that mounting a volume is something that can be done when creating a container. So the only option I have to avoid reconfiguring a new container from scratch is to commit the existing container to a repository and use that as the basis of a new one whilst mounting the volume.
Is this indeed the only way to add a volume to an existing container?
",https://stackoverflow.com/questions/28302178/how-can-i-add-a-volume-to-an-existing-docker-container,605,591606.0,11.0,,,2015-02-03 15:08:17,2025-08-18 08:15:26,2020-07-15 09:31:44,2025-08-18 09:56:02,Not suitable for this site,docker,mahonya,10201,238517,registered,true,33956387,,,,1077,981,3,0,0,1,true,true,false,true,true,true,55,11,true,0.019,0.001,4309,2015,2,15,Tuesday,false,false,false,false,false,false,false
64804749,Why is docker build not showing any output from commands?,"Snippet from my Dockerfile:
FROM node:12.18.0
RUN echo "hello world"
RUN psql --version
When I run docker build . I don't see any output from these two commands even if they are not cached. The documentation says that docker build is verbose by default. Why am I not seeing the output from commands? I used to see them before.
The output while building:
=> [7/18] RUN echo "hello world" 0.9s
The output I am seeing after building finishes:
=> CACHED [6/18] RUN apt-get install postgresql -y 0.0s
=> [7/18] RUN echo "hello world" 6.4s
=> [8/18] RUN psql --version 17.1s
The Dockerfile is created from node:12.18.0 which is based on Debian 9.
Docker version 19.03.13, build 4484c46d9d.
",https://stackoverflow.com/questions/64804749/why-is-docker-build-not-showing-any-output-from-commands,601,508073.0,6.0,,,2020-11-12 13:23:57,2023-12-21 13:50:34,2022-06-22 06:30:25,,,docker;docker-build,Noname,6495,12381816,registered,true,64805337,,CC BY-SA 4.0,,973,807,7,0,0,2,true,false,false,true,true,true,57,10,true,0.012,0.0012,2200,2020,11,13,Thursday,false,false,false,false,false,false,false
24537340,Docker: adding a file from a parent directory,"In my Dockerfile I've got :
ADD ../../myapp.war /opt/tomcat7/webapps/
That file exists as ls ../../myapp.war returns me the correct file but when I execute sudo docker build -t myapp . I've got :
Step 1 : ADD ../../myapp.war /opt/tomcat7/webapps/
2014/07/02 19:18:09 ../../myapp.war: no such file or directory
Does somebody know why and how to do it correctly?
",https://stackoverflow.com/questions/24537340/docker-adding-a-file-from-a-parent-directory,598,583304.0,16.0,,,2014-07-02 17:24:36,2025-05-15 15:55:45,,,,docker,Anthony O.,25083,535203,registered,true,34300129,,CC BY-SA 3.0,,475,367,5,0,0,1,true,false,false,true,true,false,45,8,false,0.027,0.001,4525,2014,7,17,Wednesday,false,false,false,false,false,false,false
22944631,How to get the IP address of the docker host from inside a docker container,"I need to be able to retrieve the IP address the docker hosts and the portmaps from the host to the container, and doing that inside of the container.
",https://stackoverflow.com/questions/22944631/how-to-get-the-ip-address-of-the-docker-host-from-inside-a-docker-container,593,954509.0,28.0,,,2014-04-08 17:53:32,2026-09-08 07:59:17,2026-09-08 07:59:17,2025-10-17 11:16:34,Not suitable for this site,docker;ip,xiamx,7208,335918,registered,true,24716645,,,,158,151,0,0,0,2,true,true,false,true,true,true,75,15,false,0.029,0.0006,4610,2014,4,17,Tuesday,false,false,false,false,false,false,false
30209776,Docker container will automatically stop after "docker run -d","According to tutorial I read so far, use ""docker run -d"" will start a container from image, and the container will run in background. This is how it looks like, we can see we already have container id.
root@docker:/home/root# docker run -d centos
605e3928cdddb844526bab691af51d0c9262e0a1fc3d41de3f59be1a58e1bd1d
But if I ran ""docker ps"", nothing was returned.
So I tried ""docker ps -a"", I can see container already exited:
root@docker:/home/root# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
605e3928cddd centos:latest ""/bin/bash"" 31 minutes ago Exited (0) 31 minutes ago kickass_swartz
Anything I did wrong? How can I troubleshoot this issue?
",https://stackoverflow.com/questions/30209776/docker-container-will-automatically-stop-after-docker-run-d,591,990021.0,22.0,,,2015-05-13 08:41:06,2023-05-07 10:16:43,2022-01-17 13:06:43,,,docker;devops;docker-container;docker-image;docker-run,J John,5941,4414185,registered,true,30209974,,CC BY-SA 4.0,,960,811,5,0,0,5,true,false,false,true,true,true,72,9,false,0.022,0.0006,4210,2015,5,8,Wednesday,false,false,false,false,false,false,false
19688314,How do you attach and detach from Docker's process?,"I can attach to a docker process but Ctrl+C doesn't work to detach from it. exit basically halts the process.
What's the recommended workflow to have the process running, occasionally attaching to it to make some changes, and then detaching?
",https://stackoverflow.com/questions/19688314/how-do-you-attach-and-detach-from-dockers-process,584,534430.0,18.0,,,2013-10-30 16:20:14,2023-06-14 05:49:21,2023-02-01 07:24:06,,,docker,MarkL,9200,671573,registered,true,19689048,,CC BY-SA 4.0,,291,242,1,0,0,1,true,false,false,true,true,true,55,9,true,0.034,0.0011,4770,2013,10,16,Wednesday,false,false,false,false,false,false,false
37458287,How to run a cron job inside a docker container?,"I am trying to run a cronjob inside a docker container that invokes a shell script.
How can I do this?
",https://stackoverflow.com/questions/37458287/how-to-run-a-cron-job-inside-a-docker-container,574,856059.0,32.0,,,2016-05-26 10:32:53,2026-01-02 18:30:59,2024-01-23 06:35:55,,,docker;cron;containers;sh,C Heyer,5733,6268839,registered,true,37458519,,CC BY-SA 4.0,2022-12-15 17:20:38,117,103,0,0,0,4,true,false,false,true,true,true,48,10,true,0.037,0.0007,3831,2016,5,10,Thursday,false,false,false,false,false,false,false
27701930,How to add users to Docker container?,"I have a docker container with some processes (uwsgi and celery) running inside. I want to create a celery user and a uwsgi user for these processes as well as a worker group that they will both belong to, in order to assign permissions.
I tried adding RUN adduser uwsgi and RUN adduser celery to my Dockerfile, but this is causing problems, since these commands prompt for input (I've posted the responses from the build below).
What is the best way to add users to a Docker container so as to set permissions for workers running in the container?
My Docker image is built from the official Ubuntu14.04 base.
Here is the output from the Dockerfile when the adduser commands are run:
Adding user `uwsgi' ...
Adding new group `uwsgi' (1000) ...
Adding new user `uwsgi' (1000) with group `uwsgi' ...
Creating home directory `/home/uwsgi' ...
Copying files from `/etc/skel' ...
[91mEnter new UNIX password: Retype new UNIX password: [0m
[91mpasswd: Authentication token manipulation error
passwd: password unchanged
[0m
[91mUse of uninitialized value $answer in chop at /usr/sbin/adduser line 563.
[0m
[91mUse of uninitialized value $answer in pattern match (m//) at /usr/sbin/adduser line 564.
[0m
Try again? [y/N]
Changing the user information for uwsgi
Enter the new value, or press ENTER for the default
Full Name []:
Room Number []: Work Phone []: Home Phone []: Other []:
[91mUse of uninitialized value $answer in chop at /usr/sbin/adduser line 589.
[0m
[91mUse of uninitialized value $answer in pattern match (m//) at /usr/sbin/adduser line 590.
[0m
Is the information correct? [Y/n]
---> 258f2f2f13df
Removing intermediate container 59948863162a
Step 5 : RUN adduser celery
---> Running in be06f1e20f64
Adding user `celery' ...
Adding new group `celery' (1001) ...
Adding new user `celery' (1001) with group `celery' ...
Creating home directory `/home/celery' ...
Copying files from `/etc/skel' ...
[91mEnter new UNIX password: Retype new UNIX password: [0m
[91mpasswd: Authentication token manipulation error
passwd: password unchanged
[0m
[91mUse of uninitialized value $answer in chop at /usr/sbin/adduser line 563.
[0m
[91mUse of uninitialized value $answer in pattern match (m//) at /usr/sbin/adduser line 564.
[0m
Try again? [y/N]
Changing the user information for celery
Enter the new value, or press ENTER for the default
Full Name []: Room Number []: Work Phone []:
Home Phone []: Other []:
[91mUse of uninitialized value $answer in chop at /usr/sbin/adduser line 589.
[0m
[91mUse of uninitialized value $answer in pattern match (m//) at /usr/sbin/adduser line 590.
[0m
Is the information correct? [Y/n]
",https://stackoverflow.com/questions/27701930/how-to-add-users-to-docker-container,566,894691.0,10.0,,,2014-12-30 08:26:07,2023-04-20 15:38:04,2020-05-26 02:55:03,,,linux;ubuntu;dockerfile,rfj001,8588,2686639,registered,true,27703359,,CC BY-SA 4.0,,2768,2683,3,0,0,3,true,false,false,true,true,true,37,7,true,0.011,0.0006,4344,2014,12,8,Tuesday,false,false,false,false,false,false,false
30233105,docker-compose up for only certain containers,"I have a docker-compose.yml which contain several containers. Three of them are for my app (client, server and database) and the rest are for various dev tools (e.g. psql, npm, manage.py, etc). When I do docker-compose up all of them are started, but I only want the three main ones to start. Because of the links I've specified, I can start just those three with docker-compose up client but then the output is only from that one container. So, is there a way to do one of the following:
- Tell docker-compose which containers should by started by
docker-compose up
- Get output from all linked containers from
docker-compose up client
",https://stackoverflow.com/questions/30233105/docker-compose-up-for-only-certain-containers,565,639708.0,10.0,,,2015-05-14 08:52:54,2025-04-29 22:39:50,,,,docker;docker-compose,aquavitae,19566,1235039,registered,true,63052762,,CC BY-SA 3.0,,738,639,5,0,0,2,true,false,false,true,true,false,45,6,false,0.016,0.0009,4209,2015,5,8,Thursday,false,false,false,false,false,false,false
65456814,Docker (Apple Silicon/M1 Preview) MySQL "no matching manifest for linux/arm64/v8 in the manifest list entries","I'm running the latest build of the Docker Apple Silicon Preview. I created the tutorial container/images and it works fine. When I went to create a custom YAML file and run docker-compose I get the following error when pulling mysql:
ERROR: no matching manifest for linux/arm64/v8 in the manifest list entries
Here is a snippet from my YAMl file:
version: '3'
services:
# Database
db:
image: mysql-server:5.7
volumes:
- db_data:/var/lib/mysql
restart: always
environment:
MYSQL_ROOT_PASSWORD: pass
MYSQL_DATABASE: wp
MYSQL_USER: wp
MYSQL_PASSWORD: wp
networks:
- wpsite
I've tried :latest and :8 which result in the same error. It pulls phpmyadmin and wordpress fine.
",https://stackoverflow.com/questions/65456814/docker-apple-silicon-m1-preview-mysql-no-matching-manifest-for-linux-arm64-v8,559,589382.0,27.0,,,2020-12-26 13:20:20,2025-12-08 06:54:24,,,,mysql;docker;apple-silicon,Sam,6594,1013946,registered,true,65592942,,CC BY-SA 4.0,,903,732,1,1,0,3,true,false,false,true,true,false,120,15,false,0.046,0.0009,2156,2020,12,13,Saturday,true,false,false,false,false,false,false
29377853,How can I use environment variables in docker-compose?,"I would like to be able to use environment variables inside docker-compose.yml, with values passed in at the time of docker-compose up. This is the example.
I am doing this today with a basic docker run command, which is wrapped around my own script. Is there a way to achieve it with compose, without any such bash wrappers?
proxy:
hostname: $hostname
volumes:
- /mnt/data/logs/$hostname:/logs
- /mnt/data/$hostname:/data
",https://stackoverflow.com/questions/29377853/how-can-i-use-environment-variables-in-docker-compose,559,1110925.0,21.0,,,2015-03-31 20:23:11,2025-06-10 09:01:04,2023-02-17 01:30:36,,,docker;docker-compose,Dmitry z,6053,1739713,registered,true,34129973,,CC BY-SA 4.0,,548,436,3,0,0,2,true,false,false,true,true,true,54,8,true,0.019,0.0005,4253,2015,3,20,Tuesday,false,false,false,false,false,false,false
66514436,Difference between "docker compose" and "docker-compose","(Note: this question was created BEFORE Docker docs were updated (it was the reason they were updated - see this answer). Please do not post answers pointing out the docs on the differences).
I have been using docker-compose, but noticed there is also a docker compose (without the dash). I have not been able to quickly determine the differences between the two forms by googling.
docker compose's help:
docker-compose's help:
",https://stackoverflow.com/questions/66514436/difference-between-docker-compose-and-docker-compose,551,261104.0,9.0,,,2021-03-07 08:10:54,2026-10-22 18:23:16,2026-10-22 18:23:16,,,docker;docker-compose,Veverke,11778,1219280,registered,true,66526176,,CC BY-SA 4.0,,904,430,4,3,2,2,true,false,false,true,true,true,76,6,false,0.034,0.0021,2085,2021,3,8,Sunday,true,false,false,false,false,false,false
30256386,How to copy multiple files in one layer using a Dockerfile?,"The following Dockerfile contains four COPY layers:
COPY README.md ./
COPY package.json ./
COPY gulpfile.js ./
COPY __BUILD_NUMBER ./
How to copy these files using one layer instead? The following was tried:
COPY [
""__BUILD_NUMBER ./"",
""README.md ./"",
""gulpfile ./"",
""another_file ./"",
]
",https://stackoverflow.com/questions/30256386/how-to-copy-multiple-files-in-one-layer-using-a-dockerfile,544,511291.0,6.0,,,2015-05-15 09:49:49,2023-03-23 20:51:52,2017-03-27 07:54:10,,,dockerfile,kazhuravlev,6017,2537772,registered,true,30316600,,CC BY-SA 3.0,,397,309,4,0,0,1,true,false,false,true,true,true,59,11,true,0.012,0.0011,4208,2015,5,9,Friday,false,false,false,false,false,false,false
28721699,Root password inside a Docker container,"I'm using a Docker image which was built using the USER command to use a non-root user called dev.
Inside a container, I'm ""dev"", but I want to edit the /etc/hosts file.
So I need to be root. I'm trying the su command, but I'm asked to enter the root password.
What's the default root user's password inside a Docker container?
",https://stackoverflow.com/questions/28721699/root-password-inside-a-docker-container,542,722762.0,21.0,,,2015-02-25 14:34:12,2023-10-27 04:34:14,2018-09-15 21:27:27,,,docker,guillaume,7347,1581295,registered,true,28769950,,CC BY-SA 4.0,,377,330,2,0,0,1,true,false,false,true,true,true,39,6,false,0.029,0.0007,4287,2015,2,14,Wednesday,false,false,false,false,false,false,false
55313610,ImportError: libGL.so.1: cannot open shared object file: No such file or directory,"
I am trying to run cv2, but when I try to import it, I get the following error:
ImportError: libGL.so.1: cannot open shared object file: No such file or directory
My suggested solution online is to install
apt install libgl1-mesa-glx
but this is already installed and the latest version.
NB: I am actually running this on Docker, and I am not able to check the OpenCV version. I tried importing matplotlib and that imports fine.
",https://stackoverflow.com/questions/55313610/importerror-libgl-so-1-cannot-open-shared-object-file-no-such-file-or-directo,535,927740.0,32.0,,,2019-03-23 12:14:10,2024-12-24 18:36:10,2024-07-17 09:06:20,,,python;docker;ubuntu-14.04,Ryan ,10329,8176285,registered,true,,,CC BY-SA 4.0,2024-11-13 10:47:28,586,432,2,0,0,3,false,false,false,true,true,true,82,12,false,0.034,0.0006,2800,2019,3,12,Saturday,true,true,false,false,false,false,false
25845538,How to use sudo inside a docker container?,"Normally, docker containers are run using the user root. I'd like to use a different user, which is no problem using docker's USER directive. But this user should be able to use sudo inside the container. This command is missing.
Here's a simple Dockerfile for this purpose:
FROM ubuntu:12.04
RUN useradd docker && echo ""docker:docker"" | chpasswd
RUN mkdir -p /home/docker && chown -R docker:docker /home/docker
USER docker
CMD /bin/bash
Running this container, I get logged in with user 'docker'. When I try to use sudo, the command isn't found. So I tried to install the sudo package inside my Dockerfile using
RUN apt-get install sudo
This results in Unable to locate package sudo
",https://stackoverflow.com/questions/25845538/how-to-use-sudo-inside-a-docker-container,529,825284.0,14.0,,,2014-09-15 10:07:35,2024-07-19 22:22:40,2018-04-07 18:13:19,,,docker;sudo;linux-containers,drubb,16101,4042051,registered,true,25908200,,CC BY-SA 3.0,,838,710,2,0,0,3,true,false,false,true,true,true,42,8,true,0.017,0.0006,4450,2014,9,10,Monday,false,false,false,false,false,false,false
18136389,Using SSH keys inside docker container,"I have an app that executes various fun stuff with Git (like running git clone & git push) and I'm trying to docker-ize it.
I'm running into an issue though where I need to be able to add an SSH key to the container for the container 'user' to use.
I tried copying it into /root/.ssh/, changing $HOME, creating a git ssh wrapper, and still no luck.
Here is the Dockerfile for reference:
#DOCKER-VERSION 0.3.4
from ubuntu:12.04
RUN apt-get update
RUN apt-get install python-software-properties python g++ make git-core openssh-server -y
RUN add-apt-repository ppa:chris-lea/node.js
RUN echo ""deb http://archive.ubuntu.com/ubuntu precise universe"" >> /etc/apt/sources.list
RUN apt-get update
RUN apt-get install nodejs -y
ADD . /src
ADD ../../home/ubuntu/.ssh/id_rsa /root/.ssh/id_rsa
RUN cd /src; npm install
EXPOSE 808:808
CMD [ ""node"", ""/src/app.js""]
app.js runs the git commands like git pull
",https://stackoverflow.com/questions/18136389/using-ssh-keys-inside-docker-container,523,659180.0,36.0,,,2013-08-08 21:23:00,2024-09-11 14:25:46,2017-12-22 09:54:04,,,ssh-keys;docker,ebensing,6847,930005,registered,true,18138352,,CC BY-SA 3.0,,1587,1476,5,0,0,2,true,false,false,true,true,true,38,6,false,0.055,0.0008,4853,2013,8,21,Thursday,false,false,false,false,false,false,false
16296753,Can you run GUI applications in a Linux Docker container?,"How can you run GUI applications in a Linux Docker container?
Are there any images that set up vncserver or something so that you can - for example - add an extra speedbump sandbox around say Firefox?
",https://stackoverflow.com/questions/16296753/can-you-run-gui-applications-in-a-linux-docker-container,521,457338.0,24.0,,,2013-04-30 09:40:54,2025-09-22 09:18:57,2021-06-03 18:16:08,,,linux;docker;x11;sandbox;vnc,Will,76141,15721,registered,true,16311264,,CC BY-SA 4.0,2014-09-28 01:07:15,280,201,1,1,0,5,true,false,false,true,true,true,57,10,true,0.052,0.0011,4953,2013,4,9,Tuesday,false,false,false,false,false,false,false
27273412,Cannot install packages inside docker Ubuntu image,"I installed Ubuntu 14.04 image on docker. After that, when I try to install packages inside the ubuntu image, I'm getting unable to locate package error:
apt-get install curl
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package curl
How to fix this error?
",https://stackoverflow.com/questions/27273412/cannot-install-packages-inside-docker-ubuntu-image,514,399343.0,10.0,,,2014-12-03 13:50:37,2025-05-26 09:57:13,2016-07-02 15:45:51,2023-01-11 12:52:26,Not suitable for this site,docker;ubuntu-14.04,Developer,6291,2424871,registered,true,27273543,,,,370,332,1,0,0,2,true,true,false,true,true,true,50,7,false,0.025,0.0013,4371,2014,12,13,Wednesday,false,false,false,false,false,false,false
19897743,Exposing a port on a live Docker container,"I'm trying to create a Docker container that acts like a full-on virtual machine. I know I can use the EXPOSE instruction inside a Dockerfile to expose a port, and I can use the -p flag with docker run to assign ports, but once a container is actually running, is there a command to open/map additional ports live?
For example, let's say I have a Docker container that is running sshd. Someone else using the container ssh's in and installs httpd. Is there a way to expose port 80 on the container and map it to port 8080 on the host, so that people can visit the web server running in the container, without restarting it?
",https://stackoverflow.com/questions/19897743/exposing-a-port-on-a-live-docker-container,512,597902.0,15.0,,,2013-11-11 02:00:56,2024-12-25 11:44:17,2017-03-12 13:26:36,2024-06-19 18:29:56,Duplicate,docker,reberhardt,5223,2079798,registered,true,19905563,,,2019-07-31 17:06:42,665,625,2,0,0,1,true,true,false,true,true,true,42,8,false,0.025,0.0009,4758,2013,11,2,Monday,false,false,false,false,false,false,false
25267372,Correct way to detach from a container without stopping it,"In Docker 1.1.2 (latest), what's the correct way to detach from a container without stopping it?
So for example, if I try:
docker run -i -t foo /bin/bash or
docker attach foo (for already running container)
both of which get me to a terminal in the container, how do I exit the container's terminal without stopping it?
exit and CTR+C both stop the container.
",https://stackoverflow.com/questions/25267372/correct-way-to-detach-from-a-container-without-stopping-it,506,547501.0,13.0,,,2014-08-12 14:48:00,2025-05-01 15:14:24,,,,docker,mtmacdonald,15350,942635,registered,true,25268154,,CC BY-SA 3.0,2025-05-01 17:03:08,473,366,4,0,0,1,true,false,false,true,true,false,58,10,false,0.024,0.0009,4484,2014,8,14,Tuesday,false,false,false,false,false,false,false
26220957,How can I inspect the file system of a failed `docker build`?,"I'm trying to build a new Docker image for our development process, using cpanm to install a bunch of Perl modules as a base image for various projects.
While developing the Dockerfile, cpanm returns a failure code because some of the modules did not install cleanly.
I'm fairly sure I need to get apt to install some more things.
Where can I find the /.cpanm/work directory quoted in the output, in order to inspect the logs? In the general case, how can I inspect the file system of a failed docker build command?
After running a find I discovered
/var/lib/docker/aufs/diff/3afa404e[...]/.cpanm
Is this reliable, or am I better off building a "bare" container and running stuff manually until I have all the things I need?
",https://stackoverflow.com/questions/26220957/how-can-i-inspect-the-file-system-of-a-failed-docker-build,506,274144.0,12.0,,,2014-10-06 16:50:19,2026-04-15 04:20:05,2023-01-19 14:02:44,,,debugging;docker;cpanm,Altreus,6369,2386199,registered,true,26222636,,CC BY-SA 4.0,,880,736,7,0,0,3,true,false,false,true,true,true,61,12,true,0.044,0.0018,4429,2014,10,16,Monday,false,false,false,false,false,false,false
46672001,Is it safe to clean docker/overlay2/,"I got some docker containers running on AWS EC2, the /var/lib/docker/overlay2 folder grows very fast in disk size.
I'm wondering if it is safe to delete its content?
or if docker has some kind of command to free up some disk usage.
UPDATE:
I actually tried docker system prune -a already, which reclaimed 0Kb.
Also my /docker/overlay2 disk size is much larger than the output from docker system df
After reading docker documentation and BMitch's answer, I believe it is a stupid idea to touch this folder and I will try other ways to reclaim my disk space.
",https://stackoverflow.com/questions/46672001/is-it-safe-to-clean-docker-overlay2,504,651556.0,28.0,,,2017-10-10 16:53:06,2025-08-30 10:23:38,2022-04-22 18:00:49,,,docker;docker-compose;docker-machine,qichao_he,5884,7003310,registered,true,46672068,,CC BY-SA 4.0,2023-11-22 09:04:04,666,558,2,0,0,3,true,false,false,true,true,true,36,6,false,0.043,0.0008,3329,2017,10,16,Tuesday,false,false,false,false,false,false,false
28996907,docker: "build" requires 1 argument. See 'docker build --help',"Trying to follow the instructions for building a docker image from the docker website.
https://docs.docker.com/examples/running_redis_service/
this is the error I get will following the instructions on the doc and using this Dockerfile
FROM ubuntu:14.04
RUN apt-get update && apt-get install -y redis-server
EXPOSE 6379
ENTRYPOINT [""/usr/bin/redis-server""]
sudo docker build -t myrepo/redis
docker: ""build"" requires 1 argument. See 'docker build --help'.
How do resolve?
",https://stackoverflow.com/questions/28996907/docker-build-requires-1-argument-see-docker-build-help,501,409026.0,17.0,,,2015-03-11 20:40:21,2022-09-25 13:31:35,2021-07-24 13:31:34,,,docker,Tampa,78968,1203556,registered,true,28997256,,CC BY-SA 4.0,2018-07-30 12:38:39,630,508,1,1,0,1,true,false,false,true,true,true,80,9,false,0.042,0.0012,4273,2015,3,20,Wednesday,false,false,false,false,false,false,false
40459280,Docker cannot start on Windows,"Executing docker version command on Windows returns the following results:
C:\Projects> docker version
Client:
Version: 1.13.0-dev
API version: 1.25
Go version: go1.7.3
Git commit: d8d3314
Built: Tue Nov 1 03:05:34 2016
OS/Arch: windows/amd64
error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.25/version: open //./pipe/docker_engine: The system cannot find the file
specified. In the default daemon configuration on Windows, the docker client must be run elevated to connect. This error may also indicate that the docker daemon is not running.
Running the diagnostics produces the following:
C:\Projects> wget https://github.com/Microsoft/Virtualization-
Documentation/raw/master/windows-server-container-tools/Debug-
ContainerHost/Debug-ContainerHost.ps1 -UseBasicParsin | iex
Checking for common problems
Describing Windows Version and Prerequisites
[+] Is Windows 10 Anniversary Update or Windows Server 2016 608ms
[+] Has KB3192366, KB3194496, or later installed if running Windows build 14393 141ms
[+] Is not a build with blocking issues 29ms
Describing Docker is installed
[-] A Docker service is installed - 'Docker' or 'com.Docker.Service' 134ms
Expected: value to not be empty
27: $services | Should Not BeNullOrEmpty
at <ScriptBlock>, <No file>: line 27
[+] Service is running 127ms
[+] Docker.exe is in path 2.14s
Describing User has permissions to use Docker daemon
[+] docker.exe should not return access denied 42ms
Describing Windows container settings are correct
[-] Do not have DisableVSmbOplock set to 1 53ms
Expected: {0}
But was: {1}
66: $regvalue.VSmbDisableOplocks | Should Be 0
at <ScriptBlock>, <No file>: line 66
[+] Do not have zz values set 42ms
Describing The right container base images are installed
error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.25/images/json: open //./pipe/docker_engine: The system cannot find the file specified. In the default daemon configuration on Windows, the docker client must be run elevated to connect. This error may also indicate that the docker daemon is not running.
[-] At least one of 'microsoft/windowsservercore' or 'microsoft/nanoserver' should be installed 129ms
ValidationMetadataException: The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
ParameterBindingValidationException: Cannot validate argument on parameter 'Property'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
at <ScriptBlock>, <No file>: line 90
Describing Container network is created
[-] Error occurred in Describe block 1.08s
RuntimeException: Cannot index into a null array.
at <ScriptBlock>, <No file>: line 119
Showing output from: docker info
Showing output from: docker version
Client:
Version: 1.13.0-dev
API version: 1.25
Go version: go1.7.3
Git commit: d8d3314
Built: Tue Nov 1 03:05:34 2016
OS/Arch: windows/amd64
Showing output from: docker network ls
Warnings & errors from the last 24 hours
Logs saved to C:\Projects\logs_20161107-084122.csv
C:\Projects>
",https://stackoverflow.com/questions/40459280/docker-cannot-start-on-windows,501,1321743.0,61.0,,,2016-11-07 06:46:25,2025-01-27 17:13:41,2024-02-29 06:50:50,,,windows;docker;docker-desktop,Jim,16237,231821,registered,true,,,CC BY-SA 4.0,2018-06-22 20:26:27,3359,3267,3,0,0,3,false,false,false,true,true,true,30,5,false,0.046,0.0004,3666,2016,11,6,Monday,false,false,false,false,false,false,false
34782678,Difference between Running and Starting a Docker container,"In practice to start a container I do:
docker run a8asd8f9asdf0
If thats the case, what does:
docker start
do?
In the manual it says
Start one or more stopped containers
",https://stackoverflow.com/questions/34782678/difference-between-running-and-starting-a-docker-container,496,189746.0,6.0,,,2016-01-14 06:04:08,2024-02-11 14:54:48,2017-11-28 07:59:31,,,docker,mskw,10418,1454775,registered,true,46138763,,CC BY-SA 3.0,,307,182,2,0,0,1,true,false,false,true,true,true,58,8,false,0.032,0.0026,3964,2016,1,6,Thursday,false,false,false,false,false,false,false
32353055,How to start a stopped Docker container with a different command?,"I would like to start a stopped Docker container with a different command, as the default command crashes - meaning I can't start the container and then use docker exec command.
Basically I would like to start a shell so I can inspect the contents of the container.
Luckily I created the container with the -it option!
",https://stackoverflow.com/questions/32353055/how-to-start-a-stopped-docker-container-with-a-different-command,488,472122.0,16.0,,,2015-09-02 12:23:18,2026-05-26 14:22:38,2024-02-11 14:18:49,,,docker,aaa90210,12333,150050,registered,true,39329138,,CC BY-SA 4.0,,366,319,2,0,0,1,true,false,false,true,true,true,65,11,true,0.034,0.001,4098,2015,9,12,Wednesday,false,false,false,false,false,false,false
20635472,Using the RUN instruction in a Dockerfile with 'source' does not work,"I have a Dockerfile that I am putting together to install a vanilla python environment (into which I will be installing an app, but at a later date).
FROM ubuntu:12.04
# required to build certain python libraries
RUN apt-get install python-dev -y
# install pip - canonical installation instructions from pip-installer.org
# http://www.pip-installer.org/en/latest/installing.html
ADD https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py /tmp/ez_setup.py
ADD https://raw.github.com/pypa/pip/master/contrib/get-pip.py /tmp/get-pip.py
RUN python /tmp/ez_setup.py
RUN python /tmp/get-pip.py
RUN pip install --upgrade pip
# install and configure virtualenv
RUN pip install virtualenv
RUN pip install virtualenvwrapper
ENV WORKON_HOME ~/.virtualenvs
RUN mkdir -p $WORKON_HOME
RUN source /usr/local/bin/virtualenvwrapper.sh
The build runs ok until the last line, where I get the following exception:
[previous steps 1-9 removed for clarity]
...
Successfully installed virtualenvwrapper virtualenv-clone stevedore
Cleaning up...
---> 1fc253a8f860
Step 10 : ENV WORKON_HOME ~/.virtualenvs
---> Running in 8b0145d2c80d
---> 0f91a5d96013
Step 11 : RUN mkdir -p $WORKON_HOME
---> Running in 9d2552712ddf
---> 3a87364c7b45
Step 12 : RUN source /usr/local/bin/virtualenvwrapper.sh
---> Running in c13a187261ec
/bin/sh: 1: source: not found
If I ls into that directory (just to test that the previous steps were committed) I can see that the files exist as expected:
$ docker run 3a87 ls /usr/local/bin
easy_install
easy_install-2.7
pip
pip-2.7
virtualenv
virtualenv-2.7
virtualenv-clone
virtualenvwrapper.sh
virtualenvwrapper_lazy.sh
If I try just running the source command I get the same 'not found' error as above. If I RUN an interactive shell session however, source does work:
$ docker run 3a87 bash
source
bash: line 1: source: filename argument required
source: usage: source filename [arguments]
I can run the script from here, and then happily access workon, mkvirtualenv etc.
I've done some digging, and initially it looked as if the problem might lie in the difference between bash as the Ubuntu login shell, and dash as the Ubuntu system shell, dash not supporting the source command.
However, the answer to this appears to be to use '.' instead of source, but this just causes the Docker runtime to blow up with a go panic exception.
What is the best way to run a shell script from a Dockerfile RUN instruction to get around this (am running off the default base image for Ubuntu 12.04 LTS).
",https://stackoverflow.com/questions/20635472/using-the-run-instruction-in-a-dockerfile-with-source-does-not-work,488,538809.0,19.0,,,2013-12-17 13:29:34,2024-07-11 10:05:01,2023-12-22 14:08:32,,,bash;docker;shell,Hugo Rodger-Brown,11750,45698,registered,true,,,CC BY-SA 4.0,,2862,2546,10,0,0,3,false,false,false,true,true,true,77,12,false,0.035,0.0009,4722,2013,12,13,Tuesday,false,false,false,false,false,false,false
32612650,How can I get Docker Compose to always recreate containers from fresh images?,"My Docker images are built on a Jenkins CI server and are pushed to our private Docker Registry. My goal is to provision environments with Docker Compose which always start the originally built state of the images.
I am currently using Docker Compose 1.3.2 as well as 1.4.0 on different machines, but we also used older versions previously.
I always used the docker-compose pull && docker-compose up -d commands to fetch the fresh images from the registry and start them up. I believe my preferred behaviour was working as expected up to a certain point in time, but since then docker-compose up started to rerun previously stopped containers instead of starting the originally built images every time.
Is there a way to get rid of this behaviour? Could that way be one which is wired in the docker-compose.yml configuration file to not depend "not forgetting" something on the command line upon every invocation?
PS: Besides finding a way to achieve my goal, I would also love to know a bit more about the background of this behaviour. I think the basic idea of Docker is to build an immutable infrastructure. The current behaviour of Docker Compose just seem to plain clash with this approach... Or do I miss some points here?
",https://stackoverflow.com/questions/32612650/how-can-i-get-docker-compose-to-always-recreate-containers-from-fresh-images,484,844789.0,12.0,,,2015-09-16 15:18:09,2026-01-12 04:48:04,2026-01-12 04:33:02,2025-08-12 11:59:54,Not suitable for this site,docker;docker-compose,Kristof Jozsa,7612,548915,registered,true,32618288,,,,1601,1247,2,3,0,2,true,true,false,true,true,true,77,13,true,0.014,0.0006,4084,2015,9,15,Wednesday,false,false,false,false,false,false,false
40944479,How can I use Bash with an Alpine-based Docker image?,"I created a Docker image from openjdk:8-jdk-alpine, and I want to use Bash, rather than sh as my shell. However, when I try to execute simple commands, I get the following errors:
RUN bash
/bin/sh: bash: not found
RUN ./gradlew build
env: can't execute 'bash': No such file or directory
",https://stackoverflow.com/questions/40944479/how-can-i-use-bash-with-an-alpine-based-docker-image,484,499550.0,8.0,,,2016-12-03 05:14:18,2026-11-06 20:33:14,2026-11-06 19:49:59,,,bash;docker;shell;alpine-linux,iamdeit,6165,4830460,registered,true,40944512,,CC BY-SA 4.0,,385,289,3,0,0,4,true,false,false,true,true,true,53,10,true,0.016,0.001,3640,2016,12,5,Saturday,true,false,false,false,false,false,false
30969435,Where is the Docker daemon log?,"Where is the Docker daemon log? Oddly cannot find an answer to this via man, StackOverflow or Docker Docs. Note I am not asking for the docker container STDOUT, but the daemon log for troubleshooting communications between the client and container via daemon / proxy.
",https://stackoverflow.com/questions/30969435/where-is-the-docker-daemon-log,482,495616.0,14.0,,,2015-06-21 21:18:38,2023-05-22 20:25:52,,,,logging;docker,user2603634,4941,2603634,registered,true,,,CC BY-SA 3.0,,277,270,0,0,0,2,false,false,false,true,true,false,31,6,true,0.028,0.001,4171,2015,6,21,Sunday,true,false,false,false,false,false,false
42297387,docker build with --build-arg with multiple arguments,"According to the documentation, it's possible to define multiple args for the flag --build-arg, but I can't find out how. I tried the following:
docker build -t essearch/ess-elasticsearch:1.7.6 --build-arg number_of_shards=5 number_of_replicas=2 --no-cache .
=> This returns an error.
I also tried:
docker build -t essearch/ess-elasticsearch:1.7.6 --build-arg number_of_shards=5,number_of_replicas=2 --no-cache .
=> This sets one variable, number_of_shards, to the value ""5,number_of_replicas=2""
Any idea how I can define multiple arguments?
",https://stackoverflow.com/questions/42297387/docker-build-with-build-arg-with-multiple-arguments,477,530888.0,7.0,,,2017-02-17 11:57:44,2024-02-12 18:35:08,2018-12-26 06:13:04,,,docker;build;arguments,Emilien Brigand,11261,2858871,registered,true,42297949,,CC BY-SA 4.0,2021-04-09 07:18:23,785,550,4,1,0,3,true,false,false,true,true,true,53,7,false,0.013,0.0009,3564,2017,2,11,Friday,false,false,false,false,false,false,false
28212380,Why docker container exits immediately,"I run a container in the background using
docker run -d --name hadoop h_Service
it exits quickly. But if I run in the foreground, it works fine. I checked logs using
docker logs hadoop
there was no error. Any ideas?
DOCKERFILE
FROM java_ubuntu_new
RUN wget http://archive.cloudera.com/cdh4/one-click-install/precise/amd64/cdh4-repository_1.0_all.deb
RUN dpkg -i cdh4-repository_1.0_all.deb
RUN curl -s http://archive.cloudera.com/cdh4/ubuntu/precise/amd64/cdh/archive.key | apt-key add -
RUN apt-get update
RUN apt-get install -y hadoop-0.20-conf-pseudo
RUN dpkg -L hadoop-0.20-conf-pseudo
USER hdfs
RUN hdfs namenode -format
USER root
RUN apt-get install -y sudo
ADD . /usr/local/
RUN chmod 777 /usr/local/start-all.sh
CMD [""/usr/local/start-all.sh""]
start-all.sh
#!/usr/bin/env bash
/etc/init.d/hadoop-hdfs-namenode start
/etc/init.d/hadoop-hdfs-datanode start
/etc/init.d/hadoop-hdfs-secondarynamenode start
/etc/init.d/hadoop-0.20-mapreduce-tasktracker start
sudo -u hdfs hadoop fs -chmod 777 /
/etc/init.d/hadoop-0.20-mapreduce-jobtracker start
/bin/bash
",https://stackoverflow.com/questions/28212380/why-docker-container-exits-immediately,477,740360.0,22.0,,,2015-01-29 10:30:21,2025-01-05 21:54:00,2017-02-01 03:01:14,,,docker,Gibbs,23118,2694184,registered,true,28214133,,CC BY-SA 3.0,,1244,1096,4,0,0,1,true,false,false,true,true,true,38,5,false,0.03,0.0006,4314,2015,1,10,Thursday,false,false,false,false,false,false,false
30133664,How do you list volumes in docker containers?,"When using docker images from registries, I often need to see the volumes created by the image's containers.
Note: I'm using docker version 1.3.2 on Red Hat 7.
Example
The postgres official image from the Docker Registry has a volume configured for containers at /var/lib/postgresql/data.
What's the most succinct command to show the volume at /var/lib/postgresql/data in a postgres container?
",https://stackoverflow.com/questions/30133664/how-do-you-list-volumes-in-docker-containers,472,614427.0,17.0,,,2015-05-08 22:18:17,2025-10-10 14:20:33,2023-12-15 02:17:08,2025-10-21 10:30:08,Not suitable for this site,docker;docker-volume;docker-container,CivFan,15654,2125392,registered,true,30133768,,,,496,398,4,0,0,3,true,true,false,true,true,true,45,8,true,0.028,0.0008,4215,2015,5,22,Friday,false,false,false,false,false,false,false
19585028,I lose my data when the container exits,"Despite Docker's Interactive tutorial and faq I lose my data when the container exits.
I have installed Docker as described here: http://docs.docker.io/en/latest/installation/ubuntulinux
without any problem on ubuntu 13.04.
But it loses all data when exits.
iman@test:~$ sudo docker version
Client version: 0.6.4
Go version (client): go1.1.2
Git commit (client): 2f74b1c
Server version: 0.6.4
Git commit (server): 2f74b1c
Go version (server): go1.1.2
Last stable version: 0.6.4
iman@test:~$ sudo docker run ubuntu ping
2013/10/25 08:05:47 Unable to locate ping
iman@test:~$ sudo docker run ubuntu apt-get install ping
Reading package lists...
Building dependency tree...
The following NEW packages will be installed:
iputils-ping
0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded.
Need to get 56.1 kB of archives.
After this operation, 143 kB of additional disk space will be used.
Get:1 http://archive.ubuntu.com/ubuntu/ precise/main iputils-ping amd64 3:20101006-1ubuntu1 [56.1 kB]
debconf: delaying package configuration, since apt-utils is not installed
Fetched 56.1 kB in 0s (195 kB/s)
Selecting previously unselected package iputils-ping.
(Reading database ... 7545 files and directories currently installed.)
Unpacking iputils-ping (from .../iputils-ping_3%3a20101006-1ubuntu1_amd64.deb) ...
Setting up iputils-ping (3:20101006-1ubuntu1) ...
iman@test:~$ sudo docker run ubuntu ping
2013/10/25 08:06:11 Unable to locate ping
iman@test:~$ sudo docker run ubuntu touch /home/test
iman@test:~$ sudo docker run ubuntu ls /home/test
ls: cannot access /home/test: No such file or directory
I also tested it with interactive sessions with the same result. Did I forget something?
EDIT: IMPORTANT FOR NEW DOCKER USERS
As @mohammed-noureldin and others said, actually this is NOT a container exiting. Every time it just creates a new container.
",https://stackoverflow.com/questions/19585028/i-lose-my-data-when-the-container-exits,468,356546.0,11.0,,,2013-10-25 08:36:30,2024-11-25 07:58:25,2019-04-03 06:40:09,,,docker,iman,22638,1675586,registered,true,19586345,,CC BY-SA 4.0,,2259,1890,1,3,0,1,true,false,false,true,true,true,39,8,false,0.031,0.0013,4775,2013,10,8,Friday,false,false,false,false,false,false,false
35832095,Difference between links and depends_on in docker_compose.yml,"According to the Docker Compose's compose-file documentation:
depends_on - Express dependency between services.
links - Link to containers in another service and also express dependency between services in the same way as depends_on.
I don't understand the purpose of linking to other containers so the difference between two options still seems quite difficult for me.
It would be much easier if there is an example, but I can't find any.
I noticed, when I link container B with container A then container B will be ""pingable"" inside container A's shell.
I ran ping B inside container A's bash and got result like this (just for reference, image from the Internet)
",https://stackoverflow.com/questions/35832095/difference-between-links-and-depends-on-in-docker-compose-yml,460,393776.0,4.0,,,2016-03-06 20:24:13,2021-10-06 13:50:15,2017-12-16 17:24:42,,,docker;docker-compose;dockerfile,itsjef,4889,6026378,registered,true,54251381,,CC BY-SA 3.0,,1118,675,4,3,1,3,true,false,false,true,true,true,61,7,false,0.01,0.0012,3912,2016,3,20,Sunday,true,false,false,false,false,false,false
28320134,How can I list all tags for a Docker image on a remote registry?,"How can I list all tags of a Docker image on a remote Docker registry using the CLI (preferred) or curl?
Preferably without pulling all versions from the remote registry. I just want to list the tags.
",https://stackoverflow.com/questions/28320134/how-can-i-list-all-tags-for-a-docker-image-on-a-remote-registry,459,600440.0,32.0,,,2015-02-04 11:22:46,2025-09-16 13:31:15,2019-11-12 11:04:28,,,docker,Johan,41412,398441,registered,true,39454426,,CC BY-SA 4.0,,216,202,0,0,0,1,true,false,false,true,true,true,64,14,true,0.053,0.0008,4308,2015,2,11,Wednesday,false,false,false,false,false,false,false
32230577,How do I define the name of image built with docker-compose,"I'm using docker-compose to create my development environment. I want to build a specific image, but I don't know how to set a name for that image.
wildfly:
build: /path/to/dir/Dockerfile
container_name: wildfly_server
ports:
- 9990:9990
- 80:8080
environment:
- MYSQL_HOST=mysql_server
- MONGO_HOST=mongo_server
- ELASTIC_HOST=elasticsearch_server
volumes:
- /Volumes/CaseSensitive/development/wildfly/deployments/:/opt/jboss/wildfly/standalone/deployments/
links:
- mysql:mysql_server
- mongo:mongo_server
- elasticsearch:elasticsearch_server
When I execute docker-compose everything is ok, but I get a random name for the new image. Is it possible to set a name to the build image?
",https://stackoverflow.com/questions/32230577/how-do-i-define-the-name-of-image-built-with-docker-compose,456,582449.0,13.0,,,2015-08-26 15:21:32,2025-02-13 06:41:26,2018-06-13 10:27:57,,,docker;docker-compose;orchestration,Robert,11069,988174,registered,true,,,CC BY-SA 4.0,,863,727,2,1,0,3,false,false,false,true,true,true,59,11,false,0.022,0.0008,4105,2015,8,15,Wednesday,false,false,false,false,false,false,false
33913020,Docker remove <none> TAG images,"root@server:~# docker images -a
REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE
<none> <none> 5e2dfc857e73 5 days ago 261.6 MB
<none> <none> d053e988f23d 5 days ago 261.6 MB
<none> <none> 1d5d4a2d89eb 5 days ago 261.6 MB
<none> <none> ea0d189fdb19 5 days ago 100.5 MB
<none> <none> 26c6175962b3 5 days ago 100.5 MB
<none> <none> 73d5cec4a0b3 5 days ago 100.5 MB
<none> <none> e19590e1bac1 5 days ago 100.5 MB
I've tried the following:
docker rmi $(docker images | grep ""^<none>"" | awk ""{print $3}"")
And the following:
docker rmi $(docker images -f ""dangling=true"" -q)
Get the following error:
docker: ""rmi"" requires a minimum of 1 argument.
See 'docker rmi --help'.
Usage: docker rmi [OPTIONS] IMAGE [IMAGE...]
Remove one or more images
",https://stackoverflow.com/questions/33913020/docker-remove-none-tag-images,449,436002.0,38.0,,,2015-11-25 09:39:19,2025-08-30 22:31:44,2015-11-25 10:00:54,,,docker,basickarl,41351,1137669,registered,true,33913711,,CC BY-SA 3.0,2021-09-06 08:20:03,1336,1219,4,0,0,1,true,false,false,true,true,true,37,5,false,0.087,0.001,4014,2015,11,9,Wednesday,false,false,false,false,false,false,false
47536536,What's the difference between Docker Compose and Kubernetes?,"While diving into Docker, Google Cloud and Kubernetes, and without clearly understanding all three of them yet, it seems to me these products are overlapping, yet they're not compatible.
For example, a docker-compose.yml file needs to be re-written so an app can be deployed to Kubernetes.
Could someone provide a high-level, rough description of where Docker, Docker Compose, Docker Cloud, and Kubernetes overlap and where one is dependent on the other?
",https://stackoverflow.com/questions/47536536/whats-the-difference-between-docker-compose-and-kubernetes,448,163876.0,5.0,,,2017-11-28 16:34:31,2024-04-19 03:19:38,2020-12-10 16:08:49,,,docker;kubernetes;docker-compose,George Katsanos,14363,458060,registered,true,47537046,,CC BY-SA 4.0,2020-06-28 17:33:23,491,457,1,0,0,3,true,false,false,true,true,true,64,8,true,0.031,0.0027,3280,2017,11,16,Tuesday,false,false,false,false,false,false,false
20632258,Change directory command in Docker?,"In docker I want to do this:
git clone XYZ
cd XYZ
make XYZ
However because there is no cd command, I have to pass in the full path everytime (make XYZ /fullpath). Any good solutions for this?
",https://stackoverflow.com/questions/20632258/change-directory-command-in-docker,447,626330.0,6.0,,,2013-12-17 10:55:04,2024-07-31 22:27:25,2021-10-16 08:20:34,,,docker;dockerfile;cd,RParadox,6961,1460614,registered,true,20632625,,CC BY-SA 4.0,,233,195,1,0,0,3,true,false,false,true,true,true,35,5,true,0.01,0.0007,4722,2013,12,10,Tuesday,false,false,false,false,false,false,false
30137135,Confused about Docker -t option to Allocate a pseudo-TTY,"What exactly does this option do? I've been reading a lot on TTY and I'm still confused. I played around without having the -t and just -i and it seems like programs that expect user input throw an error without the -t. Why is it important for pseudo-TTY to be enabled?
",https://stackoverflow.com/questions/30137135/confused-about-docker-t-option-to-allocate-a-pseudo-tty,446,162182.0,9.0,,,2015-05-09 07:11:59,2022-10-02 09:32:23,2021-03-04 22:06:40,,,docker;tty;pty,user1099123,6733,1099123,registered,true,40026942,,CC BY-SA 4.0,,316,270,3,0,0,3,true,false,false,true,true,true,56,9,false,0.055,0.0027,4214,2015,5,7,Saturday,true,false,false,false,false,false,false
22080706,How to create named and latest tag in Docker?,"Supposed I have an image that I want to tag as 0.10.24 (in my case it's an image containing Node.js 0.10.24). I built that image using a Dockerfile and executing docker build and by providing a tag using the -t parameter.
I expect that one day I will have additional versions of that image, so I will rerun the process, just with another tag name.
So far, so good. This works great and fine and all is well.
But, and this is where problems start, I also want to always have the newest image tagged as latest additionally. So I guess I need to give two names to the very same image.
How do I do this? Do I really need to re-run docker build on the exact same version again, but this time use another tag, is is there a better option?
",https://stackoverflow.com/questions/22080706/how-to-create-named-and-latest-tag-in-docker,445,528648.0,9.0,,,2014-02-27 21:22:12,2026-05-21 16:27:39,2024-09-16 23:05:54,,,docker;tags,Golo Roden,153081,1333873,registered,true,36398336,,CC BY-SA 4.0,,833,733,5,0,0,2,true,false,false,true,true,true,45,9,true,0.017,0.0008,4650,2014,2,21,Thursday,false,false,false,false,false,false,false
27380641,See full command of running/stopped container in Docker,"How can I see the full command of a running container/process in Docker?
$ docker ps --all
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
5b6291859b61 nginx:1.7.8 ""nginx -g 'daemon of 4 minutes ago Exited (0) 4 minutes ago thirsty_brattain
I can only see ""nginx -g 'daemon of"".. here, not the full command.
",https://stackoverflow.com/questions/27380641/see-full-command-of-running-stopped-container-in-docker,444,331615.0,6.0,,,2014-12-09 13:55:10,2020-03-04 09:55:36,2018-07-23 19:48:29,,,docker,Niklas9,9546,1258192,registered,true,33023527,,CC BY-SA 4.0,,438,400,1,0,0,1,true,false,false,true,true,true,55,8,false,0.018,0.0013,4365,2014,12,13,Tuesday,false,false,false,false,false,false,false
40905761,How do I mount a host directory as a volume in docker compose,"I have a development environment I'm dockerizing and I would like the ability to livereload my changes without having to rebuild docker images. I'm using docker compose because redis is one of my app's dependencies and I like being able to link a redis container
I have two containers defined in my docker-compose.yml:
node:
build: ./node
links:
- redis
ports:
- "8080"
env_file:
- node-app.env
redis:
image: redis
ports:
- "6379"
I've gotten to the point in my node app's dockerfile where I add a volume, but how do I mount the the host's directory in the volume so that all my live edits to the code are reflected in the container?
Here's my current Dockerfile:
# Set the base image to Ubuntu
FROM node:boron
# File Author / Maintainer
MAINTAINER Amin Shah Gilani <amin@gilani.me>
# Install nodemon
RUN npm install -g nodemon
# Add a /app volume
VOLUME ["/app"]
# TODO: link the current . to /app
# Define working directory
WORKDIR /app
# Run npm install
RUN npm install
# Expose port
EXPOSE 8080
# Run app using nodemon
CMD ["nodemon", "/app/app.js"]
My project looks like this:
/
- docker-compose.yml
- node-app.env
- node/
- app.js
- Dockerfile.js
",https://stackoverflow.com/questions/40905761/how-do-i-mount-a-host-directory-as-a-volume-in-docker-compose,443,968895.0,9.0,,,2016-12-01 08:25:17,2026-06-01 20:10:36,2020-10-27 16:25:37,2026-06-03 23:19:08,Not suitable for this site,docker;docker-compose;docker-volume,Amin Shah Gilani,10116,3970701,registered,true,40905828,,,,1473,1257,5,0,0,3,true,true,false,true,true,true,61,13,false,0.009,0.0005,3642,2016,12,8,Thursday,false,false,false,false,false,false,false
23544282,What is the (best) way to manage permissions for Docker shared volumes?,"I've been playing around with Docker for a while and keep on finding the same issue when dealing with persistent data.
I create my Dockerfile and expose a volume or use --volumes-from to mount a host folder inside my container.
What permissions should I apply to the shared volume on the host?
I can think of two options:
So far I've given everyone read/write access, so I can write to the folder from the Docker container.
Map the users from host into the container, so I can assign more granular permissions. Not sure this is possible though and haven't found much about it. So far, all I can do is run the container as some user: docker run -i -t -user=""myuser"" postgres, but this user has a different UID than my host myuser, so permissions do not work. Also, I'm unsure if mapping the users will pose some security risks.
Are there other alternatives?
How are you guys/gals dealing with this issue?
",https://stackoverflow.com/questions/23544282/what-is-the-best-way-to-manage-permissions-for-docker-shared-volumes,441,478607.0,15.0,,,2014-05-08 14:11:10,2023-06-18 14:29:23,2018-07-25 04:55:45,,,docker,Xabs,4694,794401,registered,true,27021154,,CC BY-SA 4.0,,1245,912,4,2,0,1,true,false,false,true,true,true,71,12,true,0.031,0.0009,4580,2014,5,14,Thursday,false,false,false,false,false,false,false
41637505,How to persist data in a dockerized postgres database using volumes,"My docker compose file has three containers, web, nginx, and postgres. Postgres looks like this:
postgres:
container_name: postgres
restart: always
image: postgres:latest
volumes:
- ./database:/var/lib/postgresql
ports:
- 5432:5432
My goal is to mount a volume which corresponds to a local folder called ./database inside the postgres container as /var/lib/postgres. When I start these containers and insert data into postgres, I verify that /var/lib/postgres/data/base/ is full of the data I'm adding (in the postgres container), but in my local system, ./database only gets a data folder in it, i.e. ./database/data is created, but it's empty. Why?
Notes:
UPDATE 1
Per Nick's suggestion, I did a docker inspect and found:
"Mounts": [
{
"Source": "/Users/alex/Documents/MyApp/database",
"Destination": "/var/lib/postgresql",
"Mode": "rw",
"RW": true,
"Propagation": "rprivate"
},
{
"Name": "e5bf22471215db058127109053e72e0a423d97b05a2afb4824b411322efd2c35",
"Source": "/var/lib/docker/volumes/e5bf22471215db058127109053e72e0a423d97b05a2afb4824b411322efd2c35/_data",
"Destination": "/var/lib/postgresql/data",
"Driver": "local",
"Mode": "",
"RW": true,
"Propagation": ""
}
],
Which makes it seem like the data is being stolen by another volume I didn't code myself. Not sure why that is. Is the postgres image creating that volume for me? If so, is there some way to use that volume instead of the volume I'm mounting when I restart? Otherwise, is there a good way of disabling that other volume and using my own, ./database?
",https://stackoverflow.com/questions/41637505/how-to-persist-data-in-a-dockerized-postgres-database-using-volumes,435,488732.0,7.0,,,2017-01-13 15:02:12,2025-10-30 16:23:39,2022-12-03 12:42:19,,,postgresql;docker;docker-compose;docker-volume,Alex Lenail,14830,2584721,registered,true,41650891,,CC BY-SA 4.0,,2466,2061,10,2,0,4,true,false,false,true,true,true,67,11,false,0.014,0.0009,3599,2017,1,15,Friday,false,false,false,false,false,false,false
45357771,Stop and remove all docker containers,"How can I stop and remove all docker containers to create a clean slate with my Docker containers? Lots of times I feel it is easier to start from scratch, but I have a bunch of containers that I am not sure what their states are, then when I run docker rm it won't let me because the docker container could still be in use.
",https://stackoverflow.com/questions/45357771/stop-and-remove-all-docker-containers,434,902708.0,17.0,,,2017-07-27 17:50:00,2025-10-06 05:03:27,2021-07-10 08:39:23,,,docker,jjbskir,11645,3107798,registered,true,51316176,,CC BY-SA 4.0,,345,325,1,0,0,1,true,false,false,true,true,true,37,6,false,0.019,0.0005,3404,2017,7,17,Thursday,false,false,false,false,false,false,false
48546124,What is the Linux equivalent of "host.docker.internal"?,"On Mac and Windows, it is possible to use host.docker.internal (Docker 18.03+) inside a container.
Is there one for Linux that will work out of the box without passing environment variables or extracting it using various CLI commands?
",https://stackoverflow.com/questions/48546124/what-is-the-linux-equivalent-of-host-docker-internal,432,674696.0,11.0,,,2018-01-31 15:48:05,2025-08-12 09:41:53,2023-12-06 17:15:38,2022-04-28 21:50:48,Duplicate,docker;docker-for-windows;docker-for-mac;docker-desktop,klor,4766,3221403,registered,true,62431165,,,,262,235,1,0,0,4,true,true,false,true,true,true,65,7,true,0.016,0.0006,3216,2018,1,15,Wednesday,false,false,false,false,false,false,false
43654656,Dockerfile if else condition with external arguments,"I have dockerfile
FROM centos:7
ENV foo=42
then I build it
docker build -t my_docker .
and run it.
docker run -it -d my_docker
Is it possible to pass arguments from command line and use it with if else in Dockerfile? I mean something like
FROM centos:7
if (my_arg==42)
{ENV=TRUE}
else:
{ENV=FALSE}
and build with this argument.
docker build -t my_docker . --my_arg=42
",https://stackoverflow.com/questions/43654656/dockerfile-if-else-condition-with-external-arguments,432,581427.0,15.0,,,2017-04-27 10:05:23,2023-09-27 09:53:17,,,,docker;dockerfile,nick_gabpe,6013,3545745,registered,true,43656644,,CC BY-SA 3.0,,550,395,5,0,0,2,true,false,false,true,true,false,52,7,false,0.026,0.0007,3495,2017,4,10,Thursday,false,false,false,false,false,false,false
29181032,"Add a volume to Docker, but exclude a sub-folder","Supposed I have a Docker container and a folder on my host /hostFolder. Now if I want to add this folder to the Docker container as a volume, then I can do this either by using ADD in the Dockerfile or mounting it as a volume.
So far, so good.
Now /hostFolder contains a sub-folder, /hostFolder/subFolder.
I want to mount /hostFolder into the Docker container (whether as read-write or read-only does not matter, works both for me), but I do NOT want to have it included /hostFolder/subFolder. I want to exclude this, and I also want the Docker container be able to make changes to this sub-folder, without the consequence of having it changed on the host as well.
Is this possible? If so, how?
",https://stackoverflow.com/questions/29181032/add-a-volume-to-docker-but-exclude-a-sub-folder,431,234680.0,13.0,,,2015-03-21 09:13:31,2024-01-07 21:52:56,,,,docker;dockerfile,Golo Roden,153081,1333873,registered,true,37898591,,CC BY-SA 3.0,,842,699,7,0,0,2,true,false,false,true,true,false,48,9,false,0.055,0.0018,4263,2015,3,9,Saturday,true,false,false,false,false,false,false
19104847,How can I generate a Dockerfile from an image?,"Is it possible to generate a Dockerfile from an image? I want to know for two reasons:
I can download images from the repository, but I would like to see the recipe that generated them.
I like the idea of saving snapshots, but once I am done, it would be nice to have a structured format to review what was done.
",https://stackoverflow.com/questions/19104847/how-can-i-generate-a-dockerfile-from-an-image,431,424514.0,11.0,,,2013-09-30 22:16:38,2026-02-04 18:52:57,2026-02-04 15:58:23,,,image;repository;docker,user1026169,5895,1026169,registered,true,30793515,,CC BY-SA 4.0,2020-08-19 08:53:37,366,318,0,0,0,3,true,false,false,true,true,true,46,9,true,0.026,0.001,4800,2013,9,22,Monday,false,false,false,false,false,false,false
31251356,How to get a list of images on docker registry v2,"I'm using docker registry v1 and I'm interested in migrating to the newer version, v2. But I need some way to get a list of images present on registry; for example with registry v1 I can execute a GET request to http://myregistry:5000/v1/search? and the result is:
{
"num_results": 2,
"query": "",
"results": [
{
"description": "",
"name": "deis/router"
},
{
"description": "",
"name": "deis/database"
}
]
}
But I can't find on official documentation something similar to get a list of image on registry. Anybody knows a way to do it on new version v2?
",https://stackoverflow.com/questions/31251356/how-to-get-a-list-of-images-on-docker-registry-v2,429,1099321.0,23.0,,,2015-07-06 16:47:39,2025-10-07 04:22:48,2025-10-07 04:22:48,,,docker;docker-registry,enrique-carbonell,6552,896830,registered,true,31750543,,CC BY-SA 4.0,2021-07-29 03:54:21,895,722,2,1,0,2,true,false,false,true,true,true,49,11,false,0.021,0.0004,4156,2015,7,16,Monday,false,false,false,false,false,false,false
43308319,How can I run bash in a docker container?,"I am able to run arbitrary shell commands in a container created from docker/whalesay image.
$ docker run docker/whalesay ls -l
total 56
-rw-r--r-- 1 root root 931 May 25 2015 ChangeLog
...
However, I am unable to run bash in a container created from this image, as the container exits immediately:
$ docker run docker/whalesay bash
$ docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
7ce600cc9904 docker/whalesay "bash" 5 seconds ago Exited (0) 3 seconds ago loving_mayer
Why did it not work? How can I make it work?
",https://stackoverflow.com/questions/43308319/how-can-i-run-bash-in-a-docker-container,428,773421.0,1.0,,,2017-04-09 15:07:52,2026-01-07 03:44:56,2026-01-07 03:44:56,,,bash;docker,Lone Learner,21480,1175080,registered,true,43309168,,CC BY-SA 4.0,,781,699,3,0,0,2,true,false,false,true,true,true,41,9,true,0.001,0.0006,3513,2017,4,15,Sunday,true,false,false,false,false,false,false
21928691,How to continue a Docker container which has exited,"Consider:
docker run -it centos /bin/bash
I pressed Ctrl+D to exit it.
I want to continue to run this container, but I found I can't.
The only method is
docker commit `docker ps -q -l` my_image
docker run -it my_image /bin/bash
Am I right? Is there a better method? (I'm using docker 0.8.0.)
",https://stackoverflow.com/questions/21928691/how-to-continue-a-docker-container-which-has-exited,426,498939.0,16.0,,,2014-02-21 08:05:16,2023-09-28 07:10:20,2018-07-23 19:15:56,,,docker,Daniel YC Lin,16302,730346,registered,true,21928864,,CC BY-SA 4.0,,439,300,2,0,0,1,true,false,false,true,true,true,51,9,false,0.032,0.0009,4656,2014,2,8,Friday,false,false,false,false,false,false,false
24288616,Permission denied on accessing host directory in Docker,"I am trying to mount a host directory in Docker, but then I cannot access it from within the container, even if the access permissions look good.
I am doing
sudo docker run -i -v /data1/Downloads:/Downloads ubuntu bash
and then
ls -al
It gives me:
total 8892
drwxr-xr-x. 23 root root 4096 Jun 18 14:34 .
drwxr-xr-x. 23 root root 4096 Jun 18 14:34 ..
-rwxr-xr-x. 1 root root 0 Jun 18 14:34 .dockerenv
-rwx------. 1 root root 9014486 Jun 17 22:09 .dockerinit
drwxrwxr-x. 18 1000 1000 12288 Jun 16 11:40 Downloads
drwxr-xr-x. 2 root root 4096 Jan 29 18:10 bin
drwxr-xr-x. 2 root root 4096 Apr 19 2012 boot
drwxr-xr-x. 4 root root 340 Jun 18 14:34 dev
drwxr-xr-x. 56 root root 4096 Jun 18 14:34 etc
drwxr-xr-x. 2 root root 4096 Apr 19 2012 home
and a lot more lines like that (I think this is the relevant portion).
If I do
cd /Downloads
ls
the result is
ls: cannot open directory .: Permission denied
The host is Fedora 20, with Docker 1.0.0 and go1.2.2.
What is going wrong?
",https://stackoverflow.com/questions/24288616/permission-denied-on-accessing-host-directory-in-docker,425,579748.0,13.0,,,2014-06-18 14:47:22,2024-08-23 17:14:56,2022-02-07 16:52:59,2026-02-22 12:22:07,Not suitable for this site,docker;file-permissions;fedora;mount;permission-denied,user3753011,4351,3753011,registered,true,,,,,1209,1026,5,0,0,5,false,true,false,true,true,true,55,8,false,0.022,0.0007,4539,2014,6,14,Wednesday,false,false,false,false,false,false,false
42158596,Can Windows containers be hosted on Linux?,"The scenario involves an application written in .NET Framework (legacy .NET) and a Linux user who wants to run it using Docker. The goal is to provide a net462-based API accessible on localhost.
I am using the beta version of Docker Desktop for Windows.
If not, why can Windows run Linux containers, but Linux cannot run Windows containers?
As some time has passed and this question is a popular one, I'd like to add one note here that the workaround is to use the new .NET Standard. It allowed me to pack the 4.6.2 framework into a new library.
",https://stackoverflow.com/questions/42158596/can-windows-containers-be-hosted-on-linux,425,396715.0,10.0,,,2017-02-10 11:44:28,2025-11-30 23:09:47,2025-11-30 23:07:01,,,linux;docker;docker-for-windows;windows-container;docker-desktop,Sebastian 506563,7288,2047022,registered,true,42185265,,CC BY-SA 4.0,2018-06-27 00:36:17,824,547,0,2,0,5,true,false,false,true,true,true,42,7,true,0.025,0.0011,3571,2017,2,11,Friday,false,false,false,false,false,false,false
27409761,Docker: Multiple Dockerfiles in project,"How do you organize the Dockerfiles belonging to a project when you have one Dockerfile for the database, one for the application server, and so on? Do you create some sort of hierachy in the source?
A big enterprise project can't consist of only one Dockerfile?
",https://stackoverflow.com/questions/27409761/docker-multiple-dockerfiles-in-project,421,285819.0,6.0,,,2014-12-10 19:58:28,2022-08-07 11:49:58,2020-05-05 17:47:49,,,docker,LuckyLuke,49301,454049,registered,true,27410493,,CC BY-SA 4.0,,270,263,0,0,0,1,true,false,false,true,true,true,39,5,false,0.021,0.0015,4364,2014,12,19,Wednesday,false,false,false,false,false,false,false
17989306,What does Docker add to lxc-tools (the userspace LXC tools)?,"If you take a look at Docker's features, most of them are already provided by LXC.
So what does Docker add? Why would I use Docker over plain LXC?
",https://stackoverflow.com/questions/17989306/what-does-docker-add-to-lxc-tools-the-userspace-lxc-tools,421,111258.0,5.0,,,2013-08-01 08:50:42,2022-12-22 10:42:07,2015-08-02 21:12:10,,,docker;lxc,Flimm,155656,247696,registered,true,18208445,,CC BY-SA 3.0,,162,148,0,0,0,2,true,false,false,true,true,true,60,10,true,0.045,0.0038,4860,2013,8,8,Thursday,false,false,false,false,false,false,false
24718706,Backup/Restore a dockerized PostgreSQL database,"I'm trying to backup/restore a PostgreSQL database as is explained on the Docker website, but the data is not restored.
The volumes used by the database image are:
VOLUME [""/etc/postgresql"", ""/var/log/postgresql"", ""/var/lib/postgresql""]
and the CMD is:
CMD [""/usr/lib/postgresql/9.3/bin/postgres"", ""-D"", ""/var/lib/postgresql/9.3/main"", ""-c"", ""config_file=/etc/postgresql/9.3/main/postgresql.conf""]
I create the DB container with this command:
docker run -it --name ""$DB_CONTAINER_NAME"" -d ""$DB_IMAGE_NAME""
Then I connect another container to insert some data manually:
docker run -it --rm --link ""$DB_CONTAINER_NAME"":db ""$DB_IMAGE_NAME"" sh -c 'exec bash'
psql -d test -h $DB_PORT_5432_TCP_ADDR
# insert some data in the db
<CTRL-D>
<CTRL-D>
The tar archive is then created:
$ sudo docker run --volumes-from ""$DB_CONTAINER_NAME"" --rm -v $(pwd):/backup ubuntu tar cvf /backup/backup.tar /etc/postgresql /var/log/postgresql /var/lib/postgresql
Now I remove the container used for the db and create another one, with the same name, and try to restore the data inserted before:
$ sudo docker run --volumes-from ""$DB_CONTAINER_NAME"" --rm -v $(pwd):/backup ubuntu tar xvf /backup/backup.tar
But the tables are empty, why is the data not properly restored ?
",https://stackoverflow.com/questions/24718706/backup-restore-a-dockerized-postgresql-database,419,483020.0,17.0,,,2014-07-13 01:10:38,2024-02-05 13:11:26,2016-07-06 20:51:56,,,database;postgresql;backup;docker,Carl Levasseur,4791,2512774,registered,true,29913462,,CC BY-SA 3.0,,1483,1283,6,0,0,4,true,false,false,true,true,true,47,5,false,0.035,0.0009,4514,2014,7,1,Sunday,true,false,false,false,false,false,false
45142528,What is a dangling image and what is an unused image?,"In the docker documentation of docker image prune it is possible to use the -a flag to
Remove all unused images, not just dangling ones
and later
Remove all dangling images. If -a is specified, will also remove all images not referenced by any container.
Q: What are dangling images?
Q: What's the difference between dangling and unused images?
",https://stackoverflow.com/questions/45142528/what-is-a-dangling-image-and-what-is-an-unused-image,418,200634.0,9.0,,,2017-07-17 11:01:50,2024-05-09 11:50:21,2024-01-18 21:20:38,,,docker;docker-image,herm,16855,7683711,registered,true,45143234,,CC BY-SA 4.0,,576,349,3,1,0,2,true,false,false,true,true,true,53,11,true,0.045,0.0021,3414,2017,7,11,Monday,false,false,false,false,false,false,false
26753087,How to analyze disk usage of a Docker container,"I can see that Docker takes 12GB of my filesystem:
2.7G /var/lib/docker/vfs/dir
2.7G /var/lib/docker/vfs
2.8G /var/lib/docker/devicemapper/mnt
6.3G /var/lib/docker/devicemapper/devicemapper
9.1G /var/lib/docker/devicemapper
12G /var/lib/docker
But, how do I know how this is distributed over the containers?
I tried to attach to the containers by running (the new v1.3 command)
docker exec -it <container_name> bash
and then running df -h to analyze the disk usage. It seems to be working, but not with containers that use 'volumes-from'.
For example, I use a data-only container for MongoDB, called 'mongo-data'.
When I run docker run -it --volumes-from mongo-data busybox, and then df -h inside the container, It says that the filesystem mounted on /data/db (my 'mongo-data' data-only container) uses 11.3G, but when I do du -h /data/db, it says that it uses only 2.1G.
So, how do I analyze a container/volume disk usage? Or, in my case, how do I find out the 'mongo-data' container size?
",https://stackoverflow.com/questions/26753087/how-to-analyze-disk-usage-of-a-docker-container,414,434187.0,12.0,,,2014-11-05 09:01:17,2025-04-20 20:29:38,2023-08-22 22:50:46,,,docker;docker-container,AlonL,6860,1563935,registered,true,33344280,,CC BY-SA 4.0,,1181,1019,7,0,0,2,true,false,false,true,true,true,47,9,false,0.028,0.001,4399,2014,11,9,Wednesday,false,false,false,false,false,false,false
19537645,How to get an environment variable value into Dockerfile during "docker build"?,"I'm building a container for a ruby app. My app's configuration is contained within environment variables (loaded inside the app with dotenv).
One of those configuration variables is the public ip of the app, which is used internally to make links.
I need to add a dnsmasq entry pointing this ip to 127.0.0.1 inside the container, so it can fetch the app's links as if it were not containerized.
I'm therefore trying to set an ENV in my Dockerfile which would pass an environment variable to the container.
I tried a few things.
ENV REQUEST_DOMAIN $REQUEST_DOMAIN
ENV REQUEST_DOMAIN `REQUEST_DOMAIN`
Everything passes the ""REQUEST_DOMAIN"" string instead of the value of the environment variable though.
Is there a way to pass environment variables values from the host machine to the container?
",https://stackoverflow.com/questions/19537645/how-to-get-an-environment-variable-value-into-dockerfile-during-docker-build,410,565144.0,9.0,,,2013-10-23 09:16:03,2025-05-06 08:24:17,2023-12-02 02:58:20,,,docker;dockerfile;docker-build,Damien MATHIEU,32739,122080,registered,true,34600106,,CC BY-SA 4.0,,921,801,2,1,0,3,true,false,false,true,true,true,89,12,true,0.016,0.0007,4777,2013,10,9,Wednesday,false,false,false,false,false,false,false
27158840,docker: executable file not found in $PATH,"I have a docker image which installs grunt, but when I try to run it, I get an error:
Error response from daemon: Cannot start container foo_1: \
exec: ""grunt serve"": executable file not found in $PATH
If I run bash in interactive mode, grunt is available.
What am I doing wrong?
Here is my Dockerfile:
# https://registry.hub.docker.com/u/dockerfile/nodejs/ (builds on ubuntu:14.04)
FROM dockerfile/nodejs
MAINTAINER My Name, me@email.com
ENV HOME /home/web
WORKDIR /home/web/site
RUN useradd web -d /home/web -s /bin/bash -m
RUN npm install -g grunt-cli
RUN npm install -g bower
RUN chown -R web:web /home/web
USER web
RUN git clone https://github.com/repo/site /home/web/site
RUN npm install
RUN bower install --config.interactive=false --allow-root
ENV NODE_ENV development
# Port 9000 for server
# Port 35729 for livereload
EXPOSE 9000 35729
CMD [""grunt""]
",https://stackoverflow.com/questions/27158840/docker-executable-file-not-found-in-path,408,821806.0,15.0,,,2014-11-26 21:03:44,2024-07-23 13:17:50,2014-11-26 21:18:01,2025-12-03 11:37:26,Not suitable for this site,docker,Steve Lorimer,29076,955273,registered,true,27615958,,,,984,882,4,0,0,1,true,true,false,true,true,true,42,7,false,0.018,0.0005,4378,2014,11,21,Wednesday,false,false,false,false,false,false,false
51066146,What is the point of WORKDIR on Dockerfile?,"I'm learning Docker. For many times I've seen that Dockerfile has WORKDIR command:
FROM node:latest
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
COPY package.json /usr/src/app/
RUN npm install
COPY . /usr/src/app
EXPOSE 3000
CMD [ “npm”, “start” ]
Can't I just omit WORKDIR and Copy and just have my Dockerfile at the root of my project? What are the downsides of using this approach?
",https://stackoverflow.com/questions/51066146/what-is-the-point-of-workdir-on-dockerfile,408,538054.0,8.0,,,2018-06-27 15:07:30,2025-09-28 20:35:08,2019-05-22 20:34:37,,,docker;dockerfile,Le garcon,8747,5084982,registered,true,51066379,,CC BY-SA 4.0,,494,391,6,0,0,2,true,false,false,true,true,true,43,8,true,0.015,0.0008,3069,2018,6,15,Wednesday,false,false,false,false,false,false,false
45141402,Build and run Dockerfile with one command,"Is it possible to build image from Dockerfile and run it with a single command?
There is one command docker build to build a Dockerfile and docker run -it to run the image.
Is there any combination of these two commands to make it easier to build and run with just one command?
",https://stackoverflow.com/questions/45141402/build-and-run-dockerfile-with-one-command,405,397607.0,11.0,,,2017-07-17 10:08:42,2026-03-20 19:57:23,2019-12-06 23:15:14,,,docker;dockerfile,Twinkle,4151,7489510,registered,true,45141443,,CC BY-SA 4.0,,341,280,2,0,0,2,true,false,false,true,true,true,41,7,false,0.028,0.001,3414,2017,7,10,Monday,false,false,false,false,false,false,false
23111631,Cannot download Docker images behind a proxy,"I installed Docker on my Ubuntu 13.10 (Saucy Salamander) and when I type in my console:
sudo docker pull busybox
I get the following error:
Pulling repository busybox
2014/04/16 09:37:07 Get https://index.docker.io/v1/repositories/busybox/images: dial tcp: lookup index.docker.io on 127.0.1.1:53: no answer from server
Docker version:
$ sudo docker version
Client version: 0.10.0
Client API version: 1.10
Go version (client): go1.2.1
Git commit (client): dc9c28f
Server version: 0.10.0
Server API version: 1.10
Git commit (server): dc9c28f
Go version (server): go1.2.1
Last stable version: 0.10.0
I am behind a proxy server with no authentication, and this is my /etc/apt/apt.conf file:
Acquire::http::proxy ""http://192.168.1.1:3128/"";
Acquire::https::proxy ""https://192.168.1.1:3128/"";
Acquire::ftp::proxy ""ftp://192.168.1.1:3128/"";
Acquire::socks::proxy ""socks://192.168.1.1:3128/"";
What am I doing wrong?
",https://stackoverflow.com/questions/23111631/cannot-download-docker-images-behind-a-proxy,404,684849.0,29.0,,,2014-04-16 13:58:32,2025-11-20 09:33:52,2018-09-19 16:43:15,,,proxy;docker,rpayanm,6613,2172151,registered,true,28093517,,CC BY-SA 4.0,2018-05-13 03:22:26,1065,921,5,0,0,2,true,false,false,true,true,true,44,7,false,0.042,0.0006,4602,2014,4,13,Wednesday,false,false,false,false,false,false,false
45594707,What is pip's `--no-cache-dir` good for?,"I've recently seen the --no-cache-dir being used in a Docker file. I've never seen that flag before and the help is not explaining it:
--no-cache-dir Disable the cache.
- Question: What is cached?
- Question: What is the cache used for?
- Question: Why would I want to disable it?
",https://stackoverflow.com/questions/45594707/what-is-pips-no-cache-dir-good-for,401,397291.0,6.0,,,2017-08-09 15:20:36,2025-01-14 20:18:00,2023-02-12 16:40:17,,,python;docker;pip,Martin Thoma,139375,562769,registered,true,45594808,,CC BY-SA 4.0,,425,294,2,0,0,3,true,false,false,true,true,true,44,6,true,0.015,0.001,3391,2017,8,15,Wednesday,false,true,false,false,false,false,false
41485217,Mount current directory as a volume in Docker on Windows 10,"Description
I am using Docker version 1.12.5 on Windows 10 via Hyper-V and want to use container executables as commands in the current path. I built a Docker image that is running fine, but I have a problem to mount the current path. The idea is to create an alias and do a docker run --rm [...] command so that it could be used system-wide in the current directory.
Setup
I have a drive E with a folder ""test"" and in there a folder called ""folder on windows host"" to show that the command is working. The Dockerfile create the directory /data, defines it as VOLUME and WORKDIR.
Having E:\test as the current directory in PowerShell and executing the Docker command with an absolute path, I can see the content of E:\test:
PS E:\test> docker run --rm -it -v E:\test:/data mirkohaaser/docker-clitools ls -la
total 0
drwxr-xr-x 2 root root 0 Jan 4 11:45 .
drwxr-xr-x 2 root root 0 Jan 5 12:17 folder on windows host
Problem
I want to use the current directory and not an absolute notation. I could not use pwd in the volume because of different error messages:
Trying with ($pwd)
PS E:\test> docker run --rm -it -v ($pwd):/data mirkohaaser/docker-clitools ls -la
C:\Program Files\Docker\Docker\Resources\bin\docker.exe: Error parsing reference: "":/data"" is not a valid repository/tag.
See 'C:\Program Files\Docker\Docker\Resources\bin\docker.exe run --help'.
Trying with /($pwd)
PS E:\test> docker run --rm -it -v /($pwd):/data mirkohaaser/docker-clitools ls -la
C:\Program Files\Docker\Docker\Resources\bin\docker.exe: Error parsing reference: ""E:\\test"" is not a valid repository/tag.
See 'C:\Program Files\Docker\Docker\Resources\bin\docker.exe run --help'.
Trying with \´pwd\´
PS E:\test> docker run --rm -it -v ´$pwd´:/data mirkohaaser/docker-clitools ls -la
C:\Program Files\Docker\Docker\Resources\bin\docker.exe: Error response from daemon: Invalid bind mount spec ""´E:\\test´:/data"": invalid mode: /data.
See 'C:\Program Files\Docker\Docker\Resources\bin\docker.exe run --help'.
Trying with `pwd`
PS E:\test> docker run --rm -it -v `$pwd`:/data mirkohaaser/docker-clitools ls -la
C:\Program Files\Docker\Docker\Resources\bin\docker.exe: Error response from daemon: create $pwd: ""$pwd"" includes invalid characters for a local volume name, only ""[a-zA-Z0-9][a-zA-Z0-9_.-]"" are allowed.
See 'C:\Program Files\Docker\Docker\Resources\bin\docker.exe run --help'.
What is the correct syntax of mounting the current directory as a volume in Docker on Windows 10?
",https://stackoverflow.com/questions/41485217/mount-current-directory-as-a-volume-in-docker-on-windows-10,399,507549.0,15.0,,,2017-01-05 12:32:21,2023-10-22 07:34:07,2018-08-06 17:20:28,,,windows;docker,McGo,4227,4034179,registered,true,41489151,,CC BY-SA 4.0,,2809,2502,9,0,0,2,true,false,false,true,true,true,59,11,false,0.03,0.0008,3607,2017,1,12,Thursday,false,false,false,false,false,false,false
26598738,How to create User/Database in script for Docker Postgres,"I have been trying to set up a container for a development postgres instance by creating a custom user & database. I am using the official postgres docker image. In the documentation it instructs you to insert a bash script inside of the /docker-entrypoint-initdb.d/ folder to set up the database with any custom parameters.
My bash script: make_db.sh
su postgres -c ""createuser -w -d -r -s docker""
su postgres -c ""createdb -O docker docker""
Dockerfile
FROM library/postgres
RUN [""mkdir"", ""/docker-entrypoint-initdb.d""]
ADD make_db.sh /docker-entrypoint-initdb.d/
The error I get from the docker logs -f db (db is my container name) is:
createuser: could not connect to database postgres: could not connect to server: No such file or directory
It seems that the commands inside of the /docker-entrypoint-initdb.d/ folder are being executed before postgres is started. My question is, how do I set up a user/database programmatically using the official postgres container? Is there any way to do this with a script?
",https://stackoverflow.com/questions/26598738/how-to-create-user-database-in-script-for-docker-postgres,399,603749.0,10.0,,,2014-10-27 23:47:58,2023-11-15 16:54:12,2017-02-13 04:52:29,,,bash;postgresql;docker;dockerhub,pech0rin,5105,2308178,registered,true,26599273,,CC BY-SA 3.0,,1266,1033,5,1,0,4,true,false,false,true,true,true,57,9,false,0.017,0.0007,4408,2014,10,23,Monday,false,false,false,false,false,false,false
34658836,"Docker is in volume in use, but there aren't any Docker containers","EDIT (2/19/21): A lot of time has elapsed since I asked this original question years ago and I've seen a flurry of activity since then. I re-selected an answer which I think is consistent with the most localized and safe option for solving this issue (which is typically associated with docker-compose). While docker did introduce the prune command, it is generally a dangerous operation and I would be cautious about using it as you may unintentionally impact other applications or setups you have on your machine
I've been having issues with removing Docker volumes with Docker 1.9.1.
I've removed all my stopped containers so that docker ps -a returns empty.
When I use docker volume ls, I'm given a whole host of Docker containers:
docker volume ls
DRIVER VOLUME NAME
local a94211ea91d66142886d72ec476ece477bb5d2e7e52a5d73b2f2f98f6efa6e66
local 4f673316d690ca2d41abbdc9bf980c7a3f8d67242d76562bbd44079f5f438317
local eb6ab93effc4b90a2162e6fab6eeeb65bd0e4bd8a9290e1bad503d2a47aa8a78
local 91acb0f7644aec16d23a70f63f70027899017a884dab1f33ac8c4cf0dabe5f2c
local 4932e2fbad8f7e6246af96208d45a266eae11329f1adf176955f80ca2e874f69
local 68fd38fc78a8f02364a94934e9dd3b5d10e51de5b2546e7497eb21d6a1e7b750
local 7043a9642614dd6e9ca013cdf662451d2b3df6b1dddff97211a65ccf9f4c6d47
#etc x 50
Since none of these volumes contain anything important, I try to purge all the volumes with docker volume rm $(docker volume ls -q).
In the process, the majority are removed, but I get back:
Error response from daemon: Conflict: volume is in use
Error response from daemon: Conflict: volume is in use
Error response from daemon: Conflict: volume is in use
Error response from daemon: Conflict: volume is in use
Error response from daemon: Conflict: volume is in use
For a sizeable portion of them. If I don't have any containers existing in the first place, how are these volumes being used?
",https://stackoverflow.com/questions/34658836/docker-is-in-volume-in-use-but-there-arent-any-docker-containers,393,337296.0,12.0,,,2016-01-07 15:22:46,2024-12-31 02:19:06,2021-02-19 22:53:32,2024-12-31 17:41:43,Not suitable for this site,docker;docker-machine,Tkwon123,4290,5141687,registered,true,52326805,,,,2140,1985,6,0,0,2,true,true,false,true,true,true,70,12,false,0.036,0.0012,3971,2016,1,15,Thursday,false,false,false,false,false,false,false
64221861,"An error, "failed to solve with frontend dockerfile.v0"","I was trying to build my Docker image for my Gatsby application. Whenever I run the command docker build . -t gatsbyapp, it gives me an error:
failed to solve with frontend dockerfile.v0: failed to build LLB:
failed to compute cache key: "/.env" not found: not found
Meanwhile my Dockerfile is shown below:
FROM node:13
WORKDIR /app
COPY package.json .
RUN yarn global add gatsby-cli
RUN yarn install
COPY gatsby-config.js .
COPY .env .
EXPOSE 8000
CMD ["gatsby","develop","-H","0.0.0.0"]
",https://stackoverflow.com/questions/64221861/an-error-failed-to-solve-with-frontend-dockerfile-v0,390,764612.0,59.0,,,2020-10-06 08:14:03,2024-06-14 12:54:09,2022-08-18 03:09:27,,,docker;docker-compose;dockerfile;gatsby,Muhammad Yasir,4014,14399364,registered,true,64468815,,CC BY-SA 4.0,2021-05-03 21:47:40,759,549,3,1,0,4,true,false,false,true,true,true,65,8,false,0.077,0.0005,2237,2020,10,8,Tuesday,false,false,false,false,false,false,false
43380939,Where does the convention of using /healthz for application health checks come from?,"In the Kubernetes/Docker ecosystem there is a convention of using /healthz as a health-check endpoint for applications.
Where does the name 'healthz' come from, and are there any particular semantics associated with that name?
",https://stackoverflow.com/questions/43380939/where-does-the-convention-of-using-healthz-for-application-health-checks-come-f,387,101263.0,1.0,,,2017-04-12 22:59:07,2025-12-30 07:41:12,,,,docker;kubernetes;kubernetes-health-check,Andy Hume,42104,46460,registered,true,43381061,,CC BY-SA 3.0,2020-07-20 12:20:54,255,228,1,0,0,3,true,false,false,true,true,false,84,13,true,0.01,0.0038,3510,2017,4,22,Wednesday,false,false,false,false,false,false,false
23391839,Clone private git repo with dockerfile,"I have copied this code from what seems to be various working dockerfiles around, here is mine:
FROM ubuntu
MAINTAINER Luke Crooks ""luke@pumalo.org""
# Update aptitude with new repo
RUN apt-get update
# Install software
RUN apt-get install -y git python-virtualenv
# Make ssh dir
RUN mkdir /root/.ssh/
# Copy over private key, and set permissions
ADD id_rsa /root/.ssh/id_rsa
RUN chmod 700 /root/.ssh/id_rsa
RUN chown -R root:root /root/.ssh
# Create known_hosts
RUN touch /root/.ssh/known_hosts
# Remove host checking
RUN echo ""Host bitbucket.org\n\tStrictHostKeyChecking no\n"" >> /root/.ssh/config
# Clone the conf files into the docker container
RUN git clone git@bitbucket.org:Pumalo/docker-conf.git /home/docker-conf
This gives me the error
Step 10 : RUN git clone git@bitbucket.org:Pumalo/docker-conf.git /home/docker-conf
---> Running in 0d244d812a54
Cloning into '/home/docker-conf'...
Warning: Permanently added 'bitbucket.org,131.103.20.167' (RSA) to the list of known hosts.
Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
2014/04/30 16:07:28 The command [/bin/sh -c git clone git@bitbucket.org:Pumalo/docker-conf.git /home/docker-conf] returned a non-zero code: 128
This is my first time using dockerfiles, but from what I have read (and taken from working configs) I cannot see why this doesn't work.
My id_rsa is in the same folder as my dockerfile and is a copy of my local key which can clone this repo no problem.
Edit:
In my dockerfile I can add:
RUN cat /root/.ssh/id_rsa
And it prints out the correct key, so I know its being copied correctly.
I have also tried to do as noah advised and ran:
RUN echo ""Host bitbucket.org\n\tIdentityFile /root/.ssh/id_rsa\n\tStrictHostKeyChecking no"" >> /etc/ssh/ssh_config
This sadly also doesn't work.
",https://stackoverflow.com/questions/23391839/clone-private-git-repo-with-dockerfile,386,468313.0,12.0,,,2014-04-30 15:14:10,2023-10-07 09:05:30,2022-04-01 13:44:26,,,bash;git;docker,crooksey,8678,2508665,registered,true,23411161,,CC BY-SA 4.0,2024-09-27 18:55:43,2067,1908,4,0,0,3,true,false,false,true,true,true,38,6,false,0.026,0.0008,4588,2014,4,15,Wednesday,false,false,false,false,false,false,false
37966552,What is the difference between docker and docker-compose,"docker and docker-compose seem to be interacting with the same dockerFile, what is the difference between the two tools?
",https://stackoverflow.com/questions/37966552/what-is-the-difference-between-docker-and-docker-compose,385,177666.0,4.0,,,2016-06-22 11:21:19,2024-07-14 00:28:44,2016-06-22 11:57:09,2025-12-28 20:07:45,Not suitable for this site,docker;docker-compose,Hafiz,5287,1119938,registered,true,37966689,,,,154,121,2,0,0,2,true,true,false,true,true,true,56,8,false,0.023,0.0022,3804,2016,6,11,Wednesday,false,false,false,false,false,false,false
35511604,Docker - unable to prepare context: unable to evaluate symlinks in Dockerfile path: GetFileAttributesEx,"I just downloaded Docker Toolbox for Windows 10 64-bit today. I'm going through the tutorial. I'm receiving the following error when trying to build an image using a Dockerfile.
Steps:
- Launched Docker Quickstart terminal.
- testdocker after creating it.
- Prepare Dockerfile as documented in "Build your own image" web link
- ran the below command
docker build -t docker-whale .
Error: $ docker build -t docker-whale .
unable to prepare context: unable to evaluate symlinks in Dockerfile path: GetFileAttributesEx C:\Users\Villanueva\Test\testdocker\Dockerfile: The system cannot find the file specified.
BTW: I tried several options mentioned @ https://github.com/docker/docker/issues/14339
docker info
Output:
Containers: 4
Running: 0
Paused: 0
Stopped: 4
Images: 2
Server Version: 1.10.1
Storage Driver: aufs
Root Dir: /mnt/sda1/var/lib/docker/aufs
Backing Filesystem: extfs
Dirs: 20
Dirperm1 Supported: true
Execution Driver: native-0.2
Logging Driver: json-file
Plugins:
Volume: local
Network: bridge null host
Kernel Version: 4.1.17-boot2docker
Operating System: Boot2Docker 1.10.1 (TCL 6.4.1); master : b03e158 - Thu Feb 11 22:34:01 UTC 2016
OSType: linux
Architecture: x86_64
CPUs: 1
Total Memory: 996.2 MiB
Name: default
ID: C7DS:CIAJ:FTSN:PCGD:ZW25:MQNG:H3HK:KRJL:G6FC:VPRW:SEWW:KP7B
Debug mode (server): true
File Descriptors: 32
Goroutines: 44
System Time: 2016-02-19T17:37:37.706076803Z
EventsListeners: 0
Init SHA1:
Init Path: /usr/local/bin/docker
Docker Root Dir: /mnt/sda1/var/lib/docker
Labels:
provider=virtualbox
",https://stackoverflow.com/questions/35511604/docker-unable-to-prepare-context-unable-to-evaluate-symlinks-in-dockerfile-pa,382,649118.0,45.0,,,2016-02-19 17:48:22,2024-07-31 08:18:29,2022-12-12 22:02:20,,,docker;dockerfile;docker-toolbox;docker-build,villanux,3851,2863818,registered,true,,,CC BY-SA 4.0,2019-03-14 15:33:13,1839,1564,5,1,0,4,false,false,false,true,true,true,103,14,false,0.069,0.0006,3928,2016,2,17,Friday,false,false,false,false,false,false,false
26050899,How to mount host volumes into docker containers in Dockerfile during build,"Since 2014 when this question has been asked, many situations had happened and many things has changed. I'm revisiting the topic again today, and I'm editing this question for the 12th time to reflect the latest changes. The question may seem long but it is arranged in the reverse chronological order, so the latest changes are at the top and feel free stop reading at any point.
The question I wanted to solve was -- how to mount host volumes into docker containers in Dockerfile during build, i.e., having the docker run -v /export:/export capability during docker build.
One reason behind it, for me, is when building things in Docker, I don't want those (apt-get install) caches locked in a single docker, but to share/reuse them.
That was the main reason I was asking this question. And one more reason I'm facing today is trying to make use of a huge private repo from host which I have to otherwise do git clone from a private repo within docker using my private ssh key, which I don't know how and haven't looked into yet.
Latest Update:
The Buildkit in @BMitch's answer
With that RUN --mount syntax, you can also bind mount read-only directories from the build-context...
it has now been built-in in docker (which I thought being a third-party tool), as long as yours' over 18.09. Mine is 20.10.7 now --
https://docs.docker.com/develop/develop-images/build_enhancements/
To enable BuildKit builds
Easiest way from a fresh install of docker is to set the DOCKER_BUILDKIT=1 environment variable when invoking the docker build command, such as:
$ DOCKER_BUILDKIT=1 docker build .
Else, you'll get:
the --mount option requires BuildKit. Refer to https://docs.docker.com/go/buildkit/ to learn how to build images with BuildKit enabled
So it'll be the perfect solution to my second use-case as explained above.
Update as of May 7, 2019:
Before docker v18.09, the correct answer should be the one that starts with:
There is a way to mount a volume during a build, but it doesn't involve Dockerfiles.
However, that was a poorly stated, organized and supported answer. When I was reinstalling my docker contains, I happened to stumble upon the following article:
Dockerize an apt-cacher-ng service
https://docs.docker.com/engine/examples/apt-cacher-ng/
That's the docker's solution to this/my question, not directly but indirectly. It's the orthodox way docker suggests us to do. And I admit it is better than the one I was trying to ask here.
Another way is, the newly accepted answer, e.g., the Buildkit in v18.09.
Pick whichever suits you.
Was: There had been a solution -- rocker, which was not from Docker, but now that rocker is discontinued, I revert the answer back to "Not possible" again.
Old Update: So the answer is "Not possible". I can accept it as an answer as I know the issue has been extensively discussed at https://github.com/docker/docker/issues/3156. I can understand that portability is a paramount issue for docker developer; but as a docker user, I have to say I'm very disappointed about this missing feature. Let me close my argument with a quote from aforementioned discussion: "I would like to use Gentoo as a base image but definitely don't want > 1GB of Portage tree data to be in any of the layers once the image has been built. You could have some nice a compact containers if it wasn't for the gigantic portage tree having to appear in the image during the install." Yes, I can use wget or curl to download whatever I need, but the fact that merely a portability consideration is now forcing me to download > 1GB of Portage tree each time I build a Gentoo base image is neither efficient nor user friendly. Further more, the package repository WILL ALWAYS be under /usr/portage, thus ALWAYS PORTABLE under Gentoo. Again, I respect the decision, but please allow me expressing my disappointment as well in the mean time. Thanks.
Original question in details:
From
Share Directories via Volumes
http://docker.readthedocs.org/en/v0.7.3/use/working_with_volumes/
it says that Data volumes feature "have been available since version 1 of the Docker Remote API". My docker is of version 1.2.0, but I found the example given in above article not working:
# BUILD-USING: docker build -t data .
# RUN-USING: docker run -name DATA data
FROM busybox
VOLUME ["/var/volume1", "/var/volume2"]
CMD ["/usr/bin/true"]
What's the proper way in Dockerfile to mount host-mounted volumes into docker containers, via the VOLUME command?
$ apt-cache policy lxc-docker
lxc-docker:
Installed: 1.2.0
Candidate: 1.2.0
Version table:
*** 1.2.0 0
500 https://get.docker.io/ubuntu/ docker/main amd64 Packages
100 /var/lib/dpkg/status
$ cat Dockerfile
FROM debian:sid
VOLUME ["/export"]
RUN ls -l /export
CMD ls -l /export
$ docker build -t data .
Sending build context to Docker daemon 2.56 kB
Sending build context to Docker daemon
Step 0 : FROM debian:sid
---> 77e97a48ce6a
Step 1 : VOLUME ["/export"]
---> Using cache
---> 59b69b65a074
Step 2 : RUN ls -l /export
---> Running in df43c78d74be
total 0
---> 9d29a6eb263f
Removing intermediate container df43c78d74be
Step 3 : CMD ls -l /export
---> Running in 8e4916d3e390
---> d6e7e1c52551
Removing intermediate container 8e4916d3e390
Successfully built d6e7e1c52551
$ docker run data
total 0
$ ls -l /export | wc
20 162 1131
$ docker -v
Docker version 1.2.0, build fa7b24f
",https://stackoverflow.com/questions/26050899/how-to-mount-host-volumes-into-docker-containers-in-dockerfile-during-build,380,407273.0,15.0,,,2014-09-26 02:00:44,2023-11-30 08:21:51,2022-02-18 20:24:23,,,share;docker;host;mount,xpt,23784,2125837,registered,true,52762779,,CC BY-SA 4.0,,6614,5584,9,4,0,4,true,false,false,true,true,true,75,12,false,0.037,0.0009,4439,2014,9,2,Friday,false,false,false,false,false,false,false
39684974,Docker for Windows error: "Hardware assisted virtualization and data execution protection must be enabled in the BIOS","I've installed Docker and I'm getting this error when I run the GUI:
Hardware assisted virtualization and data execution protection must
be enabled in the BIOS
Seems like a bug since Docker works like a charm from the command line, but I'm wondering if anyone has a clue about why this is happening?
Before you ask, yes, I've enabled virtualization in the BIOS and the Intel Processor Identification Utility confirms that it's activated. Docker, docker-machine and docker-compose all work from the command line, Virtualbox works, running Docker from a Debian or Ubuntu VM works.
There's just this weird issue about the GUI.
My specs:
- Windows 10 Pro x64 Anniversary Edition
- Intel core i5-6300HQ @ 2.30GHz
",https://stackoverflow.com/questions/39684974/docker-for-windows-error-hardware-assisted-virtualization-and-data-execution-p,379,634591.0,22.0,,,2016-09-25 08:45:26,2023-07-11 16:47:46,,,,windows;docker,Julien,4564,2273553,registered,true,39989990,,CC BY-SA 3.0,2020-03-01 08:14:14,812,718,0,0,0,2,true,false,false,true,true,false,128,17,false,0.035,0.0006,3709,2016,9,8,Sunday,true,false,false,false,false,false,false
28490874,docker run <IMAGE> <MULTIPLE COMMANDS>,"I'm trying to run MULTIPLE commands like this.
docker run image cd /path/to/somewhere && python a.py
But this gives me ""No such file or directory"" error because it is interpreted as...
""docker run image cd /path/to/somewhere"" && ""python a.py""
It seems that some ESCAPE characters like """" or () are needed.
So I also tried
docker run image ""cd /path/to/somewhere && python a.py""
docker run image (cd /path/to/somewhere && python a.py)
but these didn't work.
I have searched for Docker Run Reference but have not find any hints about ESCAPE characters.
",https://stackoverflow.com/questions/28490874/docker-run-image-multiple-commands,379,237849.0,10.0,,,2015-02-13 01:04:04,2023-01-10 05:52:00,2018-10-02 16:28:20,,,docker;docker-image,ai0307,4257,4561679,registered,true,28490909,,CC BY-SA 4.0,,762,595,3,1,0,2,true,false,false,true,true,true,50,5,false,0.042,0.0016,4299,2015,2,1,Friday,false,false,false,false,false,false,false
33935807,How to define a variable in a Dockerfile?,"In my Dockerfile, I would like to define variables that I can use later in the Dockerfile.
I am aware of the ENV instruction, but I do no want these variables to be environment variables.
Is there a way to declare variables at Dockerfile scope?
",https://stackoverflow.com/questions/33935807/how-to-define-a-variable-in-a-dockerfile,377,400742.0,7.0,,,2015-11-26 10:10:07,2024-06-06 19:48:07,2022-02-10 13:03:08,,,variables;docker;dockerfile,Maxime,10888,5475103,registered,true,37639938,,CC BY-SA 4.0,,279,245,1,0,0,3,true,false,false,true,true,true,41,8,true,0.017,0.0009,4013,2015,11,10,Thursday,false,false,false,false,false,false,false
17466699,How do I build a docker image if the name of the Dockerfile isn't `Dockerfile`?,"I am able a build a Dockerfile like
docker build -t deepak/ruby .
But for a Dockerfile which is not named Dockerfile
# DOCKER-VERSION 0.4.8
FROM deepak/ruby
MAINTAINER Deepak Kannan ""deepak@example.com""
RUN ./bin/rails s
let us say it is called Dockerfile.app
which we build with
docker build -t deepak/app Dockerfile.app
then i get the error
Uploading context 0 bytes
Error build: EOF
EOF
",https://stackoverflow.com/questions/17466699/how-do-i-build-a-docker-image-if-the-name-of-the-dockerfile-isnt-dockerfile,374,462485.0,11.0,,,2013-07-04 09:28:26,2026-10-13 15:11:29,2025-08-30 16:09:22,,,docker,deepak,8350,337902,registered,true,,,CC BY-SA 4.0,,544,402,6,0,0,1,false,false,false,true,true,true,83,15,true,0.024,0.0008,4888,2013,7,9,Thursday,false,false,false,false,false,false,false
66146088,Docker gets error "failed to compute cache key: not found" - runs fine in Visual Studio,"I've generated a Dockerfile with Visual Studio. It runs in Visual Studio just fine and now I'm trying to build it from Windows itself (docker build ., and I tried many combinations). Yet I get the following error:
> [build 3/7] COPY [client/client.csproj, client/]:
------
failed to compute cache key: "/client/client.csproj" not found: not found
When I change copy to ./client.csproj it does continue and then I get:
=> ERROR [build 7/7] RUN dotnet build "client.csproj" -c Release -o /app/build 3.3s
------
> [build 7/7] RUN dotnet build "client.csproj" -c Release -o /app/build:
#15 0.652 Microsoft (R) Build Engine version 16.8.3+39993d9d for .NET
#15 0.652 Copyright (C) Microsoft Corporation. All rights reserved.
#15 0.652
#15 1.169 Determining projects to restore...
#15 1.483 All projects are up-to-date for restore.
#15 3.231 CSC : error CS5001: Program does not contain a static 'Main' method suitable for an entry point [/src/client/client.csproj]
#15 3.240
#15 3.240 Build FAILED.
#15 3.240
#15 3.240 CSC : error CS5001: Program does not contain a static 'Main' method suitable for an entry point [/src/client/client.csproj]
#15 3.240 0 Warning (5)
#15 3.240 1 Error (5)
#15 3.240
#15 3.240 Time Elapsed 00:00:02.51
-----
executor failed running [/bin/sh -c dotnet build "client.csproj" -c Release -o /app/build]: exit code: 1
What am I doing wrong? I changed Docker Linux to Windows, changed WSL, and restarted everything.
#See https://aka.ms/containerfastmode to understand how Visua...
FROM mcr.microsoft.com/dotnet/aspnet:5.0-buster-slim AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443
FROM mcr.microsoft.com/dotnet/sdk:5.0-buster-slim AS build
WORKDIR /src
COPY ["client/client.csproj", "client/"]
RUN dotnet restore "client/client.csproj"
COPY . .
WORKDIR "/src/client"
RUN dotnet build "client.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "client.csproj" -c Release -o /app/publish
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet', "client.dll"]
",https://stackoverflow.com/questions/66146088/docker-gets-error-failed-to-compute-cache-key-not-found-runs-fine-in-visual,373,636614.0,33.0,,,2021-02-10 22:32:45,2025-02-11 21:41:29,2023-09-18 13:11:04,,,windows;visual-studio;docker;command-line-interface;windows-subsystem-for-linux,Sjardi Djoy Willems,3842,7419676,registered,true,67944726,,CC BY-SA 4.0,2024-11-12 16:02:15,2395,2187,5,1,0,5,true,false,false,true,true,true,97,16,false,0.052,0.0006,2110,2021,2,22,Wednesday,false,false,false,false,false,false,false
29663459,Why doesn't Python app print anything when run in a detached docker container?,"I have a Python (2.7) app which is started in my dockerfile:
CMD [""python"",""main.py""]
main.py prints some strings when it is started and goes into a loop afterwards:
print ""App started""
while True:
time.sleep(1)
As long as I start the container with the -it flag, everything works as expected:
$ docker run --name=myapp -it myappimage
> App started
And I can see the same output via logs later:
$ docker logs myapp
> App started
If I try to run the same container with the -d flag, the container seems to start normally, but I can't see any output:
$ docker run --name=myapp -d myappimage
> b82db1120fee5f92c80000f30f6bdc84e068bafa32738ab7adb47e641b19b4d1
$ docker logs myapp
$ (empty)
But the container still seems to run;
$ docker ps
Container Status ...
myapp up 4 minutes ...
Attach does not display anything either:
$ docker attach --sig-proxy=false myapp
(working, no output)
Any ideas whats going wrong? Does ""print"" behave differently when ran in background?
Docker version:
Client version: 1.5.0
Client API version: 1.17
Go version (client): go1.4.2
Git commit (client): a8a31ef
OS/Arch (client): linux/arm
Server version: 1.5.0
Server API version: 1.17
Go version (server): go1.4.2
Git commit (server): a8a31ef
",https://stackoverflow.com/questions/29663459/why-doesnt-python-app-print-anything-when-run-in-a-detached-docker-container,369,257637.0,16.0,,,2015-04-16 00:47:16,2024-03-28 17:09:51,2023-11-23 00:00:58,,,python;docker;dockerfile;docker-run,jpdus,10459,1152166,registered,true,29745541,,CC BY-SA 4.0,,1527,1263,8,0,0,4,true,false,false,true,true,true,82,13,true,0.062,0.0014,4237,2015,4,0,Thursday,false,true,false,false,false,false,false
27879713,Is it ok to run Docker from inside Docker?,"I'm running Jenkins inside a Docker container. I wonder if it's ok for the Jenkins container to also be a Docker host?
What I'm thinking about is to start a new Docker container for each integration test build from inside Jenkins (to start databases, message brokers etc). The containers should thus be shut down after the integration tests are completed.
Is there a reason to avoid running Docker containers from inside another Docker container in this way?
",https://stackoverflow.com/questions/27879713/is-it-ok-to-run-docker-from-inside-docker,369,301489.0,5.0,,,2015-01-10 18:29:53,2026-01-23 09:31:04,2026-01-23 09:25:48,,,docker;jenkins;docker-in-docker,Johan,41412,398441,registered,true,33003273,,CC BY-SA 4.0,,480,459,0,0,0,3,true,false,false,true,true,true,42,9,true,0.017,0.0012,4333,2015,1,18,Saturday,true,false,false,false,false,false,false
24482822,How to share my Docker-Image without using the Docker-Hub?,"I'm wondering where Docker's images are exactly stored to in my local host machine.
Can I share my Docker-Image without using the Docker-Hub or a Dockerfile but the 'real' Docker-Image? And what is exactly happening when I 'push' my Docker-Image to Docker-Hub?
",https://stackoverflow.com/questions/24482822/how-to-share-my-docker-image-without-using-the-docker-hub,368,188962.0,4.0,,,2014-06-30 04:09:57,2022-02-01 12:31:50,2016-12-04 21:17:28,,,docker;docker-registry,yaquawa,7498,3577446,registered,true,24485196,,CC BY-SA 3.0,,294,261,2,0,0,2,true,false,false,true,true,true,58,9,true,0.021,0.0019,4527,2014,6,4,Monday,false,false,false,false,false,false,false
40216311,Reading in environment variables from an environment file,"I'd like to run in a local environment a Python script which is normally run in a Docker container. The docker-compose.yml specifies an env_file which looks (partially) like the following:
DB_ADDR=rethinkdb
DB_PORT=28015
DB_NAME=ipercron
In order to run this locally, I would like these lines to be converted to
os.environ['DB_ADDR'] = 'rethinkdb'
os.environ['DB_PORT'] = '28015'
os.environ['DB_NAME'] = 'ipercron'
I could write my parser, but I was wondering if there are any existing modules/tools to read in environment variables from configuration files?
",https://stackoverflow.com/questions/40216311/reading-in-environment-variables-from-an-environment-file,365,645907.0,13.0,,,2016-10-24 10:36:45,2025-09-22 21:14:21,2019-08-16 03:34:22,,,python;docker,Kurt Peek,58818,995862,registered,true,,,CC BY-SA 4.0,,720,565,3,1,0,2,false,false,false,true,true,true,57,8,false,0.02,0.0006,3680,2016,10,10,Monday,false,true,false,false,false,false,false
48066994,Docker: "no matching manifest for windows/amd64 in the manifest list entries","I use Docker on Windows, and when I tried to pull a PHP image with this command
$ docker pull php
I got this message:
Using default tag: latest
latest: Pulling from library/php no matching manifest for windows/amd64
in the manifest list entries
How can I fix this problem?
",https://stackoverflow.com/questions/48066994/docker-no-matching-manifest-for-windows-amd64-in-the-manifest-list-entries,360,558303.0,27.0,,,2018-01-02 19:52:15,2025-01-10 09:47:08,2018-07-24 08:32:42,,,docker,Mohammad Trabelsi,3738,8616848,registered,true,51071057,,CC BY-SA 4.0,2019-07-29 16:20:04,357,288,2,0,0,1,true,false,false,true,true,true,87,11,false,0.048,0.0006,3245,2018,1,19,Tuesday,false,false,false,false,false,false,false
25775266,How to keep Docker container running after starting services?,"I've seen a bunch of tutorials that seem do the same thing I'm trying to do, but for some reason my Docker containers exit. Basically, I'm setting up a web-server and a few daemons inside a Docker container. I do the final parts of this through a bash script called run-all.sh that I run through CMD in my Dockerfile. run-all.sh looks like this:
service supervisor start
service nginx start
And I start it inside of my Dockerfile as follows:
CMD [""sh"", ""/root/credentialize_and_run.sh""]
I can see that the services all start up correctly when I run things manually (i.e. getting on to the image with -i -t /bin/bash), and everything looks like it runs correctly when I run the image, but it exits once it finishes starting up my processes. I'd like the processes to run indefinitely, and as far as I understand, the container has to keep running for this to happen. Nevertheless, when I run docker ps -a, I see:
➜ docker_test docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
c7706edc4189 some_name/some_repo:blah ""sh /root/run-all.sh 8 minutes ago Exited (0) 8 minutes ago grave_jones
What gives? Why is it exiting? I know I could just put a while loop at the end of my bash script to keep it up, but what's the right way to keep it from exiting?
",https://stackoverflow.com/questions/25775266/how-to-keep-docker-container-running-after-starting-services,359,570829.0,15.0,,,2014-09-10 21:18:39,2024-11-25 11:21:44,2022-01-17 13:01:32,,,docker;devops;docker-container;docker-image,Eli,39467,392975,registered,true,25775424,,CC BY-SA 4.0,2024-11-25 11:25:20,1551,1412,6,0,0,4,true,false,false,true,true,true,61,9,true,0.026,0.0006,4455,2014,9,21,Wednesday,false,false,false,false,false,false,false
36075525,How do I run a docker instance from a DockerFile?,"I finally figured out how to get docker up and running.
docker run --name my-forum-nodebb --link my-forum-redis:redis -p 80:80 -p 443:443 -p 4567:4567 -P -t -i nodebb/docker:ubuntu
I linked it to a redis instance, cool.
This is from scratch and I assume that when I created the redis instance
docker run --name my-forum-redis -d -p 6379:6379 nodebb/docker:ubuntu-redis
it pulls the image from a remote repo?
NodeBB offers a Dockerfile https://github.com/NodeBB/NodeBB/blob/master/Dockerfile I am not really quite sure how to use it. I am assuming that I can somehow create a local environment by calling this Dockerfile on my remote.
Is this correct? If so how can I create the local instance pointing to the remote?
",https://stackoverflow.com/questions/36075525/how-do-i-run-a-docker-instance-from-a-dockerfile,358,948161.0,8.0,,,2016-03-18 03:19:47,2025-01-01 21:19:08,2016-03-18 03:51:23,,,docker;docker-machine,Michael Joseph Aubry,13762,1971279,registered,true,36076856,,CC BY-SA 3.0,,919,729,3,1,0,2,true,false,false,true,true,true,49,10,true,0.008,0.0004,3900,2016,3,3,Friday,false,false,false,false,false,false,false
62441307,How can I change the location of docker images when using Docker Desktop on WSL2 with Windows 10 Home?,"I've just upgraded to Windows 10 Home May 2020, activated WSL2, and installed Docker Desktop.
WSL2 must be installed in my system disk, which is a small SSD. I don't want to fill it with docker images. How do I change the docker images path? I'd like to use a path in my big Windows filesystem.
The image location is somewhat confusing. I believe it is in /mnt/wsl/docker-desktop-data/.
How do I change the directory of docker images inside WSL2? May I change docker configuration to select a path inside /mnt/d, or mount a path from /mnt/d over docker data dirs?
",https://stackoverflow.com/questions/62441307/how-can-i-change-the-location-of-docker-images-when-using-docker-desktop-on-wsl2,357,170143.0,13.0,,,2020-06-18 02:21:37,2025-03-30 06:34:29,2021-02-06 19:18:09,,,docker;windows-10;docker-desktop;windows-subsystem-for-linux,neves,40701,10335,registered,true,63752264,,CC BY-SA 4.0,,912,564,2,3,0,4,true,false,false,true,true,true,102,19,true,0.076,0.0021,2347,2020,6,2,Thursday,false,false,false,false,false,false,false
43720339,"Docker "ERROR: could not find an available, non-overlapping IPv4 address pool among the defaults to assign to the network"","I have a directory apkmirror-scraper-compose with the following structure:
.
├── docker-compose.yml
├── privoxy
│ ├── config
│ └── Dockerfile
├── scraper
│ ├── Dockerfile
│ ├── newnym.py
│ └── requirements.txt
└── tor
└── Dockerfile
I'm trying to run the following docker-compose.yml:
version: '3'
services:
privoxy:
build: ./privoxy
ports:
- ""8118:8118""
links:
- tor
tor:
build:
context: ./tor
args:
password: """"
ports:
- ""9050:9050""
- ""9051:9051""
scraper:
build: ./scraper
links:
- tor
- privoxy
where the Dockerfile for tor is
FROM alpine:latest
EXPOSE 9050 9051
ARG password
RUN apk --update add tor
RUN echo ""ControlPort 9051"" >> /etc/tor/torrc
RUN echo ""HashedControlPassword $(tor --quiet --hash-password $password)"" >> /etc/tor/torrc
CMD [""tor""]
that for privoxy is
FROM alpine:latest
EXPOSE 8118
RUN apk --update add privoxy
COPY config /etc/privoxy/config
CMD [""privoxy"", ""--no-daemon""]
where config consists of the two lines
listen-address 0.0.0.0:8118
forward-socks5 / tor:9050 .
and the Dockerfile for scraper is
FROM python:2.7-alpine
ADD . /scraper
WORKDIR /scraper
RUN pip install -r requirements.txt
CMD [""python"", ""newnym.py""]
where requirements.txt contains the single line requests. Finally, the program newnym.py is designed to simply test whether changing the IP address using Tor is working:
from time import sleep, time
import requests as req
import telnetlib
def get_ip():
IPECHO_ENDPOINT = 'http://ipecho.net/plain'
HTTP_PROXY = 'http://privoxy:8118'
return req.get(IPECHO_ENDPOINT, proxies={'http': HTTP_PROXY}).text
def request_ip_change():
tn = telnetlib.Telnet('tor', 9051)
tn.read_until(""Escape character is '^]'."", 2)
tn.write('AUTHENTICATE """"\r\n')
tn.read_until(""250 OK"", 2)
tn.write(""signal NEWNYM\r\n"")
tn.read_until(""250 OK"", 2)
tn.write(""quit\r\n"")
tn.close()
if __name__ == '__main__':
dts = []
try:
while True:
ip = get_ip()
t0 = time()
request_ip_change()
while True:
new_ip = get_ip()
if new_ip == ip:
sleep(1)
else:
break
dt = time() - t0
dts.append(dt)
print(""{} -> {} in ~{}s"".format(ip, new_ip, int(dt)))
except KeyboardInterrupt:
print(""Stopping..."")
print(""Average: {}"".format(sum(dts) / len(dts)))
The docker-compose build builds successfully, but if I try docker-compose up, I get the following error message:
Creating network ""apkmirrorscrapercompose_default"" with the default driver
ERROR: could not find an available, non-overlapping IPv4 address pool among the defaults to assign to the network
I tried searching for help on this error message, but couldn't find any. What is causing this error?
",https://stackoverflow.com/questions/43720339/docker-error-could-not-find-an-available-non-overlapping-ipv4-address-pool-am,355,317846.0,21.0,,,2017-05-01 13:59:29,2025-04-21 08:11:58,,2025-04-21 08:51:44,Not suitable for this site,python;docker;docker-compose,Kurt Peek,58818,995862,registered,true,43721103,,,2022-03-21 05:25:53,3379,2955,21,0,0,3,true,true,false,true,true,false,132,19,false,0.066,0.0011,3491,2017,5,13,Monday,false,true,false,false,false,false,false
41935435,Understanding "VOLUME" instruction in DockerFile,"Below is the content of my "Dockerfile"
FROM node:boron
# Create app directory
RUN mkdir -p /usr/src/app
# Change working dir to /usr/src/app
WORKDIR /usr/src/app
VOLUME . /usr/src/app
RUN npm install
EXPOSE 8080
CMD ["node" , "server" ]
In this file I am expecting VOLUME . /usr/src/app instruction to mount
contents of present working directory in host to be mounted on /usr/src/app
folder of container.
Please let me know if this is the correct way?
",https://stackoverflow.com/questions/41935435/understanding-volume-instruction-in-dockerfile,355,545187.0,9.0,,,2017-01-30 12:01:39,2025-02-04 15:40:03,2021-09-16 20:23:03,,,docker;dockerfile,refactor,15384,2693545,registered,true,41935728,,CC BY-SA 4.0,,561,490,3,0,0,2,true,false,false,true,true,true,58,5,false,0.017,0.0007,3582,2017,1,12,Monday,false,false,false,false,false,false,false
42494853,standard_init_linux.go:178: exec user process caused "exec format error","docker started throwing this error:
standard_init_linux.go:178: exec user process caused ""exec format error""
whenever I run a specific docker container with CMD or ENTRYPOINT, with no regard to any changes to the file other then removing CMD or ENTRYPOINT. here is the docker file I have been working with which worked perfectly until about an hour ago:
FROM buildpack-deps:jessie
ENV PATH /usr/local/bin:$PATH
ENV LANG C.UTF-8
RUN apt-get update && apt-get install -y --no-install-recommends \
tcl \
tk \
&& rm -rf /var/lib/apt/lists/*
ENV GPG_KEY 0D96DF4D4110E5C43FBFB17F2D347EA6AA65421D
ENV PYTHON_VERSION 3.6.0
ENV PYTHON_PIP_VERSION 9.0.1
RUN set -ex \
&& buildDeps=' \
tcl-dev \
tk-dev \
' \
&& apt-get update && apt-get install -y $buildDeps --no-install-recommends && rm -rf /var/lib/apt/lists/* \
\
&& wget -O python.tar.xz ""https://www.python.org/ftp/python/${PYTHON_VERSION%%[a-z]*}/Python-$PYTHON_VERSION.tar.xz"" \
&& wget -O python.tar.xz.asc ""https://www.python.org/ftp/python/${PYTHON_VERSION%%[a-z]*}/Python-$PYTHON_VERSION.tar.xz.asc"" \
&& export GNUPGHOME=""$(mktemp -d)"" \
&& gpg --keyserver ha.pool.sks-keyservers.net --recv-keys ""$GPG_KEY"" \
&& gpg --batch --verify python.tar.xz.asc python.tar.xz \
&& rm -r ""$GNUPGHOME"" python.tar.xz.asc \
&& mkdir -p /usr/src/python \
&& tar -xJC /usr/src/python --strip-components=1 -f python.tar.xz \
&& rm python.tar.xz \
\
&& cd /usr/src/python \
&& ./configure \
--enable-loadable-sqlite-extensions \
--enable-shared \
&& make -j$(nproc) \
&& make install \
&& ldconfig \
\
&& if [ ! -e /usr/local/bin/pip3 ]; then : \
&& wget -O /tmp/get-pip.py 'https://bootstrap.pypa.io/get-pip.py' \
&& python3 /tmp/get-pip.py ""pip==$PYTHON_PIP_VERSION"" \
&& rm /tmp/get-pip.py \
; fi \
&& pip3 install --no-cache-dir --upgrade --force-reinstall ""pip==$PYTHON_PIP_VERSION"" \
&& [ ""$(pip list |tac|tac| awk -F '[ ()]+' '$1 == ""pip"" { print $2; exit }')"" = ""$PYTHON_PIP_VERSION"" ] \
\
&& find /usr/local -depth \
\( \
\( -type d -a -name test -o -name tests \) \
-o \
\( -type f -a -name '*.pyc' -o -name '*.pyo' \) \
\) -exec rm -rf '{}' + \
&& apt-get purge -y --auto-remove $buildDeps \
&& rm -rf /usr/src/python ~/.cache
RUN cd /usr/local/bin \
&& { [ -e easy_install ] || ln -s easy_install-* easy_install; } \
&& ln -s idle3 idle \
&& ln -s pydoc3 pydoc \
&& ln -s python3 python \
&& ln -s python3-config python-config
RUN pip install uwsgi
RUN mkdir /config
RUN mkdir /logs
ENV HOME /var/www
WORKDIR /config
ADD conf/requirements.txt /config
RUN pip install -r /config/requirements.txt
ADD conf/wsgi.py /config
ADD conf/wsgi.ini /config
ADD conf/__init__.py /config
ADD start.sh /bin/start.sh
RUN chmod +x /bin/start.sh
EXPOSE 8000
ENTRYPOINT [""start.sh"", ""uwsgi"", ""--ini"", ""wsgi.ini""]
",https://stackoverflow.com/questions/42494853/standard-init-linux-go178-exec-user-process-caused-exec-format-error,353,423241.0,21.0,,,2017-02-27 20:08:54,2024-05-06 07:35:28,,,,python;linux;bash;docker,Marcus Ruddick,10455,3901400,registered,true,42494944,,CC BY-SA 3.0,2022-01-19 13:29:52,3372,3302,1,0,0,4,true,false,false,true,true,false,82,8,false,0.05,0.0008,3554,2017,2,20,Monday,false,true,false,false,false,false,false
17903705,Is it possible to start a shell session in a running container (without ssh),"I was naively expecting this command to run a bash shell in a running container :
docker run ""id of running container"" /bin/bash
it looks like it's not possible, I get the error :
2013/07/27 20:00:24 Internal server error: 404 trying to fetch remote history for 27d757283842
So, if I want to run bash shell in a running container (ex. for diagnosis purposes)
do I have to run an SSH server in it and loggin via ssh ?
",https://stackoverflow.com/questions/17903705/is-it-possible-to-start-a-shell-session-in-a-running-container-without-ssh,352,260065.0,15.0,,,2013-07-28 00:05:06,2020-11-08 18:44:26,2013-07-28 00:09:07,,,docker,Boutran,10254,535782,registered,true,17931950,,CC BY-SA 3.0,,502,426,2,0,0,1,true,false,false,true,true,true,76,14,false,0.058,0.0014,4864,2013,7,0,Sunday,true,false,false,false,false,false,false
59812009,What is the use of PYTHONUNBUFFERED in docker file?,"I was watching a tutorial to dockerize my Django application. I did not understand why we use PYTHONUNBUFFERED as an environment variable in Dockerfile.
Can anyone explain?
",https://stackoverflow.com/questions/59812009/what-is-the-use-of-pythonunbuffered-in-docker-file,350,189844.0,3.0,,,2020-01-19 16:23:11,2025-09-09 04:57:28,2023-03-25 09:21:27,,,django;docker;dockerfile,MayankBudhiraja,3733,9830616,registered,true,,,CC BY-SA 4.0,,213,173,2,0,0,3,false,false,false,true,true,true,51,9,true,0.016,0.0018,2498,2020,1,16,Sunday,true,false,false,false,false,false,false
53835198,Integrating Python Poetry with Docker,"Can you give me an example of a Dockerfile in which I can install all the packages I need from poetry.lock and pyproject.toml into my image/container from Docker?
",https://stackoverflow.com/questions/53835198/integrating-python-poetry-with-docker,345,344446.0,16.0,,,2018-12-18 14:28:18,2024-12-16 17:38:30,2020-05-12 04:39:44,,,python;docker;dockerfile;python-poetry,Alex Bodea,3467,10806576,registered,true,,,CC BY-SA 4.0,,209,163,3,0,0,4,false,false,false,true,true,true,37,5,false,0.046,0.001,2895,2018,12,14,Tuesday,false,true,false,false,false,false,false
37971961,Docker Error bind: address already in use,"When I run docker-compose up in my Docker project it fails with the following message:
Error starting userland proxy: listen tcp 0.0.0.0:3000: bind: address already in use
netstat -pna | grep 3000
shows this:
tcp 0 0 0.0.0.0:3000 0.0.0.0:* LISTEN -
I've already tried docker-compose down, but it doesn't help.
",https://stackoverflow.com/questions/37971961/docker-error-bind-address-already-in-use,345,1096158.0,43.0,,,2016-06-22 15:09:21,2026-08-09 17:59:06,2022-07-01 17:24:10,,,ubuntu;docker;ubuntu-14.04;bind;docker-compose,Ngoral,4862,6014860,registered,true,44759326,,CC BY-SA 4.0,2022-04-19 14:13:22,485,358,4,0,0,5,true,false,false,true,true,true,41,7,false,0.039,0.0003,3804,2016,6,15,Wednesday,false,false,false,false,false,false,false
42345235,How to specify Memory & CPU limit in docker compose version 3,"I am unable to specify CPU and memory limitation for services specified in version 3.
With version 2 it works fine with mem_limit & cpu_shares parameters under the services. But it fails while using version 3, putting them under deploy section doesn't seem worthy unless I am using swarm mode.
Can somebody help?
version: "3"
services:
node:
build:
context: .
dockerfile: ./docker-build/Dockerfile.node
restart: always
environment:
- VIRTUAL_HOST=localhost
volumes:
- logs:/app/out/
expose:
- 8083
command: ["npm","start"]
cap_drop:
- NET_ADMIN
- SYS_ADMIN
",https://stackoverflow.com/questions/42345235/how-to-specify-memory-cpu-limit-in-docker-compose-version-3,344,677038.0,7.0,,,2017-02-20 12:59:04,2025-06-12 11:20:26,2021-12-07 20:09:42,,,docker;docker-compose,vivekyad4v,15233,3802507,registered,true,,,CC BY-SA 4.0,,854,731,4,0,0,2,false,false,false,true,true,true,65,12,false,0.01,0.0005,3561,2017,2,12,Monday,false,false,false,false,false,false,false
21498832,"In Docker, what's the difference between a container and an image?","What's the difference between a container and an image in Docker? In the Get started with Docker tutorial these terms are both used, but I do not understand the difference.
Can anybody please shed some light?
",https://stackoverflow.com/questions/21498832/in-docker-whats-the-difference-between-a-container-and-an-image,343,96579.0,12.0,,,2014-02-01 13:49:08,2019-03-07 05:40:04,2017-12-28 19:58:07,2019-05-06 18:23:29,Duplicate,docker;terminology,Golo Roden,153081,1333873,registered,true,23667302,,,2019-02-19 12:18:01,298,210,0,1,0,2,true,true,false,true,true,true,70,11,true,0.124,0.0036,4676,2014,2,13,Saturday,true,false,false,false,false,false,false
30449313,How do I make a Docker container start automatically on system boot?,"Supposed I have a Docker container that I want to run, then I can call
$ docker run ...
and everything is fine. Is there a built-in way to run a container in a way that it will be restarted automatically, if the system crashes and reboots?
If so, is this also available in Docker Compose?
",https://stackoverflow.com/questions/30449313/how-do-i-make-a-docker-container-start-automatically-on-system-boot,341,545767.0,12.0,,,2015-05-26 04:10:27,2025-01-31 07:59:19,,,,docker;docker-compose,Golo Roden,153081,1333873,registered,true,30450350,,CC BY-SA 3.0,,338,293,1,0,0,2,true,false,false,true,true,false,68,12,true,0.022,0.0006,4197,2015,5,4,Tuesday,false,false,false,false,false,false,false
46176584,Docker - Bind for 0.0.0.0:4000 failed: port is already allocated,"I am using docker for the first time and I was trying to implement this -
https://docs.docker.com/get-started/part2/#tag-the-image
At one stage I was trying to connect with localhost by this command -
$ curl http://localhost:4000
which showed this error-
curl: (7) Failed to connect to localhost port 4000: Connection refused
However, I have solved this by following code -
$ docker-machine ip default
$ curl http://192.168.99.100:4000
After that everything was going fine, but in the last part, I was trying to run the app by using following line according to the tutorial...
$ docker run -p 4000:80 anibar/get-started:part1
But, I got this error
C:\Program Files\Docker Toolbox\docker.exe: Error response from daemon: driver failed programming external connectivity on endpoint goofy_bohr (63f5691ef18ad6d6389ef52c56198389c7a627e5fa4a79133d6bbf13953a7c98): Bind for 0.0.0.0:4000 failed: port is already allocated.
",https://stackoverflow.com/questions/46176584/docker-bind-for-0-0-0-04000-failed-port-is-already-allocated,340,610441.0,28.0,,,2017-09-12 12:37:20,2025-08-07 07:52:48,2021-01-04 08:12:57,2025-08-07 09:17:28,Not suitable for this site,docker;port,Anik Barua,3561,8597571,registered,true,46177519,,,,1171,921,5,1,0,2,true,true,false,true,true,true,64,10,false,0.046,0.0006,3357,2017,9,12,Tuesday,false,false,false,false,false,false,false
26077543,How to name Dockerfiles,"I'm unsure of how to name Dockerfiles. Many on GitHub use Dockerfile without a file extension. Do I give them a name and extension; if so what? Or do I just call them Dockerfile?
",https://stackoverflow.com/questions/26077543/how-to-name-dockerfiles,339,285516.0,12.0,,,2014-09-27 17:56:05,2024-08-13 13:10:06,2018-07-06 07:32:00,,,docker;dockerfile;naming-conventions,Lloyd R. Prentice,4957,862103,registered,true,26084010,,CC BY-SA 4.0,,212,179,2,0,0,3,true,false,false,true,true,true,23,4,false,0.042,0.0012,4438,2014,9,17,Saturday,true,false,false,false,false,false,false
36685980,Why is Docker installed but not Docker Compose?,"I have installed docker on CentOS 7 by running following commands,
curl -sSL https://get.docker.com/ | sh
systemctl enable docker && systemctl start docker
docker run hello-world
NOTE: helloworld runs correctly and no issues.
however when I try to run docker-compose (docker-compose.yml exists and valid) it gives me the error on CentOS only (Windows version works fine for the docker-compose file)
/usr/local/bin/docker-compose: line 1: {error:Not Found}: command not found
",https://stackoverflow.com/questions/36685980/why-is-docker-installed-but-not-docker-compose,335,752162.0,28.0,,,2016-04-18 05:22:17,2025-05-30 23:53:16,2025-05-23 16:58:39,,,docker;docker-compose;dockerfile;centos,mahen3d,7823,1179459,registered,true,36689427,,CC BY-SA 4.0,2024-06-03 08:38:09,584,485,3,0,0,4,true,false,false,true,true,true,47,8,true,0.037,0.0004,3869,2016,4,5,Monday,false,false,false,false,false,false,false
40513545,How to prevent docker from starting a container automatically on system startup?,"Docker starts a container on every system startup (debian) but I didn't create a service to do so. How can I prevent docker from doing that?
",https://stackoverflow.com/questions/40513545/how-to-prevent-docker-from-starting-a-container-automatically-on-system-startup,335,233289.0,4.0,,,2016-11-09 18:21:03,2024-04-29 14:03:18,2020-03-07 17:34:05,2018-03-02 15:51:38,Duplicate,docker;startup,Techradar,4254,6360083,registered,true,45022623,,,,148,141,0,0,0,2,true,true,false,true,true,true,80,12,true,0.017,0.0014,3664,2016,11,18,Wednesday,false,false,false,false,false,false,false
36022892,How to know if docker is already logged in to a docker registry server,"I'm not sure if I have already logged in to a docker registry in cmd line by using cmd: docker login. How can you test or see whether you are logged in or not, without trying to push?
",https://stackoverflow.com/questions/36022892/how-to-know-if-docker-is-already-logged-in-to-a-docker-registry-server,335,429289.0,19.0,,,2016-03-15 21:50:07,2025-03-28 10:16:44,,,,docker,Ville Miekk-oja,21585,4662347,registered,true,36023944,,CC BY-SA 3.0,,191,184,0,0,0,1,true,false,false,true,true,false,70,14,false,0.044,0.0008,3903,2016,3,21,Tuesday,false,false,false,false,false,false,false
39223249,"Multiple RUN vs. single chained RUN in Dockerfile, which is better?","Dockerfile.1 executes multiple RUN statements:
FROM busybox
RUN echo This is the A > a
RUN echo This is the B > b
RUN echo This is the C > c
Dockerfile.2 joins them:
FROM busybox
RUN echo This is the A > a &&\
echo This is the B > b &&\
echo This is the C > c
Each RUN creates a layer, so I always assumed that fewer layers is better and thus Dockerfile.2 is better.
This is obviously true when a RUN removes something added by a previous RUN (e.g. yum install nano && yum clean all), but in cases where every RUN adds something, there are a few points we need to consider:
Layers are supposed to just add a diff from the previous one, so if a layer does not remove anything added in a previous one, the difference in disk space should be negligible between the two methods.
Layers are pulled in parallel from Docker Hub, so Dockerfile.1, although probably slightly bigger, would theoretically get downloaded faster.
If we add a 4th command (e.g. echo This is the D > d) and rebuild, then Dockerfile.1 would build faster thanks to caching, but Dockerfile.2 would have to run all 4 commands again.
So, the question: Which is a better way to organize a Dockerfile?
",https://stackoverflow.com/questions/39223249/multiple-run-vs-single-chained-run-in-dockerfile-which-is-better,334,231644.0,4.0,,,2016-08-30 09:09:53,2025-04-29 16:26:33,2025-04-29 16:26:33,,,docker;dockerfile,Yajo,6630,1468388,registered,true,39330458,,CC BY-SA 4.0,,1549,1223,15,0,0,2,true,false,false,true,true,true,67,11,true,0.017,0.0014,3735,2016,8,9,Tuesday,false,false,false,false,false,false,false
43181654,Locating data volumes in Docker Desktop (Windows),"I'm trying to learn docker at the moment and I'm getting confused about where data volumes actually exist.
I'm using Docker Desktop for Windows. (Windows 10)
In the docs they say that running docker inspect on the object will give you the source:https://docs.docker.com/engine/tutorials/dockervolumes/#locating-a-volume
$ docker inspect web
""Mounts"": [
{
""Name"": ""fac362...80535"",
""Source"": ""/var/lib/docker/volumes/fac362...80535/_data"",
""Destination"": ""/webapp"",
""Driver"": ""local"",
""Mode"": """",
""RW"": true,
""Propagation"": """"
}
]
however I don't see this, I get the following:
$ docker inspect blog_postgres-data
[
{
""Driver"": ""local"",
""Labels"": null,
""Mountpoint"": ""/var/lib/docker/volumes/blog_postgres-data/_data"",
""Name"": ""blog_postgres-data"",
""Options"": {},
""Scope"": ""local""
}
]
Can anyone help me? I just want to know where my data volume actually exists is it on my host machine? If so how can i get the path to it?
",https://stackoverflow.com/questions/43181654/locating-data-volumes-in-docker-desktop-windows,330,396752.0,20.0,,,2017-04-03 10:00:05,2024-07-23 10:13:11,2019-03-08 10:08:36,,,docker;docker-for-windows;docker-desktop,Brad,8848,6019903,registered,true,43182885,,CC BY-SA 4.0,,1257,1052,2,1,0,3,true,false,false,true,true,true,49,7,false,0.05,0.0008,3519,2017,4,10,Monday,false,false,false,false,false,false,false
25292198,Docker - how can I copy a file from an image to a host?,"My question is related to this question on copying files from containers to hosts; I have a Dockerfile that fetches dependencies, compiles a build artifact from source, and runs an executable. I also want to copy the build artifact (in my case it's a .zip produced by sbt dist in '../target/`, but I think this question also applies to jars, binaries, etc.
docker cp works on containers, not images; do I need to start a container just to get a file out of it? In a script, I tried running /bin/bash in interactive mode in the background, copying the file out, and then killing the container, but this seems kludgey. Is there a better way?
On the other hand, I would like to avoid unpacking a .tar file after running docker save $IMAGENAME just to get one file out (but that seems like the simplest, if slowest, option right now).
I would use docker volumes, e.g.:
docker run -v hostdir:out $IMAGENAME /bin/cp/../blah.zip /out
but I'm running boot2docker in OSX and I don't know how to directly write to my mac host filesystem (read-write volumes are mounting inside my boot2docker VM, which means I can't easily share a script to extract blah.zip from an image with others. Thoughts?
",https://stackoverflow.com/questions/25292198/docker-how-can-i-copy-a-file-from-an-image-to-a-host,330,247456.0,14.0,,,2014-08-13 17:09:44,2024-02-11 17:21:50,2017-05-23 12:03:06,,,docker;boot2docker,Mark,3319,3938327,registered,true,,,CC BY-SA 3.0,,1455,1193,9,1,0,2,false,false,false,true,true,true,55,14,true,0.057,0.0013,4483,2014,8,17,Wednesday,false,false,false,false,false,false,false
49955097,How do I add a user when I'm using Alpine as a base image?,"I'm using alpine (or an image that is based on Alpine) as the base image in my Dockerfile. Which instructions do I need to add to create a user?
Eventually I'll use this user to run the application I'll place into the container so that the root user does not.
",https://stackoverflow.com/questions/49955097/how-do-i-add-a-user-when-im-using-alpine-as-a-base-image,329,360081.0,4.0,,,2018-04-21 11:04:23,2025-07-18 12:27:43,2018-10-26 14:43:52,,,docker;alpine-linux,Daniel Gartmann,13594,402231,registered,true,49955098,,CC BY-SA 4.0,,289,262,1,0,0,2,true,false,false,true,true,true,62,14,true,0.011,0.0009,3136,2018,4,11,Saturday,true,false,false,false,false,false,false
43671482,How to run docker-compose up -d at system start up?,"To let the containers autostart at startup point, I tried to add the command:
cd directory_has_docker-compose.yml && docker-compose up -d
in /etc/rc.local
but then after I rebooted the machine, the containers did not work.
How can I run docker-compose up -d at system start up?
",https://stackoverflow.com/questions/43671482/how-to-run-docker-compose-up-d-at-system-start-up,326,429888.0,10.0,,,2017-04-28 03:28:35,2025-12-21 11:25:39,2024-04-15 23:35:00,,,docker;docker-compose,user39544,3877,2020974,registered,true,,,CC BY-SA 4.0,,365,287,3,0,0,2,false,false,false,true,true,true,51,10,true,0.023,0.0008,3494,2017,4,3,Friday,false,false,false,false,false,false,false
31249112,Allow docker container to connect to a local/host postgres database,"I've recently been playing around with Docker and QGIS and have installed a container following the instructions in this tutorial.
Everything works great, although I am unable to connect to a localhost postgres database that contains all my GIS data. I figure this is because my postgres database is not configured to accept remote connections and have been editing the postgres conf files to allow remote connections using the instructions in this article.
I'm still getting an error message when I try and connect to my database running QGIS in Docker: could not connect to server: Connection refused Is the server running on host ""localhost"" (::1) and accepting TCP/IP connections to port 5433?
The postgres server is running, and I've edited my pg_hba.conf file to allow connections from a range of IP addresses (172.17.0.0/32). I had previously queried the IP address of the docker container using docker ps and although the IP address changes, it has so far always been in the range 172.17.0.x
Any ideas why I can't connect to this database? Probably something very simple I imagine!
I'm running Ubuntu 14.04; Postgres 9.3
",https://stackoverflow.com/questions/31249112/allow-docker-container-to-connect-to-a-local-host-postgres-database,325,467970.0,18.0,,,2015-07-06 14:57:41,2025-01-23 22:59:24,2023-10-20 16:23:35,2025-01-24 06:55:58,Not suitable for this site,postgresql;docker;ubuntu;qgis,marty_c,6609,2609232,registered,true,31249288,,,,1410,1134,2,2,0,4,true,true,false,true,true,true,67,10,false,0.038,0.0007,4156,2015,7,14,Monday,false,false,false,false,false,false,false
26600769,build context for docker image very large,"I have created a couple different directories on my host machine as I try to learn about Docker just to keep my dockerfiles organized. My Dockerfile I just ran looks like this:
FROM crystal/centos
MAINTAINER crystal
ADD ./rpms/test.rpm ./rpms/
RUN yum -y --nogpgcheck localinstall /rpms/test.rpm
My actual rpm is only 1 GB. But when I try to do sudo docker build -t=""crystal/test"" ., I get sending build context to Docker daemon 3.5 GB. Is there something else that I'm unaware of as you continue to build Docker images? Is my memory accumulating as I build more images in my other directories on my host machine?
",https://stackoverflow.com/questions/26600769/build-context-for-docker-image-very-large,322,236427.0,13.0,,,2014-10-28 04:10:49,2024-09-04 07:56:05,,,,docker,Crystal,29828,207524,registered,true,26604307,,CC BY-SA 3.0,,675,624,2,0,0,1,true,false,false,true,true,false,41,7,false,0.055,0.0014,4407,2014,10,4,Tuesday,false,false,false,false,false,false,false
30379381,docker command not found even though installed with apt-get,"Adding this for reference for others because it would have saved me 10 minutes if such an answer existed.
I tried installing Docker using ubuntu 14.0LTS virtualbox
sudo apt get install docker
However, when I try running docker it gives me the following error
The program 'docker' is currently not installed. You can install it by typing:
sudo apt-get install docker
Why is ubuntu not seeing docker?
",https://stackoverflow.com/questions/30379381/docker-command-not-found-even-though-installed-with-apt-get,320,577567.0,6.0,,,2015-05-21 16:26:36,2024-10-24 19:08:14,2015-06-16 23:19:31,,,docker;ubuntu-14.04,ThinkBonobo,16743,2668545,registered,true,30379382,,CC BY-SA 3.0,,478,406,2,0,0,2,true,false,false,true,true,true,59,9,false,0.01,0.0006,4202,2015,5,16,Thursday,false,false,false,false,false,false,false
26852321,Docker: Add a restart policy to a container that was already created,"I see that Docker has added something called restarting policies to handle restart of containers in case of, for instance, reboot.
While this is very useful, I see that the restart policy command just work with docker run and not docker start. So my question is:
Is there any way to add restarting policies to a container that was already created in the past?
",https://stackoverflow.com/questions/26852321/docker-add-a-restart-policy-to-a-container-that-was-already-created,315,142915.0,3.0,,,2014-11-10 20:20:55,2019-07-14 14:03:14,,,,docker,Enrique Moreno Tent,25591,392684,registered,true,37479753,,CC BY-SA 3.0,,409,362,2,0,0,1,true,false,false,true,true,false,68,12,false,0.021,0.0022,4394,2014,11,20,Monday,false,false,false,false,false,false,false
44766665,How do I Docker COPY as non root?,"While building a Docker image, how do I COPY a file into the image so that the resulting file is owned by a user other than root?
",https://stackoverflow.com/questions/44766665/how-do-i-docker-copy-as-non-root,315,178692.0,2.0,,,2017-06-26 18:48:34,2023-03-04 16:08:56,,,,docker;dockerfile,FGreg,15670,953327,registered,true,44766666,,CC BY-SA 3.0,,150,130,1,0,0,2,true,false,false,true,true,false,33,8,true,0.011,0.0018,3435,2017,6,18,Monday,false,false,false,false,false,false,false
27937185,Assign static IP to Docker container,"I'm now trying to assign a static IP 172.17.0.1 when a Docker container be started up.
I use port 2122 as the ssh port of this container so that I let this container listen port 2122.
sudo docker run -i -t -p 2122:2122 ubuntu
This command will run a Docker container with a random IP like 172.17.0.5, but I need to assign a specific IP to the container.
The following shell script is what I reference Docker documentation in advanced network settings.
pid=$(sudo docker inspect -f '{{.State.Pid}}' <container_name> 2>/dev/null)
sudo rm -rf /var/run/netns/*
sudo ln -s /proc/$pid/ns/net /var/run/netns/$pid
sudo ip link add A type veth peer name B
sudo brctl addif docker0 A
sudo ip link set A up
sudo ip link set B netns $pid
sudo ip netns exec $pid ip link set eth0 down
sudo ip netns exec $pid ip link delete eth0
sudo ip netns exec $pid ip link set dev B name eth0
sudo ip netns exec $pid ip link set eth0 address 12:34:56:78:9a:bc
sudo ip netns exec $pid ip link set eth0 down
sudo ip netns exec $pid ip link set eth0 up
sudo ip netns exec $pid ip addr add 172.17.0.1/16 dev eth0
sudo ip netns exec $pid ip route add default via 172.17.42.1
This shell script will assign a static IP 172.17.0.1 and link to the world fine. But whenever I try to ssh to this container from my local, it didn't work. What's the problem possibly I met?
",https://stackoverflow.com/questions/27937185/assign-static-ip-to-docker-container,314,652101.0,6.0,,,2015-01-14 06:45:48,2025-02-03 18:25:25,2016-07-01 16:49:50,,,docker,LarryLo,3233,3349245,registered,true,,,CC BY-SA 3.0,2019-03-25 20:00:09,1437,1354,2,0,0,1,false,false,false,true,true,true,36,6,false,0.009,0.0005,4329,2015,1,6,Wednesday,false,false,false,false,false,false,false
48719921,pull access denied repository does not exist or may require docker login,"I am using Laravel 4.2 with docker. I setup it on local. It worked without any problem but when I am trying to setup online using same procedure then I am getting error:
pull access denied for <projectname>/php, repository does not exist or may require 'docker login'
is it something relevant to create repository here https://cloud.docker.com/ or need to docker login in command?
After days of study I am still not able to figure out what could be the fix in this case and what are the right steps?
I have the complete code. I can paste here if need to check certain parts.
",https://stackoverflow.com/questions/48719921/pull-access-denied-repository-does-not-exist-or-may-require-docker-login,314,1205079.0,46.0,,,2018-02-10 10:49:25,2026-04-14 13:51:30,2021-09-02 17:49:30,,,docker;ubuntu-16.04,Jass,4285,4738959,registered,true,,,CC BY-SA 4.0,2022-08-26 08:07:30,692,583,1,1,0,2,false,false,false,true,true,true,72,12,false,0.038,0.0003,3206,2018,2,10,Saturday,true,false,false,false,false,false,false
31870222,How can I keep a container running on Kubernetes?,"I'm now trying to run a simple container with shell (/bin/bash) on a Kubernetes cluster.
I thought that there was a way to keep a container running on a Docker container by using pseudo-tty and detach option (-td option on docker run command).
For example,
$ sudo docker run -td ubuntu:latest
Is there an option like this in Kubernetes?
I've tried running a container by using a kubectl run-container command like:
kubectl run-container test_container ubuntu:latest --replicas=1
But the container exits for a few seconds (just like launching with the docker run command without options I mentioned above). And ReplicationController launches it again repeatedly.
Is there a way to keep a container running on Kubernetes like the -td options in the docker run command?
",https://stackoverflow.com/questions/31870222/how-can-i-keep-a-container-running-on-kubernetes,312,646850.0,19.0,,,2015-08-07 05:20:51,2025-07-17 07:34:53,2024-04-05 00:47:26,,,docker;kubernetes;google-kubernetes-engine,springwell,3231,4402782,registered,true,31879013,,CC BY-SA 4.0,,965,777,9,0,0,3,true,false,false,true,true,true,49,9,true,0.029,0.0005,4124,2015,8,5,Friday,false,false,false,false,false,false,false
34254200,How to pass arguments to a Dockerfile?,"I am using RUN instruction within a Dockerfile to install a rpm
RUN yum -y install samplerpm-2.3
However, I want to pass the value ""2.3"" as an argument.
My RUN instruction should look something like:
RUN yum -y install samplerpm-$arg
where $arg=2.3
",https://stackoverflow.com/questions/34254200/how-to-pass-arguments-to-a-dockerfile,312,371114.0,2.0,,,2015-12-13 17:42:27,2023-09-08 11:51:32,2017-01-07 02:42:55,,,docker;dockerfile;docker-compose;docker-registry;dockerhub,meallhour,15945,5632400,registered,true,34254700,,CC BY-SA 3.0,,350,255,4,0,0,5,true,false,false,true,true,true,38,7,true,0.005,0.0008,3996,2015,12,17,Sunday,true,false,false,false,false,false,false
43041331,Docker forever in "Docker is starting.." at Windows task,"I have installed a Docker stable version, and it took forever to start.
Until now I have not seen the notification showing Docker is running.
I can only see the Docker icon at the taskbar, showing Docker is starting.
I am running on Windows 10 Pro, Intel Core 2 Duo E8500, supporting virtualization.
",https://stackoverflow.com/questions/43041331/docker-forever-in-docker-is-starting-at-windows-task,310,541032.0,50.0,,,2017-03-27 08:25:36,2026-06-06 23:00:37,2020-11-25 12:36:51,,,docker,davidlee,6293,324850,registered,true,,,CC BY-SA 4.0,2023-01-16 10:25:27,314,300,0,0,0,1,false,false,false,true,true,true,66,9,false,0.092,0.0006,3526,2017,3,8,Monday,false,false,false,false,false,false,false
33001750,Connect to mysql in a docker container from the host,"In a nutshell
I want to run mysql in a docker container and connect to it from my host. So far, the best I have achieved is:
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
More details
I'm using the following Dockerfile:
FROM ubuntu:14.04.3
RUN apt-get update && apt-get install -y mysql-server
# Ensure we won't bind to localhost only
RUN grep -v bind-address /etc/mysql/my.cnf > temp.txt \
&& mv temp.txt /etc/mysql/my.cnf
# It doesn't seem needed since I'll use -p, but it can't hurt
EXPOSE 3306
CMD /etc/init.d/mysql start && tail -F /var/log/mysql.log
In the directory where there is this file, I can succesfully build the image and run it with:
> docker build -t my-image .
> docker run -d -p 12345:3306 my-image
When I attach to the image, it seems to work just fine:
# from the host
> docker exec -it <my_image_name> bash
#inside of the container now
$ mysql -u root
Welcome to the MySQL monitor. Commands end with ; or \g.
[...]
However I don't have that much success from the host:
> mysql -P 12345 -uroot
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
Even more details
- I've seen that there's a question which looks like mine. However, it isn't the same (and it doesn't have any answers anyway)
- I've seen that there are images dedicated to mysql, but I didn't have more success with them
- My
grep -v may feel weird. Admittedly, there may be cleaner way to do it. But when I attach my image, I can observe it actually worked as expected (ie: removed the bind-address). And I can see in the container /var/log/mysql/error.log:
Server hostname (bind-address): '0.0.0.0'; port: 3306
- '0.0.0.0' resolves to '0.0.0.0';
Server socket created on IP: '0.0.0.0'.
",https://stackoverflow.com/questions/33001750/connect-to-mysql-in-a-docker-container-from-the-host,308,627611.0,24.0,,,2015-10-07 20:21:44,2025-02-25 15:23:41,2023-02-02 15:49:39,,,mysql;docker;dockerfile,gturri,14842,1796345,registered,true,40159703,,CC BY-SA 4.0,,2320,1841,9,2,0,3,true,false,false,true,true,true,52,10,false,0.038,0.0005,4063,2015,10,20,Wednesday,false,false,false,false,false,false,false
38882654,docker entrypoint running bash script gets "permission denied","I'm trying to dockerize my node.js app. When the container is built I want it to run a git clone and then start the node server. Therefore I put these operations in a .sh script. And run the script as a single command in the ENTRYPOINT:
FROM ubuntu:14.04
RUN apt-get update && apt-get install -y build-essential libssl-dev gcc curl npm git
#install gcc 4.9
RUN apt-get install -y software-properties-common python-software-properties
RUN add-apt-repository -y ppa:ubuntu-toolchain-r/test
RUN apt-get update
RUN apt-get install -y libstdc++-4.9-dev
#install newst nodejs
RUN curl -sL https://deb.nodesource.com/setup_4.x | sudo -E bash -
RUN apt-get install -y nodejs
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
ADD package.json /usr/src/app/
RUN npm install
ADD docker-entrypoint.sh /usr/src/app/
EXPOSE 8080
ENTRYPOINT [""/usr/src/app/docker-entrypoint.sh""]
My docker-entrypoint.sh looks like this:
git clone git@<repo>.git
git add remote upstream git@<upstream_repo>.git
/usr/bin/node server.js
After building this image and run:
docker run --env NODE_ENV=development -p 8080:8080 -t -i <image>
I'm getting:
docker: Error response from daemon: oci runtime error: exec: ""/usr/src/app/docker-entrypoint.sh"": permission denied.
I shell into the container and the permission of docker-entrypoint.sh is:
-rw-r--r-- 1 root root 292 Aug 10 18:41 docker-entrypoint.sh
three questions:
Does my bash script have wrong syntax?
How do I change the permission of a bash file before adding it into an image?
What's the best way to run multiple git commands in entrypoint without using a bash script?
Thanks.
",https://stackoverflow.com/questions/38882654/docker-entrypoint-running-bash-script-gets-permission-denied,308,520460.0,15.0,,,2016-08-10 20:11:04,2024-07-01 04:59:26,2016-08-10 20:20:06,2024-07-01 05:12:38,Duplicate,bash;shell;docker,Calvin Hu,4075,4840567,registered,true,38882798,,,,1893,1654,6,0,0,3,true,true,false,true,true,true,72,8,false,0.029,0.0006,3755,2016,8,20,Wednesday,false,false,false,false,false,false,false
37599128,docker - how do you disable auto-restart on a container?,"I can enable auto-restart with --restart=always, but after I stop the container, how do I turn off that attribute?
I normally run a webserver and typically map port 80:
docker run -d --restart=always -p 80:80 -i -t myuser/myproj /bin/bash
But there are times when I want to run a newer version of my image, but I want to keep the old container around. The problem is that if there are multiple containers with --restart=always, only one of them (random?) starts because they're all contending for port 80 on the host.
",https://stackoverflow.com/questions/37599128/docker-how-do-you-disable-auto-restart-on-a-container,305,206676.0,9.0,,,2016-06-02 18:03:51,2025-10-15 14:34:38,,,,docker,Brad Grissom,4113,1760405,registered,true,37600885,,CC BY-SA 3.0,,594,523,3,0,0,1,true,false,false,true,true,false,56,10,true,0.044,0.0015,3824,2016,6,18,Thursday,false,false,false,false,false,false,false
49316462,How to update existing images with docker-compose?,"I have multiple microservices and I am using docker-compose for development deployments. When there are some changes in the microservices code base, I am triggering ci job to re-deploy them. I have below script to do this. But each time I have to build all images from scratch, then run them. After all of this operation, I have anonymous images. So I am using the last script to remove them. What you would suggest making this process more practical? Is there any way to update an existing image without removing it with new changes?
- docker-compose build
- docker-compose down
- docker-compose up -d --force-recreate
- docker rmi $(docker images -f ""dangling=true"" -q) -f
Additional info: i am using gitlab-ci
",https://stackoverflow.com/questions/49316462/how-to-update-existing-images-with-docker-compose,303,584821.0,9.0,,,2018-03-16 08:49:03,2026-03-19 09:53:04,2021-10-20 08:55:02,,,docker;docker-compose,Efe,6086,9034168,registered,true,49316987,,CC BY-SA 4.0,,780,716,3,0,0,2,true,false,false,true,true,true,50,7,true,0.015,0.0005,3172,2018,3,8,Friday,false,false,false,false,false,false,false
35134713,Disable cache for specific RUN commands,"I have a few RUN commands in my Dockerfile that I would like to run with -no-cache each time I build a Docker image.
I understand the docker build --no-cache will disable caching for the entire Dockerfile.
Is it possible to disable cache for a specific RUN command?
This can be useful during debugging.
For example, if a Dockerfile fails on a particular line, it may be useful to run all previous lines up to a certain point, while maintaining the cache of some of those previous lines.
The reason being some Docker commands can take a long time (perhaps several minutes?) to run.
",https://stackoverflow.com/questions/35134713/disable-cache-for-specific-run-commands,302,214084.0,11.0,,,2016-02-01 15:53:16,2025-02-10 21:39:14,2025-02-10 21:39:14,,,docker,Vingtoft,14886,1581803,registered,true,,,CC BY-SA 4.0,,675,581,4,0,0,1,false,false,false,true,true,true,39,6,false,0.051,0.0014,3946,2016,2,15,Monday,false,false,false,false,false,false,false
30231187,List only stopped Docker containers,"Docker gives you a way of listing running containers or all containers including stopped ones.
This can be done by:
$ docker ps # To list running containers
Or by
$ docker ps -a # To list running and stopped containers
Do we have a way of only listing containers that have been stopped?
",https://stackoverflow.com/questions/30231187/list-only-stopped-docker-containers,301,292823.0,4.0,,,2015-05-14 06:56:21,2023-10-23 17:07:24,2018-07-23 17:11:10,,,docker;containers,Yogesh_D,19069,1747018,registered,true,30231188,,CC BY-SA 4.0,,370,294,2,0,0,2,true,false,false,true,true,true,35,5,false,0.014,0.001,4209,2015,5,6,Thursday,false,false,false,false,false,false,false
40523307,Brew install docker does not include docker engine?,"Trying to setup docker from brew, however the engine does not seem to be included in any of the any of the official formulas.
brew install docker-machine docker-compose
So these only installs the clients?
Is there no keg with the engine/daemon?
",https://stackoverflow.com/questions/40523307/brew-install-docker-does-not-include-docker-engine,300,342057.0,8.0,,,2016-11-10 08:47:38,2023-10-20 13:51:10,2016-11-10 09:04:04,,,macos;docker;homebrew,David Karlsson,9866,1641868,registered,true,40523608,,CC BY-SA 3.0,,286,248,1,0,0,3,true,false,false,true,true,true,51,8,true,0.023,0.0009,3663,2016,11,8,Thursday,false,false,false,false,false,false,false
20481225,How can I use a local image as the base image with a dockerfile?,"I'm working on a dockerfile.
I just realised that I've been using FROM with indexed images all along.
So I wonder:
- How can I use one of my local (custom) images as my base (
FROM) image without pushing it to the index?
",https://stackoverflow.com/questions/20481225/how-can-i-use-a-local-image-as-the-base-image-with-a-dockerfile,299,330458.0,15.0,,,2013-12-09 21:30:54,2025-09-13 06:43:53,,,,docker,Phil,14931,853934,registered,true,20501690,,CC BY-SA 3.0,,293,222,3,0,0,1,true,false,false,true,true,false,64,14,true,0.045,0.0009,4730,2013,12,21,Monday,false,false,false,false,false,false,false
26423515,"How to automatically update your docker containers, if base-images are updated","Say I have a trivial container based on the ubuntu:latest. Now there is a security update and ubuntu:latest is updated in the docker repo .
How would I know my local image and its containers are running behind?
Is there some best practice for automatically updating local images and containers to follow the docker repo updates, which in practice would give you the same niceties of having unattended-upgrades running on a conventional ubuntu-machine
",https://stackoverflow.com/questions/26423515/how-to-automatically-update-your-docker-containers-if-base-images-are-updated,299,214566.0,16.0,,,2014-10-17 10:56:28,2021-12-10 20:55:03,2018-09-05 15:31:25,,,docker;automatic-updates,hbogert,4401,1099851,registered,true,51911097,,CC BY-SA 4.0,,529,455,2,0,0,2,true,false,false,true,true,true,78,11,false,0.075,0.0014,4418,2014,10,10,Friday,false,false,false,false,false,false,false
52119832,"Tail docker logs to see recent records, not all","If you use the Coreutils tail command in Linux, you have a -f option that lets you follow a log file from the log's current position (it does not go to the very beginning of the file and display everything).
Is this functionality available in docker logs without waiting for it to traverse the whole log?
I have tried:
docker logs --since 1m somecontainer
and
docker logs -f --since 1m somecontainer
It appears that it actually traverses the entire log file (which can take a long time) and then starts echoing to the screen once it reaches the time frame you specify.
Is there a way to start tailing from the current point without waiting?
Is my best option to always log out to some external file and tail that with the Coreutils tail command?
",https://stackoverflow.com/questions/52119832/tail-docker-logs-to-see-recent-records-not-all,298,594670.0,7.0,,,2018-08-31 16:56:00,2023-05-06 03:32:16,2022-03-16 17:42:38,,,docker;logging,svenwinkle,3097,5035210,registered,true,52168857,,CC BY-SA 4.0,,838,748,2,0,0,2,true,false,false,true,true,true,47,9,false,0.012,0.0005,3004,2018,8,16,Friday,false,false,false,false,false,false,false
30043872,Docker-compose: node_modules not present in a volume after npm install succeeds,"I have an app with the following services:
web/ - holds and runs a python 3 flask web server on port 5000. Uses sqlite3.
worker/ - has an index.js file which is a worker for a queue. the web server interacts with this queue using a json API over port 9730. The worker uses redis for storage. The worker also stores data locally in the folder worker/images/
Now this question only concerns the worker.
worker/Dockerfile
FROM node:0.12
WORKDIR /worker
COPY package.json /worker/
RUN npm install
COPY . /worker/
docker-compose.yml
redis:
image: redis
worker:
build: ./worker
command: npm start
ports:
- ""9730:9730""
volumes:
- worker/:/worker/
links:
- redis
When I run docker-compose build, everything works as expected and all npm modules are installed in /worker/node_modules as I'd expect.
npm WARN package.json unfold@1.0.0 No README data
> phantomjs@1.9.2-6 install /worker/node_modules/pageres/node_modules/screenshot-stream/node_modules/phantom-bridge/node_modules/phantomjs
> node install.js
<snip>
But when I do docker-compose up, I see this error:
worker_1 | Error: Cannot find module 'async'
worker_1 | at Function.Module._resolveFilename (module.js:336:15)
worker_1 | at Function.Module._load (module.js:278:25)
worker_1 | at Module.require (module.js:365:17)
worker_1 | at require (module.js:384:17)
worker_1 | at Object.<anonymous> (/worker/index.js:1:75)
worker_1 | at Module._compile (module.js:460:26)
worker_1 | at Object.Module._extensions..js (module.js:478:10)
worker_1 | at Module.load (module.js:355:32)
worker_1 | at Function.Module._load (module.js:310:12)
worker_1 | at Function.Module.runMain (module.js:501:10)
Turns out none of the modules are present in /worker/node_modules (on host or in the container).
If on the host, I npm install, then everything works just fine. But I don't want to do that. I want the container to handle dependencies.
What's going wrong here?
(Needless to say, all packages are in package.json.)
",https://stackoverflow.com/questions/30043872/docker-compose-node-modules-not-present-in-a-volume-after-npm-install-succeeds,298,232650.0,21.0,,,2015-05-05 03:40:00,2025-03-10 13:52:20,2016-11-17 03:26:02,,,node.js;docker;ubuntu-14.04;docker-compose,KGo,20384,2392038,registered,true,,,CC BY-SA 3.0,,2460,2081,18,0,0,4,false,false,false,true,true,true,79,11,false,0.09,0.0013,4218,2015,5,3,Tuesday,false,false,false,false,false,false,false
37254881,Is there any way to disable a service in docker-compose.yml,"I find myself in the situation, that I want to disable a service temporarily in a docker-compose file.
Of course I could comment it out, but is there any option to just say ""enabled: false"" ?
",https://stackoverflow.com/questions/37254881/is-there-any-way-to-disable-a-service-in-docker-compose-yml,297,185814.0,10.0,,,2016-05-16 13:16:27,2024-08-31 16:34:09,2016-05-16 13:25:39,2025-08-14 07:59:19,Not suitable for this site,docker;docker-compose,Mandragor,5934,5039582,registered,true,37255042,,,,236,196,2,0,0,2,true,true,false,true,true,true,59,10,false,0.054,0.0016,3841,2016,5,13,Monday,false,false,false,false,false,false,false
36354423,What is the best way to pass AWS credentials to a Docker container?,"I am running docker-container on Amazon EC2. Currently I have added AWS Credentials to Dockerfile. Could you please let me know the best way to do this?
",https://stackoverflow.com/questions/36354423/what-is-the-best-way-to-pass-aws-credentials-to-a-docker-container,296,356722.0,13.0,,,2016-04-01 10:50:51,2024-05-20 09:50:37,2021-01-25 18:47:02,,,amazon-web-services;docker;docker-compose,suraj chopade,3383,5730257,registered,true,36357388,,CC BY-SA 4.0,2024-05-05 11:40:36,160,153,0,0,0,3,true,false,false,true,true,true,67,13,true,0.036,0.0008,3886,2016,4,10,Friday,false,false,false,false,false,false,false
34689445,Can't push image to Amazon ECR - fails with "no basic auth credentials","I'm trying to push a docker image to an Amazon ECR registry. I'm using docker client Docker version 1.9.1, build a34a1d5. I use aws ecr get-login --region us-east-1 to get the docker login creds. Then I successfully login with those creds as follows:
docker login -u AWS -p XXXX -e none https://####.dkr.ecr.us-east-1.amazonaws.com
WARNING: login credentials saved in /Users/ar/.docker/config.json
Login Succeeded
But when I try to push my image I get the following error:
$ docker push ####.dkr.ecr.us-east-1.amazonaws.com/image:latest
The push refers to a repository [####.dkr.ecr.us-east-1.amazonaws.com/image] (len: 1)
bcff5e7e3c7c: Preparing
Post https://####.dkr.ecr.us-east-1.amazonaws.com/v2/image/blobs/uploads/: no basic auth credentials
I made sure that the aws user had the correct permissions. I also made sure that the repository allowed that user to push to it. Just to make sure that wasn't an issue I set the registry to allow all users full access. Nothing changes the "no basic auth credentials" error. I don't know how to begin to debug this since all the traffic is encrypted.
UPDATE
So I had a bit of Homer Simpson D'Oh moment when I realized the root cause of my problem. I have access to multiple AWS accounts. Even though I was using aws configure to set my credentials for the account where I had setup my repository the aws cli was actually using the environment variables AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY. So when I did aws ecr get-login-password it was returning a login for the wrong account. I failed to notice that the account numbers were different until I just went back now to try some of the proposed answers. When I remove the environment variables everything works correctly. I guess the motto of the story is if you hit this error, make sure that the repository you are logging into matches the tag you have applied to the image.
",https://stackoverflow.com/questions/34689445/cant-push-image-to-amazon-ecr-fails-with-no-basic-auth-credentials,296,259257.0,53.0,,,2016-01-09 03:38:41,2024-12-01 11:07:12,2024-09-02 13:23:00,,,amazon-web-services;docker;amazon-ecr,Alec Rooney,3233,2785377,registered,true,,,CC BY-SA 4.0,,2084,1893,9,0,0,3,false,false,false,true,true,true,85,13,false,0.204,0.0011,3969,2016,1,3,Saturday,true,false,false,false,false,false,false
25436742,How to delete images from a private docker registry?,"I run a private docker registry, and I want to delete all images but the latest from a repository. I don't want to delete the entire repository, just some of the images inside it. The API docs don't mention a way to do this, but surely it's possible?
",https://stackoverflow.com/questions/25436742/how-to-delete-images-from-a-private-docker-registry,296,547302.0,18.0,,,2014-08-21 22:09:29,2025-07-05 17:12:51,2017-07-31 17:44:31,,,docker;docker-registry,Leo,3346,3562538,registered,true,25551160,,CC BY-SA 3.0,2018-02-20 18:42:13,345,251,1,1,0,2,true,false,false,true,true,true,52,9,true,0.033,0.0005,4475,2014,8,22,Thursday,false,false,false,false,false,false,false
21928780,create multiple tag docker image,"How can several tags be attached to one Docker image? Is it possible to create multiple tags using one Dockerfile?
It is possible, somehow; for example docker pull ubuntu will get several images, some of which have multiple tags:
ubuntu 13.10 9f676bd305a4 2 weeks ago 182.1 MB
ubuntu saucy 9f676bd305a4 2 weeks ago 182.1 MB
ubuntu raring eb601b8965b8 2 weeks ago 170.2 MB
ubuntu 13.04 eb601b8965b8 2 weeks ago 170.2 MB
ubuntu 12.10 5ac751e8d623 2 weeks ago 161.4 MB
ubuntu quantal 5ac751e8d623 2 weeks ago 161.4 MB
ubuntu 10.04 9cc9ea5ea540 2 weeks ago 183 MB
ubuntu lucid 9cc9ea5ea540 2 weeks ago 183 MB
ubuntu 12.04 9cd978db300e 2 weeks ago 204.7 MB
ubuntu latest 9cd978db300e 2 weeks ago 204.7 MB
ubuntu precise 9cd978db300e 2 weeks ago 204.7 MB
",https://stackoverflow.com/questions/21928780/create-multiple-tag-docker-image,295,268954.0,4.0,,,2014-02-21 08:10:07,2022-10-05 15:13:06,2022-07-11 20:35:17,,,docker;tags,Daniel YC Lin,16302,730346,registered,true,23161348,,CC BY-SA 4.0,,1327,1250,2,0,0,2,true,false,false,true,true,true,32,5,false,0.015,0.0011,4656,2014,2,8,Friday,false,false,false,false,false,false,false
45682010,docker : invalid reference format,"I'm following this tutorial that uses Docker. When I tried to run Docker (inside the run.sh script):
docker run \
-p 8888:8888
-v `pwd`/../src:/src \
-v `pwd`/../data:/data -w /src supervisely_anpr \
--rm \
-it \
bash
I got the error:
docker: invalid reference format.
I spent 2 hours and I can't really understand what's wrong. Any idea really appreciated.
",https://stackoverflow.com/questions/45682010/docker-invalid-reference-format,295,826557.0,30.0,,,2017-08-14 19:49:10,2025-06-12 17:44:16,2022-03-01 14:48:37,,,docker,ai2016,3209,7071236,registered,true,,,CC BY-SA 4.0,,600,385,2,1,0,1,false,false,false,true,true,true,33,5,false,0.036,0.0004,3386,2017,8,19,Monday,false,false,false,false,false,false,false
38118791,Can’t delete docker image with dependent child images,"I am trying
docker rmi c565603bc87f
Error:
Error response from daemon: conflict: unable to delete c565603bc87f
(cannot be forced) - image has dependent child images
So i can't delete image even with -f flag. How to delete image then and all of its children ?
Linux and docker version:
uname -a
Linux goracio-pc 4.4.0-24-generic #43-Ubuntu SMP Wed Jun 8 19:27:37 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux
docker version
Client:
Version: 1.11.2
API version: 1.23
Go version: go1.5.4
Git commit: b9f10c9
Built: Wed Jun 1 22:00:43 2016
OS/Arch: linux/amd64
Server:
Version: 1.11.2
API version: 1.23
Go version: go1.5.4
Git commit: b9f10c9
Built: Wed Jun 1 22:00:43 2016
OS/Arch: linux/amd64
",https://stackoverflow.com/questions/38118791/can-t-delete-docker-image-with-dependent-child-images,294,352313.0,26.0,,,2016-06-30 09:17:58,2024-11-18 00:28:18,2019-03-06 20:48:01,,,docker;docker-image,YakovlevRoman,3542,819474,registered,true,50650745,,CC BY-SA 4.0,2018-04-24 04:30:49,806,701,1,0,0,2,true,false,false,true,true,true,53,8,false,0.074,0.0008,3796,2016,6,9,Thursday,false,false,false,false,false,false,false
39988844,docker-compose up vs docker-compose up --build vs docker-compose build --no-cache,"I couldn't figure out what the difference between those.
docker-compose up
docker-compose up --build
docker-compose build --no-cache
Is there any command for upwithout cache?
",https://stackoverflow.com/questions/39988844/docker-compose-up-vs-docker-compose-up-build-vs-docker-compose-build-no-cach,294,152437.0,2.0,,,2016-10-12 00:43:01,2024-02-04 19:27:54,,,,docker;docker-compose,Toshi,6430,2850944,registered,true,,,CC BY-SA 3.0,,303,180,4,0,0,2,false,false,false,true,true,false,81,10,false,0.013,0.0019,3692,2016,10,0,Wednesday,false,false,false,false,false,false,false
24309526,How to change the docker image installation directory?,"From what I can tell, docker images are installed to /var/lib/docker as they are pulled. Is there a way to change this location, such as to a mounted volume like /mnt?
",https://stackoverflow.com/questions/24309526/how-to-change-the-docker-image-installation-directory,293,252554.0,21.0,,,2014-06-19 14:49:02,2024-04-23 14:38:59,2014-11-20 20:18:17,,,docker,Michael Barton,9796,91144,registered,true,24312133,,CC BY-SA 3.0,,201,168,2,0,0,1,true,false,false,true,true,true,54,8,true,0.083,0.0012,4538,2014,6,14,Thursday,false,false,false,false,false,false,false
51508150,standard_init_linux.go:190: exec user process caused "no such file or directory" - Docker,"When I am running my docker image on windows 10. I am getting this error:
standard_init_linux.go:190: exec user process caused ""no such file or directory""
my docker file is:
FROM openjdk:8
EXPOSE 8080
VOLUME /tmp
ADD appagent.tar.gz /opt/app-agent
ADD services.jar app.jar
ADD run.sh /run.sh
# Install compiler and perl stuff
RUN apt-get update
RUN apt-get install -y build-essential
RUN apt-get install -y gcc-multilib
RUN apt-get install -y perl
# Install Percona Toolkit
RUN apt-get install --yes percona-toolkit
RUN [""chmod"", ""+x"", ""/run.sh""]
ENTRYPOINT [""/run.sh""]
and the script is start with #!/bin/sh
#!/bin/sh
set -e
JAVA_OPTS=""-Dfile.encoding=UTF-8 -Djava.security.egd=file:/dev/urandom""
if [ ""${APPD_APP_NAME}"" != """" ]; then
JAVA_AGENT=""-javaagent:/opt/app-agent/javaagent.jar
fi
exec java ${JVM_OPTS} ${JAVA_OPTS} ${JAVA_AGENT} -jar /app.jar
Tried method1:
Tried changing #!/bin/sh to #!/bin/bash but getting same error.
Tried method2:
added dos2unix in docker file
RUN apt-get install -y dos2unix
RUN dos2unix /run.sh
",https://stackoverflow.com/questions/51508150/standard-init-linux-go190-exec-user-process-caused-no-such-file-or-directory,291,293178.0,29.0,,,2018-07-24 22:03:22,2023-07-11 07:29:03,,,,docker;dockerfile;docker-for-windows,gamechanger17,4739,7756971,registered,true,52665687,,CC BY-SA 4.0,2022-03-18 11:46:27,1216,1051,4,0,0,3,true,false,false,true,true,false,99,12,false,0.099,0.001,3042,2018,7,22,Tuesday,false,false,false,false,false,false,false
65612411,Forcing docker to use linux/amd64 platform by default on macOS,"Current beta version of docker requires you to specify a --platform=linux/amd64 each time you need to build or run an amd64 image/container.
The documentation mentions
When running an image with multi-architecture support, docker will automatically select an image variant which matches your OS and architecture.
The documentation does not specify a way to alter this automatic behaviour using env variables. It seems to ignore both BUILDPLATFORM and TARGETPLATFORM.
Is there any other way to force docker to run all build and run commands with a platform linux/amd64 instead of linux/arm64/v8 by default on macOS running on apple-silicon?
",https://stackoverflow.com/questions/65612411/forcing-docker-to-use-linux-amd64-platform-by-default-on-macos,290,449818.0,7.0,,,2021-01-07 12:29:20,2025-12-08 13:18:14,,,,docker;multiplatform;apple-silicon,Vojtech Letal,3348,5094001,registered,true,66900911,,CC BY-SA 4.0,,824,642,8,0,0,3,true,false,false,true,true,false,62,10,false,0.016,0.0006,2144,2021,1,12,Thursday,false,false,false,false,false,false,false
37685581,How to get Docker Compose to use the latest image from the repository,"I don't know what I'm doing wrong, but I simply cannot get docker-compose up to use the latest image from our registry without first removing the old containers from the system completely. It looks like compose is using the previously started image even though docker-compose pull has fetched a newer image.
I looked at How can I get Docker Compose to always recreate containers from fresh images? which seemed to be similar to my issue, but none of the provided solutions there work for me, since I'm looking for a solution I can use on the production server and there I don't want to be removing all containers before starting them again (possible data loss?). I would like for compose only to detect the new version of the changed images, pull them and then restart the services with those new images.
I created a simple test project for this in which the only goal is to get a version nr to increase on each new build. The version nr is displayed if I browse to the nginx server that is created (this works as expected locally).
- docker version: 1.11.2
- docker-compose version: 1.7.1
- OS: tested on both CentOS 7 and OS X v10.10 (Yosemite) using docker-toolbox
My docker-compose.yml file:
version: '2'
services:
application:
image: ourprivate.docker.reg:5000/ourcompany/buildchaintest:0.1.8-dev
volumes:
- /var/www/html
tty: true
nginx:
build: nginx
ports:
- "80:80"
volumes_from:
- application
volumes:
- ./logs/nginx/:/var/log/nginx
php:
container_name: buildchaintest_php_1
build: php-fpm
expose:
- "9000"
volumes_from:
- application
volumes:
- ./logs/php-fpm/:/var/www/logs
On our Jenkins server, I run the following to build and tag the image:
cd $WORKSPACE && PROJECT_VERSION=$(cat VERSION)-dev
/usr/local/bin/docker-compose rm -f
/usr/local/bin/docker-compose build
docker tag ourprivate.docker.reg:5000/ourcompany/buildchaintest ourprivate.docker.reg:5000/ourcompany/buildchaintest:$PROJECT_VERSION
docker push ourprivate.docker.reg:5000/ourcompany/buildchaintest
This seems to be doing what it's supposed to be since I get a new version tag in our repository each time the build completes and the version number has been bumped.
If I now run
docker-compose pull && docker-compose -f docker-compose.yml up -d
in a folder on my computer, where the contents is only the docker-compose.yml file and the necessary Dockerfiles to build the nginx and PHP services, the output I get is not the latest version number as has been tagged in the registry or is shown in the docker-compose.yml file (0.1.8), but the version before that, which is 0.1.7. However the output of the pull command would suggest that a new version of the image was fetched:
Pulling application (ourprivate.docker.reg:5000/ourcompany/buildchaintest:latest)...
latest: Pulling from ourcompany/buildchaintest
Digest: sha256:8f7a06203005ff932799fe89e7756cd21719cccb9099b7898af2399414bfe62a
Status: Downloaded newer image for docker.locotech.fi:5000/locotech/buildchaintest:0.1.8-dev
Only if I run
docker-compose stop && docker-compose rm -f
and then run the docker-compose up command do I get the new version to show up on screen as expected.
Is this intended behaviour of Docker Compose? I.e., should I always do a docker-compose rm -f before running up again, even on production servers? Or am I doing something against the grain here, which is why it's not working?
The goal is to have our build process build and create tagged versions of the images needed in a docker-compose.yml file, push those to our private registry and then for the "release to production-step" to simply copy the docker-compose.yml file to the production server and run a docker-compose pull && docker-compose -f docker-compose.yml up -d for the new image to start in production.
If anyone has tips on this or can point to a best practices tutorial for this kind of setup that would be much appreciated also.
",https://stackoverflow.com/questions/37685581/how-to-get-docker-compose-to-use-the-latest-image-from-the-repository,289,506953.0,20.0,,,2016-06-07 17:24:19,2026-06-27 16:54:14,2026-01-12 04:38:45,2026-06-26 21:22:45,Not suitable for this site,docker;docker-compose;build,Jens Wegar,5082,371806,registered,true,38116620,,,,4792,4023,11,4,0,3,true,true,false,true,true,true,69,13,false,0.039,0.0006,3819,2016,6,17,Tuesday,false,false,false,false,false,false,false
31222377,What are Docker image "layers"?,"I am brand new to Docker and am trying to understand exactly what a Docker image is. Every single definition of a Docker image uses the term "layer", but does not seem to define what is meant by layer.
From the official Docker docs:
We’ve already seen that Docker images are read-only templates from which Docker containers are launched. Each image consists of a series of layers. Docker makes use of union file systems to combine these layers into a single image. Union file systems allow files and directories of separate file systems, known as branches, to be transparently overlaid, forming a single coherent file system.
So I ask, what is a layer exactly? Can someone give a few concrete examples of them? And how do these layers "snap together" to form an image?
",https://stackoverflow.com/questions/31222377/what-are-docker-image-layers,289,142723.0,11.0,,,2015-07-04 15:38:07,2023-10-31 21:43:02,2023-08-21 17:30:31,,,docker,smeeb,29947,4009451,registered,true,,,CC BY-SA 4.0,,981,791,0,1,0,1,false,false,false,true,true,true,41,5,true,0.077,0.002,4158,2015,7,15,Saturday,true,false,false,false,false,false,false
62473932,At least one invalid signature was encountered,"I am trying to build and deploy microservices images to a single-node Kubernetes cluster running on my development machine using minikube. I am using the cloud-native microservices demo application Online Boutique by Google to understand the use of technologies like Kubernetes, Istio etc.
While following the installation process, and on running command skaffold run to build and deploy my application, I get some errors:
Step 10/11 : RUN apt-get -qq update && apt-get install -y --no-install-recommends curl
---> Running in 43d61232617c
W: GPG error: http://deb.debian.org/debian buster InRelease: At least one invalid signature was encountered.
E: The repository 'http://deb.debian.org/debian buster InRelease' is not signed.
W: GPG error: http://deb.debian.org/debian buster-updates InRelease: At least one invalid signature was encountered.
E: The repository 'http://deb.debian.org/debian buster-updates InRelease' is not signed.
W: GPG error: http://security.debian.org/debian-security buster/updates InRelease: At least one invalid signature was encountered.
E: The repository 'http://security.debian.org/debian-security buster/updates InRelease' is not signed.
failed to build: couldn't build "loadgenerator": unable to stream build output: The command '/bin/sh -c apt-get -qq update && apt-get install -y --no-install-recommends curl' returned a non-zero code: 100
I receive these errors when trying to build loadgenerator.
How can I resolve this issue?
",https://stackoverflow.com/questions/62473932/at-least-one-invalid-signature-was-encountered,287,187495.0,16.0,,,2020-06-19 15:48:04,2025-06-15 05:51:35,2024-11-06 13:44:14,,,docker;kubernetes;minikube;skaffold,Saranya Gupta,3207,11568363,registered,true,62510927,,CC BY-SA 4.0,,1665,1518,2,1,0,4,true,false,false,true,true,true,46,7,false,0.085,0.0015,2346,2020,6,15,Friday,false,false,false,false,false,false,false
20430371,My docker container has no internet,"I had it working allright but now it stopped. I tried the following commands with no avail:
docker run -dns 8.8.8.8 base ping google.com
docker run base ping google.com
sysctl -w net.ipv4.ip_forward=1 - both on the host and on the container
All I get is unknown host google.com. Docker version 0.7.0
Any ideas?
P.S. ufw disabled as well
",https://stackoverflow.com/questions/20430371/my-docker-container-has-no-internet,286,643442.0,40.0,,,2013-12-06 17:51:37,2025-08-02 14:33:31,2021-12-20 15:08:32,2025-08-03 08:06:10,Not suitable for this site,docker;devops,Romeo Mihalcea,10412,1515697,registered,true,20431030,,,2018-06-27 22:40:03,458,344,5,0,0,2,true,true,false,true,true,true,35,6,false,0.062,0.0004,4733,2013,12,17,Friday,false,false,false,false,false,false,false
25185405,Using GPU from a docker container?,"I'm searching for a way to use the GPU from inside a docker container.
The container will execute arbitrary code so i don't want to use the privileged mode.
Any tips?
From previous research i understood that run -v and/or LXC cgroup was the way to go but i'm not sure how to pull that off exactly
",https://stackoverflow.com/questions/25185405/using-gpu-from-a-docker-container,286,548103.0,13.0,,,2014-08-07 14:41:34,2024-12-24 18:28:10,2014-08-18 16:26:39,,,cuda;docker,Regan,8931,3918651,registered,true,58432877,,CC BY-SA 3.0,,355,301,2,0,0,2,true,false,false,true,true,true,34,6,true,0.024,0.0005,4489,2014,8,14,Thursday,false,false,false,false,false,false,false
33907835,"Docker error cannot delete docker container, conflict: unable to remove repository reference","I want to remove the container at Docker, but an error occurs when you want to delete
My next step before removing the container, see the list of existing container
sts@Yudi:~/docker$ sudo docker ps -as
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES SIZE
78479ffeba5c ubuntu ""/bin/bash"" 42 hours ago Exited (0) 42 hours ago sharp_wescoff 81 B (virtual 187.7 MB)
0bd2b54678c7 training/webapp ""python app.py"" 5 days ago Exited (0) 5 days ago backstabbing_ritchie 0 B (virtual 323.7 MB)
0adbc74a3803 training/webapp ""python app.py"" 5 days ago Exited (143) 5 days ago drunk_feynman 0 B (virtual 323.7 MB)
one I want to delete the list, namely ""training / webapp""
but an error that occurred
sts@Yudi:~/docker$ sudo docker rmi training/webapp
Error response from daemon: conflict: unable to remove repository reference ""training/webapp"" (must force) - container 0bd2b54678c7 is using its referenced image 54bb4e8718e8
Error: failed to remove images: [training/webapp]
Whether the container is running in the images?
Please help
",https://stackoverflow.com/questions/33907835/docker-error-cannot-delete-docker-container-conflict-unable-to-remove-reposito,285,330920.0,12.0,,,2015-11-25 03:06:42,2024-02-25 22:37:09,2016-07-28 16:34:24,,,docker;containers,Yuday,4539,5594439,registered,true,33907950,,CC BY-SA 3.0,,1404,1304,2,0,0,2,true,false,false,true,true,true,92,12,false,0.036,0.0009,4014,2015,11,3,Wednesday,false,false,false,false,false,false,false
39597925,How do I set environment variables during the "docker build" process?,"I'm trying to set environment variables in docker container during the build but without success. Setting them when using run command works but I need to set them during the build.
Dockerfile
FROM ubuntu:latest
ARG TEST_ENV=something
Command I'm using to build
docker build -t --build-arg TEST_ENV="test" myimage .
Running
docker run -dit myimage
I'm checking available environment variables by using
docker exec containerid printenv
And the result is
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=e49c1abfd58b
TERM=xterm
no_proxy=*.local, 169.254/16
HOME=/root
TEST_ENV is not present
",https://stackoverflow.com/questions/39597925/how-do-i-set-environment-variables-during-the-docker-build-process,285,454621.0,2.0,,,2016-09-20 15:20:39,2023-12-02 03:11:35,2023-12-02 03:11:35,,,docker;dockerfile;environment-variables;docker-build,Michał Pietraszko,6299,6599814,registered,true,39598751,,CC BY-SA 4.0,,939,630,6,0,0,4,true,false,false,true,true,true,79,11,true,0.004,0.0006,3714,2016,9,15,Tuesday,false,false,false,false,false,false,false
40454470,How can I use a variable inside a Dockerfile CMD?,"Inside my Dockerfile:
ENV PROJECTNAME mytestwebsite
CMD ["django-admin", "startproject", "$PROJECTNAME"]
Error:
CommandError: '$PROJECTNAME' is not a valid project name
What is the quickest workaround here? Does Docker have any plan to "fix" or introduce this functionality in later versions of Docker?
NOTE: If I remove the CMD line from the Docker file and then run the Docker container, I am able to manually run django-admin startproject $PROJECTNAME from inside the container and it will create the project...
",https://stackoverflow.com/questions/40454470/how-can-i-use-a-variable-inside-a-dockerfile-cmd,284,203724.0,6.0,,,2016-11-06 20:59:24,2024-04-17 17:23:05,2024-04-17 17:23:05,,,docker;dockerfile;docker-cmd,david,6905,2680978,registered,true,40454758,,CC BY-SA 4.0,,651,562,3,0,0,3,true,false,false,true,true,true,49,10,true,0.029,0.0014,3667,2016,11,20,Sunday,true,false,false,false,false,false,false
45142855,/bin/sh: apt-get: not found,"I am trying to change a dockerFile to work with aspell. I have a bash script that I want to wrap in a dock
Step 4: Wrap the script in a Docker container.
The sample SDK we downloaded earlier contains an example of an action wrapped in a Docker container. In particular, the sample SDK includes a Dockerfile that builds the C program in client/example.c and installs the binary as /blackbox/client/action .
The key line in the sample Dockerfile is:
RUN cd /blackbox/client; gcc -o action example.c
Instead of compiling example.c and installing the binary as an action, we’ll change the Dockerfile to install aspell into the Linux environment, and then install our action.sh script as the executable action command.
To do so, we delete the RUN command above, and insert the following commands into the Dockerfile:
RUN apt-get install -y aspell
RUN rm -f /blackbox/client/action
ADD action.sh /blackbox/client/action
I am trying to do this on the dockerfile below
# Dockerfile for example whisk docker action
FROM openwhisk/dockerskeleton
ENV FLASK_PROXY_PORT 8080
### Add source file(s)
ADD example.c /action/example.c
RUN sudo apt-get install -y aspell
RUN rm -f /blackbox/client/action
ADD action.sh /blackbox/client/action
CMD ["/home/huseyin/bin", "-c", "cd actionProxy && python -u actionproxy.py"]
The tutorial is outdated so I can't figure out how to make it work. What am I doing wrong?
",https://stackoverflow.com/questions/45142855/bin-sh-apt-get-not-found,283,458480.0,2.0,,,2017-07-17 11:18:39,2024-10-05 08:27:39,2022-09-22 21:15:43,,,bash;docker;dockerfile;aspell,Hüseyin Orkun Elmas,2943,7877578,registered,true,45143116,,CC BY-SA 4.0,,1593,1440,3,0,0,4,true,false,false,true,true,true,27,4,false,0.004,0.0006,3414,2017,7,11,Monday,false,false,false,false,false,false,false
29924843,How do I set hostname in docker-compose?,"In my docker-compose.yml file, I have the following. However the container does not pick up the hostname value. Any ideas?
dns:
image: phensley/docker-dns
hostname: affy
domainname: affy.com
volumes:
- /var/run/docker.sock:/docker.sock
When I check the hostname in the container it does not pick up affy.
",https://stackoverflow.com/questions/29924843/how-do-i-set-hostname-in-docker-compose,283,524970.0,6.0,,,2015-04-28 16:25:12,2025-04-03 07:52:47,2022-01-29 18:55:28,,,docker;docker-compose,David Medinets,5686,219658,registered,true,63291253,,CC BY-SA 4.0,,421,318,3,0,0,2,true,false,false,true,true,true,40,7,true,0.011,0.0005,4225,2015,4,16,Tuesday,false,false,false,false,false,false,false
33322103,Multiple FROMs - what it means,"I want to build a docker image, which requires both a Neo4j database and Node.js to run.
My first approach was to declare a base image for my image, containing Neo4j. The reference docs do not define "base image" in any helpful manner:
Base image:
An image that has no parent is a base image
from which I read that I may only have a base image if that image has no base image itself.
But what is a base image? Does it mean, if I declare neo4j/neo4j in a FROM directive, that when my image is run the neo database will automatically run and be available within the container on port 7474?
Reading the Docker reference I see:
FROM can appear multiple times within a single Dockerfile in order to create multiple images. Simply make a note of the last image ID output by the commit before each new FROM command.
Do I want to create multiple images? It would seem what I want is to have a single image that contains the contents of other images e.g. neo4j and node.js.
I've found no directive to declare dependencies in the reference manual. Are there no dependencies like in RPM where in order to run my image the calling context must first install the images it needs?
",https://stackoverflow.com/questions/33322103/multiple-froms-what-it-means,283,310322.0,4.0,,,2015-10-24 18:58:48,2024-03-26 14:19:31,2023-03-02 15:33:25,,,docker;dockerfile,ekkis,10362,709223,registered,true,33322374,,CC BY-SA 4.0,,1380,1181,0,1,0,2,true,false,false,true,true,true,30,6,false,0.013,0.0009,4046,2015,10,18,Saturday,true,false,false,false,false,false,false
17770902,Forward host port to docker container,"Is it possible to have a Docker container access ports opened by the host? Concretely I have MongoDB and RabbitMQ running on the host and I'd like to run a process in a Docker container to listen to the queue and (optionally) write to the database.
I know I can forward a port from the container to the host (via the -p option) and have a connection to the outside world (i.e. internet) from within the Docker container but I'd like to not expose the RabbitMQ and MongoDB ports from the host to the outside world.
EDIT: some clarification:
Starting Nmap 5.21 ( http://nmap.org ) at 2013-07-22 22:39 CEST
Nmap scan report for localhost (127.0.0.1)
Host is up (0.00027s latency).
PORT STATE SERVICE
6311/tcp open unknown
joelkuiper@vps20528 ~ % docker run -i -t base /bin/bash
root@f043b4b235a7:/# apt-get install nmap
root@f043b4b235a7:/# nmap 172.16.42.1 -p 6311 # IP found via docker inspect -> gateway
Starting Nmap 6.00 ( http://nmap.org ) at 2013-07-22 20:43 UTC
Nmap scan report for 172.16.42.1
Host is up (0.000060s latency).
PORT STATE SERVICE
6311/tcp filtered unknown
MAC Address: E2:69:9C:11:42:65 (Unknown)
Nmap done: 1 IP address (1 host up) scanned in 13.31 seconds
I had to do this trick to get any internet connection within the container: My firewall is blocking network connections from the docker container to outside
EDIT: Eventually I went with creating a custom bridge using pipework and having the services listen on the bridge IP's. I went with this approach instead of having MongoDB and RabbitMQ listen on the docker bridge because it gives more flexibility.
",https://stackoverflow.com/questions/17770902/forward-host-port-to-docker-container,283,375186.0,11.0,,,2013-07-21 09:32:41,2026-05-08 17:13:20,2022-08-20 21:45:41,,,linux;network-programming;port;docker,JoelKuiper,4830,1829370,registered,true,18646069,,CC BY-SA 4.0,,1889,1605,1,2,0,4,true,false,false,true,true,true,37,6,false,0.029,0.0008,4871,2013,7,9,Sunday,true,false,false,false,false,false,false
70946140,Docker Desktop WSL ext4.vhdx too large,"I have WSL installed as well as Docker Desktop.
I tried to clean up docker as much as I could by running
docker system prune -a
docker volume rm $(docker volume ls -q -f dangling=true)
Then I verified with
❯ docker system df
TYPE TOTAL ACTIVE SIZE RECLAIMABLE
Images 0 0 0B 0B
Containers 0 0 0B 0B
Local Volumes 0 0 0B 0B
Build Cache 0 0 0B 0B
However, I see that I still have nearly 12G used by WSL.
I assume this file is docker related. Why is it so large despite me removing all containers and volumes?
How do I shrink it (or can I delete it?)
",https://stackoverflow.com/questions/70946140/docker-desktop-wsl-ext4-vhdx-too-large,282,285340.0,6.0,,,2022-02-01 19:07:34,2026-02-16 17:04:07,,2023-11-23 17:45:14,Not suitable for this site,docker;windows-subsystem-for-linux,K Split X,5251,7058735,registered,true,,,,,926,686,2,1,1,2,false,true,false,true,true,false,38,6,false,0.021,0.001,1754,2022,2,19,Tuesday,false,false,false,false,false,false,false
29696656,Finding the layers and layer sizes for each Docker image,"For research purposes I'm trying to crawl the public Docker registry ( https://registry.hub.docker.com/ ) and find out 1) how many layers an average image has and 2) the sizes of these layers to get an idea of the distribution.
However I studied the API and public libraries as well as the details on the github but I cant find any method to:
- retrieve all the public repositories/images (even if those are thousands I still need a starting list to iterate through)
- find all the layers of an image
- find the size for a layer (so not an image but for the individual layer).
Can anyone help me find a way to retrieve this information?
EDIT: is anyone able to verify that searching for '*' in Docker registry is returning all the repositories and not just anything that mentions '*' anywhere? https://registry.hub.docker.com/search?q=\*
",https://stackoverflow.com/questions/29696656/finding-the-layers-and-layer-sizes-for-each-docker-image,282,329901.0,12.0,,,2015-04-17 10:26:12,2023-04-09 21:54:39,2023-04-09 21:54:39,,,docker;web-crawler;docker-image,user134589,3069,1659940,registered,true,,,CC BY-SA 4.0,,1038,834,0,2,0,3,false,false,false,true,true,true,56,10,false,0.036,0.0009,4236,2015,4,10,Friday,false,false,false,false,false,false,false
26331651,How can I backup a Docker-container with its data-volumes?,"I've been using this Docker-image tutum/wordpress to demonstrate a Wordpress website. Recently I found out that the image uses volumes for the MySQL-data.
So the problem is this: If I want to backup and restore the container I can try to commit an image, and then later delete the container, and create a new container from the committed image. But if I do that the volume gets deleted and all my data is gone.
There must be some simple way to backup my container plus its volume-data but I can't find it anywhere.
",https://stackoverflow.com/questions/26331651/how-can-i-backup-a-docker-container-with-its-data-volumes,282,533039.0,20.0,,,2014-10-13 01:09:36,2026-10-19 10:24:15,2015-07-20 01:10:59,,,backup;docker;linux-containers,pguardiario,55238,966023,registered,true,,,CC BY-SA 3.0,2026-10-19 10:30:24,603,517,0,1,0,3,false,false,false,true,true,true,58,9,true,0.038,0.0005,4422,2014,10,1,Monday,false,false,false,false,false,false,false
21398087,How can I delete Docker's images?,"I've the following images:
alex@alexvps:~$ sudo docker images
REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE
<none> <none> 70c0e19168cf 5 days ago 1.069 GB
<none> <none> c2ce80b62174 8 days ago 399.2 MB
<none> <none> 60afe4036d97 8 days ago 325.1 MB
and when I try to remove one of them I get:
alex@alexvps:~$ sudo docker rmi 60afe4036d97
Error: Conflict, 60afe4036d97 wasn't deleted
2014/01/28 00:54:00 Error: failed to remove one or more images
How can I remove them? Why is there such conflict?
",https://stackoverflow.com/questions/21398087/how-can-i-delete-dockers-images,280,267213.0,16.0,,,2014-01-28 06:04:18,2023-02-23 14:29:01,2017-01-10 22:03:54,,,docker,alessmar,4725,236227,registered,true,29357318,,CC BY-SA 3.0,2023-02-23 14:30:54,781,712,2,0,0,1,true,false,false,true,true,true,37,6,true,0.06,0.001,4680,2014,1,6,Tuesday,false,false,false,false,false,false,false
32727594,How to pass arguments to Shell Script through docker run,"I am new to the docker world. I have to invoke a shell script that takes command line arguments through a docker container.
Ex: My shell script looks like:
#!bin/bash
echo $1
Dockerfile looks like this:
FROM ubuntu:14.04
COPY ./file.sh /
CMD /bin/bash file.sh
I am not sure how to pass the arguments while running the container
",https://stackoverflow.com/questions/32727594/how-to-pass-arguments-to-shell-script-through-docker-run,278,597359.0,8.0,,,2015-09-22 21:53:55,2023-07-06 11:09:57,,,,bash;shell;docker;command-line-arguments,Akash Mehta,3019,1801934,registered,true,32728266,,CC BY-SA 3.0,,403,334,2,0,0,4,true,false,false,true,true,false,56,10,false,0.013,0.0005,4078,2015,9,21,Tuesday,false,false,false,false,false,false,false
66662820,M1 docker preview and keycloak 'image's platform (linux/amd64) does not match the detected host platform (linux/arm64/v8)' Issue,"I just downloaded Docker Preview v3.1 https://docs.docker.com/docker-for-mac/apple-m1/ and tried running keycloak.
Anyone else running into this issue?
docker run -p 8080:8080 -e KEYCLOAK_USER=admin -e KEYCLOAK_PASSWORD=admin quay.io/keycloak/keycloak:12.0.4
WARNING: The requested image's platform (linux/amd64) does not match the detected host platform (linux/arm64/v8) and no specific platform was requested
",https://stackoverflow.com/questions/66662820/m1-docker-preview-and-keycloak-images-platform-linux-amd64-does-not-match-th,277,450048.0,17.0,,,2021-03-16 20:19:44,2024-07-31 04:33:33,2021-03-16 21:23:09,,,macos;docker;keycloak;apple-m1,Etep,3741,4100000,registered,true,,,CC BY-SA 4.0,,530,412,1,1,0,4,false,false,false,true,true,true,140,17,false,0.038,0.0006,2076,2021,3,20,Tuesday,false,false,false,false,false,false,false
33054369,How to change the default docker registry from docker.io to my private registry?,"By default, if I issue command:
sudo docker pull ruby:2.2.1
it will pull from the docker.io offical site by default.
Pulling repository docker.io/library/ruby
How do I change it to my private registry. That means if I issue
sudo docker pull ruby:2.2.1
it will pull from my own private registry, the output is something like:
Pulling repository my_private.registry:port/library/ruby
",https://stackoverflow.com/questions/33054369/how-to-change-the-default-docker-registry-from-docker-io-to-my-private-registry,274,418294.0,12.0,,,2015-10-10 13:10:18,2024-05-14 12:08:08,2018-02-07 09:40:52,,,docker;docker-registry,mainframer,22749,4258008,registered,true,,,CC BY-SA 3.0,2022-04-22 19:51:11,519,395,4,0,0,2,false,false,false,true,true,true,80,13,true,0.029,0.0007,4060,2015,10,13,Saturday,true,false,false,false,false,false,false
40366192,Kubernetes how to make Deployment to update image,"I do have deployment with single pod, with my custom docker image like:
containers:
- name: mycontainer
image: myimage:latest
During development I want to push new latest version and make Deployment updated.
Can't find how to do that, without explicitly defining tag/version and increment it for each build, and do
kubectl set image deployment/my-deployment mycontainer=myimage:1.9.1
",https://stackoverflow.com/questions/40366192/kubernetes-how-to-make-deployment-to-update-image,273,415520.0,10.0,,,2016-11-01 18:20:16,2025-04-03 23:11:02,,,,docker;kubernetes,Andriy Kopachevskyy,7776,306025,registered,true,40368520,,CC BY-SA 3.0,,457,395,2,0,0,2,true,false,false,true,true,false,49,8,false,0.024,0.0007,3672,2016,11,18,Tuesday,false,false,false,false,false,false,false
64952238,docker.errors.DockerException: Error while fetching server API version,"I want to install this module but there is something wrong when I try the step docker-compose build ...
I tried to update the Docker version and restart Docker many times. But it didn't work.
git clone https://github.com/uhh-lt/158.git
cd 158
docker-compose build
File "/home/ming/.local/bin/docker-compose", line 8, in <module>
sys.exit(main())
File "/home/ming/.local/lib/python3.8/site-packages/compose/cli/main.py", line 67, in main
command()
File "/home/ming/.local/lib/python3.8/site-packages/compose/cli/main.py", line 123, in perform_command
project = project_from_options('.', options)
File "/home/ming/.local/lib/python3.8/site-packages/compose/cli/command.py", line 60, in project_from_options
return get_project(
File "/home/ming/.local/lib/python3.8/site-packages/compose/cli/command.py", line 131, in get_project
client = get_client(
File "/home/ming/.local/lib/python3.8/site-packages/compose/cli/docker_client.py", line 41, in get_client
client = docker_client(
File "/home/ming/.local/lib/python3.8/site-packages/compose/cli/docker_client.py", line 170, in docker_client
client = APIClient(**kwargs)
File "/home/ming/.local/lib/python3.8/site-packages/docker/api/client.py", line 188, in __init__
self._version = self._retrieve_server_version()
File "/home/ming/.local/lib/python3.8/site-packages/docker/api/client.py", line 212, in _retrieve_server_version
raise DockerException(
docker.errors.DockerException: Error while fetching server API version: ('Connection aborted.', FileNotFoundError(2, 'No such file or directory'))
Update 2020-11-23
Thanks for two of you helping me with the error! I tried the commend but can't connect to my Docker:
ming@KITM-7664:~$ sudo /etc/init.d/docker start
[sudo] password for ming:
* Starting Docker: docker [ OK ]
ming@KITM-7664:~$ which docker
/usr/bin/docker
ming@KITM-7664:~$ docker version
Client: Docker Engine - Community
Version: 19.03.13
API version: 1.40
Go version: go1.13.15
Git commit: 4484c46d9d
Built: Wed Sep 16 17:02:52 2020
OS/Arch: linux/amd64
Experimental: false
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
ming@KITM-7664:~$ systemctl status docker
System has not been booted with systemd as init system (PID 1). Can't operate.
Failed to connect to bus: Host is down
ming@KITM-7664:~$ systemctl start docker
System has not been booted with systemd as init system (PID 1). Can't operate.
Failed to connect to bus: Host is down
ming@KITM-7664:~$ sudo /etc/init.d/docker start
* Starting Docker: docker [ OK ]
ming@KITM-7664:~$ docker version
Client: Docker Engine - Community
Version: 19.03.13
API version: 1.40
Go version: go1.13.15
Git commit: 4484c46d9d
Built: Wed Sep 16 17:02:52 2020
OS/Arch: linux/amd64
Experimental: false
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
",https://stackoverflow.com/questions/64952238/docker-errors-dockerexception-error-while-fetching-server-api-version,270,489648.0,31.0,,,2020-11-22 08:53:15,2024-11-16 21:50:08,2023-02-08 01:48:28,,,python;linux;docker;docker-compose,ming,2701,14685247,registered,true,,,CC BY-SA 4.0,,3469,3315,4,0,0,4,false,false,false,true,true,true,70,7,false,0.063,0.0006,2190,2020,11,8,Sunday,true,true,false,false,false,false,false
20010199,How to determine if a process runs inside lxc/Docker?,"Is there any way to determine if a process (script) runs inside an lxc container (~ Docker runtime)? I know that some programs are able to detect whether they run inside a virtual machine, is something similar available for lxc/docker?
",https://stackoverflow.com/questions/20010199/how-to-determine-if-a-process-runs-inside-lxc-docker,268,122767.0,20.0,,,2013-11-15 20:42:04,2025-08-09 03:27:57,2018-04-07 22:40:47,,,linux;bash;docker,Mate Varga,3446,2216860,registered,true,20012536,,CC BY-SA 3.0,,243,236,0,0,0,3,true,false,false,true,true,true,53,9,true,0.163,0.0022,4754,2013,11,20,Friday,false,false,false,false,false,false,false
48368411,What is docker run -it flag?,"I was doing some complex stuff with Docker, but as turn out I don't know what -it flag means.
Recently I've come across on some example of docker run command which has confused me a little:
docker run -itd ubuntu:xenial /bin/bash
My question is what is sense to write -it flag here, if container during instantiation run bin/bash
In documentation we have an example
docker run --name test -it debian
with explanation:
The -it instructs Docker to allocate a pseudo-TTY connected to the
container’s stdin; creating an interactive bash shell in the
container.
and explanation for -t flag from help page
-t, --tty Allocate a pseudo-TTY
if I delete -it flag during
docker run -d ubuntu:xenial /bin/bash
my newly created container doesn't live so much: when doing docker ps -a it is designated as exited.
Sorry, if my question quite stupid, I can't find explanation on the Internet (I have significant misunderstanding of that point).
",https://stackoverflow.com/questions/48368411/what-is-docker-run-it-flag,268,249314.0,6.0,,,2018-01-21 15:27:45,2025-06-09 10:43:28,2025-06-09 10:20:29,,,docker;command-line-arguments,Alex,4563,5993278,registered,true,,,CC BY-SA 4.0,,1256,957,10,0,0,2,false,false,false,true,true,true,28,6,true,0.024,0.0011,3226,2018,1,15,Sunday,true,false,false,false,false,false,false
59139453,Repository is not signed in docker build,"I have the following Dockerfile that uses the latest Ubuntu image pulled from dockerhub:
FROM ubuntu:latest
RUN apt-get update && apt-get install -y g++ llvm lcov
when I launch the docker build command, the following errors occur:
Err:2 http://archive.ubuntu.com/ubuntu bionic InRelease
At least one invalid signature was encountered.
Err:1 http://security.ubuntu.com/ubuntu bionic-security InRelease
At least one invalid signature was encountered.
Err:3 http://archive.ubuntu.com/ubuntu bionic-updates InRelease
At least one invalid signature was encountered.
Err:4 http://archive.ubuntu.com/ubuntu bionic-backports InRelease
At least one invalid signature was encountered.
Reading package lists...
W: GPG error: http://archive.ubuntu.com/ubuntu bionic InRelease: At least one invalid signature was encountered.
E: The repository 'http://archive.ubuntu.com/ubuntu bionic InRelease' is not signed.
W: GPG error: http://security.ubuntu.com/ubuntu bionic-security InRelease: At least one invalid signature was encountered.
E: The repository 'http://security.ubuntu.com/ubuntu bionic-security InRelease' is not signed.
W: GPG error: http://archive.ubuntu.com/ubuntu bionic-updates InRelease: At least one invalid signature was encountered.
E: The repository 'http://archive.ubuntu.com/ubuntu bionic-updates InRelease' is not signed.
W: GPG error: http://archive.ubuntu.com/ubuntu bionic-backports InRelease: At least one invalid signature was encountered.
E: The repository 'http://archive.ubuntu.com/ubuntu bionic-backports InRelease' is not signed.
I read here https://superuser.com/questions/1331936/how-can-i-get-past-a-repository-is-not-signed-message-when-attempting-to-upgr that you can pass this error using --allow-unauthenitcated or --allow-insecure-repositories but both seem to me workarounds that may compromize security of the container.
EDIT
Tried to pull ubuntu:18.04, ubuntu:19:04, ubuntu:19.10 same error with different distro name
",https://stackoverflow.com/questions/59139453/repository-is-not-signed-in-docker-build,267,196433.0,16.0,,,2019-12-02 13:00:55,2024-04-11 13:26:32,2023-02-23 23:00:46,,,docker;ubuntu;apt,Antonio La Marra,7999,6404771,registered,true,59141204,,CC BY-SA 4.0,,2209,1977,2,1,0,3,true,false,false,true,true,true,40,7,false,0.081,0.0014,2546,2019,12,13,Monday,false,false,false,false,false,false,false
33562109,Docker command can't connect to Docker daemon,"I want to make a move to Docker, so I've just started to mess around with it. I've installed Docker on a VirtualBox Ubuntu 15.10 (Wily Werewolf) installation and as suggested here I then tried running a basic nginx Docker image:
$ docker run --name mynginx1 -P -d nginx
Cannot connect to the Docker daemon. Is the docker daemon running on this host?
So I checked out whether Docker was running:
$ sudo service docker status
● docker.service - Docker Application Container Engine
Loaded: loaded (/lib/systemd/system/docker.service; enabled; vendor preset: enabled)
Active: active (running) since vr 2015-11-06 08:41:48 CET; 15min ago
Docs: https://docs.docker.com
Main PID: 7542 (docker)
CGroup: /system.slice/docker.service
└─7542 /usr/bin/docker daemon -H fd://
nov 06 08:41:47 kramer65-VirtualBox systemd[1]: Starting Docker Application Container Engine...
nov 06 08:41:47 kramer65-VirtualBox docker[7542]: time=""2015-11-06T08:41:47.900410966+01:00"" level=info msg=""API ...ock""
nov 06 08:41:48 kramer65-VirtualBox docker[7542]: time=""2015-11-06T08:41:48.033514149+01:00"" level=info msg=""Fire...lse""
nov 06 08:41:48 kramer65-VirtualBox docker[7542]: time=""2015-11-06T08:41:48.141594321+01:00"" level=info msg=""Defa...ess""
nov 06 08:41:48 kramer65-VirtualBox docker[7542]: time=""2015-11-06T08:41:48.416294436+01:00"" level=warning msg=""Y...it.""
nov 06 08:41:48 kramer65-VirtualBox docker[7542]: time=""2015-11-06T08:41:48.565507576+01:00"" level=info msg=""Load...rt.""
nov 06 08:41:48 kramer65-VirtualBox docker[7542]: time=""2015-11-06T08:41:48.567907022+01:00"" level=info msg=""Load...ne.""
nov 06 08:41:48 kramer65-VirtualBox docker[7542]: time=""2015-11-06T08:41:48.567945214+01:00"" level=info msg=""Daem...ion""
nov 06 08:41:48 kramer65-VirtualBox docker[7542]: time=""2015-11-06T08:41:48.567969891+01:00"" level=info msg=""Dock....9.0
nov 06 08:41:48 kramer65-VirtualBox systemd[1]: Started Docker Application Container Engine.
Hint: Some lines were ellipsized, use -l to show in full.
This suggests that the Docker daemon is actually already running, but to be sure I just started the Docker daemon manually:
$ sudo docker daemon
INFO[0000] API listen on /var/run/docker.sock
INFO[0000] [graphdriver] using prior storage driver ""aufs""
INFO[0000] Firewalld running: false
INFO[0000] Default bridge (docker0) is assigned with an IP address XXX.XX.X.X/XX. Daemon option --bip can be used to set a preferred IP address
WARN[0000] Your kernel does not support swap memory limit.
INFO[0000] Loading containers: start.
INFO[0000] Loading containers: done.
INFO[0000] Daemon has completed initialization
INFO[0000] Docker daemon commit=76d6bc9 execdriver=native-0.2 graphdriver=aufs version=1.9.0
I then tried running the image again, but with the same result:
$ docker run --name mynginx1 -P -d nginx
Cannot connect to the Docker daemon. Is the docker daemon running on this host?
I tried sudo'ing the command, but to no avail. What am I doing wrong here?
",https://stackoverflow.com/questions/33562109/docker-command-cant-connect-to-docker-daemon,267,306299.0,26.0,,,2015-11-06 08:06:32,2023-10-04 21:58:49,2017-03-11 10:22:37,,,linux;ubuntu;docker;daemon,kramer65,54777,1650012,registered,true,33782459,,CC BY-SA 3.0,2017-06-21 01:00:33,3412,3099,4,2,0,4,true,false,false,true,true,true,49,7,false,0.085,0.0009,4033,2015,11,8,Friday,false,false,false,false,false,false,false
35689628,Starting a shell in the Docker Alpine container,"To start an interactive shell for the Ubuntu image we can run:
ole@T:~$ docker run -it --rm ubuntu
root@1a6721e1fb64:/# ls
bin boot dev etc home lib lib64 media mnt opt proc root run sbin srv sys tmp usr var
But when this is run for the Alpine Docker image, the following results:
ole@T:~$ docker run -it --rm alpine
Error response from daemon: No command specified
What is the command for starting an interactive shell in an Alpine base container?
",https://stackoverflow.com/questions/35689628/starting-a-shell-in-the-docker-alpine-container,266,351987.0,4.0,,,2016-02-28 23:28:46,2020-03-19 20:20:07,2018-08-07 12:29:06,,,linux;docker;containers;alpine-linux,Ole,48560,1684269,registered,true,35689633,,CC BY-SA 4.0,,606,473,2,1,0,4,true,false,false,true,true,true,47,8,false,0.011,0.0008,3919,2016,2,23,Sunday,true,false,false,false,false,false,false
34051747,Get Environment Variable from Docker Container,"What's the simplest way to get an environment variable from a docker container that has not been declared in the Dockerfile?
For instance, an environment variable that has been set through some docker exec container /bin/bash session?
I can do docker exec container env | grep ENV_VAR, but I would prefer something that just returns the value.
I've tried using docker exec container echo ""$ENV_VAR"", but the substitution seems to happen outside of the container, so I don't get the env var from the container, but rather the env var from my own computer.
Thanks.
",https://stackoverflow.com/questions/34051747/get-environment-variable-from-docker-container,265,456486.0,12.0,,,2015-12-02 19:51:30,2022-07-20 17:16:37,2015-12-02 19:59:30,,,bash;docker;environment-variables,Citronen,4630,4463660,registered,true,34052766,,CC BY-SA 3.0,,650,567,3,0,0,3,true,false,false,true,true,true,46,6,false,0.026,0.0006,4007,2015,12,19,Wednesday,false,false,false,false,false,false,false
24225647,Docker - a way to give access to a host USB or serial device?,"Last time I checked, Docker didn't have any means to give container access to host serial or USB port. Is there a trick which allows doing that?
",https://stackoverflow.com/questions/24225647/docker-a-way-to-give-access-to-a-host-usb-or-serial-device,264,539499.0,11.0,,,2014-06-15 00:56:48,2022-04-25 00:22:59,2018-08-14 17:00:17,,,docker,galets,18750,14395,registered,true,24231872,,CC BY-SA 4.0,,206,145,0,1,0,1,true,false,false,true,true,true,61,14,true,0.02,0.0005,4542,2014,6,0,Sunday,true,false,false,false,false,false,false
18861834,Mounting multiple volumes on a docker container?,"I know I can mount a directory in my host on my container using something like
docker run -t -i -v '/on/my/host:/on/the/container' ubuntu /bin/bash
Is there a way to create more than one host-container pair? e.g. a comma-separated list, or pass in an array?
",https://stackoverflow.com/questions/18861834/mounting-multiple-volumes-on-a-docker-container,264,261694.0,8.0,,,2013-09-18 00:04:21,2024-04-12 13:30:18,,,,docker,Seldo,6073,604777,registered,true,,,CC BY-SA 3.0,,299,261,1,0,0,1,false,false,false,true,true,false,48,7,true,0.031,0.001,4812,2013,9,0,Wednesday,false,false,false,false,false,false,false
35122773,single command to stop and remove docker container,"Is there any command which can combine the docker stop and docker rm command together ? Each time I want to delete a running container, I need to execute 2 commands sequentially, I wonder if there is a combined command can simplify this process.
docker stop CONTAINER_ID
docker rm CONTATINER_ID
",https://stackoverflow.com/questions/35122773/single-command-to-stop-and-remove-docker-container,263,195144.0,12.0,,,2016-02-01 03:53:59,2026-02-11 20:48:50,,,,docker,mainframer,22749,4258008,registered,true,35122815,,CC BY-SA 3.0,2018-08-14 10:11:53,354,297,3,0,0,1,true,false,false,true,true,false,50,8,false,0.061,0.0013,3946,2016,2,3,Monday,false,false,false,false,false,false,false
33816456,How to tag docker image with docker-compose,"I want to build image via docker-compose and set specific tag to it. Documentation says:
Compose will build and tag it with a generated name, and use that
image thereafter.
But I can't find a way to specify tag and for built images I always see 'latest' tag.
",https://stackoverflow.com/questions/33816456/how-to-tag-docker-image-with-docker-compose,263,343610.0,9.0,,,2015-11-19 23:43:25,2024-04-13 02:15:04,2024-04-13 02:15:04,,,docker;docker-compose,4ybaka,3364,2639744,registered,true,37574953,,CC BY-SA 4.0,,379,268,0,1,0,2,true,false,false,true,true,true,43,7,false,0.026,0.0008,4020,2015,11,23,Thursday,false,false,false,false,false,false,false
32073971,Stopping Docker containers by image name - Ubuntu,"On Ubuntu 14.04 (Trusty Tahr) I'm looking for a way to stop a running container and the only information I have is the image name that was used in the Docker run command.
Is there a command to find all the matching running containers that match that image name and stop them?
",https://stackoverflow.com/questions/32073971/stopping-docker-containers-by-image-name-ubuntu,262,274196.0,23.0,,,2015-08-18 13:35:17,2024-10-24 21:33:57,2019-05-02 17:53:11,,,docker;ubuntu;docker-image,Collin Estes,5839,20748,registered,true,32074098,,CC BY-SA 4.0,,298,284,0,0,0,3,true,false,false,true,true,true,49,8,false,0.084,0.001,4113,2015,8,13,Tuesday,false,false,false,false,false,false,false
31528384,Conditional COPY/ADD in Dockerfile?,"Inside of my Dockerfiles I would like to COPY a file into my image if it exists, the requirements.txt file for pip seems like a good candidate but how would this be achieved?
COPY (requirements.txt if test -e requirements.txt; fi) /destination
...
RUN if test -e requirements.txt; then pip install -r requirements.txt; fi
or
if test -e requirements.txt; then
COPY requiements.txt /destination;
fi
RUN if test -e requirements.txt; then pip install -r requirements.txt; fi
",https://stackoverflow.com/questions/31528384/conditional-copy-add-in-dockerfile,262,238258.0,10.0,,,2015-07-21 00:16:51,2025-04-17 23:05:37,2018-06-20 18:09:12,,,docker;dockerfile,derrend,4778,3335799,registered,true,31532674,,CC BY-SA 4.0,,544,482,2,0,0,2,true,false,false,true,true,true,35,4,true,0.042,0.0011,4141,2015,7,0,Tuesday,false,false,false,false,false,false,false
35110146,What is the purpose of the file "docker.sock"?,"I am trying to understand the actual reason for mounting docker.sock in docker-compose.yml file. Is it for auto-discovery?
volumes:
- /var/run/docker.sock:/var/run/docker.sock
",https://stackoverflow.com/questions/35110146/what-is-the-purpose-of-the-file-docker-sock,262,201415.0,4.0,,,2016-01-31 03:55:18,2025-12-01 03:05:50,2023-05-17 13:49:55,2025-12-01 11:15:49,Not suitable for this site,docker;docker-compose,uzubair,2641,3633016,registered,true,,,,,238,181,3,0,0,2,false,true,false,true,true,true,56,8,true,0.02,0.0013,3947,2016,1,3,Sunday,true,false,false,false,false,false,false
44346109,How to easily install and uninstall Docker on macOS,"How to easily install Docker to have it available in terminal and how to uninstall Docker on macOS?
",https://stackoverflow.com/questions/44346109/how-to-easily-install-and-uninstall-docker-on-macos,261,439818.0,6.0,,,2017-06-03 16:25:17,2025-07-08 16:03:24,2025-05-12 22:06:06,,,macos;docker,Kamil Kiełczewski,94175,860099,registered,true,45595502,,CC BY-SA 4.0,,107,100,0,0,0,2,true,false,false,true,true,true,51,9,false,0.014,0.0006,3458,2017,6,16,Saturday,true,false,false,false,false,false,false
39175194,Docker-Compose persistent data MySQL,"I can't seem to get MySQL data to persist if I run $ docker-compose down with the following .yml
version: '2'
services:
# other services
data:
container_name: flask_data
image: mysql:latest
volumes:
- /var/lib/mysql
command: ""true""
mysql:
container_name: flask_mysql
restart: always
image: mysql:latest
environment:
MYSQL_ROOT_PASSWORD: 'test_pass' # TODO: Change this
MYSQL_USER: 'test'
MYSQL_PASS: 'pass'
volumes_from:
- data
ports:
- ""3306:3306""
My understanding is that in my data container using volumes: - /var/lib/mysql maps it to my local machines directory where mysql stores data to the container and because of this mapping the data should persist even if the containers are destroyed. And the mysql container is just a client interface into the db and can see the local directory because of volumes_from: - data
Attempted this answer and it did not work. Docker-Compose Persistent Data Trouble
EDIT
Changed my .yml as shown below and created a the dir ./data but now when I run docker-compose up --build the mysql container wont start throws error saying
data:
container_name: flask_data
image: mysql:latest
volumes:
- ./data:/var/lib/mysql
command: ""true""
mysql:
container_name: flask_mysql
restart: always
image: mysql:latest
environment:
MYSQL_ROOT_PASSWORD: 'test_pass' # TODO: Change this
MYSQL_USER: 'test'
MYSQL_PASS: 'pass'
volumes_from:
- data
ports:
- ""3306:3306""
flask_mysql | mysqld: Can't create/write to file '/var/lib/mysql/is_writable' (Errcode: 13 - Permission denied)
flask_mysql | 2016-08-26T22:29:21.182144Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
flask_mysql | 2016-08-26T22:29:21.185392Z 0 [ERROR] --initialize specified but the data directory exists and is not writable. Aborting.
",https://stackoverflow.com/questions/39175194/docker-compose-persistent-data-mysql,261,382950.0,8.0,,,2016-08-26 22:00:50,2023-04-25 11:48:25,2017-05-23 12:10:27,,,docker;docker-compose,Adam,4202,3990806,registered,true,39208187,,CC BY-SA 3.0,,2341,2013,12,1,0,2,true,false,false,true,true,true,36,4,false,0.021,0.0007,3739,2016,8,22,Friday,false,false,false,false,false,false,false
37904682,How do I use Docker environment variable in ENTRYPOINT array?,"If I set an environment variable, say ENV ADDRESSEE=world, and I want to use it in the entry point script concatenated into a fixed string like:
ENTRYPOINT [""./greeting"", ""--message"", ""Hello, world!""]
with world being the value of the environment varible, how do I do it? I tried using ""Hello, $ADDRESSEE"" but that doesn't seem to work, as it takes the $ADDRESSEE literally.
",https://stackoverflow.com/questions/37904682/how-do-i-use-docker-environment-variable-in-entrypoint-array,260,265180.0,12.0,,,2016-06-19 06:49:35,2024-10-01 09:17:00,,,,docker;dockerfile,Psycho Punch,6982,404604,registered,true,37904830,,CC BY-SA 3.0,,468,378,5,0,0,2,true,false,false,true,true,false,61,10,true,0.045,0.001,3807,2016,6,6,Sunday,true,false,false,false,false,false,false
49726272,What is the '--rm' flag doing?,"I am trying Docker for the first time and do not yet have a "mental model". Total beginner.
All the examples that I am looking at have included the --rm flag to run, such as
docker run -it --rm ...
docker container run -it --rm ...
Question:
Why do these commands include the --rm flag? I would think that if I were to go through the trouble of setting up or downloading a container with the good stuff in it, why remove it? I want to keep it to use again.
So, I know I have the wrong idea of Docker.
",https://stackoverflow.com/questions/49726272/what-is-the-rm-flag-doing,260,222749.0,7.0,,,2018-04-09 05:43:42,2025-07-04 05:22:43,2021-06-30 07:58:51,,,docker;docker-container,matchingmoments,2825,9617731,registered,true,49726371,,CC BY-SA 4.0,,614,512,3,0,0,2,true,false,false,true,true,true,38,6,true,0.031,0.0012,3148,2018,4,5,Monday,false,false,false,false,false,false,false
31676155,Docker error response from daemon: "Conflict ... already in use by container","I've been using Docker on my PC to run Quantum GIS with the following instructions I've found here: docker-qgis-desktop - A simple docker container that runs QGIS desktop
Everything has been running fine until last week when I started to get this error message:
Error response from daemon: Conflict.
The name ""qgis-desktop-2-4"" is already in use by container 235566ae17b8.
You have to delete (or rename) that container to be able to reuse that name.
I'm not entirely sure what this means despite searching for clues on this site. I hadn't changed anything prior to this happening and have been successfully launching the container with this command:
sudo docker run --rm --name=""qgis-desktop-2-4"" -i -t -v ${HOME}:/home/${USER} -v /tmp/.X11-unix:/tmp/.X11-unix -e DISPLAY=unix$DISPLAY kartoza/qgis-desktop:latest
How can I fix this?
",https://stackoverflow.com/questions/31676155/docker-error-response-from-daemon-conflict-already-in-use-by-container,259,385261.0,10.0,,,2015-07-28 12:19:43,2024-07-02 13:43:05,2019-12-27 14:36:12,,,linux;ubuntu;docker,marty_c,6609,2609232,registered,true,,,CC BY-SA 4.0,2023-12-12 08:18:33,1052,864,2,1,0,3,false,false,false,true,true,true,87,12,false,0.026,0.0007,4134,2015,7,12,Tuesday,false,false,false,false,false,false,false
41144589,How to redirect docker container logs to a single file?,"I want to redirect all the logs of my docker container to single log file to analyse them. I tried
docker logs container > /tmp/stdout.log 2>/tmp/stderr.log
but this gives log in two different file. I already tried
docker logs container > /tmp/stdout.log
but it did not work.
",https://stackoverflow.com/questions/41144589/how-to-redirect-docker-container-logs-to-a-single-file,258,412403.0,16.0,,,2016-12-14 14:05:18,2025-05-27 10:09:05,2019-09-20 11:15:19,,,logging;docker,KETAN PATIL,2774,6666745,registered,true,41147654,,CC BY-SA 4.0,,362,293,2,0,0,2,true,false,false,true,true,true,55,10,true,0.039,0.0006,3629,2016,12,14,Wednesday,false,false,false,false,false,false,false
29101043,Can't connect to docker from docker-compose,"I installed docker-machine 0.1.0 and docker-compose 1.1.0 on Mac OS 10.8.5.
Docker-machine is running normally and able to connect by docker-machine ssh.
$ docker-machine ls
NAME ACTIVE DRIVER STATE URL SWARM
dev * virtualbox Running tcp://192.168.99.100:2376
However can't connect from docker-compose.
$ docker-compose up
Couldn't connect to Docker daemon at http+unix://var/run/docker.sock - is it running?
If it's at a non-standard location, specify the URL with the DOCKER_HOST environment variable.
My Dockerfile and docker-compose.yml is here.
Dockerfile
FROM centos:centos7
DOCKER_HOST tcp://192.168.99.100:2376
docker-compose.yml
web:
build: .
Why can't connect? Any ideas?
",https://stackoverflow.com/questions/29101043/cant-connect-to-docker-from-docker-compose,256,360258.0,34.0,,,2015-03-17 13:59:56,2022-08-15 00:59:40,2019-05-14 14:31:19,,,docker;docker-compose,DIGITALSQUAD,3534,967351,registered,true,29111083,,CC BY-SA 4.0,2022-03-16 12:51:21,944,761,4,0,0,2,true,false,false,true,true,true,47,6,false,0.094,0.0007,4267,2015,3,13,Tuesday,false,false,false,false,false,false,false
38546755,Docker Compose keep container running,"I want to start a service with docker-compose and keep the container running so I can get its IP-address via 'docker inspect'. However, the container always exits right after starting up.
I tried to add ""command: [""sleep"", ""60""]"" and other things to the docker-compose.yml but whenever I add the line with ""command:..."" I cant call ""docker-compose up"" as I will get the message ""Cannot start container ..... System error: invalid character 'k' looking for beginning of value""
I also tried adding ""CMD sleep 60"" and whatnot to the Dockerfile itself but these commands do not seem to be executed.
Is there an easy way to keep the container alive or to fix one of my problems?
EDIT:
Here is the Compose file I want to run:
version: '2'
services:
my-test:
image: ubuntu
command: bash -c ""while true; do echo hello; sleep 2; done""
It's working fine If I start this with docker-compose under OS X, but if I try the same under Ubuntu 16.04 it gives me above error message.
If I try the approach with the Dockerfile, the Dockerfile looks like this:
FROM ubuntu:latest
CMD [""sleep"", ""60""]
Which does not seem to do anything
EDIT 2:
I have to correct myself, turned out it was the same problem with the Dockerfile and the docker-compose.yml:
Each time I add either ""CMD ..."" to the Dockerfile OR add ""command ..."" to the compose file, I get above error with the invalid character. If I remove both commands, it works flawlessly.
",https://stackoverflow.com/questions/38546755/docker-compose-keep-container-running,254,318661.0,15.0,,,2016-07-23 21:56:20,2023-08-02 10:29:59,2016-12-31 12:13:59,,,docker;docker-compose,dingoglotz,2913,1650286,registered,true,45450456,,CC BY-SA 3.0,,1552,1441,2,0,0,2,true,false,false,true,true,true,37,5,false,0.047,0.0008,3773,2016,7,21,Saturday,true,false,false,false,false,false,false
45023363,What is docker.io in relation to docker-ce and docker-ee (now called "Mirantis Kubernetes Engine")?,"Previously, to install Docker, I would use
apt-get install docker.io
However, I have recently noticed the documentation for installing docker, and it uses docker-ce. I have tried to find the difference between the two, but I have come up empty. What is docker.io in relation to docker-ce?
",https://stackoverflow.com/questions/45023363/what-is-docker-io-in-relation-to-docker-ce-and-docker-ee-now-called-mirantis-k,254,163789.0,4.0,,,2017-07-11 00:00:16,2022-12-15 04:18:28,2022-12-12 23:31:59,2026-05-20 08:36:39,Not suitable for this site,docker;ubuntu;ubuntu-16.04;apt-get,Will Parzybok,3342,7828472,registered,true,45023650,,,,328,290,1,0,0,4,true,true,false,true,true,true,109,14,true,0.024,0.0016,3420,2017,7,0,Tuesday,false,false,false,false,false,false,false
49118579,Alpine Dockerfile advantages of --no-cache vs. rm /var/cache/apk/*,"When creating Dockerfiles using an Alpine image, I have often seen the use of either
apk add --no-cache, or
apk add followed by an rm /var/cache/apk/* statement.
I am curious to know whether making use of the --no-cache flag eliminates the need to manually clear the package cache using rm /var/cache/apk/*. I would also like to know which style is considered best practice.
",https://stackoverflow.com/questions/49118579/alpine-dockerfile-advantages-of-no-cache-vs-rm-var-cache-apk,254,189276.0,3.0,,,2018-03-05 20:06:51,2025-05-14 16:04:20,2023-09-03 23:17:38,,,docker;dockerfile;alpine-linux;alpine-package-keeper,Angel S. Moreno,4216,372875,registered,true,49119046,,CC BY-SA 4.0,,483,377,5,0,0,4,true,false,false,true,true,true,66,8,false,0.016,0.0013,3183,2018,3,20,Monday,false,false,false,false,false,false,false
69552636,Cannot launch docker desktop for mac,"I installed docker desktop for mac for the first time, but i couldn’t launch it.
I installed it as follows.
・Signed up with this official page(https://www.docker.com/get-started) and clicked download button for Mac intel chip.
・Opened Docker.dmg file and dragged and dropped Docker.app into Applications.
・Did a spotlight search for docker and launched it.
・Clicked on the “open” button on the notification screen that says “Docker.app” is an app downloaded from the Internet. Are you sure you want to open it?
No response from the application after this.
Current state
There is a docker app in Applications folder, and Docker in locations(with an eject button).
I cannot launch the app, and use any docker commands.
The other apps work fine and comfortably.
I tried restart my pc, turn off Firewall and FireVault, and installed again, but the exact same thing happened.
I'm on a MacBook Pro 16 (2019) with the latest version of macOS Big Sur 11.6.
",https://stackoverflow.com/questions/69552636/cannot-launch-docker-desktop-for-mac,252,338364.0,32.0,,,2021-10-13 09:04:27,2025-02-17 08:51:57,2023-11-23 14:12:47,2025-03-11 01:29:42,Not suitable for this site,docker,forestbear0110,2529,17141320,registered,true,,,,2024-04-11 20:03:25,1103,950,0,1,0,1,false,true,false,true,true,true,36,6,false,0.095,0.0007,1865,2021,10,9,Wednesday,false,false,false,false,false,false,false
34840137,How do I deploy updated Docker images to Amazon ECS tasks?,"What is the right approach to make my Amazon ECS tasks update their Docker images, once said images have been updated in the corresponding registry?
",https://stackoverflow.com/questions/34840137/how-do-i-deploy-updated-docker-images-to-amazon-ecs-tasks,252,163457.0,12.0,,,2016-01-17 15:36:31,2023-01-05 16:37:32,2016-01-17 15:46:21,,,docker;docker-registry;amazon-ecs,aknuds1,68743,265261,registered,true,34897423,,CC BY-SA 3.0,,242,149,0,1,0,3,true,false,false,true,true,true,58,11,true,0.073,0.0015,3961,2016,1,15,Sunday,true,false,false,false,false,false,false
32046334,Where can I find the sha256 code of a docker image?,"I'd like to pull the images of CentOS, Tomcat, ... using their sha256 code, like in
docker pull myimage@sha256:0ecb2ad60
But I can't find the sha256-code to use anywhere.
I checked the DockerHub repository for any hint of the sha256-code, but couldn't find any. I downloaded the images by their tag
docker pull tomcat:7-jre8
and checked the image with docker inspect to see if there's a sha256 code in the metadata, but there is none (adding the sha256 code of the image would probably change the sha256 code).
Do I have to compute the sha256 code of an image myself and use that?
",https://stackoverflow.com/questions/32046334/where-can-i-find-the-sha256-code-of-a-docker-image,250,331469.0,11.0,,,2015-08-17 08:57:28,2023-05-17 13:25:14,2020-12-29 11:44:45,,,docker;docker-registry,christian,10388,2425939,registered,true,32048857,,CC BY-SA 4.0,,674,582,3,0,0,2,true,false,false,true,true,true,51,11,true,0.033,0.0008,4114,2015,8,8,Monday,false,false,false,false,false,false,false
29145370,How can I initialize a MySQL database with schema in a Docker container?,"I am trying to create a container with a MySQL database and add a schema to these database.
My current Dockerfile is:
FROM mysql
MAINTAINER (me) <email>
# Copy the database schema to the /data directory
COPY files/epcis_schema.sql /data/epcis_schema.sql
# Change the working directory
WORKDIR data
CMD mysql -u $MYSQL_USER -p $MYSQL_PASSWORD $MYSQL_DATABASE < epcis_schema.sql
In order to create the container I am following the documentation provided on Docker and executing this command:
docker run --name ${CONTAINER_NAME} -e MYSQL_ROOT_PASSWORD=${DB_ROOT_PASSWORD} -e MYSQL_USER=${DB_USER} -e MYSQL_PASSWORD=${DB_USER_PASSWORD} -e MYSQL_DATABASE=${DB_NAME} -d mvpgomes/epcisdb
But when I execute this command the Container is not created and in the Container status it is possible to see that the CMD was not executed successfully, in fact only the mysql command is executed.
Anyway, is there a way to initialize the database with the schema or do I need to perform these operations manually?
",https://stackoverflow.com/questions/29145370/how-can-i-initialize-a-mysql-database-with-schema-in-a-docker-container,250,317189.0,12.0,,,2015-03-19 13:04:44,2025-01-12 09:14:56,2017-07-24 12:27:21,,,mysql;docker;database-schema,Marcus Gomes,2724,4096230,registered,true,29150538,,CC BY-SA 3.0,,1114,1018,3,0,0,3,true,false,false,true,true,true,72,13,true,0.038,0.0008,4265,2015,3,13,Thursday,false,false,false,false,false,false,false
28056522,Access host database from a docker container,"If I have a mysql database running on some host machine, and that host is also running a docker container: How would I access the mysql database from within the docker container that is running on the host?.
For instance, is there a way to publish a hosts port to the container (the inverse of what docker run -p does)?
",https://stackoverflow.com/questions/28056522/access-host-database-from-a-docker-container,246,242968.0,8.0,,,2015-01-20 22:45:11,2024-02-05 16:06:10,2022-07-14 12:38:28,,,docker,Ryan Anderson,2532,534254,registered,true,28058549,,CC BY-SA 4.0,,334,320,0,0,0,1,true,false,false,true,true,true,44,7,false,0.033,0.001,4323,2015,1,22,Tuesday,false,false,false,false,false,false,false
32758793,How to show the run command of a docker container,"I use a third party GUI (Synology Docker package) to setup a docker container. However, its limitation makes me need to run the container from the command line. (I want to map another host ip to bind the port)
Now, since there are lots of settings that already done, I would like to retrieve the original run command that start this container, then I can change the port mapping port to new one. eg. "docker run -p 80:8080 gitlab"
I can't find the way to do so, event use "docker inspect", no such information provided.
Please provide some advice to solve this problem.
",https://stackoverflow.com/questions/32758793/how-to-show-the-run-command-of-a-docker-container,245,283601.0,14.0,,,2015-09-24 10:15:04,2026-01-07 13:25:04,2023-04-16 11:31:20,,,docker,Jack Yu,2750,2481563,registered,true,32774347,,CC BY-SA 4.0,,631,590,1,0,0,1,true,false,false,true,true,true,49,10,false,0.049,0.0009,4076,2015,9,10,Thursday,false,false,false,false,false,false,false
57534295,npm ERR! Tracker "idealTree" already exists while creating the Docker image for Node project,"I have created one node.js project called simpleWeb. The project contains package.json and index.js.
index.js
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('How are you doing');
});
app.listen(8080, () => {
console.log('Listening on port 8080');
});
package.json
{
"dependencies": {
"express": "*"
},
"scripts": {
"start": "node index.js"
}
}
I have also created one Dockerfile to create the docker image for my node.js project.
Dockerfile
# Specify a base image
FROM node:alpine
# Install some dependencies
COPY ./ ./
RUN npm install
# Default command
CMD ["npm", "start"]
While I am tried to build the docker image using "docker build ." command it is throwing below error.
Error Logs
simpleweb » docker build . ~/Desktop/jaypal/Docker and Kubernatise/simpleweb
[+] Building 16.9s (8/8) FINISHED
=> [internal] load build definition from Dockerfile 0.0s
=> => transferring dockerfile: 37B 0.0s
=> [internal] load .dockerignore 0.0s
=> => transferring context: 2B 0.0s
=> [internal] load metadata for docker.io/library/node:alpine 8.7s
=> [auth] library/node:pull token for registry-1.docker.io 0.0s
=> [internal] load build context 0.0s
=> => transferring context: 418B 0.0s
=> [1/3] FROM docker.io/library/node:alpine@sha256:5b91260f78485bfd4a1614f1afa9afd59920e4c35047ed1c2b8cde4f239dd79b 0.0s
=> CACHED [2/3] COPY ./ ./ 0.0s
=> ERROR [3/3] RUN npm install 8.0s
------
> [3/3] RUN npm install:
#8 7.958 npm ERR! Tracker "idealTree" already exists
#8 7.969
#8 7.970 npm ERR! A complete log of this run can be found in:
#8 7.970 npm ERR! **/root/.npm/_logs/2020-12-24T16_48_44_443Z-debug.log**
------
executor failed running [/bin/sh -c npm install]: exit code: 1
The log file above it is providing one path "/root/.npm/_logs/2020-12-24T16_48_44_443Z-debug.log" where I can find the full logs.
But, The above file is not present on my local machine.
I don't understand what is the issue.
",https://stackoverflow.com/questions/57534295/npm-err-tracker-idealtree-already-exists-while-creating-the-docker-image-for,245,227832.0,15.0,,,2019-08-17 07:41:18,2024-05-30 02:45:53,2021-04-05 09:43:25,,,docker;dockerfile,Jaypal Sodha,2938,5874233,registered,true,65443098,,CC BY-SA 4.0,2025-08-01 15:52:12,3383,3141,4,0,0,2,true,false,false,true,true,true,102,14,false,0.066,0.0011,2653,2019,8,7,Saturday,true,false,false,false,false,false,false
43721513,How to check if the docker engine and a docker container are running?,"In a script, I need to check:
a) Is the docker engine running?
b) Given a container name, is that docker container running?
",https://stackoverflow.com/questions/43721513/how-to-check-if-the-docker-engine-and-a-docker-container-are-running,245,714350.0,20.0,,,2017-05-01 15:19:50,2023-05-13 10:05:56,2023-04-21 13:32:33,,,bash;docker,user5517392,2469,5517392,registered,true,,,CC BY-SA 4.0,2021-01-29 18:10:32,144,124,0,0,0,2,false,false,false,true,true,true,69,13,true,0.028,0.0003,3491,2017,5,15,Monday,false,false,false,false,false,false,false
34724980,Finding a string in docker logs of container,"What is the best way to find a specific string in the logs of a docker container? Let's say I want to see all requests, that are made in the ""nginx"" docker image that came from a ip starting with ""127.""
grep wont work as expected on docker logs command:
docker logs nginx | grep ""127.""
It prints all logs, but does not filter the result!
",https://stackoverflow.com/questions/34724980/finding-a-string-in-docker-logs-of-container,245,269977.0,12.0,,,2016-01-11 15:19:43,2024-06-19 09:31:00,2019-07-02 13:24:56,,,docker;grep,Gering,3740,599186,registered,true,38207098,,CC BY-SA 4.0,,387,342,1,0,0,2,true,false,false,true,true,true,44,8,false,0.044,0.0009,3967,2016,1,15,Monday,false,false,false,false,false,false,false
25305788,How to avoid reinstalling packages when building Docker image for Python projects?,"My Dockerfile is something like
FROM my/base
ADD . /srv
RUN pip install -r requirements.txt
RUN python setup.py install
ENTRYPOINT ["run_server"]
Every time I build a new image, dependencies have to be reinstalled, which could be very slow in my region.
One way I think of to cache packages that have been installed is to override the my/base image with newer images like this:
docker build -t new_image_1 .
docker tag new_image_1 my/base
So next time I build with this Dockerfile, my/base already has some packages installed.
But this solution has two problems:
- It is not always possible to override a base image
- The base image grow bigger and bigger as newer images are layered on it
So what better solution could I use to solve this problem?
EDIT:
Some information about the docker on my machine:
☁ test docker version
Client version: 1.1.2
Client API version: 1.13
Go version (client): go1.2.1
Git commit (client): d84a070
Server version: 1.1.2
Server API version: 1.13
Go version (server): go1.2.1
Git commit (server): d84a070
☁ test docker info
Containers: 0
Images: 56
Storage Driver: aufs
Root Dir: /var/lib/docker/aufs
Dirs: 56
Execution Driver: native-0.2
Kernel Version: 3.13.0-29-generic
WARNING: No swap limit support
",https://stackoverflow.com/questions/25305788/how-to-avoid-reinstalling-packages-when-building-docker-image-for-python-project,245,140264.0,6.0,,,2014-08-14 10:25:20,2023-08-02 11:53:55,2021-02-04 18:06:32,,,python;docker,satoru,33515,225262,registered,true,25307587,,CC BY-SA 4.0,,1437,1254,5,0,0,2,true,false,false,true,true,true,82,12,true,0.043,0.0017,4482,2014,8,10,Thursday,false,true,false,false,false,false,false
34496882,Get Docker container id from container name,"What is the command to get the Docker container id from the container name?
",https://stackoverflow.com/questions/34496882/get-docker-container-id-from-container-name,244,348651.0,15.0,,,2015-12-28 16:14:38,2025-08-07 14:04:15,2022-01-13 23:53:42,,,docker,Dimitri Kopriwa,14876,2127277,registered,true,34497614,,CC BY-SA 4.0,,117,76,0,0,0,1,true,false,false,true,true,true,43,7,false,0.043,0.0007,3981,2015,12,16,Monday,false,false,false,false,false,false,false
38532483,Where is /var/lib/docker on Mac/OS X,"I´m looking for the folder /var/lib/docker on my Mac after installing docker for Mac.
With docker info I get
Containers: 5
...
Server Version: 1.12.0-rc4
Storage Driver: aufs
Root Dir: /var/lib/docker/aufs
Backing Filesystem: extfs
Dirs: 339
Dirperm1 Supported: true
...
Name: moby
ID: LUOU:5UHI:JFNI:OQFT:BLKR:YJIC:HHE5:W4LP:YHVP:TT3V:4CB2:6TUS
Docker Root Dir: /var/lib/docker
Debug Mode (client): false
....
But I don´t have a directory /var/lib/docker on my host.
I have checked /Users/myuser/Library/Containers/com.docker.docker/ but couldn´t find anything there. Any idea where it is located?
",https://stackoverflow.com/questions/38532483/where-is-var-lib-docker-on-mac-os-x,244,149870.0,14.0,,,2016-07-22 17:44:39,2024-12-17 06:13:12,2019-11-28 01:21:04,,,macos;docker;docker-for-mac,christian,10388,2425939,registered,true,39287126,,CC BY-SA 4.0,2019-06-27 17:18:59,770,666,5,0,0,3,true,false,false,true,true,true,36,6,false,0.093,0.0016,3774,2016,7,17,Friday,false,false,false,false,false,false,false
22651647,Docker and securing passwords,"I've been experimenting with Docker recently on building some services to play around with and one thing that keeps nagging me has been putting passwords in a Dockerfile. I'm a developer so storing passwords in source feels like a punch in the face. Should this even be a concern? Are there any good conventions on how to handle passwords in Dockerfiles?
",https://stackoverflow.com/questions/22651647/docker-and-securing-passwords,244,226715.0,15.0,,,2014-03-26 04:42:33,2025-01-16 22:50:30,2014-09-06 09:02:56,2025-01-17 20:24:58,Opinion-based,security;build;docker,anthonator,5219,189347,registered,true,22652670,,,,362,355,0,0,0,3,true,true,false,true,true,true,29,4,false,0.066,0.0011,4623,2014,3,4,Wednesday,false,false,false,false,false,false,false