qid,question,date,metadata,response_j,response_k 3926936,"I have a directory of 9 images: ``` image_0001, image_0002, image_0003 image_0010, image_0011 image_0011-1, image_0011-2, image_0011-3 image_9999 ``` I would like to be able to list them in an efficient way, like this (4 entries for 9 images): ``` (image_000[1-3], image_00[10-11], image_0011-[1-3], image_9999) ``` Is there a way in python, to return a directory of images, in a short/clear way (without listing every file)? So, possibly something like this: list all images, sort numerically, create a list (counting each image in sequence from start). When an image is missing (create a new list), continue until original file list is finished. Now I should just have some lists that contain non broken sequences. I'm trying to make it easy to read/describe a list of numbers. If I had a sequence of 1000 consecutive files It could be clearly listed as file[0001-1000] rather than file['0001','0002','0003' etc...] **Edit1**(based on suggestion): Given a flattened list, how would you derive the glob patterns? **Edit2** I'm trying to break the problem down into smaller pieces. Here is an example of part of the solution: data1 works, data2 returns 0010 as 64, data3 (the realworld data) doesn't work: ``` # Find runs of consecutive numbers using groupby. The key to the solution # is differencing with a range so that consecutive numbers all appear in # same group. from operator import itemgetter from itertools import * data1=[01,02,03,10,11,100,9999] data2=[0001,0002,0003,0010,0011,0100,9999] data3=['image_0001','image_0002','image_0003','image_0010','image_0011','image_0011-2','image_0011-3','image_0100','image_9999'] list1 = [] for k, g in groupby(enumerate(data1), lambda (i,x):i-x): list1.append(map(itemgetter(1), g)) print 'data1' print list1 list2 = [] for k, g in groupby(enumerate(data2), lambda (i,x):i-x): list2.append(map(itemgetter(1), g)) print '\ndata2' print list2 ``` returns: ``` data1 [[1, 2, 3], [10, 11], [100], [9999]] data2 [[1, 2, 3], [8, 9], [64], [9999]] ```",2010/10/13,"['https://Stackoverflow.com/questions/3926936', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/178686/']","Here is a working implementation of what you want to achieve, using the code you added as a starting point: ``` #!/usr/bin/env python import itertools import re # This algorithm only works if DATA is sorted. DATA = [""image_0001"", ""image_0002"", ""image_0003"", ""image_0010"", ""image_0011"", ""image_0011-1"", ""image_0011-2"", ""image_0011-3"", ""image_0100"", ""image_9999""] def extract_number(name): # Match the last number in the name and return it as a string, # including leading zeroes (that's important for formatting below). return re.findall(r""\d+$"", name)[0] def collapse_group(group): if len(group) == 1: return group[0][1] # Unique names collapse to themselves. first = extract_number(group[0][1]) # Fetch range last = extract_number(group[-1][1]) # of this group. # Cheap way to compute the string length of the upper bound, # discarding leading zeroes. length = len(str(int(last))) # Now we have the length of the variable part of the names, # the rest is only formatting. return ""%s[%s-%s]"" % (group[0][1][:-length], first[-length:], last[-length:]) groups = [collapse_group(tuple(group)) \ for key, group in itertools.groupby(enumerate(DATA), lambda(index, name): index - int(extract_number(name)))] print groups ``` This prints `['image_000[1-3]', 'image_00[10-11]', 'image_0011-[1-3]', 'image_0100', 'image_9999']`, which is what you want. **HISTORY:** I initially answered the question backwards, as @Mark Ransom pointed out below. For the sake of history, my original answer was: You're looking for [glob](http://docs.python.org/library/glob.html). Try: ``` import glob images = glob.glob(""image_[0-9]*"") ``` Or, using your example: ``` images = [glob.glob(pattern) for pattern in (""image_000[1-3]*"", ""image_00[10-11]*"", ""image_0011-[1-3]*"", ""image_9999*"")] images = [image for seq in images for image in seq] # flatten the list ```","``` def ranges(sorted_list): first = None for x in sorted_list: if first is None: first = last = x elif x == increment(last): last = x else: yield first, last first = last = x if first is not None: yield first, last ``` The `increment` function is left as an exercise for the reader. **Edit:** here's an example of how it would be used with integers instead of strings as input. ``` def increment(x): return x+1 list(ranges([1,2,3,4,6,7,8,10])) [(1, 4), (6, 8), (10, 10)] ``` For each contiguous range in the input you get a pair indicating the start and end of the range. If an element isn't part of a range, the start and end values are identical." 3926936,"I have a directory of 9 images: ``` image_0001, image_0002, image_0003 image_0010, image_0011 image_0011-1, image_0011-2, image_0011-3 image_9999 ``` I would like to be able to list them in an efficient way, like this (4 entries for 9 images): ``` (image_000[1-3], image_00[10-11], image_0011-[1-3], image_9999) ``` Is there a way in python, to return a directory of images, in a short/clear way (without listing every file)? So, possibly something like this: list all images, sort numerically, create a list (counting each image in sequence from start). When an image is missing (create a new list), continue until original file list is finished. Now I should just have some lists that contain non broken sequences. I'm trying to make it easy to read/describe a list of numbers. If I had a sequence of 1000 consecutive files It could be clearly listed as file[0001-1000] rather than file['0001','0002','0003' etc...] **Edit1**(based on suggestion): Given a flattened list, how would you derive the glob patterns? **Edit2** I'm trying to break the problem down into smaller pieces. Here is an example of part of the solution: data1 works, data2 returns 0010 as 64, data3 (the realworld data) doesn't work: ``` # Find runs of consecutive numbers using groupby. The key to the solution # is differencing with a range so that consecutive numbers all appear in # same group. from operator import itemgetter from itertools import * data1=[01,02,03,10,11,100,9999] data2=[0001,0002,0003,0010,0011,0100,9999] data3=['image_0001','image_0002','image_0003','image_0010','image_0011','image_0011-2','image_0011-3','image_0100','image_9999'] list1 = [] for k, g in groupby(enumerate(data1), lambda (i,x):i-x): list1.append(map(itemgetter(1), g)) print 'data1' print list1 list2 = [] for k, g in groupby(enumerate(data2), lambda (i,x):i-x): list2.append(map(itemgetter(1), g)) print '\ndata2' print list2 ``` returns: ``` data1 [[1, 2, 3], [10, 11], [100], [9999]] data2 [[1, 2, 3], [8, 9], [64], [9999]] ```",2010/10/13,"['https://Stackoverflow.com/questions/3926936', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/178686/']","Here is a working implementation of what you want to achieve, using the code you added as a starting point: ``` #!/usr/bin/env python import itertools import re # This algorithm only works if DATA is sorted. DATA = [""image_0001"", ""image_0002"", ""image_0003"", ""image_0010"", ""image_0011"", ""image_0011-1"", ""image_0011-2"", ""image_0011-3"", ""image_0100"", ""image_9999""] def extract_number(name): # Match the last number in the name and return it as a string, # including leading zeroes (that's important for formatting below). return re.findall(r""\d+$"", name)[0] def collapse_group(group): if len(group) == 1: return group[0][1] # Unique names collapse to themselves. first = extract_number(group[0][1]) # Fetch range last = extract_number(group[-1][1]) # of this group. # Cheap way to compute the string length of the upper bound, # discarding leading zeroes. length = len(str(int(last))) # Now we have the length of the variable part of the names, # the rest is only formatting. return ""%s[%s-%s]"" % (group[0][1][:-length], first[-length:], last[-length:]) groups = [collapse_group(tuple(group)) \ for key, group in itertools.groupby(enumerate(DATA), lambda(index, name): index - int(extract_number(name)))] print groups ``` This prints `['image_000[1-3]', 'image_00[10-11]', 'image_0011-[1-3]', 'image_0100', 'image_9999']`, which is what you want. **HISTORY:** I initially answered the question backwards, as @Mark Ransom pointed out below. For the sake of history, my original answer was: You're looking for [glob](http://docs.python.org/library/glob.html). Try: ``` import glob images = glob.glob(""image_[0-9]*"") ``` Or, using your example: ``` images = [glob.glob(pattern) for pattern in (""image_000[1-3]*"", ""image_00[10-11]*"", ""image_0011-[1-3]*"", ""image_9999*"")] images = [image for seq in images for image in seq] # flatten the list ```","Okay, so I found your question to be a fascinating puzzle. I've left how to ""compress"" the numeric ranges up to you (marked as a TODO), as there are different ways to accomplish that depending on how you like it formatted and if you want the minimum number of elements or the minimum string description length. This solution uses a simple regular expression (digit strings) to classify each string into two groups: static and variable. After the data is classified, I use groupby to collect the static data into longest matching groups to achieve the summary effect. I mix integer index sentinals into the result (in matchGrouper) so I can re-select the varying parts from all elements (in unpack). ``` import re import glob from itertools import groupby from operator import itemgetter def classifyGroups(iterable, reObj=re.compile('\d+')): """"""Yields successive match lists, where each item in the list is either static text content, or a list of matching values. * `iterable` is a list of strings, such as glob('images/*') * `reObj` is a compiled regular expression that describes the variable section of the iterable you want to match and classify """""" def classify(text, pos=0): """"""Use a regular expression object to split the text into match and non-match sections"""""" r = [] for m in reObj.finditer(text, pos): m0 = m.start() r.append((False, text[pos:m0])) pos = m.end() r.append((True, text[m0:pos])) r.append((False, text[pos:])) return r def matchGrouper(each): """"""Returns index of matches or origional text for non-matches"""""" return [(i if t else v) for i,(t,v) in enumerate(each)] def unpack(k,matches): """"""If the key is an integer, unpack the value array from matches"""""" if isinstance(k, int): k = [m[k][1] for m in matches] return k # classify each item into matches matchLists = (classify(t) for t in iterable) # group the matches by their static content for key, matches in groupby(matchLists, matchGrouper): matches = list(matches) # Yield a list of content matches. Each entry is either text # from static content, or a list of matches yield [unpack(k, matches) for k in key] ``` Finally, we add enough logic to perform pretty printing of the output, and run an example. ``` def makeResultPretty(res): """"""Formats data somewhat like the question"""""" r = [] for e in res: if isinstance(e, list): # TODO: collapse and simplify ranges as desired here if len(set(e))<=1: # it's a list of the same element e = e[0] else: # prettify the list e = '['+' '.join(e)+']' r.append(e) return ''.join(r) fnList = sorted(glob.glob('images/*')) re_digits = re.compile(r'\d+') for res in classifyGroups(fnList, re_digits): print makeResultPretty(res) ``` My directory of images was created from your example. You can replace fnList with the following list for testing: ``` fnList = [ 'images/image_0001.jpg', 'images/image_0002.jpg', 'images/image_0003.jpg', 'images/image_0010.jpg', 'images/image_0011-1.jpg', 'images/image_0011-2.jpg', 'images/image_0011-3.jpg', 'images/image_0011.jpg', 'images/image_9999.jpg'] ``` And when I run against this directory, my output looks like: ``` StackOverflow/3926936% python classify.py images/image_[0001 0002 0003 0010].jpg images/image_0011-[1 2 3].jpg images/image_[0011 9999].jpg ```" 373831,"I need to center the title of the parts in the toc. I'm trying these two approaches: ``` \documentclass{article} \usepackage{hyperref} \usepackage{tocloft} \cftpagenumbersoff{part} \begin{document} \tableofcontents \addcontentsline{toc}{part}{\centerline{Part A}} \addcontentsline{toc}{section}{Section A} \addcontentsline{toc}{part}{\hfill{Part B}\hfill} \addcontentsline{toc}{section}{Section B} \end{document} ``` When the PDF is generated, the bookmarks have some of problems: 1. Part A appears in the bookmarks as ""toPart A"". 2. Part B appears hierarchically under Section A. 3. Part B appears correctly in the bookmarks, but it's not correctly centered in the page. What can I do to solve this problem? Thank you!",2017/06/07,"['https://tex.stackexchange.com/questions/373831', 'https://tex.stackexchange.com', 'https://tex.stackexchange.com/users/134459/']","You need to expand the number when you define \parttitle: ``` \documentclass[11pt, oneside, a4paper]{memoir} \usepackage{lipsum} \newcounter{DocPart} \setcounter{DocPart}{0} \newcommand{\pageNumber}{} \newcommand{\parttitle}{} \renewcommand{\part}[1]{% \ifnum\theDocPart = 0 \renewcommand{\parttitle}{A. #1} \renewcommand{\pageNumber}{A.\thepage} \cftaddtitleline{toc}{part}{A. #1}{} \else \edef\parttitle{A\theDocPart. #1}%<---- \edef\pageNumber{A\theDocPart.\noexpand\thepage}%<----- \cftaddtitleline{toc}{part}{A\theDocPart. #1}{} \fi \stepcounter{DocPart} } \makepagestyle{test} \makeoddhead{test}{\pageNumber}{}{\parttitle} \pagestyle{test} \begin{document} \part{PART NUMBER ZERO} % I want this to say A. PART NUMBER ZERO in the header, which it does \chapter{FAKE CHAPTER ONE} \theDocPart \thispagestyle{test} \lipsum[88] \chapter{FAKE CHAPTER TWO} \thispagestyle{test} \lipsum[120] \newpage \tableofcontents* \part{PART NUMBER ONE} % I want this to say A1. PART NUMBER ONE in the header \chapter{FAKE CHAPTER TWO} \thispagestyle{test} \lipsum \part{PART NUMBER TWO} % I want this to say A2. PART NUMBER TWO in the header \chapter{FAKE CHAPTER THREE} \thispagestyle{test} \lipsum \end{document} ```","The setting of the header is as far as I know asynchronous. However, expanding the `\theDocPart` in `\pageNumber` and `\parttitle` does work: ``` \documentclass[11pt, oneside, a4paper]{memoir} \usepackage{lipsum} \newcounter{DocPart} \setcounter{DocPart}{0} \newcommand{\pageNumber}{} \newcommand{\parttitle}{} \renewcommand{\part}[1]{ \ifnum\theDocPart = 0 \renewcommand{\parttitle}{A. #1} \renewcommand{\pageNumber}{A.\thepage} \cftaddtitleline{toc}{part}{A. #1}{} \else \xdef\parttitle{A\theDocPart. #1} \xdef\pageNumber{A\theDocPart.\noexpand\thepage} \cftaddtitleline{toc}{part}{A\theDocPart. #1}{} \fi \stepcounter{DocPart} } \makepagestyle{test} \makeoddhead{test}{\pageNumber}{}{\parttitle} \pagestyle{test} \begin{document} \part{PART NUMBER ZERO} % I want this to say A. PART NUMBER ZERO in the header, which it does \chapter{FAKE CHAPTER ONE} \thispagestyle{test} \lipsum[88] \chapter{FAKE CHAPTER TWO} \thispagestyle{test} \lipsum[120] \newpage \tableofcontents* \part{PART NUMBER ONE} % I want this to say A1. PART NUMBER ONE in the header \chapter{FAKE CHAPTER TWO} \thispagestyle{test} \lipsum \part{PART NUMBER TWO} % I want this to say A2. PART NUMBER TWO in the header \chapter{FAKE CHAPTER THREE} \thispagestyle{test} \lipsum \end{document} ```" 66189992,"If this doesnt make sense, let me show you an example. Right now, I am trying to evaluate a postfix expression. I have done everything needed, but there is one problem. When I have single digits in the expression, everything works fine. This is because during my code, I had to get rid of all spaces. For example, the postfix expression `2 1 + 3 *` evaluates to `9`. But when I have the postfix expression `4 13 5 / +` , the evaluated expression is incorrect. This is because when I got rid of all the spaces in that expression, the number 13 becomes seperated into two numbers. (1 and 3) I do not want that to happen, but I cannot figure out how to fix this error! `Input = 4 13 5 / +` `Output = 2` The output should be `6`. I am using the `.replace("" "", """")` method. How do I fix this? Here is an example of my code. ``` from __future__ import division import random formula = input() formula = formula.replace("" "", """") OPERATORS = set(['+', '-', '*', '/', '(', ')']) PRIORITY = {'+':1, '-':1, '*':2, '/':2} stack = [] prev_op = None for ch in formula: if not ch in OPERATORS: stack.append(ch) else: b = stack.pop() a = stack.pop() if ch == ""+"": output = int(b)+int(a) if ch == ""-"": output = int(b)-int(a) if ch == ""*"": output = int(b)*int(a) if ch == ""/"": output = int(b)/int(a) stack.append(output) print(output) ```",2021/02/13,"['https://Stackoverflow.com/questions/66189992', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14923907/']","There are a few issues with your code. 1. Instead of the replace, you can simply use `formula.split()` 2. You are popping the items in the wrong order, you need to pop a before b to get the right answers. You were lucky to have the first case give you the same, but second fails because instead of 13/5 it does 5/13. I have marked the changes below. Do try it out. ``` from __future__ import division import random formula = input().split() #<------ OPERATORS = set(['+', '-', '*', '/', '(', ')']) PRIORITY = {'+':1, '-':1, '*':2, '/':2} stack = [] prev_op = None for ch in formula: if not ch in OPERATORS: stack.append(ch) else: a = stack.pop() #<--------- b = stack.pop() #<--------- if ch == ""+"": output = int(b)+int(a) if ch == ""-"": output = int(b)-int(a) if ch == ""*"": output = int(b)*int(a) if ch == ""/"": output = int(b)/int(a) stack.append(output) print(output) ``` ``` 4 13 5 / + 6 ```","Instead of removing spaces, you should keep them: this will make it easy to extract the *words* from the input, using `split`: ``` for ch in formula.split(): ```" 69445978,"Lets say I have two franchise of dance schools. I have two tables. First table tells about students roll no. every Table 1 = ``` Roll No. Center ID Name Date 1 A Anna 10/10/2020 1 A Anna 11/10/2020 1 B Anna 12/10/2020 2 A Bella 12/10/2020 2 B Bella 13/10/2020 3 A Catty 10/10/2020 ``` Table 2 = ``` Roll no. Center ID Report 1 A Did well 1 A Sick 1 B Needs more twist 2 A Practice required 2 B Did well 3 A Needs more practice ``` Result table expected: I want in the result it should pick Center id as A only but Report should be from both the centers ``` Roll no. Center ID Report Name 1 A Did well ,Sick ,Needs more twist Anna 2 A Practice required,Did well Bella 3 A Needs more practice Catty ``` Could someone pls help.",2021/10/05,"['https://Stackoverflow.com/questions/69445978', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11496279/']","By `dplyr`, ``` t1 %>% mutate(Report = t2$Report) %>% group_by(Roll_No.) %>% summarise(Center_ID = ""A"", Report = paste0(Report, collapse = ', '), Name = unique(Name) ) Roll_No. Center_ID Report Name 1 1 A Did well, Sick, Needs more twist Anna 2 2 A Practice required, Did well Bella 3 3 A Needs more practice Catty ```","```r library(tidyverse) a <- tribble( ~Roll, ~Center, ~Name, ~Date, 1, ""A"", ""Anna"", ""10/10/2020"", 1, ""B"", ""Anna"", ""12/10/2020"", 3, ""A"", ""Catty"", ""10/10/2020"" ) b <- tribble( ~Roll, ~Center, ~Report, 1, ""A"", ""Dis well"", 1, ""A"", ""Sick"", 1, ""B"", ""Needs more twist"", 3, ""A"", ""Needs more practice"" ) a %>% left_join(b) %>% group_by(Roll, Center) %>% summarise( Report = c(Report, Name %>% unique()) %>% paste0(collapse = "","") ) #> Joining, by = c(""Roll"", ""Center"") #> `summarise()` has grouped output by 'Roll'. You can override using the `.groups` argument. #> # A tibble: 3 x 3 #> # Groups: Roll [2] #> Roll Center Report #> #> 1 1 A Dis well,Sick,Anna #> 2 1 B Needs more twist,Anna #> 3 3 A Needs more practice,Catty ``` Created on 2021-10-05 by the [reprex package](https://reprex.tidyverse.org) (v2.0.0)" 69445978,"Lets say I have two franchise of dance schools. I have two tables. First table tells about students roll no. every Table 1 = ``` Roll No. Center ID Name Date 1 A Anna 10/10/2020 1 A Anna 11/10/2020 1 B Anna 12/10/2020 2 A Bella 12/10/2020 2 B Bella 13/10/2020 3 A Catty 10/10/2020 ``` Table 2 = ``` Roll no. Center ID Report 1 A Did well 1 A Sick 1 B Needs more twist 2 A Practice required 2 B Did well 3 A Needs more practice ``` Result table expected: I want in the result it should pick Center id as A only but Report should be from both the centers ``` Roll no. Center ID Report Name 1 A Did well ,Sick ,Needs more twist Anna 2 A Practice required,Did well Bella 3 A Needs more practice Catty ``` Could someone pls help.",2021/10/05,"['https://Stackoverflow.com/questions/69445978', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11496279/']","By `dplyr`, ``` t1 %>% mutate(Report = t2$Report) %>% group_by(Roll_No.) %>% summarise(Center_ID = ""A"", Report = paste0(Report, collapse = ', '), Name = unique(Name) ) Roll_No. Center_ID Report Name 1 1 A Did well, Sick, Needs more twist Anna 2 2 A Practice required, Did well Bella 3 3 A Needs more practice Catty ```","With **`dplyr`** package: ``` library(dplyr) cbind(df1, Report=df2$Report) %>% group_by(Name) %>% summarize(RollNo=first(RollNo), CenterID=first(CenterID), Report=paste(toString(Report), first(Name), collapse=' ')) ``` Output: ``` Name RollNo CenterID Report 1 Anna 1 A Did well, Sick, Needs more twist Anna 2 Bella 2 A Practice Required, Did well Bella 3 Cathy 3 A Needs more practice Cathy ```" 69445978,"Lets say I have two franchise of dance schools. I have two tables. First table tells about students roll no. every Table 1 = ``` Roll No. Center ID Name Date 1 A Anna 10/10/2020 1 A Anna 11/10/2020 1 B Anna 12/10/2020 2 A Bella 12/10/2020 2 B Bella 13/10/2020 3 A Catty 10/10/2020 ``` Table 2 = ``` Roll no. Center ID Report 1 A Did well 1 A Sick 1 B Needs more twist 2 A Practice required 2 B Did well 3 A Needs more practice ``` Result table expected: I want in the result it should pick Center id as A only but Report should be from both the centers ``` Roll no. Center ID Report Name 1 A Did well ,Sick ,Needs more twist Anna 2 A Practice required,Did well Bella 3 A Needs more practice Catty ``` Could someone pls help.",2021/10/05,"['https://Stackoverflow.com/questions/69445978', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11496279/']","By `dplyr`, ``` t1 %>% mutate(Report = t2$Report) %>% group_by(Roll_No.) %>% summarise(Center_ID = ""A"", Report = paste0(Report, collapse = ', '), Name = unique(Name) ) Roll_No. Center_ID Report Name 1 1 A Did well, Sick, Needs more twist Anna 2 2 A Practice required, Did well Bella 3 3 A Needs more practice Catty ```","**update:** With the hint of @Park many thanks!: Logic: 1. `left_join` by `RollNo.` 2. `filter`, `group_by` and `summarise` ``` library(dplyr) table1 %>% left_join(table2, by=c(""RollNo.""=""Rollno."")) %>% filter(CenterID.x== ""A"") %>% group_by(RollNo., CenterID=CenterID.x, Name) %>% summarise(Report = paste(unique(Report), collapse = "", "")) ``` output: ``` RollNo. CenterID Name Report 1 1 A Anna Did well, Sick, Needs more twist 2 2 A Bella Practice required, Did well 3 3 A Catty Needs more practice ``` **First answer:** We could try this: It is depending on whether `Date` should be considered or not, so you may modify the code: ``` table1 %>% left_join(table2, by=c(""CenterID"", ""RollNo.""=""Rollno."")) %>% filter(CenterID == ""A"") %>% group_by(RollNo., CenterID, Name) %>% summarise(Report = paste(unique(Report), collapse = "", "")) ``` ``` RollNo. CenterID Name Report 1 1 A Anna Did well, Sick 2 2 A Bella Practice required 3 3 A Catty Needs more practice ```" 30107988,"I have a sparse banded matrix A and I'd like to (direct) solve Ax=b. I have about 500 vectors b, so I'd like to solve for the corresponding 500 x's. I'm brand new to CUDA, so I'm a little confused as to what options I have available. cuSOLVER has a batch direct solver cuSolverSP for sparse A\_i x\_i = b\_i using QR [here](http://devblogs.nvidia.com/parallelforall/parallel-direct-solvers-with-cusolver-batched-qr/). (I'd be fine with LU too since A is decently conditioned.) However, as far as I can tell, I can't exploit the fact that all my A\_i's are the same. Would an alternative option be to first determine a sparse LU (QR) factorization on the CPU or GPU then perform in parallel the backsubstitution (respectively, backsub and matrix mult) on the GPU? If [cusolverSp< t >csrlsvlu()](http://docs.nvidia.com/cuda/cusolver/index.html#cusolver-lt-t-gt-csrlsvlu) is for one b\_i, is there a standard way to batch perform this operation for multiple b\_i's? Finally, since I don't have intuition for this, should I expect a speedup on a GPU for either of these options, given the necessary overhead? x has length ~10000-100000. Thanks.",2015/05/07,"['https://Stackoverflow.com/questions/30107988', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1672126/']","I'm currently working on something similar myself. I decided to basically wrap the conjugate gradient and level-0 incomplete cholesky preconditioned conjugate gradient solvers utility samples that came with the CUDA SDK into a small class. You can find them in your CUDA\_HOME directory under the path: `samples/7_CUDALibraries/conjugateGradient` and `/Developer/NVIDIA/CUDA-samples/7_CUDALibraries/conjugateGradientPrecond` Basically, you would load the matrix into the device memory once (and for ICCG, compute the corresponding conditioner / matrix analysis) then call the solve kernel with different b vectors. I don't know what you anticipate your matrix band structure to look like, but if it is symmetric and either diagonally dominant (off diagonal bands along each row and column are opposite sign of diagonal and their sum is less than the diagonal entry) or positive definite (no eigenvectors with an eigenvalue of 0.) then CG and ICCG should be useful. Alternately, the various multigrid algorithms are another option if you are willing to go through coding them up. If your matrix is only positive semi-definite (e.g. has at least one eigenvector with an eigenvalue of zero) you can still ofteb get away with using CG or ICCG as long as you ensure that: 1) The right hand side (b vectors) are orthogonal to the null space (null space meaning eigenvectors with an eigenvalue of zero). 2) The solution you obtain is orthogonal to the null space. It is interesting to note that if you do have a non-trivial null space, then different numeric solvers can give you different answers for the same exact system. The solutions will end up differing by a linear combination of the null space... That problem has caused me many many man hours of debugging and frustration before I finally caught on, so its good to be aware of it. Lastly, if your matrix has a [Circulant Band structure](https://en.wikipedia.org/?title=Circulant_matrix) you might consider using a fast fourier transform (FFT) based solver. FFT based numerical solvers can often yield superior performance in cases where they are applicable.","If you don't mind going with an open-source library, you could also check out CUSP: [CUSP Quick Start Page](https://code.google.com/p/cusp-library/wiki/QuickStartGuide) It has a fairly decent suite of solvers, including a few preconditioned methods: [CUSP Preconditioner Examples](http://code.google.com/p/cusp-library/source/browse/#hg%2Fexamples%2FPreconditioners) The smoothed aggregation preconditioner (a variant of algebraic multigrid) seems to work very well as long as your GPU has enough onboard memory for it." 30107988,"I have a sparse banded matrix A and I'd like to (direct) solve Ax=b. I have about 500 vectors b, so I'd like to solve for the corresponding 500 x's. I'm brand new to CUDA, so I'm a little confused as to what options I have available. cuSOLVER has a batch direct solver cuSolverSP for sparse A\_i x\_i = b\_i using QR [here](http://devblogs.nvidia.com/parallelforall/parallel-direct-solvers-with-cusolver-batched-qr/). (I'd be fine with LU too since A is decently conditioned.) However, as far as I can tell, I can't exploit the fact that all my A\_i's are the same. Would an alternative option be to first determine a sparse LU (QR) factorization on the CPU or GPU then perform in parallel the backsubstitution (respectively, backsub and matrix mult) on the GPU? If [cusolverSp< t >csrlsvlu()](http://docs.nvidia.com/cuda/cusolver/index.html#cusolver-lt-t-gt-csrlsvlu) is for one b\_i, is there a standard way to batch perform this operation for multiple b\_i's? Finally, since I don't have intuition for this, should I expect a speedup on a GPU for either of these options, given the necessary overhead? x has length ~10000-100000. Thanks.",2015/05/07,"['https://Stackoverflow.com/questions/30107988', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1672126/']","I'm currently working on something similar myself. I decided to basically wrap the conjugate gradient and level-0 incomplete cholesky preconditioned conjugate gradient solvers utility samples that came with the CUDA SDK into a small class. You can find them in your CUDA\_HOME directory under the path: `samples/7_CUDALibraries/conjugateGradient` and `/Developer/NVIDIA/CUDA-samples/7_CUDALibraries/conjugateGradientPrecond` Basically, you would load the matrix into the device memory once (and for ICCG, compute the corresponding conditioner / matrix analysis) then call the solve kernel with different b vectors. I don't know what you anticipate your matrix band structure to look like, but if it is symmetric and either diagonally dominant (off diagonal bands along each row and column are opposite sign of diagonal and their sum is less than the diagonal entry) or positive definite (no eigenvectors with an eigenvalue of 0.) then CG and ICCG should be useful. Alternately, the various multigrid algorithms are another option if you are willing to go through coding them up. If your matrix is only positive semi-definite (e.g. has at least one eigenvector with an eigenvalue of zero) you can still ofteb get away with using CG or ICCG as long as you ensure that: 1) The right hand side (b vectors) are orthogonal to the null space (null space meaning eigenvectors with an eigenvalue of zero). 2) The solution you obtain is orthogonal to the null space. It is interesting to note that if you do have a non-trivial null space, then different numeric solvers can give you different answers for the same exact system. The solutions will end up differing by a linear combination of the null space... That problem has caused me many many man hours of debugging and frustration before I finally caught on, so its good to be aware of it. Lastly, if your matrix has a [Circulant Band structure](https://en.wikipedia.org/?title=Circulant_matrix) you might consider using a fast fourier transform (FFT) based solver. FFT based numerical solvers can often yield superior performance in cases where they are applicable.","> > is there a standard way to batch perform this operation for multiple b\_i's? > > > One option is to use the batched refactorization module in CUDA's cuSOLVER, but I am not sure if it is *standard*. Batched refactorization module in cuSOLVER provides an efficient method to solve batches of linear systems with fixed left-hand side sparse matrix (or matrices with fixed sparsity pattern but varying coefficients) and varying right-hand sides, based on LU decomposition. Only some partially completed code snippets can be found in the official documentation (as of CUDA 10.1) that are related to it. A complete example can be found [here](https://github.com/zishun/cuSolverRf-batch)." 30107988,"I have a sparse banded matrix A and I'd like to (direct) solve Ax=b. I have about 500 vectors b, so I'd like to solve for the corresponding 500 x's. I'm brand new to CUDA, so I'm a little confused as to what options I have available. cuSOLVER has a batch direct solver cuSolverSP for sparse A\_i x\_i = b\_i using QR [here](http://devblogs.nvidia.com/parallelforall/parallel-direct-solvers-with-cusolver-batched-qr/). (I'd be fine with LU too since A is decently conditioned.) However, as far as I can tell, I can't exploit the fact that all my A\_i's are the same. Would an alternative option be to first determine a sparse LU (QR) factorization on the CPU or GPU then perform in parallel the backsubstitution (respectively, backsub and matrix mult) on the GPU? If [cusolverSp< t >csrlsvlu()](http://docs.nvidia.com/cuda/cusolver/index.html#cusolver-lt-t-gt-csrlsvlu) is for one b\_i, is there a standard way to batch perform this operation for multiple b\_i's? Finally, since I don't have intuition for this, should I expect a speedup on a GPU for either of these options, given the necessary overhead? x has length ~10000-100000. Thanks.",2015/05/07,"['https://Stackoverflow.com/questions/30107988', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1672126/']","> > is there a standard way to batch perform this operation for multiple b\_i's? > > > One option is to use the batched refactorization module in CUDA's cuSOLVER, but I am not sure if it is *standard*. Batched refactorization module in cuSOLVER provides an efficient method to solve batches of linear systems with fixed left-hand side sparse matrix (or matrices with fixed sparsity pattern but varying coefficients) and varying right-hand sides, based on LU decomposition. Only some partially completed code snippets can be found in the official documentation (as of CUDA 10.1) that are related to it. A complete example can be found [here](https://github.com/zishun/cuSolverRf-batch).","If you don't mind going with an open-source library, you could also check out CUSP: [CUSP Quick Start Page](https://code.google.com/p/cusp-library/wiki/QuickStartGuide) It has a fairly decent suite of solvers, including a few preconditioned methods: [CUSP Preconditioner Examples](http://code.google.com/p/cusp-library/source/browse/#hg%2Fexamples%2FPreconditioners) The smoothed aggregation preconditioner (a variant of algebraic multigrid) seems to work very well as long as your GPU has enough onboard memory for it." 155403,"In the ancient times when things were easy, you just had to code a form in html and then your php would typically have a if($\_REQUEST['some\_value']) to handle the request. But now with Drupal, nothing is easy... Here is once more my latest battle to understand how Drupal thinks. Context: I have a list of news (content type ""news"") shown on a page with paging system. Each news title links to the news details page. This works fine. There is a new requirement that each news must have one or more ""tags"". The goal is to show a list of checkboxes on top of the news list to allow the user to filter in/out news with the selected tags. EDIT: After being defeated by Drupal's form I decided to completely bypass the Form API and generate my own fully flexible form. There is only one thing remaining, Drupal is forcing some div wrappers around each of my input fields. I want to get rid of them (and stop Drupal to think at my place). In my\_news\_list.tpl.php I coded: ```
"" onchange=""form.submit();"" checked=""checked"" />
``` Result(!): ```
Acquisitions
Corporate
Investor News
Products and Services
```",2015/04/16,"['https://drupal.stackexchange.com/questions/155403', 'https://drupal.stackexchange.com', 'https://drupal.stackexchange.com/users/39325/']","Drupal's Form API is complex but gives you lot of things: is secure, is extensible, is themeable. Indeed is more difficult than coding a simple HTML form, but with a simpel HTML form you have a simple functionality: just that simple HTML form. Form API generates the form HTML element and handles the POST requests, and validate and submithandlers, you don't and you shouldn't code your own HTML form. I recommend you to read the [Drupal 6 Form API Quickstart Guide](https://www.drupal.org/node/751826). Drupal 7 form handling is pretty the same, but check the [Drupal 7 Form API Reference](http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7) and [Form API Internal Workflow Illustration](https://www.drupal.org/node/165104). In the other hand you may prefer to use a module that address what you need without coding, that's a faceted search: [Facet API](https://www.drupal.org/project/facetapi). From its [documentation page](http://www.trellon.com/content/blog/apachesolr-and-facetapi): > > Faceted search allows our search results to be filtered by defined > criteria like category, date, author, location, or anything else that > can come out of a field. We call these criteria facets. With facets, > you can narrow down your search more and more until you get to the > desired results. > > >","The issue here is theme\_wrappers around your form elements. // @see: " 18292,"Приложение с союзом как обычно имеет дополнительное значение причинности (можно заменить придаточным причины с союзами так как, потому что, поскольку или оборотом со словом будучи) и обособляется: Как старый артиллерист, я презираю этот вид холодного оружия (Шолохов). – Будучи старым артиллеристом, я презираю этот вид холодного оружия; Я презираю этот вид холодного оружия, потому что я старый артиллерист. Мой друг, как лучший математик класса, будет участником олимпиады. Мой друг как лучший математик класса будет участником олимпиады. Здесь постановка запятых зависит от интонации? Я, как лучший математик класса, буду участником олимпиады. Я как лучший математик класса буду участником олимпиады. оба эти варианта возможны в зависимости от интонации? Или если определяемое слово - местоимение, то обязательно выделять запятыми приложение?",2013/04/09,"['https://rus.stackexchange.com/questions/18292', 'https://rus.stackexchange.com', 'https://rus.stackexchange.com/users/1197/']","Обособление - это выделение в устной речи интонационно, а в письменной речи - с помощью знаков препинания. И то, и другое в данном случае зависит от смысла, который вы вкладываете во фразу. Правильные знаки помогают читающему понять суть.","Любое приложение при личном местоимении обособляется, и прочитать вы его сможете только с интонацией выделения. Так что вариантов нет:Я, как лучший математик класса, буду участником олимпиады. А значение у приложения явно причинное. Мой друг, как лучший математик класса, будет участником олимпиады. - тоже без вариантов, потому что другого значения, кроме причинного, здесь нет. Так как он лучший математик, поэтому и будет участником олимпиады." 21438650,"I am sorry if this question has been asked before, but could not find a solution to my problem. Which `apply`-like function fits the below case? I have an `R` function which has 3 arguments `(x, y, z)`. What it does is basically to call an `PostgreSQL` function which quires `x, y, z` and retrieve a dataframe consisting of corresponding values `a, b, c`, something like this; ``` myfunc <- function(x, y, z){ get.df <- fn$sqldf(""SELECT * FROM retrieve_meta_data('$x', '$y', '$z')"") # get.df is a dataframe consisting of x number of rows and columns a, b, c # some dataframe manipulation... return(get.df) } ``` What I am looking for is to call this function by using a dataframe `(call.df)` with x number of rows and columns `x, y, z`. So `apply` the function for each ith row and using the columns as arguments. I have looked through a range of `apply`-like functions but I have failed so far. It's probably way easy. I imagine something like `apply(call.df, c(1,2), myfunc)` but this gives the error; ``` Error in eval(expr, envir, enclos) : argument ""y"" is missing, with no default ``` I hope am clear enough without supplying any dummy data. Any pointers would be very much appreciated, thanks!",2014/01/29,"['https://Stackoverflow.com/questions/21438650', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1734415/']","If x, y, and z are the first three columns of df, then this should work: ``` apply(df,1,function(params)myfunc(params[1],params[2], params[3])) ``` `apply(df,1,FUN)` takes the first argument, `df`, and passes it to FUN row-wise (because the second argument is 1). So in `function(params)`, params is a row of `df`. Hence, `params[1]` is the first column of that row, etc.","This version will work if your arguments are of different types, though in this case it looks like they are all character or can be treated as such so `apply` works fine. ``` sapply( split(df, 1:nrow(df)), function(x) do.call(myfunc, x) ) ```" 21438650,"I am sorry if this question has been asked before, but could not find a solution to my problem. Which `apply`-like function fits the below case? I have an `R` function which has 3 arguments `(x, y, z)`. What it does is basically to call an `PostgreSQL` function which quires `x, y, z` and retrieve a dataframe consisting of corresponding values `a, b, c`, something like this; ``` myfunc <- function(x, y, z){ get.df <- fn$sqldf(""SELECT * FROM retrieve_meta_data('$x', '$y', '$z')"") # get.df is a dataframe consisting of x number of rows and columns a, b, c # some dataframe manipulation... return(get.df) } ``` What I am looking for is to call this function by using a dataframe `(call.df)` with x number of rows and columns `x, y, z`. So `apply` the function for each ith row and using the columns as arguments. I have looked through a range of `apply`-like functions but I have failed so far. It's probably way easy. I imagine something like `apply(call.df, c(1,2), myfunc)` but this gives the error; ``` Error in eval(expr, envir, enclos) : argument ""y"" is missing, with no default ``` I hope am clear enough without supplying any dummy data. Any pointers would be very much appreciated, thanks!",2014/01/29,"['https://Stackoverflow.com/questions/21438650', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1734415/']","If x, y, and z are the first three columns of df, then this should work: ``` apply(df,1,function(params)myfunc(params[1],params[2], params[3])) ``` `apply(df,1,FUN)` takes the first argument, `df`, and passes it to FUN row-wise (because the second argument is 1). So in `function(params)`, params is a row of `df`. Hence, `params[1]` is the first column of that row, etc.","Just apply over `1` for your margin; then the row is passed to your function as a vector and you should be able to deal with it. For example: ``` > apply(iris, 1, function(v) paste(v[""Species""], v[""Sepal.Width""])) [1] ""setosa 3.5"" ""setosa 3.0"" ""setosa 3.2"" ""setosa 3.1"" ... ```" 21438650,"I am sorry if this question has been asked before, but could not find a solution to my problem. Which `apply`-like function fits the below case? I have an `R` function which has 3 arguments `(x, y, z)`. What it does is basically to call an `PostgreSQL` function which quires `x, y, z` and retrieve a dataframe consisting of corresponding values `a, b, c`, something like this; ``` myfunc <- function(x, y, z){ get.df <- fn$sqldf(""SELECT * FROM retrieve_meta_data('$x', '$y', '$z')"") # get.df is a dataframe consisting of x number of rows and columns a, b, c # some dataframe manipulation... return(get.df) } ``` What I am looking for is to call this function by using a dataframe `(call.df)` with x number of rows and columns `x, y, z`. So `apply` the function for each ith row and using the columns as arguments. I have looked through a range of `apply`-like functions but I have failed so far. It's probably way easy. I imagine something like `apply(call.df, c(1,2), myfunc)` but this gives the error; ``` Error in eval(expr, envir, enclos) : argument ""y"" is missing, with no default ``` I hope am clear enough without supplying any dummy data. Any pointers would be very much appreciated, thanks!",2014/01/29,"['https://Stackoverflow.com/questions/21438650', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1734415/']","If x, y, and z are the first three columns of df, then this should work: ``` apply(df,1,function(params)myfunc(params[1],params[2], params[3])) ``` `apply(df,1,FUN)` takes the first argument, `df`, and passes it to FUN row-wise (because the second argument is 1). So in `function(params)`, params is a row of `df`. Hence, `params[1]` is the first column of that row, etc.","It's helpful if you supply sample data so you get an answer that matches your situation, but it sounds like you're looking for `mapply`, e.g., ``` do.call(mapply, c(myfunc, call.df[c(x.col, y.col, z.col)])) ```" 21438650,"I am sorry if this question has been asked before, but could not find a solution to my problem. Which `apply`-like function fits the below case? I have an `R` function which has 3 arguments `(x, y, z)`. What it does is basically to call an `PostgreSQL` function which quires `x, y, z` and retrieve a dataframe consisting of corresponding values `a, b, c`, something like this; ``` myfunc <- function(x, y, z){ get.df <- fn$sqldf(""SELECT * FROM retrieve_meta_data('$x', '$y', '$z')"") # get.df is a dataframe consisting of x number of rows and columns a, b, c # some dataframe manipulation... return(get.df) } ``` What I am looking for is to call this function by using a dataframe `(call.df)` with x number of rows and columns `x, y, z`. So `apply` the function for each ith row and using the columns as arguments. I have looked through a range of `apply`-like functions but I have failed so far. It's probably way easy. I imagine something like `apply(call.df, c(1,2), myfunc)` but this gives the error; ``` Error in eval(expr, envir, enclos) : argument ""y"" is missing, with no default ``` I hope am clear enough without supplying any dummy data. Any pointers would be very much appreciated, thanks!",2014/01/29,"['https://Stackoverflow.com/questions/21438650', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1734415/']","This version will work if your arguments are of different types, though in this case it looks like they are all character or can be treated as such so `apply` works fine. ``` sapply( split(df, 1:nrow(df)), function(x) do.call(myfunc, x) ) ```","Just apply over `1` for your margin; then the row is passed to your function as a vector and you should be able to deal with it. For example: ``` > apply(iris, 1, function(v) paste(v[""Species""], v[""Sepal.Width""])) [1] ""setosa 3.5"" ""setosa 3.0"" ""setosa 3.2"" ""setosa 3.1"" ... ```" 21438650,"I am sorry if this question has been asked before, but could not find a solution to my problem. Which `apply`-like function fits the below case? I have an `R` function which has 3 arguments `(x, y, z)`. What it does is basically to call an `PostgreSQL` function which quires `x, y, z` and retrieve a dataframe consisting of corresponding values `a, b, c`, something like this; ``` myfunc <- function(x, y, z){ get.df <- fn$sqldf(""SELECT * FROM retrieve_meta_data('$x', '$y', '$z')"") # get.df is a dataframe consisting of x number of rows and columns a, b, c # some dataframe manipulation... return(get.df) } ``` What I am looking for is to call this function by using a dataframe `(call.df)` with x number of rows and columns `x, y, z`. So `apply` the function for each ith row and using the columns as arguments. I have looked through a range of `apply`-like functions but I have failed so far. It's probably way easy. I imagine something like `apply(call.df, c(1,2), myfunc)` but this gives the error; ``` Error in eval(expr, envir, enclos) : argument ""y"" is missing, with no default ``` I hope am clear enough without supplying any dummy data. Any pointers would be very much appreciated, thanks!",2014/01/29,"['https://Stackoverflow.com/questions/21438650', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1734415/']","It's helpful if you supply sample data so you get an answer that matches your situation, but it sounds like you're looking for `mapply`, e.g., ``` do.call(mapply, c(myfunc, call.df[c(x.col, y.col, z.col)])) ```","Just apply over `1` for your margin; then the row is passed to your function as a vector and you should be able to deal with it. For example: ``` > apply(iris, 1, function(v) paste(v[""Species""], v[""Sepal.Width""])) [1] ""setosa 3.5"" ""setosa 3.0"" ""setosa 3.2"" ""setosa 3.1"" ... ```" 15588510,"This is a two-part question from a newbie. First, I need an encoding for simple text (without the lowercase/caps distinction), and I need it to be more space-efficient than ASCII. So I have thought of creating my own 5-bit code, holding a range of 32 characters (the alphabet plus some punctuation marks). As far as I understand, all modern computing 'thinks' in bytes, so I cannot actually define my own 5-bit encoding without actually resorting to a 8-bit encoding. What I am thinking of doing is: I define my own 5-bit code and I save the text in 3-character blocks, each block saved as 2 bytes. Every block will occupy total of 15 bits, which will be stored within two bytes (holding 16 bits). I might use the extra bit for parity check, even if I don't actually need it. Does this approach make sense? Or is there any better approach? Alternatively, I might define a 6-bit encoding, and save the text into blocks of 4 characters each, with each block being saved in 3 bytes. The second part of the question is: assuming that the text will then be compressed (via a standard lossless algorithm for texts, such as zip for example), is it worth the trouble of creating my own encoding (as explained above)? Or will the compression algorithm take care of the space inefficiency of the 8-bit encoding, making the compressed as efficient as a compressed file which originally was encoded using a 5-bit or 6-bit encoding? If so, I would have no advantage of using a 5/6 bit encoding for pre-compression text, so I would simply skip altogether this step. I need to know from experienced programmers, what is the case? Thanks everyone",2013/03/23,"['https://Stackoverflow.com/questions/15588510', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2134205/']","This is precisely what they're doing. It's called recursion, and it's, well, hard to wrap your head around at first. Imagine you have strings: A B C D Effectively, what you do, is choose each string in turn and then find all permutations of the remaining strings, and prepend your chosen string. ``` Choose A, get all permutations of {B,C,D} and append A. Choose B, get all permutations of {A,C,D} and append B. Choose C, get all permutations of {A,B,D} and append C. Choose D, get all permutations of {A,B,C} and append D. ``` Now, we have subproblems that look very similar, but are smaller. That's the heart of recursion. Take a problem, and find a way to turn it into a smaller version of the problem. Now, keep turning it into a smaller problem until it's trivial. Now we have to figure out how to generate permutations of 3 strings. ``` Permute(A B C) Choose A, get all permutations of {B,C} and append A. Choose B, get all permutations of {A,C} and append B. Choose C, get all permutations of {A,B} and append C. ``` Same structure, but smaller problems. So take it a step further. How do we do permute(A B) ``` Permute(A B) Choose A, get all permutations of {B} and append A. Choose B, get all permutations of {A} and append B. ``` So now we just have to permute one string. That's trivial. ``` Permute(A) A ``` So now we have a way to Permute a list of strings of size 1, and we've defined how to permute a list of size N by Permuting a list of size N-1. So, we can permute any list of size >= 1, by calling ourselves with a slightly smaller version of the problem. That's the beauty of recursion. You just define how to solve the smallest problem, and how to use that solution to build a bigger solution, and it builds upon itself.","This is a recursive algorithm, it essentially takes each element in the array as the first one then adds to to it the output of calling itself without that element. Take 3 elements A, B and C and walk through the logic, lets call our function `perm`. so, we want ``` perm({A, B, C}) ``` this equals ``` A + perm({B, C}) B + perm({A, C}) C + perm({A, B}) ``` expand again ``` A + B + perm({C}) A + C + perm({B}) B + A + perm({C}) B + C + perm({A}) C + A + perm({B}) C + B + perm({A}) ``` as `perm({X}) = X` we end up with ``` A + B + C A + C + B B + A + C B + C + A C + A + B C + B + A ```" 15588510,"This is a two-part question from a newbie. First, I need an encoding for simple text (without the lowercase/caps distinction), and I need it to be more space-efficient than ASCII. So I have thought of creating my own 5-bit code, holding a range of 32 characters (the alphabet plus some punctuation marks). As far as I understand, all modern computing 'thinks' in bytes, so I cannot actually define my own 5-bit encoding without actually resorting to a 8-bit encoding. What I am thinking of doing is: I define my own 5-bit code and I save the text in 3-character blocks, each block saved as 2 bytes. Every block will occupy total of 15 bits, which will be stored within two bytes (holding 16 bits). I might use the extra bit for parity check, even if I don't actually need it. Does this approach make sense? Or is there any better approach? Alternatively, I might define a 6-bit encoding, and save the text into blocks of 4 characters each, with each block being saved in 3 bytes. The second part of the question is: assuming that the text will then be compressed (via a standard lossless algorithm for texts, such as zip for example), is it worth the trouble of creating my own encoding (as explained above)? Or will the compression algorithm take care of the space inefficiency of the 8-bit encoding, making the compressed as efficient as a compressed file which originally was encoded using a 5-bit or 6-bit encoding? If so, I would have no advantage of using a 5/6 bit encoding for pre-compression text, so I would simply skip altogether this step. I need to know from experienced programmers, what is the case? Thanks everyone",2013/03/23,"['https://Stackoverflow.com/questions/15588510', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2134205/']","This is precisely what they're doing. It's called recursion, and it's, well, hard to wrap your head around at first. Imagine you have strings: A B C D Effectively, what you do, is choose each string in turn and then find all permutations of the remaining strings, and prepend your chosen string. ``` Choose A, get all permutations of {B,C,D} and append A. Choose B, get all permutations of {A,C,D} and append B. Choose C, get all permutations of {A,B,D} and append C. Choose D, get all permutations of {A,B,C} and append D. ``` Now, we have subproblems that look very similar, but are smaller. That's the heart of recursion. Take a problem, and find a way to turn it into a smaller version of the problem. Now, keep turning it into a smaller problem until it's trivial. Now we have to figure out how to generate permutations of 3 strings. ``` Permute(A B C) Choose A, get all permutations of {B,C} and append A. Choose B, get all permutations of {A,C} and append B. Choose C, get all permutations of {A,B} and append C. ``` Same structure, but smaller problems. So take it a step further. How do we do permute(A B) ``` Permute(A B) Choose A, get all permutations of {B} and append A. Choose B, get all permutations of {A} and append B. ``` So now we just have to permute one string. That's trivial. ``` Permute(A) A ``` So now we have a way to Permute a list of strings of size 1, and we've defined how to permute a list of size N by Permuting a list of size N-1. So, we can permute any list of size >= 1, by calling ourselves with a slightly smaller version of the problem. That's the beauty of recursion. You just define how to solve the smallest problem, and how to use that solution to build a bigger solution, and it builds upon itself.","The scheme used is ""divide and conquer"". It's basic idea is to break up a big problem into a set of smaller problems to which the same mechanism is applied until an ""atomic"" level of the problem is reached. In other words: A problem of size n is broken up into n problems of size n-1 continuously. At the bottom there is a simple way of dealing with the problem of size 1 (or any other constant). This is usually done using recursion (as Calgar99) pointed out already. A very nice example of that scheme that will also twist you head a bit are the ""Towers of Hanoi"". Check it out and the ingenuity of such an approach will hit you. As for the presented code: The permutation of n words is the concatenation of the permutation of n-1 words with each of the n original words. This recursive definition represents a quite elegant solution for the problem." 33397094,"**This part works.** In my C#.NET WPF XAML, I have a **static** ComboBox and a **static** TextBox. The TextBox displays another column from the same DataTable (in the ComboBox's ItemSource). The column ""rr\_code"" is the column for company name and the column ""rr\_addr"" is the column for the address. ``` ``` The ComboBox reads programmatically from a column in a DataTable: ``` CompanyComboBox1.ItemsSource = Rails.DefaultView; // Rails is a DataTable CompanyComboBox1.DisplayMemberPath = ""rr_code""; // column name for company name ``` **This part doesn't work** The question is, I now have a ""Add Company"" button that creates a new form in a StackPanel, **dynamically** and with this exact functionality. The ComboBox works exactly as expected. Here's what I have so far: ``` ComboBox companyComboBox = new ComboBox(); companyComboBox.ItemsSource = Rails.DefaultView; companyComboBox.IsEditable = true; companyComboBox.IsTextSearchEnabled = true; companyComboBox.DisplayMemberPath = ""rr_code""; ``` The problem is in the TextBox, which is not updating when I change the dynamic companyComboBox, so I'm sure it has to do with the binding. ``` TextBox streetTextBox = new TextBox(); streetTextBox.DataContext = companyComboBox; Binding b = new Binding(""rr_addr""); b.Mode = BindingMode.Default; b.Source = companyComboBox.SelectedItem; streetTextBox.SetBinding(ComboBox.SelectedItemProperty, b); ``` What is the correct way to set the binding for the TextBox streetTextBox?",2015/10/28,"['https://Stackoverflow.com/questions/33397094', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3847534/']","The code-behind equivalent of this particular XAML + C# data binding in pure C# is: ``` ComboBox companyComboBox = new ComboBox(); companyComboBox.ItemsSource = Rails.DefaultView; // Rails being DataTable companyComboBox.IsEditable = true; companyComboBox.IsTextSearchEnabled = true; companyComboBox.DisplayMemberPath = ""rr_code""; Binding b = new Binding(""SelectedItem.rr_addr""); // The selected item's 'rr_addr' column ... b.Source = companyComboBox; // ... of the companyComboBox ... TextBox streetTextBox = new TextBox(); streetTextBox.SetBinding(TextBox.TextProperty,b); // ... is bound to streetTextBox's Text property. ``` The error was in the last line. SetBinding needed to have a property of the target, not the source. In addition, the Binding declaration needed ""SelectedItem."" for some reason.","Why are you setting the TextBox DataContext ? You can simply bind TextBox.Text property to ComboBox SelectedItem in your XAML ``` ```" 70421369,"I have ```cpp class ClassA {}; class ClassB {}; auto func_a() -> ClassA { return ClassA(); // example implementation for illustration. in reality can be different. does not match the form of func_b } auto func_b() -> ClassB { return ClassB(); // example implementation for illustration. in reality can be different. does not match the form of func_a } ``` I want to be able to use the syntax ```cpp func() // instead of func_a() func() // instead of func_b() ``` (this is as part of a bigger template) but I don't know how to implement this template specialization for the function alias. Help? What is the syntax for this? [Edit] The answers posted so far do not answer my question, so I'll edit my question to be more clear. The actual definition of func\_a and func\_b is more complex than just ""return Type();"". Also they cannot be touched. So consider them to be ``` auto func_a() -> ClassA { // unknown implementation. returns ClassA somehow } auto func_b() -> ClassB { // unknown implementation. returns ClassB somehow } ``` I cannot template the contents of func\_a or func\_b. I need the template for func to be specialized for each one of the two and be able to select the correct one to call",2021/12/20,"['https://Stackoverflow.com/questions/70421369', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11249764/']","You might do something like (c++17): ```cpp template auto func() { if constexpr (std::is_same_v) { return func_a(); } else { return func_b(); } } ``` Alternative for pre-C++17 is tag dispatching (which allows customization point): ```cpp // Utility class to allow to ""pass"" Type. template struct Tag{}; // Possibly in namespace details auto func(Tag) { return func_a(); } auto func(Tag) { return func_b(); } template auto func() { return func(Tag{}); } ```","You can do it like this : ``` #include #include class A { public: void hi() { std::cout << ""hi\n""; } }; class B { public: void boo() { std::cout << ""boo\n""; } }; template auto create() { // optional : if you only want to be able to create instances of A or B // static_assert(std::is_same_v || std::is_same_v); type_t object{}; return object; } int main() { auto a = create(); auto b = create(); a.hi(); b.boo(); return 0; } ```" 1429246,"I just compiled the latest preview of Qt4.6 on Snow Leopard in 64 bit without any major issues. Now, I am trying to do the same for PyQt4.6 with the latest snapshot from the River Bank website. However, the compiler exits with the following issue: ``` g++ -c -pipe -fPIC -arch x86_64 -O2 -Wall -W -DNDEBUG -DQT_NO_DEBUG -DQT_CORE_LIB -I. -I/Users/drufat/Downloads/PyQt-mac-gpl-4.6-snapshot-20090914/qpy/QtCore -I/System/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6 -I/usr/local/Trolltech/Qt-4.6.0/mkspecs/default -I/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers -I/usr/local/Trolltech/Qt-4.6.0/include -F/Users/drufat/Downloads/PyQt-mac-gpl-4.6-snapshot-20090914/qpy/QtCore -F/usr/local/Trolltech/Qt-4.6.0/lib -o sipQtCoreQResource.o sipQtCoreQResource.cpp /usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h: In copy constructor ‘QResource::QResource(const QResource&)’: /usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:180: error: ‘QScopedPointer::QScopedPointer(const QScopedPointer&) [with T = QResourcePrivate, Cleanup = QScopedPointerDeleter]’ is private /usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qresource.h:59: error: within this context sipQtCoreQResource.cpp: In constructor ‘sipQResource::sipQResource(const QResource&)’: sipQtCoreQResource.cpp:78: note: synthesized method ‘QResource::QResource(const QResource&)’ first required here /usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h: In static member function ‘static void QScopedPointerDeleter::cleanup(T*) [with T = QResourcePrivate]’: /usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:100: instantiated from ‘QScopedPointer::~QScopedPointer() [with T = QResourcePrivate, Cleanup = QScopedPointerDeleter]’ /usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qresource.h:59: instantiated from here /usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:59: error: invalid application of ‘sizeof’ to incomplete type ‘QResourcePrivate’ /usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:59: error: creating array with negative size (‘-0x00000000000000001’) /usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:60: error: invalid application of ‘sizeof’ to incomplete type ‘QResourcePrivate’ /usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:60: error: creating array with negative size (‘-0x00000000000000001’) /usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:62: warning: possible problem detected in invocation of delete operator: /usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:54: warning: ‘pointer’ has incomplete type /usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qresource.h:56: warning: forward declaration of ‘struct QResourcePrivate’ /usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:62: note: neither the destructor nor the class-specific operator delete will be called, even if they are declared when the class is defined. ``` Is this an error with PyQt4 trying to access a private member of a Qt4 class? Has anybody compiled PyQt4 on Snow Leopard successfully?",2009/09/15,"['https://Stackoverflow.com/questions/1429246', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/134397/']",I just got PyQt 4.6.2 working with the 64bit Python 2.6.1. I posted the instructions here: ,"In the changelogs I see Phil (PyQt's maintainer) [has issued fixes](http://www.riverbankcomputing.co.uk/static/Downloads/PyQt4/ChangeLog-4.6-snapshot-20090914) yesterday in the development snapshots specifically for Snow Leopard: > > 2009/09/14 12:12:49 phil Further > fixes for Snow Leopard on 64 bit > systems. Added > QObject.pyqtConfigure(). > > > Are you using yesterday's build of PyQt? [This thread on the mailinglist](http://www.riverbankcomputing.com/pipermail/pyqt/2009-September/thread.html#24247) is also particulary interesting. The PyQt compile troubles seems to be caused by Snow Leopards default 64bit compiles and the 64/32 bit mixed version of Python it ships with. If things continue to go wrong, i would submit your problems to this mailinglist (so they can get fixed - hopefully) and try to (temporarily) rebuild Qt and PyQt (and possibly python) in a 32-bit fashion (with the -m32 compiler flag) if you need it working now." 1429246,"I just compiled the latest preview of Qt4.6 on Snow Leopard in 64 bit without any major issues. Now, I am trying to do the same for PyQt4.6 with the latest snapshot from the River Bank website. However, the compiler exits with the following issue: ``` g++ -c -pipe -fPIC -arch x86_64 -O2 -Wall -W -DNDEBUG -DQT_NO_DEBUG -DQT_CORE_LIB -I. -I/Users/drufat/Downloads/PyQt-mac-gpl-4.6-snapshot-20090914/qpy/QtCore -I/System/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6 -I/usr/local/Trolltech/Qt-4.6.0/mkspecs/default -I/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers -I/usr/local/Trolltech/Qt-4.6.0/include -F/Users/drufat/Downloads/PyQt-mac-gpl-4.6-snapshot-20090914/qpy/QtCore -F/usr/local/Trolltech/Qt-4.6.0/lib -o sipQtCoreQResource.o sipQtCoreQResource.cpp /usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h: In copy constructor ‘QResource::QResource(const QResource&)’: /usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:180: error: ‘QScopedPointer::QScopedPointer(const QScopedPointer&) [with T = QResourcePrivate, Cleanup = QScopedPointerDeleter]’ is private /usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qresource.h:59: error: within this context sipQtCoreQResource.cpp: In constructor ‘sipQResource::sipQResource(const QResource&)’: sipQtCoreQResource.cpp:78: note: synthesized method ‘QResource::QResource(const QResource&)’ first required here /usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h: In static member function ‘static void QScopedPointerDeleter::cleanup(T*) [with T = QResourcePrivate]’: /usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:100: instantiated from ‘QScopedPointer::~QScopedPointer() [with T = QResourcePrivate, Cleanup = QScopedPointerDeleter]’ /usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qresource.h:59: instantiated from here /usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:59: error: invalid application of ‘sizeof’ to incomplete type ‘QResourcePrivate’ /usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:59: error: creating array with negative size (‘-0x00000000000000001’) /usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:60: error: invalid application of ‘sizeof’ to incomplete type ‘QResourcePrivate’ /usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:60: error: creating array with negative size (‘-0x00000000000000001’) /usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:62: warning: possible problem detected in invocation of delete operator: /usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:54: warning: ‘pointer’ has incomplete type /usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qresource.h:56: warning: forward declaration of ‘struct QResourcePrivate’ /usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:62: note: neither the destructor nor the class-specific operator delete will be called, even if they are declared when the class is defined. ``` Is this an error with PyQt4 trying to access a private member of a Qt4 class? Has anybody compiled PyQt4 on Snow Leopard successfully?",2009/09/15,"['https://Stackoverflow.com/questions/1429246', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/134397/']","In the changelogs I see Phil (PyQt's maintainer) [has issued fixes](http://www.riverbankcomputing.co.uk/static/Downloads/PyQt4/ChangeLog-4.6-snapshot-20090914) yesterday in the development snapshots specifically for Snow Leopard: > > 2009/09/14 12:12:49 phil Further > fixes for Snow Leopard on 64 bit > systems. Added > QObject.pyqtConfigure(). > > > Are you using yesterday's build of PyQt? [This thread on the mailinglist](http://www.riverbankcomputing.com/pipermail/pyqt/2009-September/thread.html#24247) is also particulary interesting. The PyQt compile troubles seems to be caused by Snow Leopards default 64bit compiles and the 64/32 bit mixed version of Python it ships with. If things continue to go wrong, i would submit your problems to this mailinglist (so they can get fixed - hopefully) and try to (temporarily) rebuild Qt and PyQt (and possibly python) in a 32-bit fashion (with the -m32 compiler flag) if you need it working now.","You might want to use PyQt from the homebrew project: straightforward build, managed dependencies. Run fine on my MBP Unibody, all 64-bit." 1429246,"I just compiled the latest preview of Qt4.6 on Snow Leopard in 64 bit without any major issues. Now, I am trying to do the same for PyQt4.6 with the latest snapshot from the River Bank website. However, the compiler exits with the following issue: ``` g++ -c -pipe -fPIC -arch x86_64 -O2 -Wall -W -DNDEBUG -DQT_NO_DEBUG -DQT_CORE_LIB -I. -I/Users/drufat/Downloads/PyQt-mac-gpl-4.6-snapshot-20090914/qpy/QtCore -I/System/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6 -I/usr/local/Trolltech/Qt-4.6.0/mkspecs/default -I/usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers -I/usr/local/Trolltech/Qt-4.6.0/include -F/Users/drufat/Downloads/PyQt-mac-gpl-4.6-snapshot-20090914/qpy/QtCore -F/usr/local/Trolltech/Qt-4.6.0/lib -o sipQtCoreQResource.o sipQtCoreQResource.cpp /usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h: In copy constructor ‘QResource::QResource(const QResource&)’: /usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:180: error: ‘QScopedPointer::QScopedPointer(const QScopedPointer&) [with T = QResourcePrivate, Cleanup = QScopedPointerDeleter]’ is private /usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qresource.h:59: error: within this context sipQtCoreQResource.cpp: In constructor ‘sipQResource::sipQResource(const QResource&)’: sipQtCoreQResource.cpp:78: note: synthesized method ‘QResource::QResource(const QResource&)’ first required here /usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h: In static member function ‘static void QScopedPointerDeleter::cleanup(T*) [with T = QResourcePrivate]’: /usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:100: instantiated from ‘QScopedPointer::~QScopedPointer() [with T = QResourcePrivate, Cleanup = QScopedPointerDeleter]’ /usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qresource.h:59: instantiated from here /usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:59: error: invalid application of ‘sizeof’ to incomplete type ‘QResourcePrivate’ /usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:59: error: creating array with negative size (‘-0x00000000000000001’) /usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:60: error: invalid application of ‘sizeof’ to incomplete type ‘QResourcePrivate’ /usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:60: error: creating array with negative size (‘-0x00000000000000001’) /usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:62: warning: possible problem detected in invocation of delete operator: /usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:54: warning: ‘pointer’ has incomplete type /usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qresource.h:56: warning: forward declaration of ‘struct QResourcePrivate’ /usr/local/Trolltech/Qt-4.6.0/lib/QtCore.framework/Headers/qscopedpointer.h:62: note: neither the destructor nor the class-specific operator delete will be called, even if they are declared when the class is defined. ``` Is this an error with PyQt4 trying to access a private member of a Qt4 class? Has anybody compiled PyQt4 on Snow Leopard successfully?",2009/09/15,"['https://Stackoverflow.com/questions/1429246', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/134397/']",I just got PyQt 4.6.2 working with the 64bit Python 2.6.1. I posted the instructions here: ,"You might want to use PyQt from the homebrew project: straightforward build, managed dependencies. Run fine on my MBP Unibody, all 64-bit." 15653028,"What is the best way to get the current location in android for the following scenario, 1. If GPS is not available, get location from Network provider 2. If GPS is available and can get current location, get location from GPS provider 3. If GPS is available but can't get current location(i.e continuously searching location), get location from the network provider. now i can getting a location from network if gps not available, the best answer to satisfy the above scenario is highly appreciated. thanks in advance.",2013/03/27,"['https://Stackoverflow.com/questions/15653028', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1351297/']","Well, you can use [Timer](http://developer.android.com/reference/java/util/Timer.html) and [TimerTask](http://developer.android.com/reference/java/util/TimerTask.html) classes. ``` LocationManager manager; TimerTask mTimertask; GPSLocationListener mGPSLocationListener; int i = 0; //Here i works as counter; private static final int MAX_ATTEMPTS = 250; public void getCurrentLocation() { manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); mGPSLocationListener = new GPSLocationListener(); manager.addGpsStatusListener(mGPSStatusListener); mTimerTask = new LocTimerTask(LocationManager.GPS_PROVIDER); if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { Log.v(TAG, ""GPS ENABLED""); manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 50.0f, mGPSLocationListener); } else { turnGPSOn(); manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 50.0f, mGPSLocationListener); } if(manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000L, 50.0f, mNetworkLocationListener); } if (manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { Log.v(TAG, ""GPS ENABLED""); manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000L, 50.0f, mGPSLocationListener); } myLocTimer = new Timer(""LocationRunner"", true); myLocTimer.schedule(mTimerTask, 0, 500); } ``` **GPSStatusListener** ``` private GpsStatus.Listener mGPSStatusListener = new GpsStatus.Listener() { @Override public synchronized void onGpsStatusChanged(int event) { switch (event) { case GpsStatus.GPS_EVENT_SATELLITE_STATUS: Log.v(TAG, ""GPS SAtellitestatus""); GpsStatus status = manager.getGpsStatus(null); mSattelites = 0; Iterable list = status.getSatellites(); for (GpsSatellite satellite : list) { if (satellite.usedInFix()) { mSattelites++; } } break; case GpsStatus.GPS_EVENT_FIRST_FIX: /* * Toast.makeText(getApplicationContext(), ""Got First Fix"", * Toast.LENGTH_LONG).show(); */ break; case GpsStatus.GPS_EVENT_STARTED: /* * Toast.makeText(getApplicationContext(), ""GPS Event Started"", * Toast.LENGTH_LONG).show(); */ break; case GpsStatus.GPS_EVENT_STOPPED: /* * Toast.makeText(getApplicationContext(), ""GPS Event Stopped"", * Toast.LENGTH_LONG).show(); */ break; default: break; } } }; ``` **LocationListener** ``` public class GPSLocationListener implements LocationListener { @Override public void onLocationChanged(Location argLocation) { location = argLocation; } public void onProviderDisabled(String provider) { } public void onProviderEnabled(String provider) { } public void onStatusChanged(String provider, int status, Bundle extras) { } } ``` **TimerTask class** ``` class LocTimerTask extends TimerTask { String provider; public LocTimerTask(String provider) { this.provider = provider; } final Handler mHandler = new Handler(Looper.getMainLooper()); Runnable r = new Runnable() { @Override public void run() { i++; Log.v(TAG, ""Timer Task run"" + i); location = manager.getLastKnownLocation(provider); if (location != null) { Log.v(TAG, ""in timer task run in if location not null""); isGPS = true; onLocationReceived(location); myLocTimer.cancel(); myLocTimer.purge(); mTimerTask.cancel(); return; } else { Log.v(TAG, ""in timer task run in else location null""); isGPS = false; if (location == null && i == MAX_ATTEMPTS) { Log.v(TAG, ""if 1 max attempts done""); turnGPSOff(); location = manager .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (location != null) { Log.v(TAG, ""if 1 max attempts done Location from network not null""); Log.v(TAG, ""if 1 max attempts done Location from network not null coordinates not null""); onLocationReceived(location); myLocTimer.cancel(); myLocTimer.purge(); mTimerTask.cancel(); return; } } else { return; } } i = 0; } }; public void run() { mHandler.post(r); } } ``` Here the timer has been scheduled to run on every 500 milliseconds. Means, on every 500 milliseconds the timer task's `run method` will executed. In run method try get location from GPS provider for specific no. of attempts(**Here MAX\_ATTEMPTS**) say 5 or 10. If it gets location within specified no. of attempts then use that location else if counter(**Here i**) value has exceeded MAX\_ATTEMPTS, then get location from Network Provider. on getting location, I had passed that location to callback method `onLocationReceived(Location mLoc)` in which you can do your further work with location data. Here's how you will use callback method: **Listener** ``` public interface OnLocationReceivedListener { public void onLocationReceived(Location mLoc); //callback method which will be defined in your class. ``` } Your class should implement the above defined listener. In your class: ``` @Override public void onLocationReceived(Location mLoc) { //Do your stuff } ``` Hope it helps. If anybody have a better approach, then please let me know.","``` If GPS is available and can get current location, ``` For the above question you can try like this.. Using this you can get the latitude and longitude for the current location then pass the value to get the map. ``` public class MyLocationListener implements LocationListener { @Override public void onLocationChanged(Location loc) { loc.getLatitude(); loc.getLongitude(); String Text = “My current location is: “ + “Latitud = “ + loc.getLatitude() + “Longitud = “ + loc.getLongitude(); Toast.makeText( getApplicationContext(), Text, Toast.LENGTH_SHORT).show(); } @Override public void onProviderDisabled(String provider) { Toast.makeText( getApplicationContext(), “Gps Disabled”, Toast.LENGTH_SHORT ).show(); } @Override public void onProviderEnabled(String provider) { Toast.makeText( getApplicationContext(), “Gps Enabled”, Toast.LENGTH_SHORT).show(); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } } } ```" 15653028,"What is the best way to get the current location in android for the following scenario, 1. If GPS is not available, get location from Network provider 2. If GPS is available and can get current location, get location from GPS provider 3. If GPS is available but can't get current location(i.e continuously searching location), get location from the network provider. now i can getting a location from network if gps not available, the best answer to satisfy the above scenario is highly appreciated. thanks in advance.",2013/03/27,"['https://Stackoverflow.com/questions/15653028', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1351297/']","Well, you can use [Timer](http://developer.android.com/reference/java/util/Timer.html) and [TimerTask](http://developer.android.com/reference/java/util/TimerTask.html) classes. ``` LocationManager manager; TimerTask mTimertask; GPSLocationListener mGPSLocationListener; int i = 0; //Here i works as counter; private static final int MAX_ATTEMPTS = 250; public void getCurrentLocation() { manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); mGPSLocationListener = new GPSLocationListener(); manager.addGpsStatusListener(mGPSStatusListener); mTimerTask = new LocTimerTask(LocationManager.GPS_PROVIDER); if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { Log.v(TAG, ""GPS ENABLED""); manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 50.0f, mGPSLocationListener); } else { turnGPSOn(); manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 50.0f, mGPSLocationListener); } if(manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000L, 50.0f, mNetworkLocationListener); } if (manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { Log.v(TAG, ""GPS ENABLED""); manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000L, 50.0f, mGPSLocationListener); } myLocTimer = new Timer(""LocationRunner"", true); myLocTimer.schedule(mTimerTask, 0, 500); } ``` **GPSStatusListener** ``` private GpsStatus.Listener mGPSStatusListener = new GpsStatus.Listener() { @Override public synchronized void onGpsStatusChanged(int event) { switch (event) { case GpsStatus.GPS_EVENT_SATELLITE_STATUS: Log.v(TAG, ""GPS SAtellitestatus""); GpsStatus status = manager.getGpsStatus(null); mSattelites = 0; Iterable list = status.getSatellites(); for (GpsSatellite satellite : list) { if (satellite.usedInFix()) { mSattelites++; } } break; case GpsStatus.GPS_EVENT_FIRST_FIX: /* * Toast.makeText(getApplicationContext(), ""Got First Fix"", * Toast.LENGTH_LONG).show(); */ break; case GpsStatus.GPS_EVENT_STARTED: /* * Toast.makeText(getApplicationContext(), ""GPS Event Started"", * Toast.LENGTH_LONG).show(); */ break; case GpsStatus.GPS_EVENT_STOPPED: /* * Toast.makeText(getApplicationContext(), ""GPS Event Stopped"", * Toast.LENGTH_LONG).show(); */ break; default: break; } } }; ``` **LocationListener** ``` public class GPSLocationListener implements LocationListener { @Override public void onLocationChanged(Location argLocation) { location = argLocation; } public void onProviderDisabled(String provider) { } public void onProviderEnabled(String provider) { } public void onStatusChanged(String provider, int status, Bundle extras) { } } ``` **TimerTask class** ``` class LocTimerTask extends TimerTask { String provider; public LocTimerTask(String provider) { this.provider = provider; } final Handler mHandler = new Handler(Looper.getMainLooper()); Runnable r = new Runnable() { @Override public void run() { i++; Log.v(TAG, ""Timer Task run"" + i); location = manager.getLastKnownLocation(provider); if (location != null) { Log.v(TAG, ""in timer task run in if location not null""); isGPS = true; onLocationReceived(location); myLocTimer.cancel(); myLocTimer.purge(); mTimerTask.cancel(); return; } else { Log.v(TAG, ""in timer task run in else location null""); isGPS = false; if (location == null && i == MAX_ATTEMPTS) { Log.v(TAG, ""if 1 max attempts done""); turnGPSOff(); location = manager .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (location != null) { Log.v(TAG, ""if 1 max attempts done Location from network not null""); Log.v(TAG, ""if 1 max attempts done Location from network not null coordinates not null""); onLocationReceived(location); myLocTimer.cancel(); myLocTimer.purge(); mTimerTask.cancel(); return; } } else { return; } } i = 0; } }; public void run() { mHandler.post(r); } } ``` Here the timer has been scheduled to run on every 500 milliseconds. Means, on every 500 milliseconds the timer task's `run method` will executed. In run method try get location from GPS provider for specific no. of attempts(**Here MAX\_ATTEMPTS**) say 5 or 10. If it gets location within specified no. of attempts then use that location else if counter(**Here i**) value has exceeded MAX\_ATTEMPTS, then get location from Network Provider. on getting location, I had passed that location to callback method `onLocationReceived(Location mLoc)` in which you can do your further work with location data. Here's how you will use callback method: **Listener** ``` public interface OnLocationReceivedListener { public void onLocationReceived(Location mLoc); //callback method which will be defined in your class. ``` } Your class should implement the above defined listener. In your class: ``` @Override public void onLocationReceived(Location mLoc) { //Do your stuff } ``` Hope it helps. If anybody have a better approach, then please let me know.","class member `boolean mIsGpsFix`; Request Gps location update and set up a countdown timer ``` mCountDown.start(); private CountDownTimer mCountDown = new CountDownTimer(time to wait for Gps fix, same as right) { @Override public void onTick(long millisUntilFinished) { } @Override public void onFinish() { // No fix after the desire amount of time collapse if (!mIsGpsFix) // Register for Network } }; ```" 58362757,"I'm using `netstandard2.1` library in my `netcoreapp3.0` web application. When adding my service in `Startup`, I'm getting the below error: > > 'Could not load type 'Microsoft.AspNetCore.Mvc.MvcJsonOptions' from > assembly 'Microsoft.AspNetCore.Mvc.Formatters.Json, Version=3.0.0.0 > > > I'm also using some features from `Microsoft.AspNetCore.Mvc` 2.2.0 package in my class library. Here is my library `.csproj`, ```xml netstandard2.1 ``` Here is my `ServiceExtensions` class from my library, ```cs public static class ServiceExtensions { public static IMvcBuilder AddMyLibrary(this IMvcBuilder builder) { builder.Services.TryAddSingleton(); builder.AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new DefaultContractResolver(); }); builder.Services.ConfigureOptions(); return builder; } } ``` Here is my `ConfigureLibraryOptions` class, ```cs public class ConfigureLibraryOptions : IConfigureOptions { public void Configure(MvcOptions options) { options.ModelBinderProviders.Insert(0, new CustomBinderProvider()); } } ``` Here is the `ConfigureServices` from `Startup`, ```cs services.AddControllersWithViews().AddMyLibrary(); ``` Please help on why I'm getting this error and assist on how to solve this?",2019/10/13,"['https://Stackoverflow.com/questions/58362757', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10851213/']",The reason why you're getting the error is because `MvcJsonOptions` was removed in .NET Core 3.0; you can read more about the breaking changes [here](https://github.com/aspnet/Announcements/issues/325).,"In my case, the solution was to add `services.AddControllers()` as described under ." 58362757,"I'm using `netstandard2.1` library in my `netcoreapp3.0` web application. When adding my service in `Startup`, I'm getting the below error: > > 'Could not load type 'Microsoft.AspNetCore.Mvc.MvcJsonOptions' from > assembly 'Microsoft.AspNetCore.Mvc.Formatters.Json, Version=3.0.0.0 > > > I'm also using some features from `Microsoft.AspNetCore.Mvc` 2.2.0 package in my class library. Here is my library `.csproj`, ```xml netstandard2.1 ``` Here is my `ServiceExtensions` class from my library, ```cs public static class ServiceExtensions { public static IMvcBuilder AddMyLibrary(this IMvcBuilder builder) { builder.Services.TryAddSingleton(); builder.AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new DefaultContractResolver(); }); builder.Services.ConfigureOptions(); return builder; } } ``` Here is my `ConfigureLibraryOptions` class, ```cs public class ConfigureLibraryOptions : IConfigureOptions { public void Configure(MvcOptions options) { options.ModelBinderProviders.Insert(0, new CustomBinderProvider()); } } ``` Here is the `ConfigureServices` from `Startup`, ```cs services.AddControllersWithViews().AddMyLibrary(); ``` Please help on why I'm getting this error and assist on how to solve this?",2019/10/13,"['https://Stackoverflow.com/questions/58362757', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10851213/']","netstandard2.1 to netcoreapp3.0 MvcJsonOptions -> MvcNewtonsoftJsonOptions ``` public IServiceProvider ConfigureServices(IServiceCollection services) { //MVC services.AddControllersWithViews(options => { }).AddNewtonsoftJson(); services.PostConfigure(options => { options.SerializerSettings.ContractResolver = new MyCustomContractResolver() { NamingStrategy = new CamelCaseNamingStrategy() }; options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; }); } ```","When you config ""Swashbuckle.AspNetCore"", needed for configuring ApiKeyScheme become to OpenApiSecurityScheme it is changing the scheme from ``` c.AddSecurityDefinition(""Bearer"", new ApiKeyScheme { In = ""header"", Description = ""Please enter JWT with Bearer into field"", Name = ""Authorization"", Type = ""apiKey"" }); c.AddSecurityRequirement(new Dictionary> { { ""Bearer"", Enumerable.Empty() }, }); ``` To ``` c.AddSecurityDefinition(""Bearer"", new OpenApiSecurityScheme { Description = ""JWT Authorization header using the Bearer scheme. \r\n\r\n Enter 'Bearer' [space] and then your token in the text input below.\r\n\r\nExample: \""Bearer 12345abcdef\"""", Name = ""Authorization"", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey, Scheme = ""Bearer"" }); c.AddSecurityRequirement(new OpenApiSecurityRequirement() { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = ""Bearer"" }, Scheme = ""oauth2"", Name = ""Bearer"", In = ParameterLocation.Header, }, new List() } }); ```" 58362757,"I'm using `netstandard2.1` library in my `netcoreapp3.0` web application. When adding my service in `Startup`, I'm getting the below error: > > 'Could not load type 'Microsoft.AspNetCore.Mvc.MvcJsonOptions' from > assembly 'Microsoft.AspNetCore.Mvc.Formatters.Json, Version=3.0.0.0 > > > I'm also using some features from `Microsoft.AspNetCore.Mvc` 2.2.0 package in my class library. Here is my library `.csproj`, ```xml netstandard2.1 ``` Here is my `ServiceExtensions` class from my library, ```cs public static class ServiceExtensions { public static IMvcBuilder AddMyLibrary(this IMvcBuilder builder) { builder.Services.TryAddSingleton(); builder.AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new DefaultContractResolver(); }); builder.Services.ConfigureOptions(); return builder; } } ``` Here is my `ConfigureLibraryOptions` class, ```cs public class ConfigureLibraryOptions : IConfigureOptions { public void Configure(MvcOptions options) { options.ModelBinderProviders.Insert(0, new CustomBinderProvider()); } } ``` Here is the `ConfigureServices` from `Startup`, ```cs services.AddControllersWithViews().AddMyLibrary(); ``` Please help on why I'm getting this error and assist on how to solve this?",2019/10/13,"['https://Stackoverflow.com/questions/58362757', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10851213/']","I'm not sure if this solves OP's problem, but this error also occurs when you use Swashbuckle 4 in .Net Core 3. The solution is to use Swashbuckle 5. (use command `install-package Swashbuckle.AspNetCore`) to have in .csproj ``` ``` Then you'll need to upgrade it in Startup.cs. Generally that involves prefixing classes that don't compile with `OpenApi` e.g. `options.SwaggerDoc(""v1"" new Info ...` becomes `options.SwaggerDoc(""v1"", OpenApiInfo` Also `OpenApiSecurityScheme` becomes `ApiKeyScheme` See also docs at ",The reason why you're getting the error is because `MvcJsonOptions` was removed in .NET Core 3.0; you can read more about the breaking changes [here](https://github.com/aspnet/Announcements/issues/325). 58362757,"I'm using `netstandard2.1` library in my `netcoreapp3.0` web application. When adding my service in `Startup`, I'm getting the below error: > > 'Could not load type 'Microsoft.AspNetCore.Mvc.MvcJsonOptions' from > assembly 'Microsoft.AspNetCore.Mvc.Formatters.Json, Version=3.0.0.0 > > > I'm also using some features from `Microsoft.AspNetCore.Mvc` 2.2.0 package in my class library. Here is my library `.csproj`, ```xml netstandard2.1 ``` Here is my `ServiceExtensions` class from my library, ```cs public static class ServiceExtensions { public static IMvcBuilder AddMyLibrary(this IMvcBuilder builder) { builder.Services.TryAddSingleton(); builder.AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new DefaultContractResolver(); }); builder.Services.ConfigureOptions(); return builder; } } ``` Here is my `ConfigureLibraryOptions` class, ```cs public class ConfigureLibraryOptions : IConfigureOptions { public void Configure(MvcOptions options) { options.ModelBinderProviders.Insert(0, new CustomBinderProvider()); } } ``` Here is the `ConfigureServices` from `Startup`, ```cs services.AddControllersWithViews().AddMyLibrary(); ``` Please help on why I'm getting this error and assist on how to solve this?",2019/10/13,"['https://Stackoverflow.com/questions/58362757', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10851213/']","I'm not sure if this solves OP's problem, but this error also occurs when you use Swashbuckle 4 in .Net Core 3. The solution is to use Swashbuckle 5. (use command `install-package Swashbuckle.AspNetCore`) to have in .csproj ``` ``` Then you'll need to upgrade it in Startup.cs. Generally that involves prefixing classes that don't compile with `OpenApi` e.g. `options.SwaggerDoc(""v1"" new Info ...` becomes `options.SwaggerDoc(""v1"", OpenApiInfo` Also `OpenApiSecurityScheme` becomes `ApiKeyScheme` See also docs at ","The problem is most likely with the incompatible nuget packages for .net core 3.1 above. Take a look at your packages and eventually upgrade to compatible version of core 3.1. That should really fix the issue I had one with Automapper and others had with Swagger. If you are using AutoMapper you should upgrade to 7.0.0 See " 58362757,"I'm using `netstandard2.1` library in my `netcoreapp3.0` web application. When adding my service in `Startup`, I'm getting the below error: > > 'Could not load type 'Microsoft.AspNetCore.Mvc.MvcJsonOptions' from > assembly 'Microsoft.AspNetCore.Mvc.Formatters.Json, Version=3.0.0.0 > > > I'm also using some features from `Microsoft.AspNetCore.Mvc` 2.2.0 package in my class library. Here is my library `.csproj`, ```xml netstandard2.1 ``` Here is my `ServiceExtensions` class from my library, ```cs public static class ServiceExtensions { public static IMvcBuilder AddMyLibrary(this IMvcBuilder builder) { builder.Services.TryAddSingleton(); builder.AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new DefaultContractResolver(); }); builder.Services.ConfigureOptions(); return builder; } } ``` Here is my `ConfigureLibraryOptions` class, ```cs public class ConfigureLibraryOptions : IConfigureOptions { public void Configure(MvcOptions options) { options.ModelBinderProviders.Insert(0, new CustomBinderProvider()); } } ``` Here is the `ConfigureServices` from `Startup`, ```cs services.AddControllersWithViews().AddMyLibrary(); ``` Please help on why I'm getting this error and assist on how to solve this?",2019/10/13,"['https://Stackoverflow.com/questions/58362757', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10851213/']",The reason why you're getting the error is because `MvcJsonOptions` was removed in .NET Core 3.0; you can read more about the breaking changes [here](https://github.com/aspnet/Announcements/issues/325).,"The problem is most likely with the incompatible nuget packages for .net core 3.1 above. Take a look at your packages and eventually upgrade to compatible version of core 3.1. That should really fix the issue I had one with Automapper and others had with Swagger. If you are using AutoMapper you should upgrade to 7.0.0 See " 58362757,"I'm using `netstandard2.1` library in my `netcoreapp3.0` web application. When adding my service in `Startup`, I'm getting the below error: > > 'Could not load type 'Microsoft.AspNetCore.Mvc.MvcJsonOptions' from > assembly 'Microsoft.AspNetCore.Mvc.Formatters.Json, Version=3.0.0.0 > > > I'm also using some features from `Microsoft.AspNetCore.Mvc` 2.2.0 package in my class library. Here is my library `.csproj`, ```xml netstandard2.1 ``` Here is my `ServiceExtensions` class from my library, ```cs public static class ServiceExtensions { public static IMvcBuilder AddMyLibrary(this IMvcBuilder builder) { builder.Services.TryAddSingleton(); builder.AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new DefaultContractResolver(); }); builder.Services.ConfigureOptions(); return builder; } } ``` Here is my `ConfigureLibraryOptions` class, ```cs public class ConfigureLibraryOptions : IConfigureOptions { public void Configure(MvcOptions options) { options.ModelBinderProviders.Insert(0, new CustomBinderProvider()); } } ``` Here is the `ConfigureServices` from `Startup`, ```cs services.AddControllersWithViews().AddMyLibrary(); ``` Please help on why I'm getting this error and assist on how to solve this?",2019/10/13,"['https://Stackoverflow.com/questions/58362757', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10851213/']","I'm not sure if this solves OP's problem, but this error also occurs when you use Swashbuckle 4 in .Net Core 3. The solution is to use Swashbuckle 5. (use command `install-package Swashbuckle.AspNetCore`) to have in .csproj ``` ``` Then you'll need to upgrade it in Startup.cs. Generally that involves prefixing classes that don't compile with `OpenApi` e.g. `options.SwaggerDoc(""v1"" new Info ...` becomes `options.SwaggerDoc(""v1"", OpenApiInfo` Also `OpenApiSecurityScheme` becomes `ApiKeyScheme` See also docs at ","In my case, the solution was to add `services.AddControllers()` as described under ." 58362757,"I'm using `netstandard2.1` library in my `netcoreapp3.0` web application. When adding my service in `Startup`, I'm getting the below error: > > 'Could not load type 'Microsoft.AspNetCore.Mvc.MvcJsonOptions' from > assembly 'Microsoft.AspNetCore.Mvc.Formatters.Json, Version=3.0.0.0 > > > I'm also using some features from `Microsoft.AspNetCore.Mvc` 2.2.0 package in my class library. Here is my library `.csproj`, ```xml netstandard2.1 ``` Here is my `ServiceExtensions` class from my library, ```cs public static class ServiceExtensions { public static IMvcBuilder AddMyLibrary(this IMvcBuilder builder) { builder.Services.TryAddSingleton(); builder.AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new DefaultContractResolver(); }); builder.Services.ConfigureOptions(); return builder; } } ``` Here is my `ConfigureLibraryOptions` class, ```cs public class ConfigureLibraryOptions : IConfigureOptions { public void Configure(MvcOptions options) { options.ModelBinderProviders.Insert(0, new CustomBinderProvider()); } } ``` Here is the `ConfigureServices` from `Startup`, ```cs services.AddControllersWithViews().AddMyLibrary(); ``` Please help on why I'm getting this error and assist on how to solve this?",2019/10/13,"['https://Stackoverflow.com/questions/58362757', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10851213/']","The problem is most likely with the incompatible nuget packages for .net core 3.1 above. Take a look at your packages and eventually upgrade to compatible version of core 3.1. That should really fix the issue I had one with Automapper and others had with Swagger. If you are using AutoMapper you should upgrade to 7.0.0 See ","In my case, the solution was to add `services.AddControllers()` as described under ." 58362757,"I'm using `netstandard2.1` library in my `netcoreapp3.0` web application. When adding my service in `Startup`, I'm getting the below error: > > 'Could not load type 'Microsoft.AspNetCore.Mvc.MvcJsonOptions' from > assembly 'Microsoft.AspNetCore.Mvc.Formatters.Json, Version=3.0.0.0 > > > I'm also using some features from `Microsoft.AspNetCore.Mvc` 2.2.0 package in my class library. Here is my library `.csproj`, ```xml netstandard2.1 ``` Here is my `ServiceExtensions` class from my library, ```cs public static class ServiceExtensions { public static IMvcBuilder AddMyLibrary(this IMvcBuilder builder) { builder.Services.TryAddSingleton(); builder.AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new DefaultContractResolver(); }); builder.Services.ConfigureOptions(); return builder; } } ``` Here is my `ConfigureLibraryOptions` class, ```cs public class ConfigureLibraryOptions : IConfigureOptions { public void Configure(MvcOptions options) { options.ModelBinderProviders.Insert(0, new CustomBinderProvider()); } } ``` Here is the `ConfigureServices` from `Startup`, ```cs services.AddControllersWithViews().AddMyLibrary(); ``` Please help on why I'm getting this error and assist on how to solve this?",2019/10/13,"['https://Stackoverflow.com/questions/58362757', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10851213/']","netstandard2.1 to netcoreapp3.0 MvcJsonOptions -> MvcNewtonsoftJsonOptions ``` public IServiceProvider ConfigureServices(IServiceCollection services) { //MVC services.AddControllersWithViews(options => { }).AddNewtonsoftJson(); services.PostConfigure(options => { options.SerializerSettings.ContractResolver = new MyCustomContractResolver() { NamingStrategy = new CamelCaseNamingStrategy() }; options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; }); } ```","The problem is most likely with the incompatible nuget packages for .net core 3.1 above. Take a look at your packages and eventually upgrade to compatible version of core 3.1. That should really fix the issue I had one with Automapper and others had with Swagger. If you are using AutoMapper you should upgrade to 7.0.0 See " 58362757,"I'm using `netstandard2.1` library in my `netcoreapp3.0` web application. When adding my service in `Startup`, I'm getting the below error: > > 'Could not load type 'Microsoft.AspNetCore.Mvc.MvcJsonOptions' from > assembly 'Microsoft.AspNetCore.Mvc.Formatters.Json, Version=3.0.0.0 > > > I'm also using some features from `Microsoft.AspNetCore.Mvc` 2.2.0 package in my class library. Here is my library `.csproj`, ```xml netstandard2.1 ``` Here is my `ServiceExtensions` class from my library, ```cs public static class ServiceExtensions { public static IMvcBuilder AddMyLibrary(this IMvcBuilder builder) { builder.Services.TryAddSingleton(); builder.AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new DefaultContractResolver(); }); builder.Services.ConfigureOptions(); return builder; } } ``` Here is my `ConfigureLibraryOptions` class, ```cs public class ConfigureLibraryOptions : IConfigureOptions { public void Configure(MvcOptions options) { options.ModelBinderProviders.Insert(0, new CustomBinderProvider()); } } ``` Here is the `ConfigureServices` from `Startup`, ```cs services.AddControllersWithViews().AddMyLibrary(); ``` Please help on why I'm getting this error and assist on how to solve this?",2019/10/13,"['https://Stackoverflow.com/questions/58362757', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10851213/']","I'm not sure if this solves OP's problem, but this error also occurs when you use Swashbuckle 4 in .Net Core 3. The solution is to use Swashbuckle 5. (use command `install-package Swashbuckle.AspNetCore`) to have in .csproj ``` ``` Then you'll need to upgrade it in Startup.cs. Generally that involves prefixing classes that don't compile with `OpenApi` e.g. `options.SwaggerDoc(""v1"" new Info ...` becomes `options.SwaggerDoc(""v1"", OpenApiInfo` Also `OpenApiSecurityScheme` becomes `ApiKeyScheme` See also docs at ","netstandard2.1 to netcoreapp3.0 MvcJsonOptions -> MvcNewtonsoftJsonOptions ``` public IServiceProvider ConfigureServices(IServiceCollection services) { //MVC services.AddControllersWithViews(options => { }).AddNewtonsoftJson(); services.PostConfigure(options => { options.SerializerSettings.ContractResolver = new MyCustomContractResolver() { NamingStrategy = new CamelCaseNamingStrategy() }; options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; }); } ```" 58362757,"I'm using `netstandard2.1` library in my `netcoreapp3.0` web application. When adding my service in `Startup`, I'm getting the below error: > > 'Could not load type 'Microsoft.AspNetCore.Mvc.MvcJsonOptions' from > assembly 'Microsoft.AspNetCore.Mvc.Formatters.Json, Version=3.0.0.0 > > > I'm also using some features from `Microsoft.AspNetCore.Mvc` 2.2.0 package in my class library. Here is my library `.csproj`, ```xml netstandard2.1 ``` Here is my `ServiceExtensions` class from my library, ```cs public static class ServiceExtensions { public static IMvcBuilder AddMyLibrary(this IMvcBuilder builder) { builder.Services.TryAddSingleton(); builder.AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new DefaultContractResolver(); }); builder.Services.ConfigureOptions(); return builder; } } ``` Here is my `ConfigureLibraryOptions` class, ```cs public class ConfigureLibraryOptions : IConfigureOptions { public void Configure(MvcOptions options) { options.ModelBinderProviders.Insert(0, new CustomBinderProvider()); } } ``` Here is the `ConfigureServices` from `Startup`, ```cs services.AddControllersWithViews().AddMyLibrary(); ``` Please help on why I'm getting this error and assist on how to solve this?",2019/10/13,"['https://Stackoverflow.com/questions/58362757', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10851213/']","When you config ""Swashbuckle.AspNetCore"", needed for configuring ApiKeyScheme become to OpenApiSecurityScheme it is changing the scheme from ``` c.AddSecurityDefinition(""Bearer"", new ApiKeyScheme { In = ""header"", Description = ""Please enter JWT with Bearer into field"", Name = ""Authorization"", Type = ""apiKey"" }); c.AddSecurityRequirement(new Dictionary> { { ""Bearer"", Enumerable.Empty() }, }); ``` To ``` c.AddSecurityDefinition(""Bearer"", new OpenApiSecurityScheme { Description = ""JWT Authorization header using the Bearer scheme. \r\n\r\n Enter 'Bearer' [space] and then your token in the text input below.\r\n\r\nExample: \""Bearer 12345abcdef\"""", Name = ""Authorization"", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey, Scheme = ""Bearer"" }); c.AddSecurityRequirement(new OpenApiSecurityRequirement() { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = ""Bearer"" }, Scheme = ""oauth2"", Name = ""Bearer"", In = ParameterLocation.Header, }, new List() } }); ```","In my case, the solution was to add `services.AddControllers()` as described under ." 14796931,"Google play reports an exception on some devices (all are ""other"" and one ""LG-E400"", so it might be some custom android build) Exception is: ``` java.lang.IllegalArgumentException at android.os.StatFs.native_setup(Native Method) at android.os.StatFs.(StatFs.java:32) at android.webkit.CacheManager.init(CacheManager.java:199) at android.webkit.BrowserFrame.(BrowserFrame.java:210) at android.webkit.WebViewCore.initialize(WebViewCore.java:201) at android.webkit.WebViewCore.access$500(WebViewCore.java:54) at android.webkit.WebViewCore$WebCoreThread$1.handleMessage(WebViewCore.java:631) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:130) at android.webkit.WebViewCore$WebCoreThread.run(WebViewCore.java:653) at java.lang.Thread.run(Thread.java:1019) ``` The problem is I can't ignore this axception 'cause it is in separate thread. Is there any solution for this problem? Or what can I do with that?",2013/02/10,"['https://Stackoverflow.com/questions/14796931', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1148784/']","Much likely it's a device OS bug. I have much problems with AudioRecord library - it also fails in native init on number of devices like Yusu, Micromax, Alcatel and other low range devices. They are all shown as ""other"" in GooglePlay reports. Also I encoundered that some [Cyanogenmod](http://www.cyanogenmod.org/) ROMs have a bug in AudioRecord - on my HTC One V it worked okay until I flashed CM10. One good way to know exact device model, logcats, mem and other info about what happens on these devices is to use some advanced crash report tool, as [ACRA](http://acra.ch/) After I get report that something is definitely wrong on device with it's manufacturer's firmware, I blacklist it on GooglePlay.","Looks like some firmware had problem with StatFs I had similar issue with Samsung Galaxy Stratosphere™ II (Verizon) SCH-I415, Android:4.1.2 When I call: ``` StatFs statFs = null; statFs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath()); ``` I got exception: ``` java.lang.IllegalArgumentException at android.os.StatFs.native_setup(Native Method) at android.os.StatFs.(StatFs.java:32) ```" 14796931,"Google play reports an exception on some devices (all are ""other"" and one ""LG-E400"", so it might be some custom android build) Exception is: ``` java.lang.IllegalArgumentException at android.os.StatFs.native_setup(Native Method) at android.os.StatFs.(StatFs.java:32) at android.webkit.CacheManager.init(CacheManager.java:199) at android.webkit.BrowserFrame.(BrowserFrame.java:210) at android.webkit.WebViewCore.initialize(WebViewCore.java:201) at android.webkit.WebViewCore.access$500(WebViewCore.java:54) at android.webkit.WebViewCore$WebCoreThread$1.handleMessage(WebViewCore.java:631) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:130) at android.webkit.WebViewCore$WebCoreThread.run(WebViewCore.java:653) at java.lang.Thread.run(Thread.java:1019) ``` The problem is I can't ignore this axception 'cause it is in separate thread. Is there any solution for this problem? Or what can I do with that?",2013/02/10,"['https://Stackoverflow.com/questions/14796931', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1148784/']","Much likely it's a device OS bug. I have much problems with AudioRecord library - it also fails in native init on number of devices like Yusu, Micromax, Alcatel and other low range devices. They are all shown as ""other"" in GooglePlay reports. Also I encoundered that some [Cyanogenmod](http://www.cyanogenmod.org/) ROMs have a bug in AudioRecord - on my HTC One V it worked okay until I flashed CM10. One good way to know exact device model, logcats, mem and other info about what happens on these devices is to use some advanced crash report tool, as [ACRA](http://acra.ch/) After I get report that something is definitely wrong on device with it's manufacturer's firmware, I blacklist it on GooglePlay.","I have got similar issue and my log was looking like ``` 03-14 13:41:55.715: E/PayPalService(14037): Risk component failed to initialize, threw null 03-14 13:41:56.295: E/(14037): statfs /storage/sdcard0 failed, errno: 13 03-14 13:41:56.365: E/AndroidRuntime(14037): FATAL EXCEPTION: Thread-1219 03-14 13:41:56.365: E/AndroidRuntime(14037): java.lang.IllegalArgumentException 03-14 13:41:56.365: E/AndroidRuntime(14037): at android.os.StatFs.native_setup(Native Method) 03-14 13:41:56.365: E/AndroidRuntime(14037): at android.os.StatFs.(StatFs.java:32) ``` I found this issue related to sd card by looking the first two lines .Then I checked device setting and found I had checked their a option **apps must have permission to read sd card** and the app I was installing was not having **READ SD CARD** permission in manifest. So possibly these things are related and possible solutions for me were either put permission in manifest or to unchecke that option .Hope it will help in further research." 14796931,"Google play reports an exception on some devices (all are ""other"" and one ""LG-E400"", so it might be some custom android build) Exception is: ``` java.lang.IllegalArgumentException at android.os.StatFs.native_setup(Native Method) at android.os.StatFs.(StatFs.java:32) at android.webkit.CacheManager.init(CacheManager.java:199) at android.webkit.BrowserFrame.(BrowserFrame.java:210) at android.webkit.WebViewCore.initialize(WebViewCore.java:201) at android.webkit.WebViewCore.access$500(WebViewCore.java:54) at android.webkit.WebViewCore$WebCoreThread$1.handleMessage(WebViewCore.java:631) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:130) at android.webkit.WebViewCore$WebCoreThread.run(WebViewCore.java:653) at java.lang.Thread.run(Thread.java:1019) ``` The problem is I can't ignore this axception 'cause it is in separate thread. Is there any solution for this problem? Or what can I do with that?",2013/02/10,"['https://Stackoverflow.com/questions/14796931', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1148784/']","Much likely it's a device OS bug. I have much problems with AudioRecord library - it also fails in native init on number of devices like Yusu, Micromax, Alcatel and other low range devices. They are all shown as ""other"" in GooglePlay reports. Also I encoundered that some [Cyanogenmod](http://www.cyanogenmod.org/) ROMs have a bug in AudioRecord - on my HTC One V it worked okay until I flashed CM10. One good way to know exact device model, logcats, mem and other info about what happens on these devices is to use some advanced crash report tool, as [ACRA](http://acra.ch/) After I get report that something is definitely wrong on device with it's manufacturer's firmware, I blacklist it on GooglePlay.","Path which you are providing in Statfs constructor does not exists ``` String path = ""path to some directory""; StatFs statFs = null; statFs = new StatFs(path); ``` and you must have external storage permission in manifest file" 14796931,"Google play reports an exception on some devices (all are ""other"" and one ""LG-E400"", so it might be some custom android build) Exception is: ``` java.lang.IllegalArgumentException at android.os.StatFs.native_setup(Native Method) at android.os.StatFs.(StatFs.java:32) at android.webkit.CacheManager.init(CacheManager.java:199) at android.webkit.BrowserFrame.(BrowserFrame.java:210) at android.webkit.WebViewCore.initialize(WebViewCore.java:201) at android.webkit.WebViewCore.access$500(WebViewCore.java:54) at android.webkit.WebViewCore$WebCoreThread$1.handleMessage(WebViewCore.java:631) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:130) at android.webkit.WebViewCore$WebCoreThread.run(WebViewCore.java:653) at java.lang.Thread.run(Thread.java:1019) ``` The problem is I can't ignore this axception 'cause it is in separate thread. Is there any solution for this problem? Or what can I do with that?",2013/02/10,"['https://Stackoverflow.com/questions/14796931', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1148784/']","Much likely it's a device OS bug. I have much problems with AudioRecord library - it also fails in native init on number of devices like Yusu, Micromax, Alcatel and other low range devices. They are all shown as ""other"" in GooglePlay reports. Also I encoundered that some [Cyanogenmod](http://www.cyanogenmod.org/) ROMs have a bug in AudioRecord - on my HTC One V it worked okay until I flashed CM10. One good way to know exact device model, logcats, mem and other info about what happens on these devices is to use some advanced crash report tool, as [ACRA](http://acra.ch/) After I get report that something is definitely wrong on device with it's manufacturer's firmware, I blacklist it on GooglePlay.","Starting with Lollipop, Android placed rather extreme restrictions on accessing external SD cards. You can use: ``` StatFs stat; try { stat = new StatFs(path); } catch (IllegalArgumentException e) { // Handle the failure gracefully or just throw(e) } ``` to work-around the error. For my application, I just skip unavailable directories, essentially limiting the user to the internal storage. Not an ideal solution, but a limited application that doesn't crash is better than one which does." 14796931,"Google play reports an exception on some devices (all are ""other"" and one ""LG-E400"", so it might be some custom android build) Exception is: ``` java.lang.IllegalArgumentException at android.os.StatFs.native_setup(Native Method) at android.os.StatFs.(StatFs.java:32) at android.webkit.CacheManager.init(CacheManager.java:199) at android.webkit.BrowserFrame.(BrowserFrame.java:210) at android.webkit.WebViewCore.initialize(WebViewCore.java:201) at android.webkit.WebViewCore.access$500(WebViewCore.java:54) at android.webkit.WebViewCore$WebCoreThread$1.handleMessage(WebViewCore.java:631) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:130) at android.webkit.WebViewCore$WebCoreThread.run(WebViewCore.java:653) at java.lang.Thread.run(Thread.java:1019) ``` The problem is I can't ignore this axception 'cause it is in separate thread. Is there any solution for this problem? Or what can I do with that?",2013/02/10,"['https://Stackoverflow.com/questions/14796931', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1148784/']","Path which you are providing in Statfs constructor does not exists ``` String path = ""path to some directory""; StatFs statFs = null; statFs = new StatFs(path); ``` and you must have external storage permission in manifest file","Looks like some firmware had problem with StatFs I had similar issue with Samsung Galaxy Stratosphere™ II (Verizon) SCH-I415, Android:4.1.2 When I call: ``` StatFs statFs = null; statFs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath()); ``` I got exception: ``` java.lang.IllegalArgumentException at android.os.StatFs.native_setup(Native Method) at android.os.StatFs.(StatFs.java:32) ```" 14796931,"Google play reports an exception on some devices (all are ""other"" and one ""LG-E400"", so it might be some custom android build) Exception is: ``` java.lang.IllegalArgumentException at android.os.StatFs.native_setup(Native Method) at android.os.StatFs.(StatFs.java:32) at android.webkit.CacheManager.init(CacheManager.java:199) at android.webkit.BrowserFrame.(BrowserFrame.java:210) at android.webkit.WebViewCore.initialize(WebViewCore.java:201) at android.webkit.WebViewCore.access$500(WebViewCore.java:54) at android.webkit.WebViewCore$WebCoreThread$1.handleMessage(WebViewCore.java:631) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:130) at android.webkit.WebViewCore$WebCoreThread.run(WebViewCore.java:653) at java.lang.Thread.run(Thread.java:1019) ``` The problem is I can't ignore this axception 'cause it is in separate thread. Is there any solution for this problem? Or what can I do with that?",2013/02/10,"['https://Stackoverflow.com/questions/14796931', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1148784/']","Path which you are providing in Statfs constructor does not exists ``` String path = ""path to some directory""; StatFs statFs = null; statFs = new StatFs(path); ``` and you must have external storage permission in manifest file","I have got similar issue and my log was looking like ``` 03-14 13:41:55.715: E/PayPalService(14037): Risk component failed to initialize, threw null 03-14 13:41:56.295: E/(14037): statfs /storage/sdcard0 failed, errno: 13 03-14 13:41:56.365: E/AndroidRuntime(14037): FATAL EXCEPTION: Thread-1219 03-14 13:41:56.365: E/AndroidRuntime(14037): java.lang.IllegalArgumentException 03-14 13:41:56.365: E/AndroidRuntime(14037): at android.os.StatFs.native_setup(Native Method) 03-14 13:41:56.365: E/AndroidRuntime(14037): at android.os.StatFs.(StatFs.java:32) ``` I found this issue related to sd card by looking the first two lines .Then I checked device setting and found I had checked their a option **apps must have permission to read sd card** and the app I was installing was not having **READ SD CARD** permission in manifest. So possibly these things are related and possible solutions for me were either put permission in manifest or to unchecke that option .Hope it will help in further research." 14796931,"Google play reports an exception on some devices (all are ""other"" and one ""LG-E400"", so it might be some custom android build) Exception is: ``` java.lang.IllegalArgumentException at android.os.StatFs.native_setup(Native Method) at android.os.StatFs.(StatFs.java:32) at android.webkit.CacheManager.init(CacheManager.java:199) at android.webkit.BrowserFrame.(BrowserFrame.java:210) at android.webkit.WebViewCore.initialize(WebViewCore.java:201) at android.webkit.WebViewCore.access$500(WebViewCore.java:54) at android.webkit.WebViewCore$WebCoreThread$1.handleMessage(WebViewCore.java:631) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:130) at android.webkit.WebViewCore$WebCoreThread.run(WebViewCore.java:653) at java.lang.Thread.run(Thread.java:1019) ``` The problem is I can't ignore this axception 'cause it is in separate thread. Is there any solution for this problem? Or what can I do with that?",2013/02/10,"['https://Stackoverflow.com/questions/14796931', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1148784/']","Path which you are providing in Statfs constructor does not exists ``` String path = ""path to some directory""; StatFs statFs = null; statFs = new StatFs(path); ``` and you must have external storage permission in manifest file","Starting with Lollipop, Android placed rather extreme restrictions on accessing external SD cards. You can use: ``` StatFs stat; try { stat = new StatFs(path); } catch (IllegalArgumentException e) { // Handle the failure gracefully or just throw(e) } ``` to work-around the error. For my application, I just skip unavailable directories, essentially limiting the user to the internal storage. Not an ideal solution, but a limited application that doesn't crash is better than one which does." 26098194,"So, I export `PNotify` from bower to the `js` folder. I use `requirejs` to include my libraries **HTML** ``` ``` My architecture is like this : ``` js --- app.js --- lib ------ pnotify.core.js ------ pnotify.desktop.js ------ pnotify.buttons.js ------ pnotify.callbacks.js ------ pnotify.confirm.js ------ pnotify.history.js ------ pnotify.nonblock.js ------ pnotify.reference.js ------ jquery.js ------ ... ``` I add the primary module which is pnotify.core **APP.JS** ``` requirejs.config({ base: '/assets/js', paths: { 'jQuery': 'lib/jquery.min', 'underscore': 'lib/underscore-min', 'Backbone': 'lib/backbone', 'Modernizr' : 'lib/modernizr', 'PNotify' : 'lib/pnotify.core', 'LoginView' : 'views/login' }, shim: { 'jQuery': { exports: '$' }, 'underscore': { exports: '_' }, 'Backbone': { exports: 'Backbone' }, 'Modernizr': { exports: 'Modernizr' }, 'LoginView': { exports: 'LoginView' }, 'PNotify': { exports: 'PNotify' } } }); ``` PNotify is loaded in my page. Normally, PNotify works with requirejs : I don't know how can I import all modules, maybe concat these modules in one file pnotify.min.js? Here, when I call the `PNotify` object under the `requirejs.config` ``` define(['jQuery', 'underscore', 'Backbone', 'Modernizr', 'LoginView', 'PNotify'], function ($, _, Backbone, Modernizr, LoginView, PNotify) { $(document).ready(function(){ new PNotify({ title: 'Desktop Notice', text: 'If you\'ve given me permission, I\'ll appear as a desktop notification. If you haven\'t, I\'ll still appear as a regular PNotify notice.' }); }); }); ``` I have this error : `Uncaught TypeError: undefined is not a function` on the line ""new PNotify""... Do you have some ideas?",2014/09/29,"['https://Stackoverflow.com/questions/26098194', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2798726/']","> > When they detect AMD/RequireJS, PNotify core defines the named module > ""**pnotify**"", and PNotify's modules each define names like > ""pnotify.module"". The following example shows the use of the nonblock > and desktop modules with RequireJS. > > > So my error is here ``` requirejs.config({ base: '/assets/js', paths: { 'jQuery': 'lib/jquery.min', 'underscore': 'lib/underscore-min', 'Backbone': 'lib/backbone', 'Modernizr' : 'lib/modernizr', 'PNotify' : 'lib/pnotify.core', ^_____ 'replace by pnotify' 'LoginView' : 'views/login' }, ... ```","Compile All the modules into one minified file. These Settings work for me in Require.js ``` paths: { 'pnotify': 'lib/pnotify.min', 'pnotify.nonblock': 'lib/pnotify.min', 'pnotify.desktop': 'lib/pnotify.min, 'jquery' : 'lib/jquery' } define(['jquery', 'pnotify','pnotify.nonblock', 'pnotify.desktop', function($, pnotify){ new PNotify({ title: 'Desktop Notice', text: 'If you\'ve given me permission, I\'ll appear as a desktop notification. If you haven\'t, I\'ll still appear as a regular PNotify notice.', desktop: { desktop: true }, nonblock: { nonblock: true } }); }); ```" 2159414,"There are 3 red and 7 black balls in first pot. There are 41 red and 59 black balls in second pot. And there are 481 red and 519 black balls in third pot. One of the three pots is chosen according to the random principle and after that one ball is blindly chosen. How big is the probability to get a red ball? Solution: $\frac{397}{1000}$ How big is the probability of taking a red ball from a fourth pot, when previously the content of the first three pots is placed in empty fourth pot? Solution: $\frac{35}{74}$ My idea: I was thinking to use formula: $P(A|B)=\frac{P(B|A)P(A)}{P(B)} $ But I am not sure how to connect this formula with the things that are wanted in this example. I calculated only: $P(Red)=\frac{3}{10}$ and $P(Black)=\frac{7}{10}$",2017/02/24,"['https://math.stackexchange.com/questions/2159414', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/332291/']","$$\log\_2 x +\log\_4 x = 2$$ $$\frac{1}{\log\_ x2} +\frac{1}{\log\_ x4} = 2$$ $$\frac{1}{\log\_ x2} +\frac{1}{2\log\_ x2} = 2$$ $$\frac{3}{2\log\_ x2} = 2$$ $$\frac{1}{\log\_ x2} =\frac{4}{3}$$ $$\log\_ 2x =\frac{4}{3}$$ $$x=2^{4/3}$$","we write $$\frac{\ln(x)}{\ln(2)}+\frac{\ln(x)}{2\ln(2)}=2$$ multiplying by $$2\ln(2)$$ we obtain $$2\ln(x)+\ln(x)=4\ln(2)$$thus we get $$\ln(x)=\frac{4}{3}\ln(2)$$ can you finish this?" 2159414,"There are 3 red and 7 black balls in first pot. There are 41 red and 59 black balls in second pot. And there are 481 red and 519 black balls in third pot. One of the three pots is chosen according to the random principle and after that one ball is blindly chosen. How big is the probability to get a red ball? Solution: $\frac{397}{1000}$ How big is the probability of taking a red ball from a fourth pot, when previously the content of the first three pots is placed in empty fourth pot? Solution: $\frac{35}{74}$ My idea: I was thinking to use formula: $P(A|B)=\frac{P(B|A)P(A)}{P(B)} $ But I am not sure how to connect this formula with the things that are wanted in this example. I calculated only: $P(Red)=\frac{3}{10}$ and $P(Black)=\frac{7}{10}$",2017/02/24,"['https://math.stackexchange.com/questions/2159414', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/332291/']","If we apply 4^ to both sides, we get $$4^{\log\_2(x)+\log\_4(x)}=16$$ $$4^{\log\_2(x)}4^{\log\_4(x)}=16$$ Since $4=2^2$, this reduces to $$2^{2\log\_2(x)}4^{\log\_4(x)}=16$$ $$x^2\cdot x=16$$ $$x^3=16$$ $$x=\sqrt[3]{16}\approx2.7$$","Use the definition of $\log\_a x=\ln(x)/\ln(a)$ and multiply $\log\_2 x + \log\_4 x = 2$ by $2 \ln 2$ to get $3\ln x=2$, hence $x=\exp(2/3)$." 2159414,"There are 3 red and 7 black balls in first pot. There are 41 red and 59 black balls in second pot. And there are 481 red and 519 black balls in third pot. One of the three pots is chosen according to the random principle and after that one ball is blindly chosen. How big is the probability to get a red ball? Solution: $\frac{397}{1000}$ How big is the probability of taking a red ball from a fourth pot, when previously the content of the first three pots is placed in empty fourth pot? Solution: $\frac{35}{74}$ My idea: I was thinking to use formula: $P(A|B)=\frac{P(B|A)P(A)}{P(B)} $ But I am not sure how to connect this formula with the things that are wanted in this example. I calculated only: $P(Red)=\frac{3}{10}$ and $P(Black)=\frac{7}{10}$",2017/02/24,"['https://math.stackexchange.com/questions/2159414', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/332291/']","If we apply 4^ to both sides, we get $$4^{\log\_2(x)+\log\_4(x)}=16$$ $$4^{\log\_2(x)}4^{\log\_4(x)}=16$$ Since $4=2^2$, this reduces to $$2^{2\log\_2(x)}4^{\log\_4(x)}=16$$ $$x^2\cdot x=16$$ $$x^3=16$$ $$x=\sqrt[3]{16}\approx2.7$$","You would need to change the base of one of the $log$. For example $\log\_4 x = \frac{\log\_2 x}{log\_2 4} = \frac{\log\_2 x}{2}$ $$ 2 = \log\_2 x + \log\_4 x = \frac{3}{2} \log\_2x \implies x = 2^{4/3} = \sqrt[3]{16} $$" 2159414,"There are 3 red and 7 black balls in first pot. There are 41 red and 59 black balls in second pot. And there are 481 red and 519 black balls in third pot. One of the three pots is chosen according to the random principle and after that one ball is blindly chosen. How big is the probability to get a red ball? Solution: $\frac{397}{1000}$ How big is the probability of taking a red ball from a fourth pot, when previously the content of the first three pots is placed in empty fourth pot? Solution: $\frac{35}{74}$ My idea: I was thinking to use formula: $P(A|B)=\frac{P(B|A)P(A)}{P(B)} $ But I am not sure how to connect this formula with the things that are wanted in this example. I calculated only: $P(Red)=\frac{3}{10}$ and $P(Black)=\frac{7}{10}$",2017/02/24,"['https://math.stackexchange.com/questions/2159414', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/332291/']","$$\log\_2 x +\log\_4 x = 2$$ $$\frac{1}{\log\_ x2} +\frac{1}{\log\_ x4} = 2$$ $$\frac{1}{\log\_ x2} +\frac{1}{2\log\_ x2} = 2$$ $$\frac{3}{2\log\_ x2} = 2$$ $$\frac{1}{\log\_ x2} =\frac{4}{3}$$ $$\log\_ 2x =\frac{4}{3}$$ $$x=2^{4/3}$$","You would need to change the base of one of the $log$. For example $\log\_4 x = \frac{\log\_2 x}{log\_2 4} = \frac{\log\_2 x}{2}$ $$ 2 = \log\_2 x + \log\_4 x = \frac{3}{2} \log\_2x \implies x = 2^{4/3} = \sqrt[3]{16} $$" 2159414,"There are 3 red and 7 black balls in first pot. There are 41 red and 59 black balls in second pot. And there are 481 red and 519 black balls in third pot. One of the three pots is chosen according to the random principle and after that one ball is blindly chosen. How big is the probability to get a red ball? Solution: $\frac{397}{1000}$ How big is the probability of taking a red ball from a fourth pot, when previously the content of the first three pots is placed in empty fourth pot? Solution: $\frac{35}{74}$ My idea: I was thinking to use formula: $P(A|B)=\frac{P(B|A)P(A)}{P(B)} $ But I am not sure how to connect this formula with the things that are wanted in this example. I calculated only: $P(Red)=\frac{3}{10}$ and $P(Black)=\frac{7}{10}$",2017/02/24,"['https://math.stackexchange.com/questions/2159414', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/332291/']","$$\log\_2 x +\log\_4 x = 2$$ $$\frac{1}{\log\_ x2} +\frac{1}{\log\_ x4} = 2$$ $$\frac{1}{\log\_ x2} +\frac{1}{2\log\_ x2} = 2$$ $$\frac{3}{2\log\_ x2} = 2$$ $$\frac{1}{\log\_ x2} =\frac{4}{3}$$ $$\log\_ 2x =\frac{4}{3}$$ $$x=2^{4/3}$$","If we apply 4^ to both sides, we get $$4^{\log\_2(x)+\log\_4(x)}=16$$ $$4^{\log\_2(x)}4^{\log\_4(x)}=16$$ Since $4=2^2$, this reduces to $$2^{2\log\_2(x)}4^{\log\_4(x)}=16$$ $$x^2\cdot x=16$$ $$x^3=16$$ $$x=\sqrt[3]{16}\approx2.7$$" 2159414,"There are 3 red and 7 black balls in first pot. There are 41 red and 59 black balls in second pot. And there are 481 red and 519 black balls in third pot. One of the three pots is chosen according to the random principle and after that one ball is blindly chosen. How big is the probability to get a red ball? Solution: $\frac{397}{1000}$ How big is the probability of taking a red ball from a fourth pot, when previously the content of the first three pots is placed in empty fourth pot? Solution: $\frac{35}{74}$ My idea: I was thinking to use formula: $P(A|B)=\frac{P(B|A)P(A)}{P(B)} $ But I am not sure how to connect this formula with the things that are wanted in this example. I calculated only: $P(Red)=\frac{3}{10}$ and $P(Black)=\frac{7}{10}$",2017/02/24,"['https://math.stackexchange.com/questions/2159414', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/332291/']","we write $$\frac{\ln(x)}{\ln(2)}+\frac{\ln(x)}{2\ln(2)}=2$$ multiplying by $$2\ln(2)$$ we obtain $$2\ln(x)+\ln(x)=4\ln(2)$$thus we get $$\ln(x)=\frac{4}{3}\ln(2)$$ can you finish this?","Here is another way to think. First note that $4$ is a power of $2$ Let $\log\_4x=k\iff 4^k=x$ Now $4^k=x \implies (2^2)^k=x \implies 2^{2k}=x\iff\log\_2x=2k\implies \frac{1}{2}\log\_2{x}=\log\_4{x}$ We now have $$\log\_2x+\frac{1}{2}\log\_2x=2\\\frac{3}{2}\log\_2x=2\\\log\_2x^{3/2}=2\iff2^2=x^{3/2}\implies x=16^{1/3}$$ I added this because it reinforces the bonds between logs and powers." 2159414,"There are 3 red and 7 black balls in first pot. There are 41 red and 59 black balls in second pot. And there are 481 red and 519 black balls in third pot. One of the three pots is chosen according to the random principle and after that one ball is blindly chosen. How big is the probability to get a red ball? Solution: $\frac{397}{1000}$ How big is the probability of taking a red ball from a fourth pot, when previously the content of the first three pots is placed in empty fourth pot? Solution: $\frac{35}{74}$ My idea: I was thinking to use formula: $P(A|B)=\frac{P(B|A)P(A)}{P(B)} $ But I am not sure how to connect this formula with the things that are wanted in this example. I calculated only: $P(Red)=\frac{3}{10}$ and $P(Black)=\frac{7}{10}$",2017/02/24,"['https://math.stackexchange.com/questions/2159414', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/332291/']","$$\log\_2 x +\log\_4 x = 2$$ $$\frac{1}{\log\_ x2} +\frac{1}{\log\_ x4} = 2$$ $$\frac{1}{\log\_ x2} +\frac{1}{2\log\_ x2} = 2$$ $$\frac{3}{2\log\_ x2} = 2$$ $$\frac{1}{\log\_ x2} =\frac{4}{3}$$ $$\log\_ 2x =\frac{4}{3}$$ $$x=2^{4/3}$$","Here is another way to think. First note that $4$ is a power of $2$ Let $\log\_4x=k\iff 4^k=x$ Now $4^k=x \implies (2^2)^k=x \implies 2^{2k}=x\iff\log\_2x=2k\implies \frac{1}{2}\log\_2{x}=\log\_4{x}$ We now have $$\log\_2x+\frac{1}{2}\log\_2x=2\\\frac{3}{2}\log\_2x=2\\\log\_2x^{3/2}=2\iff2^2=x^{3/2}\implies x=16^{1/3}$$ I added this because it reinforces the bonds between logs and powers." 2159414,"There are 3 red and 7 black balls in first pot. There are 41 red and 59 black balls in second pot. And there are 481 red and 519 black balls in third pot. One of the three pots is chosen according to the random principle and after that one ball is blindly chosen. How big is the probability to get a red ball? Solution: $\frac{397}{1000}$ How big is the probability of taking a red ball from a fourth pot, when previously the content of the first three pots is placed in empty fourth pot? Solution: $\frac{35}{74}$ My idea: I was thinking to use formula: $P(A|B)=\frac{P(B|A)P(A)}{P(B)} $ But I am not sure how to connect this formula with the things that are wanted in this example. I calculated only: $P(Red)=\frac{3}{10}$ and $P(Black)=\frac{7}{10}$",2017/02/24,"['https://math.stackexchange.com/questions/2159414', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/332291/']","$$\log\_2 x +\log\_4 x = 2$$ $$\frac{1}{\log\_ x2} +\frac{1}{\log\_ x4} = 2$$ $$\frac{1}{\log\_ x2} +\frac{1}{2\log\_ x2} = 2$$ $$\frac{3}{2\log\_ x2} = 2$$ $$\frac{1}{\log\_ x2} =\frac{4}{3}$$ $$\log\_ 2x =\frac{4}{3}$$ $$x=2^{4/3}$$","Use the definition of $\log\_a x=\ln(x)/\ln(a)$ and multiply $\log\_2 x + \log\_4 x = 2$ by $2 \ln 2$ to get $3\ln x=2$, hence $x=\exp(2/3)$." 2159414,"There are 3 red and 7 black balls in first pot. There are 41 red and 59 black balls in second pot. And there are 481 red and 519 black balls in third pot. One of the three pots is chosen according to the random principle and after that one ball is blindly chosen. How big is the probability to get a red ball? Solution: $\frac{397}{1000}$ How big is the probability of taking a red ball from a fourth pot, when previously the content of the first three pots is placed in empty fourth pot? Solution: $\frac{35}{74}$ My idea: I was thinking to use formula: $P(A|B)=\frac{P(B|A)P(A)}{P(B)} $ But I am not sure how to connect this formula with the things that are wanted in this example. I calculated only: $P(Red)=\frac{3}{10}$ and $P(Black)=\frac{7}{10}$",2017/02/24,"['https://math.stackexchange.com/questions/2159414', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/332291/']","we write $$\frac{\ln(x)}{\ln(2)}+\frac{\ln(x)}{2\ln(2)}=2$$ multiplying by $$2\ln(2)$$ we obtain $$2\ln(x)+\ln(x)=4\ln(2)$$thus we get $$\ln(x)=\frac{4}{3}\ln(2)$$ can you finish this?","Use the definition of $\log\_a x=\ln(x)/\ln(a)$ and multiply $\log\_2 x + \log\_4 x = 2$ by $2 \ln 2$ to get $3\ln x=2$, hence $x=\exp(2/3)$." 2159414,"There are 3 red and 7 black balls in first pot. There are 41 red and 59 black balls in second pot. And there are 481 red and 519 black balls in third pot. One of the three pots is chosen according to the random principle and after that one ball is blindly chosen. How big is the probability to get a red ball? Solution: $\frac{397}{1000}$ How big is the probability of taking a red ball from a fourth pot, when previously the content of the first three pots is placed in empty fourth pot? Solution: $\frac{35}{74}$ My idea: I was thinking to use formula: $P(A|B)=\frac{P(B|A)P(A)}{P(B)} $ But I am not sure how to connect this formula with the things that are wanted in this example. I calculated only: $P(Red)=\frac{3}{10}$ and $P(Black)=\frac{7}{10}$",2017/02/24,"['https://math.stackexchange.com/questions/2159414', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/332291/']","we write $$\frac{\ln(x)}{\ln(2)}+\frac{\ln(x)}{2\ln(2)}=2$$ multiplying by $$2\ln(2)$$ we obtain $$2\ln(x)+\ln(x)=4\ln(2)$$thus we get $$\ln(x)=\frac{4}{3}\ln(2)$$ can you finish this?","You would need to change the base of one of the $log$. For example $\log\_4 x = \frac{\log\_2 x}{log\_2 4} = \frac{\log\_2 x}{2}$ $$ 2 = \log\_2 x + \log\_4 x = \frac{3}{2} \log\_2x \implies x = 2^{4/3} = \sqrt[3]{16} $$" 33084866,"A bit stuck on getting hash equals to data attribute. so if url.com/#house-2 then it will trigger a click for test 2. How do you get it via jquery? ``` ```",2015/10/12,"['https://Stackoverflow.com/questions/33084866', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4939773/']","You can use [`attribute equals`](http://api.jquery.com/attribute-equals-selector/) to select your target `a` element and trigger `.click()` like this; ``` $('.list a[data-loc=""' + window.location.hash.replace('#', '') + '""]').trigger('click'); ``` If your HTML contains those `data-loc` attributes, this will work. But it won't work if data was added via jQuery `.data()` function.","You can use `filter()` to find the required element by the `data-loc` attribute. Try this: ``` var fragment = window.location.hash; if (fragment) { fragment = fragment.substr(1); $('.list a').filter(function() { return $(this).data('loc') == fragment; }).click(); } ```" 38241941,"I'm exploring how jhipster manipulates data. I have found `$http.get()` in `getProfileInfo` method in `ProfileService` Service whitch interacting restful `api` : ``` function getProfileInfo() { if (!angular.isDefined(dataPromise)) { dataPromise = $http.get('api/profile-info').then(function(result) { if (result.data.activeProfiles) { var response = {}; response.activeProfiles = result.data.activeProfiles; response.ribbonEnv = result.data.ribbonEnv; response.inProduction = result.data.activeProfiles.indexOf(""prod"") !== -1; response.swaggerDisabled = result.data.activeProfiles.indexOf(""no-swagger"") !== -1; return response; } }); } return dataPromise; } ``` and some where i have found `$resouce()` manipulating `GET` method. for example in `BankAccount` factory : ``` var resourceUrl = 'api/bank-accounts/:id'; ``` I searched for when to use `$http` and when to use `$resource` and i found this : [AngularJS $http and $resource](https://stackoverflow.com/questions/13181406/angularjs-http-and-resource) why `hipster` is not following `consistent` way of interacting API and manipulating data!!? so `jhipster`, when to use `$http` and when to use `$resource` in services??",2016/07/07,"['https://Stackoverflow.com/questions/38241941', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1438055/']","We use `$resource` when requesting a RESTful endpoint, for example for an entity. `$resource` provides basic REST operations easily whereas `$http` is more specific. For profile we only need to GET `/profile-infos` so it's useless to use `$resource` because we'll never need to call POST or DELETE on that URL.","$http will fetch you the entire page or complete set of data from a given URL whereas $resouce uses http but will help you to fetch a specific object or set of data. $resource is fast and we use it when we need to increase the speed of our transaction. $http is used when we are concerned with the time." 21440326,"I am starting to work with classes in Python, and am learning how to create functions within classes. Does anyone have any tips on this sample class & function that I am testing out? ``` class test: def __init__(self): self.a = None self.b = None self.c = None def prod(self): return self.a * self.b trial = test trial.a = 4 trial.b = 5 print trial.prod ``` Ideally the result would be to see the number 20.",2014/01/29,"['https://Stackoverflow.com/questions/21440326', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3250333/']","You need to: 1. Create an instance of `test`. 2. Invoke the `prod` method of that instance. Both of these can be accomplished by adding `()` after their names: ``` trial = test() trial.a = 4 trial.b = 5 print trial.prod() ``` Below is a demonstration: ``` >>> class test: ... def __init__(self): ... self.a = None ... self.b = None ... self.c = None ... def prod(self): ... return self.a * self.b ... >>> trial = test() >>> trial.a = 4 >>> trial.b = 5 >>> print trial.prod() 20 >>> ``` --- Without the parenthesis, this line: ``` trial = test ``` is simply assigning the variable `trial` to class `test` itself, not an instance of it. Moreover, this line: ``` print trial.prod ``` is just printing the string representation of `test.prod`, not the value returned by invoking it. --- Here is a reference on [Python classes and OOP](http://docs.python.org/2/tutorial/classes.html).","Ideally you could also pass in the values to a, b, c as parameters to your object's constructor: ``` class test: def __init__(self, a, b, c): self.a = a self.b = b self.c = c def prod(self): return self.a * self.b ``` Then, constructing and calling the function would look like this: ``` trial = test(4, 5, None) print trial.prod() ```" 39963386,"I have a database with multiple dates for the same unique ID. I am trying to find the first (min) and last (max) date for each unique ID. I want the result to be: Unique ID, first Date, last date, field1, field2,field3 ``` Select max(date_Executed) as Last_Date, (select unique_ID, MIN(date_Executed)as First_Date from Table_X group by unique_ID, Field1, field2,field3 ) from Table_X where unique_ID = unique_ID group by unique_ID, Field1, field2,field3 order by unique_ID,First_Permit_Date ``` The error message I get is: > > Only one expression can be specified in the select list when the subquery is not introduced with EXISTS. > Msg 207, Level 16, State 1, Line 19 > Invalid column name 'First\_Permit\_Date'. > > > I’m new to SQL… Thanks for your help-",2016/10/10,"['https://Stackoverflow.com/questions/39963386', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6950328/']","why not a simple select with group by ``` Select max(date_Executed) as Last_Date, MIN(date_Executed) as First_Date from Table_X group by unique_ID, Field1, field2,field3 order by unique_ID,First_Permit_Date ``` You can use more then one aggregation function ina select .. (with the same group by clause)","Shouldn't it just be something like this? I have no further insight in your tables, but the second 'select' statement seems to cause the error. ``` SELECT unique_ID, min(date_Executed) as First_Date, max(date_Executed) as Last_Date, field1, field2, field3 FROM Table_X GROUP BY unique_ID, Field1, field2, field3 order by unique_ID, First_Permit_Date ```" 39764678,"I've been battling for days now to get data to save for my nested form. I basically want to be able to store a users reason for cancelling a project, along with the last stage of the project before it was cancelled. But I just can't seem to get the actions `cancel`, `cancel_save`, and `cancel_params` to play nicely! **Controller** ``` before_action :correct_user, only: [:show, :edit, :update, :destroy, :cancel, :cancel_save] ... def cancel @project.build_project_close_reason end def cancel_save @project.build_project_close_reason(cancel_params) @project.update(project_status_id: 10) redirect_to root_path, notice: 'Project has been successfully cancelled.' end private def correct_user @user = current_user @project = current_user.projects.find_by(id: params[:id]) end redirect_to user_projects_path, notice: ""You are not authorised to view this project"" if @project.nil? end def cancel_params params.require(:project).permit(project_close_reason_attributes: [:comment]).merge(project_close_reason_attributes: [project_id: @project.id, last_status_id: @project.project_status_id ]) end ``` **Models** ``` class Project < ApplicationRecord belongs_to :user has_one :project_close_reason accepts_nested_attributes_for :project_close_reason #adding this seemed to make no difference? end class ProjectCloseReason < ApplicationRecord belongs_to :project end class User < ApplicationRecord ... # All standard devise stuff has_many :projects end ``` **Nested form in the view** ``` <%= form_for([@user, @project], url: {action: ""cancel_save""}, method: :post) do |f| %> <%= fields_for :project_close_reason do |pcr| %>
<%= pcr.label ""Why are you cancelling this project? (This helps us improve!)"" %> <%= pcr.text_area :comment, class: ""form-control entry_field_text"" %>
<% end %>
<%= f.submit ""Cancel Project"", class: ""btn btn-lg btn-warning"" %>
<% end %> ``` **Routes** ``` devise_for :users devise_for :admins resources :users do resources :projects do get ""cancel"", :on => :member post ""cancel"" => 'projects#cancel_save', :on => :member end end ``` This is the error I get when I try and submit the form: `ActionController::ParameterMissing in ProjectsController#cancel_save param is missing or the value is empty: project`. It references the `cancel_params` action Thanks for any help! UPDATE Here is the log when I call `cancel_save` ``` Started POST ""/users/2/projects/10/cancel"" for ::1 at 2016-09-29 10:03:44 +0200 Processing by ProjectsController#cancel_save as HTML Parameters: {""utf8""=>""✓"", ""authenticity_token""=>""h6K+VFyjW/dV189YOePWZm+Pmjey50xAMQIJb+c3dzpEaMv8Ckh3jQGOWfVdlfVH/FxolbB45fXvTO0cdplhkg=="", ""project_close_reason""=>{""comment""=>""b""}, ""commit""=>""Cancel Project"", ""user_id""=>""2"", ""id""=>""10""} User Load (11.2ms) SELECT ""users"".* FROM ""users"" WHERE ""users"".""id"" = $1 ORDER BY ""users"".""id"" ASC LIMIT $2 [[""id"", 2], [""LIMIT"", 1]] Project Load (0.7ms) SELECT ""projects"".* FROM ""projects"" WHERE ""projects"".""user_id"" = $1 AND ""projects"".""id"" = $2 LIMIT $3 [[""user_id"", 2], [""id"", 10], [""LIMIT"", 1]] ProjectCloseReason Load (0.2ms) SELECT ""project_close_reasons"".* FROM ""project_close_reasons"" WHERE ""project_close_reasons"".""project_id"" = $1 LIMIT $2 [[""project_id"", 10], [""LIMIT"", 1]] Completed 400 Bad Request in 22ms (ActiveRecord: 12.1ms) ActionController::ParameterMissing (param is missing or the value is empty: project): ```",2016/09/29,"['https://Stackoverflow.com/questions/39764678', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6748657/']","You need [`concat`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html): ``` print (pd.concat([df1[['Type','Breed','Behaviour']], df2[['Type','Breed','Behaviour']]], ignore_index=True)) Type Breed Behaviour 0 Golden Big Fun 1 Corgi Small Crazy 2 Bulldog Medium Strong 3 Pug Small Sleepy 4 German Shepard Big Cool 5 Puddle Small Aggressive ``` More general is use [`intersection`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.intersection.html) for columns of both `DataFrames`: ``` cols = df1.columns.intersection(df2.columns) print (cols) Index(['Type', 'Breed', 'Behaviour'], dtype='object') print (pd.concat([df1[cols], df2[cols]], ignore_index=True)) Type Breed Behaviour 0 Golden Big Fun 1 Corgi Small Crazy 2 Bulldog Medium Strong 3 Pug Small Sleepy 4 German Shepard Big Cool 5 Puddle Small Aggressive ``` More general if `df1` and `df2` have no `NaN` values use [`dropna`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dropna.html) for removing columns with `NaN`: ``` print (pd.concat([df1 ,df2], ignore_index=True)) Bark Sound Behaviour Breed Common Color Other Color Type 0 NaN Fun Big Gold White Golden 1 NaN Crazy Small Brown White Corgi 2 NaN Strong Medium Black Grey Bulldog 3 Ak Sleepy Small NaN NaN Pug 4 Woof Cool Big NaN NaN German Shepard 5 Ek Aggressive Small NaN NaN Puddle print (pd.concat([df1 ,df2], ignore_index=True).dropna(1)) Behaviour Breed Type 0 Fun Big Golden 1 Crazy Small Corgi 2 Strong Medium Bulldog 3 Sleepy Small Pug 4 Cool Big German Shepard 5 Aggressive Small Puddle ```","using `join` dropping columns that don't overlap ``` df1.T.join(df2.T, lsuffix='_').dropna().T.reset_index(drop=True) ``` [![enter image description here](https://i.stack.imgur.com/wb6AL.png)](https://i.stack.imgur.com/wb6AL.png)" 29260425,"I have a postgres database with a large number of time series metrics Various operators are interested in different information and I want to provide an interface where they can chart the data, make comparisons and optionally export data as a csv. The two solutions I have come across so far are, [graphite](https://github.com/graphite-project) and [grafana](http://grafana.org/), but both these solutions tie you down to storage engines and none support postgres. What I am looking for is an interface similar to grafana, but which allows me to hook up any backend I want. Are there any tools out there, similar to grafana, which allow you to hook up any backend you want (or even just postgres). Note that the data I am collecting is highly sensitive, and is required by other areas of the application and so is not suitable for storing in graphite. The other alternative I see would be to setup a trigger on the postgres DB to feed data into graphite as it arrives, but again, not ideal.",2015/03/25,"['https://Stackoverflow.com/questions/29260425', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/527749/']",You may want to replace Graphite's storage backend with postgresql. [Here](http://obfuscurity.com/2013/12/Migrating-Graphite-from-SQLite-to-PostgreSQL) is a good primer.,"**2018 update**: Grafana now supports PostgreSQL ([link](https://grafana.com/plugins/postgres)). --- > > What I am looking for is an interface similar to grafana, but which allows me to hook up any backend I want > > > Thats possible with grafana . Check this [guide](http://docs.grafana.org/plugins/developing/datasources/) which shows how to create a datasource plugin for a datasource thats currently not supported." 28342139,"I have angularjs directive with template which consists of two tags - input and the empty list. What I want is to watch input value of the first input tag. The `$watch()` method is called once when directive is initialised but that's it. Any change of input value is silent. What do I miss? here is my [plunk](http://plnkr.co/edit/kAeuOUxovP8AaAyepNlZ?p=preview) and here is the code: ``` .directive('drpdwn', function(){ var ref = new Firebase(""https://sagavera.firebaseio.com/countries""); function link(scope, element, attrs){ function watched(){ element[0].firstChild.value = 'bumba'; //this gets called once return element[0].firstChild.value; } scope.$watch(watched, function(val){ console.log(""watched"", val) }, true); } return { scope:{ searchString: '=' }, link: link, templateUrl:'drpdwn.html' } }) ``` Edit: if I call `$interval()` within link function it works as expected. is this intentional behaviour?",2015/02/05,"['https://Stackoverflow.com/questions/28342139', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2232045/']","It doesn't get called because there is never a digest triggered on the scope. Try this instead, using ng-model: ``` function link(scope, element, attrs){ scope.searchString = 'bumba'; scope.$watch('searchString', function(val){ console.log(""watched"", val) val = val.toLowerCase(); val = val.replace(/ */g,''); var regex = /^[a-z]*$/g; if (regex.test(val)) { scope.searchString = val; // TODO something.... } }, true); ``` Template: ```
```","You are setting the the value you want in the watcher function. ``` function watched(){ element[0].firstChild.value = 'bumba'; //this gets called once return element[0].firstChild.value; } ``` is essentially the same return value as ``` function watched() { return 'bumba'; } ``` So the watcher will always return the same value. If you want to initialize the value. Do it outside of the watcher: ``` element[0].firstChild.value = 'bumba'; //this gets called once function watched(){ return element[0].firstChild.value; } ```" 57995932,"I want to build a JSON object from an array returned from http request my actual array look like: ``` [{ Description: ""Product"" IsInstanciable: false IsMasked: false Name: ""ProductBase"" Subclasses: [{ Description: ""Product2"" IsInstanciable: false IsMasked: false Name: ""ProductBase2"", Count: 5, Subclasses:[] }, { Description: ""Product3"" IsInstanciable: false IsMasked: false Name: ""ProductBase3"", Count: 4, Subclasses:[], }] }, { Description: ""Product4"" IsInstanciable: false IsMasked: false Name: ""ProductBase4"", Count: '...', Subclasses: [...] } ``` I want to create a JSON object recursively from the array above. It will look like this: ``` [ { name: 'Product', Count: 9, children: [ {name: 'Product2'}, {name: 'Product3'}, ] }, { name: 'Product4', children: [ { name: '...', Count: 'Sum of Count in all children by level' children: [ {name: '...'}, {name: '...'}, ] } ] }, ]; ``` Here is my recursively function in typescript but it doesn't work as expected. How can I fix this? ```js recursive(data, stack: TreeNode[]) { let elt: TreeNode = {name:'', children: []} if(data.Subclasses.length > 0) { elt.name = data.Description; data.Subclasses.forEach(element => { elt.children.push({name: element.Description}); this.recursive(element, stack); }); }else { elt.name = data.Description; } stack.push(elt); } ```",2019/09/18,"['https://Stackoverflow.com/questions/57995932', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/874800/']","You can use the map function together with the recursive function like this: ``` function MapObject(object) { if(!object || object.length < 0) return []; return object.map(obj => { return { name: obj.Description, children: MapObject(obj.Subclasses) }}); } ``` Follows a full work example: ```js var example = [{ Description: ""Product"", IsInstanciable: false, IsMasked: false, Name: ""ProductBase"", Subclasses: [{ Description: ""Product2"", IsInstanciable: false, IsMasked: false, Name: ""ProductBase2"", Subclasses:[] }, { Description: ""Product3"", IsInstanciable: false, IsMasked: false, Name: ""ProductBase3"", Subclasses:[] }] }, { Description: ""Product4"", IsInstanciable: false, IsMasked: false, Name: ""ProductBase4"" }] function MapObject(object) { if(!object || object.length < 0) return []; return object.map(obj => { return { name: obj.Description, children: MapObject(obj.Subclasses) }}); } console.log(MapObject(example)); ```","I would break this down into a few separate functions with clear responsibilities: ```js const sum = (ns) => ns .reduce ((a, b) => a + Number (b), 0) const getCount = (product) => (product .Count || 0) + sum ((product .Subclasses || []) .map (getCount)) const extract = (product) => ({ name: product .Name, count: getCount (product), children: product .Subclasses .map (extract) }) const extractAll = (products) => products .map (extract) const products = [{""Description"": ""Product"", ""IsInstanciable"": false, ""IsMasked"": false, ""Name"": ""ProductBase"", ""Subclasses"": [{""Count"": 5, ""Description"": ""Product2"", ""IsInstanciable"": false, ""IsMasked"": false, ""Name"": ""ProductBase2"", ""Subclasses"": []}, {""Count"": 4, ""Description"": ""Product3"", ""IsInstanciable"": false, ""IsMasked"": false, ""Name"": ""ProductBase3"", ""Subclasses"": []}]}, {""Count"": 3, ""Description"": ""Product4"", ""IsInstanciable"": false, ""IsMasked"": false, ""Name"": ""ProductBase4"", ""Subclasses"": []}] console .log ( extractAll (products) ) ``` (Note that I changed the case of the output `count` property. It just seemed more consistent with `name` and `children`.) We recur through the object to get its `Count` property, and we recur separately to get the rest of the object. While there might be a way to combine these, I would expect that the code would be significantly more complex. Note that I assumed that all `Count` properties are actually numeric, although your example above includes a string. If you do have values like `""3""`, then `getCount` will need to be a little more sophisticated." 1115762,"In c# , when sending a parameter to a method, when should we use ""ref"" and when ""out"" and when without any of them?",2009/07/12,"['https://Stackoverflow.com/questions/1115762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61156/']","They are used mainly to obtain multiple return values from a method call. Personally, I tend to not use them. If I want multiple return values from a method then I'll create a small class to hold them. ref and out are used when you want something back from the method in that parameter. As I recall, they both actually compile down to the same IL, but C# puts in place some extra stuff so you have to be specific. Here are some examples: ``` static void Main(string[] args) { string myString; MyMethod0(myString); Console.WriteLine(myString); Console.ReadLine(); } public static void MyMethod0(string param1) { param1 = ""Hello""; } ``` The above won't compile because myString is never initialised. If myString is initialised to string.Empty then the output of the program will be a empty line because all MyMethod0 does is assign a new string to a local reference to param1. ``` static void Main(string[] args) { string myString; MyMethod1(out myString); Console.WriteLine(myString); Console.ReadLine(); } public static void MyMethod1(out string param1) { param1 = ""Hello""; } ``` myString is not initialised in the Main method, yet, the program outputs ""Hello"". This is because the myString reference in the Main method is being updated from MyMethod1. MyMethod1 does not expect param1 to already contain anything, so it can be left uninitialised. However, the method should be assigning something. ``` static void Main(string[] args) { string myString; MyMethod2(ref myString); Console.WriteLine(myString); Console.ReadLine(); } public static void MyMethod2(ref string param1) { param1 = ""Hello""; } ``` This, again, will not compile. This is because ref demands that myString in the Main method is initialised to something first. But, if the Main method is changed so that myString is initialised to string.Empty then the code will compile and the output will be Hello. So, the difference is out can be used with an uninitialised object, ref must be passed an initialised object. And if you pass an object without either the reference to it cannot be replaced. Just to be clear: If the object being passed is a reference type already then the method can update the object and the updates are reflected in the calling code, however the reference to the object cannot be changed. So if I write code like this: ``` static void Main(string[] args) { string myString = ""Hello""; MyMethod0(myString); Console.WriteLine(myString); Console.ReadLine(); } public static void MyMethod0(string param1) { param1 = ""World""; } ``` The output from the program will be Hello, and not World because the method only changed its local copy of the reference, not the reference that was passed in. I hope this makes sense. My general rule of thumb is simply not to use them. I feel it is a throw back to pre-OO days. (But, that's just my opinion)","Very simple really. You use exactly the same keyword that the parameter was originally declared with in the method. If it was declared as `out`, you have to use `out`. If it was declared as `ref`, you have to use `ref`." 1115762,"In c# , when sending a parameter to a method, when should we use ""ref"" and when ""out"" and when without any of them?",2009/07/12,"['https://Stackoverflow.com/questions/1115762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61156/']","(this is supplemental to the existing answers - a few extra considerations) There is another scenario for using `ref` with C#, more commonly seen in things like XNA... Normally, when you pass a value-type (`struct`) around, it gets cloned. This uses stack-space and a few CPU cycles, and has the side-effect that any modifications to the `struct` in the invoked method are lost. (aside: normally `struct`s should be immutable, but mutable structs isn't uncommon in XNA) To get around this, it is quite common to see `ref` in such programs. But in **most** programs (i.e. where you are using `class`es as the default), you can *normally* just pass the reference ""by value"" (i.e. no `ref`/`out`). --- Another **very** common use-case of `out` is the `Try*` pattern, for example: ``` string s = Console.ReadLine(); int i; if(int.TryParse(s, out i)) { Console.WriteLine(""You entered a valid int: "" + i); } ``` Or similarly, [`TryGetValue`](http://msdn.microsoft.com/en-us/library/zkw5c9ak(VS.85).aspx) on a dictionary. This could use a tuple instead, but it is such a common pattern that it is reasonably understood, even by people who struggle with too much `ref`/`out`.",ref is to be avoided (I beleive there is an fx-cop rule for this also) however use ref when the object that is reference may itself changed. If you see the 'ref' keyword you know that the underlying object may no longer be referenced by the same variable after the method is called. 1115762,"In c# , when sending a parameter to a method, when should we use ""ref"" and when ""out"" and when without any of them?",2009/07/12,"['https://Stackoverflow.com/questions/1115762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61156/']","In addition to Colin's detailed answer, you could also use out parameters to return multiple values from one method call. See for example the method below which returns 3 values. ``` static void AssignSomeValues(out int first, out bool second, out string third) { first = 12 + 12; second = false; third = ""Output parameters are okay""; } ``` You could use it like so ``` static void Main(string[] args) { int i; string s; bool b; AssignSomeValues(out i, out b, out s); Console.WriteLine(""Int value: {0}"", i); Console.WriteLine(""Bool value: {0}"", b); Console.WriteLine(""String value: {0}"", s); //wait for enter key to terminate program Console.ReadLine(); } ``` Just make sure that you assign a valid value to each out parameter to avoid getting an error.","Try to avoid using ref. Out is okay, because you know what will happen, the old value will be gone and a new value will be in your variable even if the function failed. However, just by looking at the function you have no idea what will happen to a ref parameter. It may be the same, modified, or an entirely new object. Whenever I see ref, I get nervous." 1115762,"In c# , when sending a parameter to a method, when should we use ""ref"" and when ""out"" and when without any of them?",2009/07/12,"['https://Stackoverflow.com/questions/1115762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61156/']","(this is supplemental to the existing answers - a few extra considerations) There is another scenario for using `ref` with C#, more commonly seen in things like XNA... Normally, when you pass a value-type (`struct`) around, it gets cloned. This uses stack-space and a few CPU cycles, and has the side-effect that any modifications to the `struct` in the invoked method are lost. (aside: normally `struct`s should be immutable, but mutable structs isn't uncommon in XNA) To get around this, it is quite common to see `ref` in such programs. But in **most** programs (i.e. where you are using `class`es as the default), you can *normally* just pass the reference ""by value"" (i.e. no `ref`/`out`). --- Another **very** common use-case of `out` is the `Try*` pattern, for example: ``` string s = Console.ReadLine(); int i; if(int.TryParse(s, out i)) { Console.WriteLine(""You entered a valid int: "" + i); } ``` Or similarly, [`TryGetValue`](http://msdn.microsoft.com/en-us/library/zkw5c9ak(VS.85).aspx) on a dictionary. This could use a tuple instead, but it is such a common pattern that it is reasonably understood, even by people who struggle with too much `ref`/`out`.","Very simple really. You use exactly the same keyword that the parameter was originally declared with in the method. If it was declared as `out`, you have to use `out`. If it was declared as `ref`, you have to use `ref`." 1115762,"In c# , when sending a parameter to a method, when should we use ""ref"" and when ""out"" and when without any of them?",2009/07/12,"['https://Stackoverflow.com/questions/1115762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61156/']","(this is supplemental to the existing answers - a few extra considerations) There is another scenario for using `ref` with C#, more commonly seen in things like XNA... Normally, when you pass a value-type (`struct`) around, it gets cloned. This uses stack-space and a few CPU cycles, and has the side-effect that any modifications to the `struct` in the invoked method are lost. (aside: normally `struct`s should be immutable, but mutable structs isn't uncommon in XNA) To get around this, it is quite common to see `ref` in such programs. But in **most** programs (i.e. where you are using `class`es as the default), you can *normally* just pass the reference ""by value"" (i.e. no `ref`/`out`). --- Another **very** common use-case of `out` is the `Try*` pattern, for example: ``` string s = Console.ReadLine(); int i; if(int.TryParse(s, out i)) { Console.WriteLine(""You entered a valid int: "" + i); } ``` Or similarly, [`TryGetValue`](http://msdn.microsoft.com/en-us/library/zkw5c9ak(VS.85).aspx) on a dictionary. This could use a tuple instead, but it is such a common pattern that it is reasonably understood, even by people who struggle with too much `ref`/`out`.","Try to avoid using ref. Out is okay, because you know what will happen, the old value will be gone and a new value will be in your variable even if the function failed. However, just by looking at the function you have no idea what will happen to a ref parameter. It may be the same, modified, or an entirely new object. Whenever I see ref, I get nervous." 1115762,"In c# , when sending a parameter to a method, when should we use ""ref"" and when ""out"" and when without any of them?",2009/07/12,"['https://Stackoverflow.com/questions/1115762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61156/']","They are used mainly to obtain multiple return values from a method call. Personally, I tend to not use them. If I want multiple return values from a method then I'll create a small class to hold them. ref and out are used when you want something back from the method in that parameter. As I recall, they both actually compile down to the same IL, but C# puts in place some extra stuff so you have to be specific. Here are some examples: ``` static void Main(string[] args) { string myString; MyMethod0(myString); Console.WriteLine(myString); Console.ReadLine(); } public static void MyMethod0(string param1) { param1 = ""Hello""; } ``` The above won't compile because myString is never initialised. If myString is initialised to string.Empty then the output of the program will be a empty line because all MyMethod0 does is assign a new string to a local reference to param1. ``` static void Main(string[] args) { string myString; MyMethod1(out myString); Console.WriteLine(myString); Console.ReadLine(); } public static void MyMethod1(out string param1) { param1 = ""Hello""; } ``` myString is not initialised in the Main method, yet, the program outputs ""Hello"". This is because the myString reference in the Main method is being updated from MyMethod1. MyMethod1 does not expect param1 to already contain anything, so it can be left uninitialised. However, the method should be assigning something. ``` static void Main(string[] args) { string myString; MyMethod2(ref myString); Console.WriteLine(myString); Console.ReadLine(); } public static void MyMethod2(ref string param1) { param1 = ""Hello""; } ``` This, again, will not compile. This is because ref demands that myString in the Main method is initialised to something first. But, if the Main method is changed so that myString is initialised to string.Empty then the code will compile and the output will be Hello. So, the difference is out can be used with an uninitialised object, ref must be passed an initialised object. And if you pass an object without either the reference to it cannot be replaced. Just to be clear: If the object being passed is a reference type already then the method can update the object and the updates are reflected in the calling code, however the reference to the object cannot be changed. So if I write code like this: ``` static void Main(string[] args) { string myString = ""Hello""; MyMethod0(myString); Console.WriteLine(myString); Console.ReadLine(); } public static void MyMethod0(string param1) { param1 = ""World""; } ``` The output from the program will be Hello, and not World because the method only changed its local copy of the reference, not the reference that was passed in. I hope this makes sense. My general rule of thumb is simply not to use them. I feel it is a throw back to pre-OO days. (But, that's just my opinion)","Try to avoid using ref. Out is okay, because you know what will happen, the old value will be gone and a new value will be in your variable even if the function failed. However, just by looking at the function you have no idea what will happen to a ref parameter. It may be the same, modified, or an entirely new object. Whenever I see ref, I get nervous." 1115762,"In c# , when sending a parameter to a method, when should we use ""ref"" and when ""out"" and when without any of them?",2009/07/12,"['https://Stackoverflow.com/questions/1115762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61156/']","(this is supplemental to the existing answers - a few extra considerations) There is another scenario for using `ref` with C#, more commonly seen in things like XNA... Normally, when you pass a value-type (`struct`) around, it gets cloned. This uses stack-space and a few CPU cycles, and has the side-effect that any modifications to the `struct` in the invoked method are lost. (aside: normally `struct`s should be immutable, but mutable structs isn't uncommon in XNA) To get around this, it is quite common to see `ref` in such programs. But in **most** programs (i.e. where you are using `class`es as the default), you can *normally* just pass the reference ""by value"" (i.e. no `ref`/`out`). --- Another **very** common use-case of `out` is the `Try*` pattern, for example: ``` string s = Console.ReadLine(); int i; if(int.TryParse(s, out i)) { Console.WriteLine(""You entered a valid int: "" + i); } ``` Or similarly, [`TryGetValue`](http://msdn.microsoft.com/en-us/library/zkw5c9ak(VS.85).aspx) on a dictionary. This could use a tuple instead, but it is such a common pattern that it is reasonably understood, even by people who struggle with too much `ref`/`out`.","In addition to Colin's detailed answer, you could also use out parameters to return multiple values from one method call. See for example the method below which returns 3 values. ``` static void AssignSomeValues(out int first, out bool second, out string third) { first = 12 + 12; second = false; third = ""Output parameters are okay""; } ``` You could use it like so ``` static void Main(string[] args) { int i; string s; bool b; AssignSomeValues(out i, out b, out s); Console.WriteLine(""Int value: {0}"", i); Console.WriteLine(""Bool value: {0}"", b); Console.WriteLine(""String value: {0}"", s); //wait for enter key to terminate program Console.ReadLine(); } ``` Just make sure that you assign a valid value to each out parameter to avoid getting an error." 1115762,"In c# , when sending a parameter to a method, when should we use ""ref"" and when ""out"" and when without any of them?",2009/07/12,"['https://Stackoverflow.com/questions/1115762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61156/']","In general, you should avoid using ref and out, if possible. That being said, use ref when the method *might need* to modify the value. Use out when the method *always should* assign something to the value. The difference between ref and out, is that when using out, the compiler enforces the rule, that you need to assign something to the out paramter before returning. When using ref, you must assign a value to the variable *before* using it as a ref parameter. Obviously, the above applies, when you are writing your own methods. If you need to call methods that was declared with the ref or out modifiers on their parameters, you should use the same modifier before your parameter, when calling the method. Also remember, that C# passes reference types (classes) by reference (as in, the reference is passed by value). So if you provide some method with a reference type as a parameter, the method can modify the data of the object; even without ref or out. But it cannot modify the reference itself (as in, it cannot modify which object is being referenced).",ref is to be avoided (I beleive there is an fx-cop rule for this also) however use ref when the object that is reference may itself changed. If you see the 'ref' keyword you know that the underlying object may no longer be referenced by the same variable after the method is called. 1115762,"In c# , when sending a parameter to a method, when should we use ""ref"" and when ""out"" and when without any of them?",2009/07/12,"['https://Stackoverflow.com/questions/1115762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61156/']","In general, you should avoid using ref and out, if possible. That being said, use ref when the method *might need* to modify the value. Use out when the method *always should* assign something to the value. The difference between ref and out, is that when using out, the compiler enforces the rule, that you need to assign something to the out paramter before returning. When using ref, you must assign a value to the variable *before* using it as a ref parameter. Obviously, the above applies, when you are writing your own methods. If you need to call methods that was declared with the ref or out modifiers on their parameters, you should use the same modifier before your parameter, when calling the method. Also remember, that C# passes reference types (classes) by reference (as in, the reference is passed by value). So if you provide some method with a reference type as a parameter, the method can modify the data of the object; even without ref or out. But it cannot modify the reference itself (as in, it cannot modify which object is being referenced).","Try to avoid using ref. Out is okay, because you know what will happen, the old value will be gone and a new value will be in your variable even if the function failed. However, just by looking at the function you have no idea what will happen to a ref parameter. It may be the same, modified, or an entirely new object. Whenever I see ref, I get nervous." 1115762,"In c# , when sending a parameter to a method, when should we use ""ref"" and when ""out"" and when without any of them?",2009/07/12,"['https://Stackoverflow.com/questions/1115762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61156/']","In addition to Colin's detailed answer, you could also use out parameters to return multiple values from one method call. See for example the method below which returns 3 values. ``` static void AssignSomeValues(out int first, out bool second, out string third) { first = 12 + 12; second = false; third = ""Output parameters are okay""; } ``` You could use it like so ``` static void Main(string[] args) { int i; string s; bool b; AssignSomeValues(out i, out b, out s); Console.WriteLine(""Int value: {0}"", i); Console.WriteLine(""Bool value: {0}"", b); Console.WriteLine(""String value: {0}"", s); //wait for enter key to terminate program Console.ReadLine(); } ``` Just make sure that you assign a valid value to each out parameter to avoid getting an error.",ref is to be avoided (I beleive there is an fx-cop rule for this also) however use ref when the object that is reference may itself changed. If you see the 'ref' keyword you know that the underlying object may no longer be referenced by the same variable after the method is called. 32283,"I want to compute the total scene bounding box, so I can fit the scene in rendered image automatically. I have found `bound_box`. But why are there so many values ``` ``` There should be 6 values (x\_min,y\_min,z\_min) and (x\_max,y\_max,z\_max)",2015/06/11,"['https://blender.stackexchange.com/questions/32283', 'https://blender.stackexchange.com', 'https://blender.stackexchange.com/users/3258/']","You will get 8 values only, ``` >>> obj = bpy.context.active_object >>> obj.bound_box bpy.data.objects['Cube'].bound_box >>> [v[:] for v in obj.bound_box] [(-1.0, -1.0, -1.0), (-1.0, -1.0, 1.0), (-1.0, 1.0, 1.0), (-1.0, 1.0, -1.0), (1.0, -1.0, -1.0), (1.0, -1.0, 1.0), (1.0, 1.0, 1.0), (1.0, 1.0, -1.0)] ``` ![enter image description here](https://i.stack.imgur.com/Ssfmv.png) for Suzanne it would be: ![enter image description here](https://i.stack.imgur.com/aJ2Wp.png) Here's some code [I wrote about 2 years ago](http://blenderscripting.blogspot.nl/2013/06/named-tuples-replacement.html) to get x.min, x.max, etc., and distance over the axis for *x, y and z*. With instructions how to use it. (I have this tucked away in a module so I just import the function when I need it) ``` import bpy from mathutils import Vector def bounds(obj, local=False): local_coords = obj.bound_box[:] om = obj.matrix_world if not local: # Use @ for multiplication instead of * in Blender2.8+. Source: https://blender.stackexchange.com/a/129474/138679 worldify = lambda p: om * Vector(p[:]) coords = [worldify(p).to_tuple() for p in local_coords] else: coords = [p[:] for p in local_coords] rotated = zip(*coords[::-1]) push_axis = [] for (axis, _list) in zip('xyz', rotated): info = lambda: None info.max = max(_list) info.min = min(_list) info.distance = info.max - info.min push_axis.append(info) import collections originals = dict(zip(['x', 'y', 'z'], push_axis)) o_details = collections.namedtuple('object_details', 'x y z') return o_details(**originals) """""" obj = bpy.context.object object_details = bounds(obj) a = object_details.z.max b = object_details.z.min c = object_details.z.distance print(a, b, c) """""" ```","Each object that has a `bound_box` property will return *8* values that represent the bounding information. The 8 values describe the corners of the bounding box itself. If you have 16 values I presume that is because you have 2 objects in the scene (though it isn't clear from your question what you might have typed in to return all 16 values)." 8459,"It is easy to prove that an apple is an apple: The equation x=x is a tautology, for all x. So if x=apple, we can substitute it in the equation x=x and get apple=apple, so an apple is an apple. But how can one prove (using standard deductive logic) that an apple is not an orange, since x!=y is not a tautology for all x,y?",2013/10/23,"['https://philosophy.stackexchange.com/questions/8459', 'https://philosophy.stackexchange.com', 'https://philosophy.stackexchange.com/users/4639/']","It's not a *logical truth* that an apple is not an orange, but it's nevertheless *analytic* with respect to the meaning postulate: if predicate P holds uniformly of object a, then for all predicates Q contrary to P, ¬Q(a). For example, if something is uniformly black, then it's not of any color that is contrary to black (say red). Recall that predicates A, B are *contraries* iff they cannot simultaneously be true of an object: > > **Definition.** Predicates P and Q are *contraries* =def for all x, either ¬P(x) or ¬Q(x). > > > Here's how a proof could proceed. We have a meaning postulate, a convention that states that: > > **P1.** For all P, x: if P(x), then for all Q: if P and Q are contraries, then ¬Q(x). > > > Now we begin with the hypothesis that some object a is an A, and that A and O are contraries: > > **P2.** A(a) > > **P3.** Predicates A and O are contraries > > > Then we instantiate (P1) with a for x, obtaining: > > **P4.** For all P: if P(a), then for all Q: if P and Q are contraries, then ¬Q(a) > > > We then instantiate (P4) with A for P and O for Q, obtaining: > > **P5.** if A(a), then if A and O are contraries, then ¬O(a) > > > The rest is two applications of modus ponens starting with (P5) and using (P2) and then (P3): > > **P6.** if A and O are contraries, then ¬O(a) > > **P7.** ¬O(a) > > >","As has been pointed out already, if you are using logic to talk about apples and oranges you have already provided some model (say, *a* is an apple and *o* is an orange - formally speaking you've set up a function from constants in your logical language to objects or types or fruit or whatever). So I'm reasonably comfortable that the following proof is no less rigorous than what you've got already: let *P* (a one-place predicate) be assigned the meaning 'needs to be peeled to be eaten'\*. Then *Po* is true and *Pa* is false, so then clearly ¬(*x* = *y*) holds. \*obviously if you don't peel your oranges feel free to substitute some other predicate that fits --- To generalise a little, in case the moral of the above isn't clear, we 'prove' that two objects are distinct by providing some property that holds of one but not the other. It's an open question in metaphysics whether distinct objects can share every property (contenders might be the object of 52 cards and the object of the deck, I guess). Within logic, though, if two elements of your domain are distinct but the same predicates hold of them there isn't a way to prove that they are distinct - you could show that rigorously in a quite straightforward way; proof systems for first-order logic use (roughly) the above method for proving inequality." 8459,"It is easy to prove that an apple is an apple: The equation x=x is a tautology, for all x. So if x=apple, we can substitute it in the equation x=x and get apple=apple, so an apple is an apple. But how can one prove (using standard deductive logic) that an apple is not an orange, since x!=y is not a tautology for all x,y?",2013/10/23,"['https://philosophy.stackexchange.com/questions/8459', 'https://philosophy.stackexchange.com', 'https://philosophy.stackexchange.com/users/4639/']","In mathematics, an equals sign connects subject and predicate. The statement, apple=orange, is the same as the statement, an apple is an orange. In order to determine an apple is an apple, you used the principle of identity. That which is the same is the same. In order to determine an apple is not an orange, we use the principle of difference. That which is the same is not different, or two different things are not the same. General reasoning from sense infers that apples are not oranges. However, if we use the power of abstraction, we can take the concept of an apple, its ""appleness"", and a concept of an orange, its ""orangeness"". These conceptions are known though general reasoning from sense and are often informed from the rest of society, e.g. academia. An apple's ""appleness"" can only belong to apples. An orange's ""orangeness"" can only belong to oranges. ""appleness"" contains no ""orangeness"". Therefore, something containing ""orangeness"", namely an orange, is never something containing ""appleness"", namely an apple, i.e. apples are never oranges.","As has been pointed out already, if you are using logic to talk about apples and oranges you have already provided some model (say, *a* is an apple and *o* is an orange - formally speaking you've set up a function from constants in your logical language to objects or types or fruit or whatever). So I'm reasonably comfortable that the following proof is no less rigorous than what you've got already: let *P* (a one-place predicate) be assigned the meaning 'needs to be peeled to be eaten'\*. Then *Po* is true and *Pa* is false, so then clearly ¬(*x* = *y*) holds. \*obviously if you don't peel your oranges feel free to substitute some other predicate that fits --- To generalise a little, in case the moral of the above isn't clear, we 'prove' that two objects are distinct by providing some property that holds of one but not the other. It's an open question in metaphysics whether distinct objects can share every property (contenders might be the object of 52 cards and the object of the deck, I guess). Within logic, though, if two elements of your domain are distinct but the same predicates hold of them there isn't a way to prove that they are distinct - you could show that rigorously in a quite straightforward way; proof systems for first-order logic use (roughly) the above method for proving inequality." 8459,"It is easy to prove that an apple is an apple: The equation x=x is a tautology, for all x. So if x=apple, we can substitute it in the equation x=x and get apple=apple, so an apple is an apple. But how can one prove (using standard deductive logic) that an apple is not an orange, since x!=y is not a tautology for all x,y?",2013/10/23,"['https://philosophy.stackexchange.com/questions/8459', 'https://philosophy.stackexchange.com', 'https://philosophy.stackexchange.com/users/4639/']","In mathematics, an equals sign connects subject and predicate. The statement, apple=orange, is the same as the statement, an apple is an orange. In order to determine an apple is an apple, you used the principle of identity. That which is the same is the same. In order to determine an apple is not an orange, we use the principle of difference. That which is the same is not different, or two different things are not the same. General reasoning from sense infers that apples are not oranges. However, if we use the power of abstraction, we can take the concept of an apple, its ""appleness"", and a concept of an orange, its ""orangeness"". These conceptions are known though general reasoning from sense and are often informed from the rest of society, e.g. academia. An apple's ""appleness"" can only belong to apples. An orange's ""orangeness"" can only belong to oranges. ""appleness"" contains no ""orangeness"". Therefore, something containing ""orangeness"", namely an orange, is never something containing ""appleness"", namely an apple, i.e. apples are never oranges.","the logic used here is mathematical logic . but a mathematical logic is only accepted if there is no way to disprove the given logic i.e to say 2+3 =5 and 3+2 also=5 assures the logic that counting 5 pieces from left or right will always remain same because we cant find any two no's which dont obey this logic . so if we assume apple as x and orange as y such that we know always x=x and y=y is true(because any experiment cant disprove this .an apple remains an apple forever) now if somehow apple could change into orange after a few years then x=x would have been wrong and then x=y would hold good also falsness of only x=x directly assures the validity x=y. but validity of x=x doesnt directly assures the falsness of x=y note:apple=apple means apple will never change to anything else (including orange) and orange=orange means orange will never change to anything else (including apple) so both the chances are finished and there is no other way by which we can say that apple = orange.if one of the two statements x=x and y=y becomes false then x=y can be true means both x=x and y=y should be true" 8459,"It is easy to prove that an apple is an apple: The equation x=x is a tautology, for all x. So if x=apple, we can substitute it in the equation x=x and get apple=apple, so an apple is an apple. But how can one prove (using standard deductive logic) that an apple is not an orange, since x!=y is not a tautology for all x,y?",2013/10/23,"['https://philosophy.stackexchange.com/questions/8459', 'https://philosophy.stackexchange.com', 'https://philosophy.stackexchange.com/users/4639/']","What are these ""apple"" and ""orange"" that you speak of? In fact, none of the **terms** used in predicate logic have any meaning. The terms need to be **interpreted** according to a **model** or a domain of discourse. See [this SEP entry on Classical Logic](http://plato.stanford.edu/entries/logic-classical/), especially section 4, Semantics, for a whirl-wind tour, or [section 3.2 of the handouts by Voronkov](http://www.voronkov.com/lics_doc.cgi?what=chapter&n=3%E2%80%8E), for a longer explanation.","Use *types*: So that x:Apple, y:Orange This means that x is an apple, y is an orange. Then we cannot even compare oranges to apples - they're not of the same type; showing that they *must* be different. If one had an additional type Fruit from which these descend, then the types Orange and Apple would be comparable; but this would be *additional* type information that is unneccessary to implement and demonstrate the question asked by the OP. It's also worth noting that in an actually existing type system like Haskell, it would not be legal to construct two types of the same nature and name." 8459,"It is easy to prove that an apple is an apple: The equation x=x is a tautology, for all x. So if x=apple, we can substitute it in the equation x=x and get apple=apple, so an apple is an apple. But how can one prove (using standard deductive logic) that an apple is not an orange, since x!=y is not a tautology for all x,y?",2013/10/23,"['https://philosophy.stackexchange.com/questions/8459', 'https://philosophy.stackexchange.com', 'https://philosophy.stackexchange.com/users/4639/']","What are these ""apple"" and ""orange"" that you speak of? In fact, none of the **terms** used in predicate logic have any meaning. The terms need to be **interpreted** according to a **model** or a domain of discourse. See [this SEP entry on Classical Logic](http://plato.stanford.edu/entries/logic-classical/), especially section 4, Semantics, for a whirl-wind tour, or [section 3.2 of the handouts by Voronkov](http://www.voronkov.com/lics_doc.cgi?what=chapter&n=3%E2%80%8E), for a longer explanation.","It depends on your definition of ""apple"" and ""orange"". Is a human an ape? Most people would say ""no"", because their definition of 'ape' implicitly excludes humans. (They mostly involve animals hairier than most humans, and less verbose.) But [humans are apes](http://en.wikipedia.org/wiki/Homo) in the sense understood by modern biologists. So without precise definitions, you are unlikely to be able to prove that humans are not apes. Analogously, oranges are fruit which were introduced only a few hundred years ago to Europe, and this shows in the names given them by different European languages. In particular, in many slavic languages, nordic languages, and also Dutch, the name for ""orange"" translates into English literally as ""Chinese Apple"", after the country which they were first imported from. Clearly in English we distinguish strongly between apples and oranges, but until the mid 1800s we did not distinguish between lemons and limes; so any attempt to prove that a ""lemon"" was not a ""lime"" might have proven confusing. And complicating the matter is that technically, lemons, limes, and oranges are all merely cultivars of the same species of tree (you can cross them and get fertile offspring). This is beside the point for the apple/orange distinction, of course, except that it illustrates that distinctions we take for granted now and for practical purposes are both arbitrary (based on which citrus fruit we wish to distinguish from others) and contingent (our sense of what counts as a lime has changed with time). Another example: how do you prove that Pluto is not a planet? In the year 2000, you couldn't; it was considered a planet. Now, following [the decision by the IAU in 2006](http://en.wikipedia.org/wiki/IAU_definition_of_planet), one would *start from the agreed-upon definition of a planet*, which includes requirements which Pluto does not fulfil. In short, in order to prove that any A is not a B — *e.g.* where A is an apple, human, lemon, or the planet Pluto, and B is an orange, an ape, a lime, or a planet — definitions of A and B, or at least *some* extralogical information of what these things are, is necessary." 8459,"It is easy to prove that an apple is an apple: The equation x=x is a tautology, for all x. So if x=apple, we can substitute it in the equation x=x and get apple=apple, so an apple is an apple. But how can one prove (using standard deductive logic) that an apple is not an orange, since x!=y is not a tautology for all x,y?",2013/10/23,"['https://philosophy.stackexchange.com/questions/8459', 'https://philosophy.stackexchange.com', 'https://philosophy.stackexchange.com/users/4639/']","It's not a *logical truth* that an apple is not an orange, but it's nevertheless *analytic* with respect to the meaning postulate: if predicate P holds uniformly of object a, then for all predicates Q contrary to P, ¬Q(a). For example, if something is uniformly black, then it's not of any color that is contrary to black (say red). Recall that predicates A, B are *contraries* iff they cannot simultaneously be true of an object: > > **Definition.** Predicates P and Q are *contraries* =def for all x, either ¬P(x) or ¬Q(x). > > > Here's how a proof could proceed. We have a meaning postulate, a convention that states that: > > **P1.** For all P, x: if P(x), then for all Q: if P and Q are contraries, then ¬Q(x). > > > Now we begin with the hypothesis that some object a is an A, and that A and O are contraries: > > **P2.** A(a) > > **P3.** Predicates A and O are contraries > > > Then we instantiate (P1) with a for x, obtaining: > > **P4.** For all P: if P(a), then for all Q: if P and Q are contraries, then ¬Q(a) > > > We then instantiate (P4) with A for P and O for Q, obtaining: > > **P5.** if A(a), then if A and O are contraries, then ¬O(a) > > > The rest is two applications of modus ponens starting with (P5) and using (P2) and then (P3): > > **P6.** if A and O are contraries, then ¬O(a) > > **P7.** ¬O(a) > > >","It depends on your definition of ""apple"" and ""orange"". Is a human an ape? Most people would say ""no"", because their definition of 'ape' implicitly excludes humans. (They mostly involve animals hairier than most humans, and less verbose.) But [humans are apes](http://en.wikipedia.org/wiki/Homo) in the sense understood by modern biologists. So without precise definitions, you are unlikely to be able to prove that humans are not apes. Analogously, oranges are fruit which were introduced only a few hundred years ago to Europe, and this shows in the names given them by different European languages. In particular, in many slavic languages, nordic languages, and also Dutch, the name for ""orange"" translates into English literally as ""Chinese Apple"", after the country which they were first imported from. Clearly in English we distinguish strongly between apples and oranges, but until the mid 1800s we did not distinguish between lemons and limes; so any attempt to prove that a ""lemon"" was not a ""lime"" might have proven confusing. And complicating the matter is that technically, lemons, limes, and oranges are all merely cultivars of the same species of tree (you can cross them and get fertile offspring). This is beside the point for the apple/orange distinction, of course, except that it illustrates that distinctions we take for granted now and for practical purposes are both arbitrary (based on which citrus fruit we wish to distinguish from others) and contingent (our sense of what counts as a lime has changed with time). Another example: how do you prove that Pluto is not a planet? In the year 2000, you couldn't; it was considered a planet. Now, following [the decision by the IAU in 2006](http://en.wikipedia.org/wiki/IAU_definition_of_planet), one would *start from the agreed-upon definition of a planet*, which includes requirements which Pluto does not fulfil. In short, in order to prove that any A is not a B — *e.g.* where A is an apple, human, lemon, or the planet Pluto, and B is an orange, an ape, a lime, or a planet — definitions of A and B, or at least *some* extralogical information of what these things are, is necessary." 8459,"It is easy to prove that an apple is an apple: The equation x=x is a tautology, for all x. So if x=apple, we can substitute it in the equation x=x and get apple=apple, so an apple is an apple. But how can one prove (using standard deductive logic) that an apple is not an orange, since x!=y is not a tautology for all x,y?",2013/10/23,"['https://philosophy.stackexchange.com/questions/8459', 'https://philosophy.stackexchange.com', 'https://philosophy.stackexchange.com/users/4639/']","It depends on your definition of ""apple"" and ""orange"". Is a human an ape? Most people would say ""no"", because their definition of 'ape' implicitly excludes humans. (They mostly involve animals hairier than most humans, and less verbose.) But [humans are apes](http://en.wikipedia.org/wiki/Homo) in the sense understood by modern biologists. So without precise definitions, you are unlikely to be able to prove that humans are not apes. Analogously, oranges are fruit which were introduced only a few hundred years ago to Europe, and this shows in the names given them by different European languages. In particular, in many slavic languages, nordic languages, and also Dutch, the name for ""orange"" translates into English literally as ""Chinese Apple"", after the country which they were first imported from. Clearly in English we distinguish strongly between apples and oranges, but until the mid 1800s we did not distinguish between lemons and limes; so any attempt to prove that a ""lemon"" was not a ""lime"" might have proven confusing. And complicating the matter is that technically, lemons, limes, and oranges are all merely cultivars of the same species of tree (you can cross them and get fertile offspring). This is beside the point for the apple/orange distinction, of course, except that it illustrates that distinctions we take for granted now and for practical purposes are both arbitrary (based on which citrus fruit we wish to distinguish from others) and contingent (our sense of what counts as a lime has changed with time). Another example: how do you prove that Pluto is not a planet? In the year 2000, you couldn't; it was considered a planet. Now, following [the decision by the IAU in 2006](http://en.wikipedia.org/wiki/IAU_definition_of_planet), one would *start from the agreed-upon definition of a planet*, which includes requirements which Pluto does not fulfil. In short, in order to prove that any A is not a B — *e.g.* where A is an apple, human, lemon, or the planet Pluto, and B is an orange, an ape, a lime, or a planet — definitions of A and B, or at least *some* extralogical information of what these things are, is necessary.","Use *types*: So that x:Apple, y:Orange This means that x is an apple, y is an orange. Then we cannot even compare oranges to apples - they're not of the same type; showing that they *must* be different. If one had an additional type Fruit from which these descend, then the types Orange and Apple would be comparable; but this would be *additional* type information that is unneccessary to implement and demonstrate the question asked by the OP. It's also worth noting that in an actually existing type system like Haskell, it would not be legal to construct two types of the same nature and name." 8459,"It is easy to prove that an apple is an apple: The equation x=x is a tautology, for all x. So if x=apple, we can substitute it in the equation x=x and get apple=apple, so an apple is an apple. But how can one prove (using standard deductive logic) that an apple is not an orange, since x!=y is not a tautology for all x,y?",2013/10/23,"['https://philosophy.stackexchange.com/questions/8459', 'https://philosophy.stackexchange.com', 'https://philosophy.stackexchange.com/users/4639/']","It's not a *logical truth* that an apple is not an orange, but it's nevertheless *analytic* with respect to the meaning postulate: if predicate P holds uniformly of object a, then for all predicates Q contrary to P, ¬Q(a). For example, if something is uniformly black, then it's not of any color that is contrary to black (say red). Recall that predicates A, B are *contraries* iff they cannot simultaneously be true of an object: > > **Definition.** Predicates P and Q are *contraries* =def for all x, either ¬P(x) or ¬Q(x). > > > Here's how a proof could proceed. We have a meaning postulate, a convention that states that: > > **P1.** For all P, x: if P(x), then for all Q: if P and Q are contraries, then ¬Q(x). > > > Now we begin with the hypothesis that some object a is an A, and that A and O are contraries: > > **P2.** A(a) > > **P3.** Predicates A and O are contraries > > > Then we instantiate (P1) with a for x, obtaining: > > **P4.** For all P: if P(a), then for all Q: if P and Q are contraries, then ¬Q(a) > > > We then instantiate (P4) with A for P and O for Q, obtaining: > > **P5.** if A(a), then if A and O are contraries, then ¬O(a) > > > The rest is two applications of modus ponens starting with (P5) and using (P2) and then (P3): > > **P6.** if A and O are contraries, then ¬O(a) > > **P7.** ¬O(a) > > >","the logic used here is mathematical logic . but a mathematical logic is only accepted if there is no way to disprove the given logic i.e to say 2+3 =5 and 3+2 also=5 assures the logic that counting 5 pieces from left or right will always remain same because we cant find any two no's which dont obey this logic . so if we assume apple as x and orange as y such that we know always x=x and y=y is true(because any experiment cant disprove this .an apple remains an apple forever) now if somehow apple could change into orange after a few years then x=x would have been wrong and then x=y would hold good also falsness of only x=x directly assures the validity x=y. but validity of x=x doesnt directly assures the falsness of x=y note:apple=apple means apple will never change to anything else (including orange) and orange=orange means orange will never change to anything else (including apple) so both the chances are finished and there is no other way by which we can say that apple = orange.if one of the two statements x=x and y=y becomes false then x=y can be true means both x=x and y=y should be true" 8459,"It is easy to prove that an apple is an apple: The equation x=x is a tautology, for all x. So if x=apple, we can substitute it in the equation x=x and get apple=apple, so an apple is an apple. But how can one prove (using standard deductive logic) that an apple is not an orange, since x!=y is not a tautology for all x,y?",2013/10/23,"['https://philosophy.stackexchange.com/questions/8459', 'https://philosophy.stackexchange.com', 'https://philosophy.stackexchange.com/users/4639/']","What are these ""apple"" and ""orange"" that you speak of? In fact, none of the **terms** used in predicate logic have any meaning. The terms need to be **interpreted** according to a **model** or a domain of discourse. See [this SEP entry on Classical Logic](http://plato.stanford.edu/entries/logic-classical/), especially section 4, Semantics, for a whirl-wind tour, or [section 3.2 of the handouts by Voronkov](http://www.voronkov.com/lics_doc.cgi?what=chapter&n=3%E2%80%8E), for a longer explanation.","As has been pointed out already, if you are using logic to talk about apples and oranges you have already provided some model (say, *a* is an apple and *o* is an orange - formally speaking you've set up a function from constants in your logical language to objects or types or fruit or whatever). So I'm reasonably comfortable that the following proof is no less rigorous than what you've got already: let *P* (a one-place predicate) be assigned the meaning 'needs to be peeled to be eaten'\*. Then *Po* is true and *Pa* is false, so then clearly ¬(*x* = *y*) holds. \*obviously if you don't peel your oranges feel free to substitute some other predicate that fits --- To generalise a little, in case the moral of the above isn't clear, we 'prove' that two objects are distinct by providing some property that holds of one but not the other. It's an open question in metaphysics whether distinct objects can share every property (contenders might be the object of 52 cards and the object of the deck, I guess). Within logic, though, if two elements of your domain are distinct but the same predicates hold of them there isn't a way to prove that they are distinct - you could show that rigorously in a quite straightforward way; proof systems for first-order logic use (roughly) the above method for proving inequality." 8459,"It is easy to prove that an apple is an apple: The equation x=x is a tautology, for all x. So if x=apple, we can substitute it in the equation x=x and get apple=apple, so an apple is an apple. But how can one prove (using standard deductive logic) that an apple is not an orange, since x!=y is not a tautology for all x,y?",2013/10/23,"['https://philosophy.stackexchange.com/questions/8459', 'https://philosophy.stackexchange.com', 'https://philosophy.stackexchange.com/users/4639/']","In mathematics, an equals sign connects subject and predicate. The statement, apple=orange, is the same as the statement, an apple is an orange. In order to determine an apple is an apple, you used the principle of identity. That which is the same is the same. In order to determine an apple is not an orange, we use the principle of difference. That which is the same is not different, or two different things are not the same. General reasoning from sense infers that apples are not oranges. However, if we use the power of abstraction, we can take the concept of an apple, its ""appleness"", and a concept of an orange, its ""orangeness"". These conceptions are known though general reasoning from sense and are often informed from the rest of society, e.g. academia. An apple's ""appleness"" can only belong to apples. An orange's ""orangeness"" can only belong to oranges. ""appleness"" contains no ""orangeness"". Therefore, something containing ""orangeness"", namely an orange, is never something containing ""appleness"", namely an apple, i.e. apples are never oranges.","Use *types*: So that x:Apple, y:Orange This means that x is an apple, y is an orange. Then we cannot even compare oranges to apples - they're not of the same type; showing that they *must* be different. If one had an additional type Fruit from which these descend, then the types Orange and Apple would be comparable; but this would be *additional* type information that is unneccessary to implement and demonstrate the question asked by the OP. It's also worth noting that in an actually existing type system like Haskell, it would not be legal to construct two types of the same nature and name." 36437655,"I have been trying to create a product using Rest API for Magento Version 2.0. I am using Postman to test the rest api. URL : .***.***/rest/V1/products I have added the following headers to the request. Authorization : Bearer \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* Content-Type : application/json JSON BODY ``` { ""sku"":""10090-White-XL"", ""store_view_code"":"""", ""attribute_set_code"":""ColorSize"", ""product_type"":""virtual"", ""categories"":""Menswear/Tops"", ""product_websites"":""base"", ""name"":""10090-White-XL"", ""description"":""

Precise Long-Sleeve Shirt in Black, Denim, or White.

"", ""short_description"":"""", ""weight"":"""", ""product_online"":1, ""tax_class_name"":""Taxable Goods"", ""visibility"":""Not Visible Individually"", ""price"":119, ""special_price"":"""", ""special_price_from_date"":"""", ""special_price_to_date"":"""", ""url_key"":""10090-white-xl"", ""meta_title"":""Precise Long-Sleeve Shirt"", ""meta_keywords"":""Precise Long-Sleeve Shirt"", ""meta_description"":""Precise Long-Sleeve Shirt

Precise Long-Sleeve Shirt in Black, Denim, or White.

"", ""base_image"":"""", ""base_image_label"":"""", ""small_image"":"""", ""small_image_label"":"""", ""thumbnail_image"":"""", ""thumbnail_image_label"":"""", ""swatch_image"":"""", ""swatch_image_label"":"""", ""created_at"":""3/23/16, 2:15 PM"", ""updated_at"":""3/23/16, 2:15 PM"", ""new_from_date"":"""", ""new_to_date"":"""", ""display_product_options_in"":""Block after Info Column"", ""map_price"":"""", ""msrp_price"":"""", ""map_enabled"":"""", ""gift_message_available"":"""", ""custom_design"":"""", ""custom_design_from"":"""", ""custom_design_to"":"""", ""custom_layout_update"":"""", ""page_layout"":"""", ""product_options_container"":"""", ""msrp_display_actual_price_type"":"""", ""country_of_manufacture"":"""", ""additional_attributes"":""color=White,size=XL"", ""qty"":null, ""out_of_stock_qty"":0, ""use_config_min_qty"":1, ""is_qty_decimal"":0, ""allow_backorders"":0, ""use_config_backorders"":1, ""min_cart_qty"":1, ""use_config_min_sale_qty"":1, ""max_cart_qty"":10000, ""use_config_max_sale_qty"":1, ""is_in_stock"":0, ""notify_on_stock_below"":1, ""use_config_notify_stock_qty"":1, ""manage_stock"":0, ""use_config_manage_stock"":0, ""use_config_qty_increments"":1, ""qty_increments"":0, ""use_config_enable_qty_inc"":0, ""enable_qty_increments"":0, ""is_decimal_divided"":0, ""website_id"":1, ""related_skus"":"""", ""crosssell_skus"":"""", ""upsell_skus"":"""", ""additional_images"":"""", ""additional_image_labels"":"""", ""hide_from_product_page"":"""", ""bundle_price_type"":"""", ""bundle_sku_type"":"""", ""bundle_price_view"":"""", ""bundle_weight_type"":"""", ""bundle_values"":"""", ""configurable_variations"":"""", ""configurable_variation_labels"":"""", ""associated_skus"":"""" ``` } The error that I get is `{""message"":""%fieldName is a required field."",""parameters"":{""fieldName"":""product""}}` It will be great if someone could let me know how I could add a product. I have checked all the documents and but could not find an answer.",2016/04/05,"['https://Stackoverflow.com/questions/36437655', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2556858/']","I have found the answer to my question. The json structure need to be in this format: ``` { ""product"":{ ""id"": 12345, ""sku"": ""10090-White-XL"", ""name"": ""10090-White-XL"", ""attribute_set_id"": 9, ""price"": 119, ""status"": 1, ""visibility"": 1, ""type_id"": ""virtual"", ""created_at"": ""2016-04-05 23:04:09"", ""updated_at"": ""2016-04-05 23:04:09"", ""product_links"": [], ""options"": [], ""tier_prices"": [], ""custom_attributes"": [ { ""attribute_code"": ""description"", ""value"": ""

Precise Long-Sleeve Shirt in Black, Denim, or White.

"" }, { ""attribute_code"": ""meta_title"", ""value"": ""Precise Long-Sleeve Shirt"" }, { ""attribute_code"": ""meta_keyword"", ""value"": ""Precise Long-Sleeve Shirt"" }, { ""attribute_code"": ""meta_description"", ""value"": ""Precise Long-Sleeve Shirt

Precise Long-Sleeve Shirt in Black, Denim, or White.

"" }, { ""attribute_code"": ""color"", ""value"": ""11"" }, { ""attribute_code"": ""options_container"", ""value"": ""container2"" }, { ""attribute_code"": ""required_options"", ""value"": ""0"" }, { ""attribute_code"": ""has_options"", ""value"": ""0"" }, { ""attribute_code"": ""url_key"", ""value"": ""10090-white-xl"" }, { ""attribute_code"": ""msrp_display_actual_price_type"", ""value"": ""0"" }, { ""attribute_code"": ""tax_class_id"", ""value"": ""2"" }, { ""attribute_code"": ""size"", ""value"": ""8"" } ] },""saveOptions"": true } ``` The important thing to note is the product tag in the json.The swagger document help to idenity it. Here is the link to it: ","Simple product with custom attributes (ex: remarks). Just take note of the media\_gallery\_entries. Make sure to supply a valid base64\_encoded\_data image content and mime type. URL: METHOD: POST HEADER: application/json Authorization: Bearer POST DATA / RAW PAYLOAD: ```html { ""product"": { ""sku"": ""TESTPRD002"", ""name"": ""Women's Running - Pure Boost X Shoes"", ""attribute_set_id"": 4, ""price"": 84, ""status"": 1, ""visibility"": 4, ""type_id"": ""simple"", ""created_at"": ""2016-12-16 15:20:55"", ""updated_at"": ""2016-12-16 15:20:23"", ""weight"": 2.5, ""extension_attributes"": { ""stock_item"": { ""item_id"": 1, ""stock_id"": 1, ""qty"": 20, ""is_in_stock"": true, ""is_qty_decimal"": false } }, ""product_links"": [], ""options"": [], ""media_gallery_entries"": [ { ""media_type"": ""image"", ""label"": ""Women's Running - Pure Boost X Shoes"", ""position"": 1, ""disabled"": false, ""types"": [ ""image"", ""small_image"", ""thumbnail"" ], ""content"": { ""base64_encoded_data"": """", ""type"": ""image/jpeg"", ""name"": ""TESTPRD002-01.jpg"" } } ], ""tier_prices"": [], ""custom_attributes"": [ { ""attribute_code"": ""description"", ""value"": ""

Lightweight and sleek, these women's running shoes are fueled by boost™ energy. The low-profile runners blend an energy-returning boost™ midsole with a STRETCHWEB outsole for a cushioned ride with terrific ground-feel. They feature a breathable mesh upper with a sock-like fit that offers all-around support. With a full boost™ midsole that keeps every stride charged with light, fast energy, the shoe has an upper that hovers over a free-floating arch.

"" }, { ""attribute_code"": ""short_description"", ""value"": ""

PURE BOOST X SHOES

NATURAL RUNNING SHOES WITH ARCH SUPPORT.

"" }, { ""attribute_code"": ""meta_title"", ""value"": ""PURE BOOST X SHOES"" }, { ""attribute_code"": ""meta_keyword"", ""value"": ""boost X, running, shoes, adidas"" }, { ""attribute_code"": ""meta_description"", ""value"": ""NATURAL RUNNING SHOES WITH ARCH SUPPORT."" }, { ""attribute_code"": ""category_ids"", ""value"": [ ""2"", ""3"" ] }, { ""attribute_code"": ""url_key"", ""value"": ""womens-running-pure-boost-x-shoes"" }, { ""attribute_code"": ""tax_class_id"", ""value"": ""1"" }, { ""attribute_code"": ""remarks"", ""value"": ""Lorem ipsum.."" } ] }, ""saveOptions"": true } ```" 3144190,"I know that if $ G\_1, G\_2 $ are cyclic groups then $ G\_1 \times G\_2 $ is cyclic if and only if $ |G\_1| $ and $ |G\_2| $ are coprimes. But I have to reponds a similar question in the context of category theory: show that $ \mathbb{Z}\_n $, $ \mathbb{Z}\_m $ have a product in the category of cyclic groups if and only if $ n, m $ are coprimes. For the implication $ \leftarrow \ $ I consider that $ n,m $ coprimes $ \rightarrow \mathbb{Z}\_n \times \mathbb{Z}\_m $ is cyclic, so this group is an element of the cateogory. Now we can take the proyection $$ p\_1 : \mathbb{Z}\_n \times \mathbb{Z}\_m \rightarrow \mathbb{Z}\_n ,\ \ \ \ p\_1(x,y) = x $$ and $$ p\_2 : \mathbb{Z}\_n \times \mathbb{Z}\_m \rightarrow \mathbb{Z}\_m , \ \ \ \ p\_2(x,y) = y $$ that are homomorphism. Easily I can show that $ \mathbb{Z}\_n \times \mathbb{Z}\_m $ and $ p\_1, p\_2 $ form a product of $ \mathbb{Z}\_n $ and $ \mathbb{Z}\_m $ in the category of cyclic groups. But I am stuck in the proof of the implication $ \rightarrow $.",2019/03/11,"['https://math.stackexchange.com/questions/3144190', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/114670/']","This should also follow from a naive count of the number of homomorphisms between cyclic groups: specifically, $$\lvert \operatorname{Hom}(\mathbb{Z}\_a, \mathbb{Z}\_b) \rvert = \gcd(a,b).$$ Suppose $\mathbb{Z}\_p$ is the product of $\mathbb{Z}\_m$ and $\mathbb{Z}\_n$ in the category of cyclic groups. Then it satisfies universal property $$\operatorname{Hom}(\mathbb{Z}\_t, \mathbb{Z}\_p) \cong \operatorname{Hom}(\mathbb{Z}\_t, \mathbb{Z}\_m) \times \operatorname{Hom}(\mathbb{Z}\_t, \mathbb{Z}\_n)$$ for all $t$. Counting both sides, we obtain the relation $$\gcd(t,p) = \gcd(t,m) \cdot \gcd(t,n)$$ for all $t$. In particular, if $t = m$, we get $$\gcd(m,p) = m \cdot \gcd(m,n).$$ The left hand side is at most $m$, but in case $m, n$ are not coprime, $\gcd(m,n) > 1$, and the right hand side is strictly bigger than $m$. This would give a contradiction.","I think you can use the fact that every finite abelian group can be written as $(\mathbb{Z}\_{n\_1})^{\oplus m\_1}\oplus\cdots\oplus (\mathbb{Z}\_{n\_i})^{\oplus m\_i}$. So suppose now that $A$ is a categorical product of $\mathbb{Z}\_n$ and $\mathbb{Z}\_m$ in the category of cyclic groups, and let us show that it is also a categorical product in the category of finite abelian groups : Let $X$ be a finite abelian group, together with two maps $X \to \mathbb{Z}\_m$ and $X\to \mathbb{Z}\_n$. Writing $X = (\mathbb{Z}\_{n\_1})^{\oplus m\_1}\oplus\cdots\oplus (\mathbb{Z}\_{n\_i})^{\oplus m\_i}$, and precomposing by the various inclusions, we get a families of maps $f\_{n\_k}^j : \mathbb{Z}\_{n\_k}\to\mathbb{Z}\_n$ and $g\_{n\_k}^j : \mathbb{Z}\_{n\_k}\to\mathbb{Z}\_m$, for $j\leq m\_k$. We can now use the universal property of the product in the category of cyclic groups for each pair $(f\_{n\_k}^j,g\_{n\_k}^j)$ to get maps $h\_{n\_k}^j : \mathbb{Z}\_{n\_k}\to A$. Now let us this this family of maps for the universal property of the coproduct in the category of finite abelian groups, to get a map $h : X\to A$. You can prove that this map commutes with the initial $f,g$ modulo the projection (this is a trivial diagram, if you have understood the above construction). So if $A$ is a categorical product in the category of cyclic group, it is also a categorical product in the category of finite abelian groups, and thus it is given by the cartesian product of groups. This proof presuppose that you already know that $\times$ and $\oplus$ are respectively the product and coproduct in the category of finite abelian groups, but I think these are easier results." 46349085,"Trying to get the correct gradient colors to show based on php-time. When I try it, the gradients mismatch (I.E. topcolor from first hour-chunk and bottomcolor from fourth-hour chunk match together). ``` = 06 && $time < 12 ) $topcolor = 'black'; $bottomcolor = 'orange'; if( $time >= 12 && $time < 18 ) $topcolor = 'pink'; $bottomcolor = 'purple'; if( $time >= 18 && $time < 24 ) $topcolor = 'yellow'; $bottomcolor = 'blue'; if( $time >= 24 && $time < 6 ) $topcolor = 'red'; $bottomcolor = 'green'; ?> ```",2017/09/21,"['https://Stackoverflow.com/questions/46349085', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8303473/']","You need to wrap the statements after each `if` condition in braces: ``` if( $time >= 06 && $time < 12 ) $topcolor = 'black'; $bottomcolor = 'orange'; ``` -> ``` if( $time >= 06 && $time < 12 ) { $topcolor = 'black'; $bottomcolor = 'orange'; } ``` If you omit these, then only the first statement will be evaluated. See The reason the last `$bottomcolor` is taking effect is that all of the assignments to that variable are running regardless of the `$time` value, and the last one is taking precedence.","As you can learn from the [documentation](http://php.net/manual/en/control-structures.if.php) an `if` statement looks like: ``` if (expression) statement ``` And about [statements](http://php.net/manual/en/control-structures.intro.php): > > A statement can be an assignment, a function call, a loop, a conditional statement or even a statement that does nothing (an empty statement). Statements usually end with a semicolon. In addition, statements can be grouped into a statement-group by encapsulating a group of statements with curly braces. A statement-group is a statement by itself as well. > > > According to the new wisdom we just got, your code is the same as this (and the indentation doesn't matter, it is there only for beauty): ``` $time = date(""H""); if ($time >= 06 && $time < 12) $topcolor = 'black'; $bottomcolor = 'orange'; if ($time >= 12 && $time < 18) $topcolor = 'pink'; $bottomcolor = 'purple'; if ($time >= 18 && $time < 24) $topcolor = 'yellow'; $bottomcolor = 'blue'; if ($time >= 24 && $time < 6) // <--- this condition is impossible $topcolor = 'red'; $bottomcolor = 'green'; ``` As you can see, no matter the value of `$time` is, the value of `$bottomcolor` is changed to `'orange'` then to `'purple'` and so on and everytime its final value is the one produced by the last assignment (`$bottomcolor = 'green';`). It is [recommended](http://www.php-fig.org/psr/psr-2/#control-structures) to always use blocks for the statements of [`if`](http://php.net/manual/en/control-structures.if.php), [`else`](http://php.net/manual/en/control-structures.else.php), [`elseif/else`](http://php.net/manual/en/control-structures.elseif.php), [`while`](http://php.net/manual/en/control-structures.while.php), [`do-while`](http://php.net/manual/en/control-structures.do.while.php), [`for`](http://php.net/manual/en/control-structures.for.php) and [`foreach`](http://php.net/manual/en/control-structures.foreach.php) [control structures](http://php.net/manual/en/language.control-structures.php), even when they contain only one statement. This way the code is easier to read and understand by the programmers. It doesn't make any difference for the compiler. Back to your code, you can simplify the tests by using [`elseif`](http://php.net/manual/en/control-structures.elseif.php) statements: ``` $time = date('H'); if ($time < 6) { // night $topcolor = 'red'; $bottomcolor = 'green'; } elseif ($time < 12) { // morning $topcolor = 'black'; $bottomcolor = 'orange'; } elseif ($time < 18) { // afternoon $topcolor = 'pink'; $bottomcolor = 'purple'; } else { // evening $topcolor = 'yellow'; $bottomcolor = 'blue'; } ```" 51422311,"I have a problem with the layout on the Android Studio. The Editor (XML file) and Emulator (Nexus 10) shows the layout right. But if I run the app on my Huawei Mediaped M5, the layout changes and everything is mixed. The Emulator and my device have the same Resolution(2560\*1600). ![The Emulator](https://i.stack.imgur.com/bQExm.png) ![The screenshot of my real device](https://i.stack.imgur.com/MDMY0.jpg) ![the XML file](https://i.stack.imgur.com/379Io.png) The XML file: ``` {% endif %}
    {% for image in product.images %}
  • {% endfor %}
{% if enable_thumbnail_slides == true %} {% endif %} {% endif %} ``` I have read a couple of posts that outline a similar issue with developers trying to add a product videos however I have yet to come across a solution. If anyone can help out here that would be appreciated. Thanks",2017/10/10,"['https://Stackoverflow.com/questions/46658424', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3492429/']","Why use javascript for this when you can use simply liquid? You just need to add check for the `alt` attribute if it contains `youtube` or something unique. So for example: ``` {% if image.alt contains 'youtube' %} {% else %} {% endif %} ```","I just wanted to post the solution I arrived at based on the answer above by ""drip"". I hope this might help someone else down the track. ```
    {% for image in product.images %}
  • {% if image.alt contains 'youtube' or image.alt contains 'vimeo' %} {% assign src = image.alt | split: 'src=""' %} {% assign src = src[1] | split: '""' | first %} {% if src contains '?' %} {% assign src = src | append: '&autoplay=1' %} {% else %} {% assign src = src | append: '?autoplay=1' %} {% endif %} {% else %} {% endif %}
  • {% endfor %}
    {% for image in product.images %}
  • {% endfor %}
{{ 'jquery.flexslider-min.js' | asset_url | script_tag }} {{ 'flexslider.css' | asset_url | stylesheet_tag }} ``` Once you have updated the code you can place the embed code in the ALT tag of the image while using the image as a thumbnail placeholder. FlexSlider properties can be located here: The solution was also helped by the post here which was relating to another issue: " 4504132,"I am occasionally getting odd behavior from boost::lower, when called on a std::wstring. In particular, I have seen the following assertion fail in a release build (but *not* in a debug build): ``` Assertion failed: !is_singular(), file C:\boost_1_40_0\boost/range/iterator_range.hpp, line 281 ``` I have also seen what appear to be memory errors after calling boost::to\_lower in contexts such as: ``` void test(const wchar_t* word) { std::wstring buf(word); boost::to_lower(buf); ... } ``` Replacing the calls `boost::tolower(wstr)` with `std::transform(wstr.begin(), wstr.end(), wstr.begin(), towlower)` appears to fix the problem; but I'd like to know what's going wrong. My best guess is that perhaps the problem has something to do with changing the case of unicode characters -- perhaps the encoding size of the downcased character is different from the encoding size of the source character? Does anyone have any ideas what might be going on here? It might help if I knew what ""is\_singular()"" means in the context of boost, but after doing a few google searches I wasn't able to find any documentation for it. *Relevant software versions: Boost 1.40.0; MS Visual Studio 2008.*",2010/12/21,"['https://Stackoverflow.com/questions/4504132', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/222329/']","After further debugging, I figured out what was going on. The cause of my trouble was that one project in the solution was not defining NDEBUG (despite being in release mode), while all the other modules were. Boost allocates some extra fields in its data structures, which it uses to store debug information (such as whether a data structure has been initialized). If module A has debugging turned off, then it will create data structures that don't contain those fields. Then when module B, which has debugging turned on, gets its hands on that data structure, it will try to check those fields (which were not allocated), resulting in random memory errors. Defining NDEBUG in *all* projects in the solution fixed the problem.","An iterator range should only be singular if it's been constructed with the default constructor (stores singular iterators, i.e doesn't represent a range). As it's rather hard to believe that the boost's `to_lower` function manages to create a singular range, it suggests that the problem might also be elsewhere (a result of some undefined behavior, such as using uninitialized variables which might be initialized to some known value in debug builds). Read more on [Heisenbugs](https://stackoverflow.com/questions/1762088/common-reasons-for-bugs-in-release-version-not-present-in-debug-mode)." 73605,"I'm looking to try and identify the year this bike was built. Currently struggling to add photo's. [![enter image description here](https://i.stack.imgur.com/ibxeW.jpg)](https://i.stack.imgur.com/ibxeW.jpg) I will try and add some more in a minute. The frame number of the bike is 14246 Many thanks Wesley",2020/11/27,"['https://bicycles.stackexchange.com/questions/73605', 'https://bicycles.stackexchange.com', 'https://bicycles.stackexchange.com/users/53900/']","Nice bike - from the overall lines of the frame its definitely something from the 80s. The head tube is relatively short, so I'm guessing this is a smaller frame, maybe a 50cm or less. The pronounced curve of the front fork became straighter as time went on due to manufacturing changes. Also the right fork tine has a lamp mount which was common for the time. The three silver cable clamps on the top tube are more of a 70s design, but they may not be original. The bike has U brakes rather than cheaper calipers, so its a mid-range bike not a budget bike. These require a cable stop, so are probably original equipment. I'm sure the chainrings tell a story too - they have quite a difference between the large and small, in terms of tooth count. Your rims are interesting - I can't tell if they are steel or aluminium (ie replaced later) The only damage I can see is the two stays holding the rear of the front mudguard. Normally they'd be straight, not bent up which suggests something got in the spokes once. Minor as long as nothing's rubbing. I suggest you clean that filthy chain and cassette, then relubricate. That blackness is suspended grit which is slowly grinding away at the components of the transmission. **I would call this a touring bike from the early 1980s.** Its not a race bike, but that crankset would help it get up hills when loaded. The better brakes also help a heavily loaded bike come down the other side. Overall, looks like a loverly bike and a pleasure to ride.","Falccon continued to make high class bikes into the early 80s, the Olympic was a good alternative to something like a Dawes Galaxy - but rode even better, ime. The one in the pic looks very well used - look at the teeth on the chainrings." 73605,"I'm looking to try and identify the year this bike was built. Currently struggling to add photo's. [![enter image description here](https://i.stack.imgur.com/ibxeW.jpg)](https://i.stack.imgur.com/ibxeW.jpg) I will try and add some more in a minute. The frame number of the bike is 14246 Many thanks Wesley",2020/11/27,"['https://bicycles.stackexchange.com/questions/73605', 'https://bicycles.stackexchange.com', 'https://bicycles.stackexchange.com/users/53900/']","Adding information to Criggie's accurate answer. This is not the same bike but it is an Olympic and the style of decal matches your bike. Your frame has the wrap around stays and this one does not. [![enter image description here](https://i.stack.imgur.com/dqPpH.jpg)](https://i.stack.imgur.com/dqPpH.jpg) I don't view an ebay post as authoritative. The add says it's a 1980 - that's possible - but it's also possible that it's more like early 80s as opposed to exactly 1980. I'm still searching for a catalog or something more authoritative. [According to the ebay add](https://www.ebay.co.uk/itm/Falcon-Olympic-1980-Designed-by-Ernie-Clements-Classic-Eroica-Britannia-Bicycle/224234243858?hash=item3435670712:g:1Q0AAOSw5otfYLVF): > > Falcon Olympic 1980 > > Make: Falcon Cycles > > Model:Olympic designed by Ernie Clements > > Year: 1980 > > Size:Seat Tube: C2C 54cm , Top to C BB 55.5cm , Top tube C2C 55cm front to back 58cm > > Tubing: Reynolds 531 > > Brakes: Weinmann Vainquer Black Label Centre Pulls > > Brake Levers: Weinmann. Hooded > > Crankset: Sugino Super Maxy - 52 - 42 > > Crank Arm length: 165 > > Shifters: Shimano 600 Arabesque > > Rear Derailleur: Shimano 600 Arabesque (Long Cage) > > Front Derailleur: Shimano 600 Arabesque > > Freewheel/ Block: Shimano 5 Speed > > Hubs: Mailard Large Flange > > >","Falccon continued to make high class bikes into the early 80s, the Olympic was a good alternative to something like a Dawes Galaxy - but rode even better, ime. The one in the pic looks very well used - look at the teeth on the chainrings." 45825412,"Hello I'm new to NodeJs and am trying to work out the best way to get this chain of events working. I have to do two API calls get all the information I need. The first API call is just a list of IDs, then the second API call I pass the ID to get the rest of the information for each object. However using the method below, I have no idea when everything is finished. Please can someone help me out. ``` function getData() { var options = { method: 'GET', uri: 'https://api.call1.com', qs: { access_token: _accessToken, } }; request(options).then(function(apires){ console.log(""complete 1""); var obj = JSON.parse(apires); obj.data.forEach(function(entry) { findMore(entry.id) }); }) } function findMore(id) { var options = { method: 'GET', uri: 'https://api.call2.com', qs: { access_token: _accessToken, } }; request(options).then(function(apires){ console.log(""complete 2""); var obj = JSON.parse(apires); }) } ```",2017/08/22,"['https://Stackoverflow.com/questions/45825412', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4071548/']","You can make your findMore method return a promise, so you can pass an array of those to Promise.all and handle the .then when all promises have finished. ``` function getData() { var options = { method: 'GET', uri: 'https://api.call1.com', qs: { access_token: _accessToken, } }; request(options).then(function(apires){ console.log(""complete 1""); var obj = JSON.parse(apires); var promises = []; obj.data.forEach(function(entry) { promises.push(findMore(entry.id)); }); return Promise.all(promises); }) .then(function (response) { // Here response is an array with all the responses // from your calls to findMore }) } function findMore(id) { var options = { method: 'GET', uri: 'https://api.call2.com', qs: { access_token: _accessToken, } }; return request(options); } ```","You want to use Promise.all. So first thing first, you need an array of promises. Inside your for each loop, set findMore to a variable, and make it return the promise. Then have a line where you do Promise.all(promiseArr).then(function(){console.log(""done)}) Your code would look like this ``` function getData() { var promiseArr = [] var options = { method: 'GET', uri: 'https://api.call1.com', qs: { access_token: _accessToken, } }; request(options).then(function(apires){ console.log(""complete 1""); var obj = JSON.parse(apires); obj.data.forEach(function(entry) { var p = findMore(entry.id) promiseArr.push(p) }); }).then(function(){ Promise.all(promiseArr).then(function(){ console.log(""this is all done"") }) }) } function findMore(id) { var options = { method: 'GET', uri: 'https://api.call2.com', qs: { access_token: _accessToken, } }; return request(options).then(function(apires){ console.log(""complete 2""); var obj = JSON.parse(apires); }) } ``` the basic idea of Promise.all is that it only executes once all promises in the array have been resolved, or when any of the promises fail. You can read more about it [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all)" 45825412,"Hello I'm new to NodeJs and am trying to work out the best way to get this chain of events working. I have to do two API calls get all the information I need. The first API call is just a list of IDs, then the second API call I pass the ID to get the rest of the information for each object. However using the method below, I have no idea when everything is finished. Please can someone help me out. ``` function getData() { var options = { method: 'GET', uri: 'https://api.call1.com', qs: { access_token: _accessToken, } }; request(options).then(function(apires){ console.log(""complete 1""); var obj = JSON.parse(apires); obj.data.forEach(function(entry) { findMore(entry.id) }); }) } function findMore(id) { var options = { method: 'GET', uri: 'https://api.call2.com', qs: { access_token: _accessToken, } }; request(options).then(function(apires){ console.log(""complete 2""); var obj = JSON.parse(apires); }) } ```",2017/08/22,"['https://Stackoverflow.com/questions/45825412', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4071548/']","A couple of things to think about: **If you care about the fate of a promise, always return it**. In your case, `findMore` does not return the promise from `request`, so `getData` has no handle to track the resolution (or rejection) of that promise. **You can track the resolution of multiple promises with [Promise.all](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all).** > > The Promise.all() method returns a single Promise that resolves when all of the promises in the iterable argument have resolved or when the iterable argument contains no promises. It rejects with the reason of the first promise that rejects. > > > Lets put these to use on your example: ``` function getData() { var options = { method: 'GET', uri: 'https://api.call1.com', qs: { access_token: _accessToken, } }; return request(options) .then(function(apires){ var obj = JSON.parse(apires); var findMorePromises = obj.data.map(function(entry) { return findMore(entry.id) }); return Promise.all(findMorePromises); }) } function findMore(id) { var options = { method: 'GET', uri: 'https://api.call2.com', qs: { access_token: _accessToken, } }; return request(options) .then(function(apires){ return JSON.parse(apires); }) } ``` I've used [map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) to construct the array of promises, but you could just as well use a `foreach` and push into an array similar to be more similar to your example code. It's also good practice to make sure you are handling rejection of any promises (via `catch`), but I'll assume that is out of the scope of this question.","You want to use Promise.all. So first thing first, you need an array of promises. Inside your for each loop, set findMore to a variable, and make it return the promise. Then have a line where you do Promise.all(promiseArr).then(function(){console.log(""done)}) Your code would look like this ``` function getData() { var promiseArr = [] var options = { method: 'GET', uri: 'https://api.call1.com', qs: { access_token: _accessToken, } }; request(options).then(function(apires){ console.log(""complete 1""); var obj = JSON.parse(apires); obj.data.forEach(function(entry) { var p = findMore(entry.id) promiseArr.push(p) }); }).then(function(){ Promise.all(promiseArr).then(function(){ console.log(""this is all done"") }) }) } function findMore(id) { var options = { method: 'GET', uri: 'https://api.call2.com', qs: { access_token: _accessToken, } }; return request(options).then(function(apires){ console.log(""complete 2""); var obj = JSON.parse(apires); }) } ``` the basic idea of Promise.all is that it only executes once all promises in the array have been resolved, or when any of the promises fail. You can read more about it [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all)" 45825412,"Hello I'm new to NodeJs and am trying to work out the best way to get this chain of events working. I have to do two API calls get all the information I need. The first API call is just a list of IDs, then the second API call I pass the ID to get the rest of the information for each object. However using the method below, I have no idea when everything is finished. Please can someone help me out. ``` function getData() { var options = { method: 'GET', uri: 'https://api.call1.com', qs: { access_token: _accessToken, } }; request(options).then(function(apires){ console.log(""complete 1""); var obj = JSON.parse(apires); obj.data.forEach(function(entry) { findMore(entry.id) }); }) } function findMore(id) { var options = { method: 'GET', uri: 'https://api.call2.com', qs: { access_token: _accessToken, } }; request(options).then(function(apires){ console.log(""complete 2""); var obj = JSON.parse(apires); }) } ```",2017/08/22,"['https://Stackoverflow.com/questions/45825412', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4071548/']","You can make your findMore method return a promise, so you can pass an array of those to Promise.all and handle the .then when all promises have finished. ``` function getData() { var options = { method: 'GET', uri: 'https://api.call1.com', qs: { access_token: _accessToken, } }; request(options).then(function(apires){ console.log(""complete 1""); var obj = JSON.parse(apires); var promises = []; obj.data.forEach(function(entry) { promises.push(findMore(entry.id)); }); return Promise.all(promises); }) .then(function (response) { // Here response is an array with all the responses // from your calls to findMore }) } function findMore(id) { var options = { method: 'GET', uri: 'https://api.call2.com', qs: { access_token: _accessToken, } }; return request(options); } ```","You need to use `Promise.all` to run all async requests in parallel. Also you *must* return the result of `findMore` and `getData` (they are promises). ``` function getData() { var options = {...}; return request(options) .then(function(apires) { console.log(""complete 1""); var obj = JSON.parse(apires); var ops = obj.data.map(function(entry) { return findMore(entry.id); }); return Promise.all(ops); } function findMore(id) { var options = {...}; return request(options) .then(function(apires) { console.log(""complete 2""); return JSON.parse(apires); }); } getData() .then(data => console.log(data)) .catch(err => console.log(err)); ``` If you can use ES7, it can be written with async/await: ``` let getData = async () => { let options = {...}; let res = awit request(options); let ops = res.data.map(entry => findMore(entry.id)); let data = await Promise.all(ops); return data; }; let findMore = async (id) => { let options = {...}; let apires = awit request(options); return JSON.parse(apires); }; ```" 45825412,"Hello I'm new to NodeJs and am trying to work out the best way to get this chain of events working. I have to do two API calls get all the information I need. The first API call is just a list of IDs, then the second API call I pass the ID to get the rest of the information for each object. However using the method below, I have no idea when everything is finished. Please can someone help me out. ``` function getData() { var options = { method: 'GET', uri: 'https://api.call1.com', qs: { access_token: _accessToken, } }; request(options).then(function(apires){ console.log(""complete 1""); var obj = JSON.parse(apires); obj.data.forEach(function(entry) { findMore(entry.id) }); }) } function findMore(id) { var options = { method: 'GET', uri: 'https://api.call2.com', qs: { access_token: _accessToken, } }; request(options).then(function(apires){ console.log(""complete 2""); var obj = JSON.parse(apires); }) } ```",2017/08/22,"['https://Stackoverflow.com/questions/45825412', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4071548/']","A couple of things to think about: **If you care about the fate of a promise, always return it**. In your case, `findMore` does not return the promise from `request`, so `getData` has no handle to track the resolution (or rejection) of that promise. **You can track the resolution of multiple promises with [Promise.all](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all).** > > The Promise.all() method returns a single Promise that resolves when all of the promises in the iterable argument have resolved or when the iterable argument contains no promises. It rejects with the reason of the first promise that rejects. > > > Lets put these to use on your example: ``` function getData() { var options = { method: 'GET', uri: 'https://api.call1.com', qs: { access_token: _accessToken, } }; return request(options) .then(function(apires){ var obj = JSON.parse(apires); var findMorePromises = obj.data.map(function(entry) { return findMore(entry.id) }); return Promise.all(findMorePromises); }) } function findMore(id) { var options = { method: 'GET', uri: 'https://api.call2.com', qs: { access_token: _accessToken, } }; return request(options) .then(function(apires){ return JSON.parse(apires); }) } ``` I've used [map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) to construct the array of promises, but you could just as well use a `foreach` and push into an array similar to be more similar to your example code. It's also good practice to make sure you are handling rejection of any promises (via `catch`), but I'll assume that is out of the scope of this question.","You need to use `Promise.all` to run all async requests in parallel. Also you *must* return the result of `findMore` and `getData` (they are promises). ``` function getData() { var options = {...}; return request(options) .then(function(apires) { console.log(""complete 1""); var obj = JSON.parse(apires); var ops = obj.data.map(function(entry) { return findMore(entry.id); }); return Promise.all(ops); } function findMore(id) { var options = {...}; return request(options) .then(function(apires) { console.log(""complete 2""); return JSON.parse(apires); }); } getData() .then(data => console.log(data)) .catch(err => console.log(err)); ``` If you can use ES7, it can be written with async/await: ``` let getData = async () => { let options = {...}; let res = awit request(options); let ops = res.data.map(entry => findMore(entry.id)); let data = await Promise.all(ops); return data; }; let findMore = async (id) => { let options = {...}; let apires = awit request(options); return JSON.parse(apires); }; ```" 45825412,"Hello I'm new to NodeJs and am trying to work out the best way to get this chain of events working. I have to do two API calls get all the information I need. The first API call is just a list of IDs, then the second API call I pass the ID to get the rest of the information for each object. However using the method below, I have no idea when everything is finished. Please can someone help me out. ``` function getData() { var options = { method: 'GET', uri: 'https://api.call1.com', qs: { access_token: _accessToken, } }; request(options).then(function(apires){ console.log(""complete 1""); var obj = JSON.parse(apires); obj.data.forEach(function(entry) { findMore(entry.id) }); }) } function findMore(id) { var options = { method: 'GET', uri: 'https://api.call2.com', qs: { access_token: _accessToken, } }; request(options).then(function(apires){ console.log(""complete 2""); var obj = JSON.parse(apires); }) } ```",2017/08/22,"['https://Stackoverflow.com/questions/45825412', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4071548/']","You can make your findMore method return a promise, so you can pass an array of those to Promise.all and handle the .then when all promises have finished. ``` function getData() { var options = { method: 'GET', uri: 'https://api.call1.com', qs: { access_token: _accessToken, } }; request(options).then(function(apires){ console.log(""complete 1""); var obj = JSON.parse(apires); var promises = []; obj.data.forEach(function(entry) { promises.push(findMore(entry.id)); }); return Promise.all(promises); }) .then(function (response) { // Here response is an array with all the responses // from your calls to findMore }) } function findMore(id) { var options = { method: 'GET', uri: 'https://api.call2.com', qs: { access_token: _accessToken, } }; return request(options); } ```","EDIT: As others have mentioned, using a Promise.all() is likely a better solution in this case. If you are open to using jQuery (a JavaScript library), then you can use the .ajaxStop() event handler and specify your own function. Sample code: ``` $(document).ajaxStop(function(){ alert(""All AJAX requests are completed.""); }); ``` You will need to include the jQuery module. The instructions for Node.js are: 1. Install module through npm: ``` npm install jquery ``` 2. Then use a ""require"" to use jQuery in your JavaScript code (a window with a document is required but there is no such ""window"" in Node so you can mock one with jsdom), see [npm - jQuery](https://www.npmjs.com/package/jquery) for details: ``` require(""jsdom"").env("""", function(err, window) { if (err) { console.error(err); return; } var $ = require(""jquery"")(window); }); ``` If you want to stick to a pure JavaScript approach, you will need to create your own ""module"" to keep track of AJAX requests. In this module you can keep track of how many pending requests there are and remove them once they are terminated. Please see: [Check when all Ajax Requests are complete - Pure JavaScript](https://stackoverflow.com/questions/25971224/check-when-all-ajax-requests-are-complete-pure-javascript) for more details." 45825412,"Hello I'm new to NodeJs and am trying to work out the best way to get this chain of events working. I have to do two API calls get all the information I need. The first API call is just a list of IDs, then the second API call I pass the ID to get the rest of the information for each object. However using the method below, I have no idea when everything is finished. Please can someone help me out. ``` function getData() { var options = { method: 'GET', uri: 'https://api.call1.com', qs: { access_token: _accessToken, } }; request(options).then(function(apires){ console.log(""complete 1""); var obj = JSON.parse(apires); obj.data.forEach(function(entry) { findMore(entry.id) }); }) } function findMore(id) { var options = { method: 'GET', uri: 'https://api.call2.com', qs: { access_token: _accessToken, } }; request(options).then(function(apires){ console.log(""complete 2""); var obj = JSON.parse(apires); }) } ```",2017/08/22,"['https://Stackoverflow.com/questions/45825412', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4071548/']","You can make your findMore method return a promise, so you can pass an array of those to Promise.all and handle the .then when all promises have finished. ``` function getData() { var options = { method: 'GET', uri: 'https://api.call1.com', qs: { access_token: _accessToken, } }; request(options).then(function(apires){ console.log(""complete 1""); var obj = JSON.parse(apires); var promises = []; obj.data.forEach(function(entry) { promises.push(findMore(entry.id)); }); return Promise.all(promises); }) .then(function (response) { // Here response is an array with all the responses // from your calls to findMore }) } function findMore(id) { var options = { method: 'GET', uri: 'https://api.call2.com', qs: { access_token: _accessToken, } }; return request(options); } ```","A couple of things to think about: **If you care about the fate of a promise, always return it**. In your case, `findMore` does not return the promise from `request`, so `getData` has no handle to track the resolution (or rejection) of that promise. **You can track the resolution of multiple promises with [Promise.all](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all).** > > The Promise.all() method returns a single Promise that resolves when all of the promises in the iterable argument have resolved or when the iterable argument contains no promises. It rejects with the reason of the first promise that rejects. > > > Lets put these to use on your example: ``` function getData() { var options = { method: 'GET', uri: 'https://api.call1.com', qs: { access_token: _accessToken, } }; return request(options) .then(function(apires){ var obj = JSON.parse(apires); var findMorePromises = obj.data.map(function(entry) { return findMore(entry.id) }); return Promise.all(findMorePromises); }) } function findMore(id) { var options = { method: 'GET', uri: 'https://api.call2.com', qs: { access_token: _accessToken, } }; return request(options) .then(function(apires){ return JSON.parse(apires); }) } ``` I've used [map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) to construct the array of promises, but you could just as well use a `foreach` and push into an array similar to be more similar to your example code. It's also good practice to make sure you are handling rejection of any promises (via `catch`), but I'll assume that is out of the scope of this question." 45825412,"Hello I'm new to NodeJs and am trying to work out the best way to get this chain of events working. I have to do two API calls get all the information I need. The first API call is just a list of IDs, then the second API call I pass the ID to get the rest of the information for each object. However using the method below, I have no idea when everything is finished. Please can someone help me out. ``` function getData() { var options = { method: 'GET', uri: 'https://api.call1.com', qs: { access_token: _accessToken, } }; request(options).then(function(apires){ console.log(""complete 1""); var obj = JSON.parse(apires); obj.data.forEach(function(entry) { findMore(entry.id) }); }) } function findMore(id) { var options = { method: 'GET', uri: 'https://api.call2.com', qs: { access_token: _accessToken, } }; request(options).then(function(apires){ console.log(""complete 2""); var obj = JSON.parse(apires); }) } ```",2017/08/22,"['https://Stackoverflow.com/questions/45825412', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4071548/']","A couple of things to think about: **If you care about the fate of a promise, always return it**. In your case, `findMore` does not return the promise from `request`, so `getData` has no handle to track the resolution (or rejection) of that promise. **You can track the resolution of multiple promises with [Promise.all](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all).** > > The Promise.all() method returns a single Promise that resolves when all of the promises in the iterable argument have resolved or when the iterable argument contains no promises. It rejects with the reason of the first promise that rejects. > > > Lets put these to use on your example: ``` function getData() { var options = { method: 'GET', uri: 'https://api.call1.com', qs: { access_token: _accessToken, } }; return request(options) .then(function(apires){ var obj = JSON.parse(apires); var findMorePromises = obj.data.map(function(entry) { return findMore(entry.id) }); return Promise.all(findMorePromises); }) } function findMore(id) { var options = { method: 'GET', uri: 'https://api.call2.com', qs: { access_token: _accessToken, } }; return request(options) .then(function(apires){ return JSON.parse(apires); }) } ``` I've used [map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) to construct the array of promises, but you could just as well use a `foreach` and push into an array similar to be more similar to your example code. It's also good practice to make sure you are handling rejection of any promises (via `catch`), but I'll assume that is out of the scope of this question.","EDIT: As others have mentioned, using a Promise.all() is likely a better solution in this case. If you are open to using jQuery (a JavaScript library), then you can use the .ajaxStop() event handler and specify your own function. Sample code: ``` $(document).ajaxStop(function(){ alert(""All AJAX requests are completed.""); }); ``` You will need to include the jQuery module. The instructions for Node.js are: 1. Install module through npm: ``` npm install jquery ``` 2. Then use a ""require"" to use jQuery in your JavaScript code (a window with a document is required but there is no such ""window"" in Node so you can mock one with jsdom), see [npm - jQuery](https://www.npmjs.com/package/jquery) for details: ``` require(""jsdom"").env("""", function(err, window) { if (err) { console.error(err); return; } var $ = require(""jquery"")(window); }); ``` If you want to stick to a pure JavaScript approach, you will need to create your own ""module"" to keep track of AJAX requests. In this module you can keep track of how many pending requests there are and remove them once they are terminated. Please see: [Check when all Ajax Requests are complete - Pure JavaScript](https://stackoverflow.com/questions/25971224/check-when-all-ajax-requests-are-complete-pure-javascript) for more details." 11760258,"Consider the following Java class definitions: ``` class Animal {} class Lion extends Animal {} ``` When defining a covariant `Cage` for `Animal`s I use this code in Java: ``` class Cage { void add(T animal) { System.out.println(""Adding animal...""); } } ``` But the following Java example ... ``` public static void main(String... args) { Cage animals = null; Cage lions = null; animals = lions; // Works! animals.add(new Lion()); // Error! } ``` ... fails to compile with the following error: > > *The method add(capture#2-of ? extends Animal) > in the type Cage > is not applicable to for the arguments (Lion)* > > > Is this done because otherwise a different type like `Tiger` could be added after `animals = lions` and fail at runtime? Could a special (hypothetical) rule be made that would not rejected it iff there would be only one sub-type of `Animal`? (I know that I could replace `add`'s `T` with `Animal`.)",2012/08/01,"['https://Stackoverflow.com/questions/11760258', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/297776/']","I think this question might answer that for you: [java generics covariance](https://stackoverflow.com/questions/2660827/java-generics-covariance) Basically, Java generics are not covariant. The best explanation I know for this comes, of course, from Effective Java 2nd Edition. You can read about it here: I think the hypothetical rule would be quite hard to enforce in runtime. The compiler could theoretically check if all objects explicitly added to the list are indeed of the same type of animal, but I'm sure that there are conditions that could break this in runtime.","If so, that is likely a bug in the Scala compiler. Odersky et al. write in [An Overview of the Scala Programming Language](http://www.scala-lang.org/docu/files/ScalaOverview.pdf): > > Scala’s type system ensures that variance annotations are > sound by keeping track of the positions where a type pa- > rameter is used. These positions are classied as covariant > for the types of immutable elds and method results, and > contravariant for method argument types and upper type > parameter bounds. Type arguments to a non-variant type > parameter are always in non-variant position. The position > ips between contra- and co-variant inside a type argument > that corresponds to a contravariant parameter. The type > system enforces that covariant (respectively, contravariant) > type parameters are only used in covariant (contravariant) > positions. > > > Therefore, the covariant type parameter T must not appear as method argument, because that is a contravariant position. A similar rule (with more special cases, none of which matter in this case) is also present in the the [Scala Language Specification (version 2.9)](http://www.scala-lang.org/docu/files/ScalaReference.pdf), section 4.5." 11760258,"Consider the following Java class definitions: ``` class Animal {} class Lion extends Animal {} ``` When defining a covariant `Cage` for `Animal`s I use this code in Java: ``` class Cage { void add(T animal) { System.out.println(""Adding animal...""); } } ``` But the following Java example ... ``` public static void main(String... args) { Cage animals = null; Cage lions = null; animals = lions; // Works! animals.add(new Lion()); // Error! } ``` ... fails to compile with the following error: > > *The method add(capture#2-of ? extends Animal) > in the type Cage > is not applicable to for the arguments (Lion)* > > > Is this done because otherwise a different type like `Tiger` could be added after `animals = lions` and fail at runtime? Could a special (hypothetical) rule be made that would not rejected it iff there would be only one sub-type of `Animal`? (I know that I could replace `add`'s `T` with `Animal`.)",2012/08/01,"['https://Stackoverflow.com/questions/11760258', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/297776/']","In java : ``` Cage animals = null; ``` This is a cage, but you don't know what kind of animals it accepts. ``` animals = lions; // Works! ``` Ok, you add no opinion about what sort of cage animals was, so lion violates no expectation. ``` animals.add(new Lion()); // Error! ``` You don't know what sort of cage animals is. In this particular case, it happens to be a cage for lions you put a lion in, fine, but the rule that would allow that would just allow putting any sort of animal into any cage. It is properly disallowed. In Scala : `Cage[+T]` : if `B` extends `A`, then a `Cage[B]` should be considered a `Cage[A]`. Given that, `animals = lions` is allowed. But this is different from java, the type parameter is definitely `Animal`, not the wildcard `? extends Animal`. You are allowed to put an animal in a `Cage[Animal]`, a lion is an animal, so you can put a lion in a Cage[Animal] that could possibly be a Cage[Bird]. This is quite bad. Except that it is in fact not allowed (fortunately). Your code should not compile (if it compiled for you, you observed a compiler bug). A covariant generic parameter is not allowed to appear as an argument to a method. The reason being precisely that allowing it would allow putting lions in a bird cage. It T appears as `+T` in the definition of `Cage`, it cannot appears as an argument to method `add`. So both language disallow putting lions in birdcages. --- Regarding your updated questions. Is it done because otherwise a tiger could be added? Yes, this is of course the reason, the point of the type system is to make that impossible. Would that cause un runtime error? In all likelihood, it would at some point, but not at the moment you call add, as actual type of generic is not checked at run time (type erasure). But the type system usually rejects every program for which it cannot prove that (some kind of) errors will not happen, not just program where it can prove that they do happen. Could a special (hypothetical) rule be made that would not rejected it iff there would be only one sub-type of Animal? Maybe. Note that you still have two types of animals, namely `Animal` and `Lion`. So the important fact is that a `Lion` instance belongs to both types. On the other hand, an `Animal` instance does not belong to type `Lion`. `animals.add(new Lion())` could be allowed (the cage is either a cage for any animals, or for lions only, both ok) , but `animals.add(new Animal())` should not (as animals could be a cage for lions only). But anyway, it sounds like a very bad idea. The point of inheritance in object oriented system is that sometime later, someone else working somewhere else can add subtype, and that will not cause a correct system to become incorrect. In fact, the old code does not even need to be recompiled (maybe you do not have the source). With such a rule, that would not be true any more","I think this question might answer that for you: [java generics covariance](https://stackoverflow.com/questions/2660827/java-generics-covariance) Basically, Java generics are not covariant. The best explanation I know for this comes, of course, from Effective Java 2nd Edition. You can read about it here: I think the hypothetical rule would be quite hard to enforce in runtime. The compiler could theoretically check if all objects explicitly added to the list are indeed of the same type of animal, but I'm sure that there are conditions that could break this in runtime." 11760258,"Consider the following Java class definitions: ``` class Animal {} class Lion extends Animal {} ``` When defining a covariant `Cage` for `Animal`s I use this code in Java: ``` class Cage { void add(T animal) { System.out.println(""Adding animal...""); } } ``` But the following Java example ... ``` public static void main(String... args) { Cage animals = null; Cage lions = null; animals = lions; // Works! animals.add(new Lion()); // Error! } ``` ... fails to compile with the following error: > > *The method add(capture#2-of ? extends Animal) > in the type Cage > is not applicable to for the arguments (Lion)* > > > Is this done because otherwise a different type like `Tiger` could be added after `animals = lions` and fail at runtime? Could a special (hypothetical) rule be made that would not rejected it iff there would be only one sub-type of `Animal`? (I know that I could replace `add`'s `T` with `Animal`.)",2012/08/01,"['https://Stackoverflow.com/questions/11760258', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/297776/']","When you *declare* your variable with this type: `Cage`; you're basically saying that your variable is a cage with some *unkown* class that inherits from `Animal`. It could be a `Tiger` or a `Whale`; so the compiler doesn't have enough information to let you add a `Lion` to it. To have what you want, you declare your variable either as a `Cage` or a `Cage`.","If so, that is likely a bug in the Scala compiler. Odersky et al. write in [An Overview of the Scala Programming Language](http://www.scala-lang.org/docu/files/ScalaOverview.pdf): > > Scala’s type system ensures that variance annotations are > sound by keeping track of the positions where a type pa- > rameter is used. These positions are classied as covariant > for the types of immutable elds and method results, and > contravariant for method argument types and upper type > parameter bounds. Type arguments to a non-variant type > parameter are always in non-variant position. The position > ips between contra- and co-variant inside a type argument > that corresponds to a contravariant parameter. The type > system enforces that covariant (respectively, contravariant) > type parameters are only used in covariant (contravariant) > positions. > > > Therefore, the covariant type parameter T must not appear as method argument, because that is a contravariant position. A similar rule (with more special cases, none of which matter in this case) is also present in the the [Scala Language Specification (version 2.9)](http://www.scala-lang.org/docu/files/ScalaReference.pdf), section 4.5." 11760258,"Consider the following Java class definitions: ``` class Animal {} class Lion extends Animal {} ``` When defining a covariant `Cage` for `Animal`s I use this code in Java: ``` class Cage { void add(T animal) { System.out.println(""Adding animal...""); } } ``` But the following Java example ... ``` public static void main(String... args) { Cage animals = null; Cage lions = null; animals = lions; // Works! animals.add(new Lion()); // Error! } ``` ... fails to compile with the following error: > > *The method add(capture#2-of ? extends Animal) > in the type Cage > is not applicable to for the arguments (Lion)* > > > Is this done because otherwise a different type like `Tiger` could be added after `animals = lions` and fail at runtime? Could a special (hypothetical) rule be made that would not rejected it iff there would be only one sub-type of `Animal`? (I know that I could replace `add`'s `T` with `Animal`.)",2012/08/01,"['https://Stackoverflow.com/questions/11760258', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/297776/']","In java : ``` Cage animals = null; ``` This is a cage, but you don't know what kind of animals it accepts. ``` animals = lions; // Works! ``` Ok, you add no opinion about what sort of cage animals was, so lion violates no expectation. ``` animals.add(new Lion()); // Error! ``` You don't know what sort of cage animals is. In this particular case, it happens to be a cage for lions you put a lion in, fine, but the rule that would allow that would just allow putting any sort of animal into any cage. It is properly disallowed. In Scala : `Cage[+T]` : if `B` extends `A`, then a `Cage[B]` should be considered a `Cage[A]`. Given that, `animals = lions` is allowed. But this is different from java, the type parameter is definitely `Animal`, not the wildcard `? extends Animal`. You are allowed to put an animal in a `Cage[Animal]`, a lion is an animal, so you can put a lion in a Cage[Animal] that could possibly be a Cage[Bird]. This is quite bad. Except that it is in fact not allowed (fortunately). Your code should not compile (if it compiled for you, you observed a compiler bug). A covariant generic parameter is not allowed to appear as an argument to a method. The reason being precisely that allowing it would allow putting lions in a bird cage. It T appears as `+T` in the definition of `Cage`, it cannot appears as an argument to method `add`. So both language disallow putting lions in birdcages. --- Regarding your updated questions. Is it done because otherwise a tiger could be added? Yes, this is of course the reason, the point of the type system is to make that impossible. Would that cause un runtime error? In all likelihood, it would at some point, but not at the moment you call add, as actual type of generic is not checked at run time (type erasure). But the type system usually rejects every program for which it cannot prove that (some kind of) errors will not happen, not just program where it can prove that they do happen. Could a special (hypothetical) rule be made that would not rejected it iff there would be only one sub-type of Animal? Maybe. Note that you still have two types of animals, namely `Animal` and `Lion`. So the important fact is that a `Lion` instance belongs to both types. On the other hand, an `Animal` instance does not belong to type `Lion`. `animals.add(new Lion())` could be allowed (the cage is either a cage for any animals, or for lions only, both ok) , but `animals.add(new Animal())` should not (as animals could be a cage for lions only). But anyway, it sounds like a very bad idea. The point of inheritance in object oriented system is that sometime later, someone else working somewhere else can add subtype, and that will not cause a correct system to become incorrect. In fact, the old code does not even need to be recompiled (maybe you do not have the source). With such a rule, that would not be true any more","If so, that is likely a bug in the Scala compiler. Odersky et al. write in [An Overview of the Scala Programming Language](http://www.scala-lang.org/docu/files/ScalaOverview.pdf): > > Scala’s type system ensures that variance annotations are > sound by keeping track of the positions where a type pa- > rameter is used. These positions are classied as covariant > for the types of immutable elds and method results, and > contravariant for method argument types and upper type > parameter bounds. Type arguments to a non-variant type > parameter are always in non-variant position. The position > ips between contra- and co-variant inside a type argument > that corresponds to a contravariant parameter. The type > system enforces that covariant (respectively, contravariant) > type parameters are only used in covariant (contravariant) > positions. > > > Therefore, the covariant type parameter T must not appear as method argument, because that is a contravariant position. A similar rule (with more special cases, none of which matter in this case) is also present in the the [Scala Language Specification (version 2.9)](http://www.scala-lang.org/docu/files/ScalaReference.pdf), section 4.5." 11760258,"Consider the following Java class definitions: ``` class Animal {} class Lion extends Animal {} ``` When defining a covariant `Cage` for `Animal`s I use this code in Java: ``` class Cage { void add(T animal) { System.out.println(""Adding animal...""); } } ``` But the following Java example ... ``` public static void main(String... args) { Cage animals = null; Cage lions = null; animals = lions; // Works! animals.add(new Lion()); // Error! } ``` ... fails to compile with the following error: > > *The method add(capture#2-of ? extends Animal) > in the type Cage > is not applicable to for the arguments (Lion)* > > > Is this done because otherwise a different type like `Tiger` could be added after `animals = lions` and fail at runtime? Could a special (hypothetical) rule be made that would not rejected it iff there would be only one sub-type of `Animal`? (I know that I could replace `add`'s `T` with `Animal`.)",2012/08/01,"['https://Stackoverflow.com/questions/11760258', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/297776/']","In java : ``` Cage animals = null; ``` This is a cage, but you don't know what kind of animals it accepts. ``` animals = lions; // Works! ``` Ok, you add no opinion about what sort of cage animals was, so lion violates no expectation. ``` animals.add(new Lion()); // Error! ``` You don't know what sort of cage animals is. In this particular case, it happens to be a cage for lions you put a lion in, fine, but the rule that would allow that would just allow putting any sort of animal into any cage. It is properly disallowed. In Scala : `Cage[+T]` : if `B` extends `A`, then a `Cage[B]` should be considered a `Cage[A]`. Given that, `animals = lions` is allowed. But this is different from java, the type parameter is definitely `Animal`, not the wildcard `? extends Animal`. You are allowed to put an animal in a `Cage[Animal]`, a lion is an animal, so you can put a lion in a Cage[Animal] that could possibly be a Cage[Bird]. This is quite bad. Except that it is in fact not allowed (fortunately). Your code should not compile (if it compiled for you, you observed a compiler bug). A covariant generic parameter is not allowed to appear as an argument to a method. The reason being precisely that allowing it would allow putting lions in a bird cage. It T appears as `+T` in the definition of `Cage`, it cannot appears as an argument to method `add`. So both language disallow putting lions in birdcages. --- Regarding your updated questions. Is it done because otherwise a tiger could be added? Yes, this is of course the reason, the point of the type system is to make that impossible. Would that cause un runtime error? In all likelihood, it would at some point, but not at the moment you call add, as actual type of generic is not checked at run time (type erasure). But the type system usually rejects every program for which it cannot prove that (some kind of) errors will not happen, not just program where it can prove that they do happen. Could a special (hypothetical) rule be made that would not rejected it iff there would be only one sub-type of Animal? Maybe. Note that you still have two types of animals, namely `Animal` and `Lion`. So the important fact is that a `Lion` instance belongs to both types. On the other hand, an `Animal` instance does not belong to type `Lion`. `animals.add(new Lion())` could be allowed (the cage is either a cage for any animals, or for lions only, both ok) , but `animals.add(new Animal())` should not (as animals could be a cage for lions only). But anyway, it sounds like a very bad idea. The point of inheritance in object oriented system is that sometime later, someone else working somewhere else can add subtype, and that will not cause a correct system to become incorrect. In fact, the old code does not even need to be recompiled (maybe you do not have the source). With such a rule, that would not be true any more","When you *declare* your variable with this type: `Cage`; you're basically saying that your variable is a cage with some *unkown* class that inherits from `Animal`. It could be a `Tiger` or a `Whale`; so the compiler doesn't have enough information to let you add a `Lion` to it. To have what you want, you declare your variable either as a `Cage` or a `Cage`." 31292853,"Suppose I have a string like ""A B C (123-456-789)"", I'm wondering what's the best way to retrieve ""123-456-789"" from it. ``` strsplit(""A B C (123-456-789)"", ""\\("") [[1]] [1] ""A B C"" ""123-456-789)"" ```",2015/07/08,"['https://Stackoverflow.com/questions/31292853', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3015453/']","If we want to extract the digits with `-` between the braces, one option is `str_extract`. If there are multiple patterns within a string, use `str_extract_all` ``` library(stringr) str_extract(str1, '(?<=\\()[0-9-]+(?=\\))') #[1] ""123-456-789"" str_extract_all(str2, '(?<=\\()[0-9-]+(?=\\))') ``` In the above codes, we are using regex lookarounds to extract the numbers and the `-`. The positive lookbehind `(?<=\\()[0-9-]+` matches numbers along with `-` (`[0-9-]+`) in `(123-456-789` and not in `123-456-789`. Similarly the lookahead ('[0-9-]+(?=\)') matches numbers along with `-` in `123-456-789)` and not in `123-456-798`. Taken together it matches all the cases that satisfy both the conditions `(123-456-789)` and extract those in between the lookarounds and not with cases like `(123-456-789` or `123-456-789)` With `strsplit` you can specify the `split` as `[()]`. We keep the `()` inside the square brackets to `[]` to treat it as characters or else we have to escape the parentheses (`'\\(|\\)'`). ``` strsplit(str1, '[()]')[[1]][2] #[1] ""123-456-789"" ``` If there are multiple substrings to extract from a string, we could loop with `lapply` and extract the numeric split parts with `grep` ``` lapply(strsplit(str2, '[()]'), function(x) grep('\\d', x, value=TRUE)) ``` Or we can use `stri_split` from `stringi` which has the option to remove the empty strings as well (`omit_empty=TRUE`). ``` library(stringi) stri_split_regex(str1, '[()A-Z ]', omit_empty=TRUE)[[1]] #[1] ""123-456-789"" stri_split_regex(str2, '[()A-Z ]', omit_empty=TRUE) ``` Another option is `rm_round` from `qdapRegex` if we are interested in extracting the contents inside the brackets. ``` library(qdapRegex) rm_round(str1, extract=TRUE)[[1]] #[1] ""123-456-789"" rm_round(str2, extract=TRUE) ``` ### data ``` str1 <- ""A B C (123-456-789)"" str2 <- c(""A B C (123-425-478) A"", ""ABC(123-423-428)"", ""(123-423-498) ABCDD"", ""(123-432-423)"", ""ABC (123-423-389) GR (124-233-848) AK"") ```","or with `sub` from `base R`: ``` sub(""[^(]+\\(([^)]+)\\).*"", ""\\1"", ""A B C (123-456-789)"") #[1] ""123-456-789"" ``` Explanation: `[^(]+` : matches anything except an opening bracket `\\(` : matches an opening bracket, which is just before what you want `([^)]+)` : matches the pattern you want to capture (which is then retrieved in `replacement=""\\1""`), which is anything except a closing bracket `\\).*` matches a closing bracket followed by anything, 0 or more times ***Another option with look-ahead and look-behind*** ``` sub("".*(?<=\\()(.+)(?=\\)).*"", ""\\1"", ""A B C (123-456-789)"", perl=TRUE) #[1] ""123-456-789"" ```" 31292853,"Suppose I have a string like ""A B C (123-456-789)"", I'm wondering what's the best way to retrieve ""123-456-789"" from it. ``` strsplit(""A B C (123-456-789)"", ""\\("") [[1]] [1] ""A B C"" ""123-456-789)"" ```",2015/07/08,"['https://Stackoverflow.com/questions/31292853', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3015453/']","If we want to extract the digits with `-` between the braces, one option is `str_extract`. If there are multiple patterns within a string, use `str_extract_all` ``` library(stringr) str_extract(str1, '(?<=\\()[0-9-]+(?=\\))') #[1] ""123-456-789"" str_extract_all(str2, '(?<=\\()[0-9-]+(?=\\))') ``` In the above codes, we are using regex lookarounds to extract the numbers and the `-`. The positive lookbehind `(?<=\\()[0-9-]+` matches numbers along with `-` (`[0-9-]+`) in `(123-456-789` and not in `123-456-789`. Similarly the lookahead ('[0-9-]+(?=\)') matches numbers along with `-` in `123-456-789)` and not in `123-456-798`. Taken together it matches all the cases that satisfy both the conditions `(123-456-789)` and extract those in between the lookarounds and not with cases like `(123-456-789` or `123-456-789)` With `strsplit` you can specify the `split` as `[()]`. We keep the `()` inside the square brackets to `[]` to treat it as characters or else we have to escape the parentheses (`'\\(|\\)'`). ``` strsplit(str1, '[()]')[[1]][2] #[1] ""123-456-789"" ``` If there are multiple substrings to extract from a string, we could loop with `lapply` and extract the numeric split parts with `grep` ``` lapply(strsplit(str2, '[()]'), function(x) grep('\\d', x, value=TRUE)) ``` Or we can use `stri_split` from `stringi` which has the option to remove the empty strings as well (`omit_empty=TRUE`). ``` library(stringi) stri_split_regex(str1, '[()A-Z ]', omit_empty=TRUE)[[1]] #[1] ""123-456-789"" stri_split_regex(str2, '[()A-Z ]', omit_empty=TRUE) ``` Another option is `rm_round` from `qdapRegex` if we are interested in extracting the contents inside the brackets. ``` library(qdapRegex) rm_round(str1, extract=TRUE)[[1]] #[1] ""123-456-789"" rm_round(str2, extract=TRUE) ``` ### data ``` str1 <- ""A B C (123-456-789)"" str2 <- c(""A B C (123-425-478) A"", ""ABC(123-423-428)"", ""(123-423-498) ABCDD"", ""(123-432-423)"", ""ABC (123-423-389) GR (124-233-848) AK"") ```","Try this also: ``` k<-""A B C (123-456-789)"" regmatches(k,gregexpr(""*.(\\d+).*"",k))[[1]] [1] ""(123-456-789)"" ``` With suggestion from @Arun: ``` regmatches(k, gregexpr('(?<=\\()[^A-Z ]+(?=\\))', k, perl=TRUE))[[1]] ``` With suggestion from @akrun: ``` regmatches(k, gregexpr('[0-9-]+', k))[[1]] ```" 31292853,"Suppose I have a string like ""A B C (123-456-789)"", I'm wondering what's the best way to retrieve ""123-456-789"" from it. ``` strsplit(""A B C (123-456-789)"", ""\\("") [[1]] [1] ""A B C"" ""123-456-789)"" ```",2015/07/08,"['https://Stackoverflow.com/questions/31292853', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3015453/']","If we want to extract the digits with `-` between the braces, one option is `str_extract`. If there are multiple patterns within a string, use `str_extract_all` ``` library(stringr) str_extract(str1, '(?<=\\()[0-9-]+(?=\\))') #[1] ""123-456-789"" str_extract_all(str2, '(?<=\\()[0-9-]+(?=\\))') ``` In the above codes, we are using regex lookarounds to extract the numbers and the `-`. The positive lookbehind `(?<=\\()[0-9-]+` matches numbers along with `-` (`[0-9-]+`) in `(123-456-789` and not in `123-456-789`. Similarly the lookahead ('[0-9-]+(?=\)') matches numbers along with `-` in `123-456-789)` and not in `123-456-798`. Taken together it matches all the cases that satisfy both the conditions `(123-456-789)` and extract those in between the lookarounds and not with cases like `(123-456-789` or `123-456-789)` With `strsplit` you can specify the `split` as `[()]`. We keep the `()` inside the square brackets to `[]` to treat it as characters or else we have to escape the parentheses (`'\\(|\\)'`). ``` strsplit(str1, '[()]')[[1]][2] #[1] ""123-456-789"" ``` If there are multiple substrings to extract from a string, we could loop with `lapply` and extract the numeric split parts with `grep` ``` lapply(strsplit(str2, '[()]'), function(x) grep('\\d', x, value=TRUE)) ``` Or we can use `stri_split` from `stringi` which has the option to remove the empty strings as well (`omit_empty=TRUE`). ``` library(stringi) stri_split_regex(str1, '[()A-Z ]', omit_empty=TRUE)[[1]] #[1] ""123-456-789"" stri_split_regex(str2, '[()A-Z ]', omit_empty=TRUE) ``` Another option is `rm_round` from `qdapRegex` if we are interested in extracting the contents inside the brackets. ``` library(qdapRegex) rm_round(str1, extract=TRUE)[[1]] #[1] ""123-456-789"" rm_round(str2, extract=TRUE) ``` ### data ``` str1 <- ""A B C (123-456-789)"" str2 <- c(""A B C (123-425-478) A"", ""ABC(123-423-428)"", ""(123-423-498) ABCDD"", ""(123-432-423)"", ""ABC (123-423-389) GR (124-233-848) AK"") ```","The capture groups in `sub` will target your desired output: ``` sub('.*\\((.*)\\).*', '\\1', str1) [1] ""123-456-789"" ``` Extra check to make sure I pass @akrun's extended example: ``` sub('.*\\((.*)\\).*', '\\1', str2) [1] ""123-425-478"" ""123-423-428"" ""123-423-498"" ""123-432-423"" ""124-233-848"" ```" 31292853,"Suppose I have a string like ""A B C (123-456-789)"", I'm wondering what's the best way to retrieve ""123-456-789"" from it. ``` strsplit(""A B C (123-456-789)"", ""\\("") [[1]] [1] ""A B C"" ""123-456-789)"" ```",2015/07/08,"['https://Stackoverflow.com/questions/31292853', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3015453/']","If we want to extract the digits with `-` between the braces, one option is `str_extract`. If there are multiple patterns within a string, use `str_extract_all` ``` library(stringr) str_extract(str1, '(?<=\\()[0-9-]+(?=\\))') #[1] ""123-456-789"" str_extract_all(str2, '(?<=\\()[0-9-]+(?=\\))') ``` In the above codes, we are using regex lookarounds to extract the numbers and the `-`. The positive lookbehind `(?<=\\()[0-9-]+` matches numbers along with `-` (`[0-9-]+`) in `(123-456-789` and not in `123-456-789`. Similarly the lookahead ('[0-9-]+(?=\)') matches numbers along with `-` in `123-456-789)` and not in `123-456-798`. Taken together it matches all the cases that satisfy both the conditions `(123-456-789)` and extract those in between the lookarounds and not with cases like `(123-456-789` or `123-456-789)` With `strsplit` you can specify the `split` as `[()]`. We keep the `()` inside the square brackets to `[]` to treat it as characters or else we have to escape the parentheses (`'\\(|\\)'`). ``` strsplit(str1, '[()]')[[1]][2] #[1] ""123-456-789"" ``` If there are multiple substrings to extract from a string, we could loop with `lapply` and extract the numeric split parts with `grep` ``` lapply(strsplit(str2, '[()]'), function(x) grep('\\d', x, value=TRUE)) ``` Or we can use `stri_split` from `stringi` which has the option to remove the empty strings as well (`omit_empty=TRUE`). ``` library(stringi) stri_split_regex(str1, '[()A-Z ]', omit_empty=TRUE)[[1]] #[1] ""123-456-789"" stri_split_regex(str2, '[()A-Z ]', omit_empty=TRUE) ``` Another option is `rm_round` from `qdapRegex` if we are interested in extracting the contents inside the brackets. ``` library(qdapRegex) rm_round(str1, extract=TRUE)[[1]] #[1] ""123-456-789"" rm_round(str2, extract=TRUE) ``` ### data ``` str1 <- ""A B C (123-456-789)"" str2 <- c(""A B C (123-425-478) A"", ""ABC(123-423-428)"", ""(123-423-498) ABCDD"", ""(123-432-423)"", ""ABC (123-423-389) GR (124-233-848) AK"") ```","You may try these gsub functions. ``` > gsub(""[^\\d-]"", """", x, perl=T) [1] ""123-456-789"" > gsub("".*\\(|\\)"", """", x) [1] ""123-456-789"" > gsub(""[^0-9-]"", """", x) [1] ""123-456-789"" ``` Few more... ``` > gsub(""[0-9-](*SKIP)(*F)|."", """", x, perl=T) [1] ""123-456-789"" > gsub(""(?:(?![0-9-]).)*"", """", x, perl=T) [1] ""123-456-789"" ```" 31292853,"Suppose I have a string like ""A B C (123-456-789)"", I'm wondering what's the best way to retrieve ""123-456-789"" from it. ``` strsplit(""A B C (123-456-789)"", ""\\("") [[1]] [1] ""A B C"" ""123-456-789)"" ```",2015/07/08,"['https://Stackoverflow.com/questions/31292853', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3015453/']","or with `sub` from `base R`: ``` sub(""[^(]+\\(([^)]+)\\).*"", ""\\1"", ""A B C (123-456-789)"") #[1] ""123-456-789"" ``` Explanation: `[^(]+` : matches anything except an opening bracket `\\(` : matches an opening bracket, which is just before what you want `([^)]+)` : matches the pattern you want to capture (which is then retrieved in `replacement=""\\1""`), which is anything except a closing bracket `\\).*` matches a closing bracket followed by anything, 0 or more times ***Another option with look-ahead and look-behind*** ``` sub("".*(?<=\\()(.+)(?=\\)).*"", ""\\1"", ""A B C (123-456-789)"", perl=TRUE) #[1] ""123-456-789"" ```","Try this also: ``` k<-""A B C (123-456-789)"" regmatches(k,gregexpr(""*.(\\d+).*"",k))[[1]] [1] ""(123-456-789)"" ``` With suggestion from @Arun: ``` regmatches(k, gregexpr('(?<=\\()[^A-Z ]+(?=\\))', k, perl=TRUE))[[1]] ``` With suggestion from @akrun: ``` regmatches(k, gregexpr('[0-9-]+', k))[[1]] ```" 31292853,"Suppose I have a string like ""A B C (123-456-789)"", I'm wondering what's the best way to retrieve ""123-456-789"" from it. ``` strsplit(""A B C (123-456-789)"", ""\\("") [[1]] [1] ""A B C"" ""123-456-789)"" ```",2015/07/08,"['https://Stackoverflow.com/questions/31292853', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3015453/']","or with `sub` from `base R`: ``` sub(""[^(]+\\(([^)]+)\\).*"", ""\\1"", ""A B C (123-456-789)"") #[1] ""123-456-789"" ``` Explanation: `[^(]+` : matches anything except an opening bracket `\\(` : matches an opening bracket, which is just before what you want `([^)]+)` : matches the pattern you want to capture (which is then retrieved in `replacement=""\\1""`), which is anything except a closing bracket `\\).*` matches a closing bracket followed by anything, 0 or more times ***Another option with look-ahead and look-behind*** ``` sub("".*(?<=\\()(.+)(?=\\)).*"", ""\\1"", ""A B C (123-456-789)"", perl=TRUE) #[1] ""123-456-789"" ```","You may try these gsub functions. ``` > gsub(""[^\\d-]"", """", x, perl=T) [1] ""123-456-789"" > gsub("".*\\(|\\)"", """", x) [1] ""123-456-789"" > gsub(""[^0-9-]"", """", x) [1] ""123-456-789"" ``` Few more... ``` > gsub(""[0-9-](*SKIP)(*F)|."", """", x, perl=T) [1] ""123-456-789"" > gsub(""(?:(?![0-9-]).)*"", """", x, perl=T) [1] ""123-456-789"" ```" 31292853,"Suppose I have a string like ""A B C (123-456-789)"", I'm wondering what's the best way to retrieve ""123-456-789"" from it. ``` strsplit(""A B C (123-456-789)"", ""\\("") [[1]] [1] ""A B C"" ""123-456-789)"" ```",2015/07/08,"['https://Stackoverflow.com/questions/31292853', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3015453/']","The capture groups in `sub` will target your desired output: ``` sub('.*\\((.*)\\).*', '\\1', str1) [1] ""123-456-789"" ``` Extra check to make sure I pass @akrun's extended example: ``` sub('.*\\((.*)\\).*', '\\1', str2) [1] ""123-425-478"" ""123-423-428"" ""123-423-498"" ""123-432-423"" ""124-233-848"" ```","Try this also: ``` k<-""A B C (123-456-789)"" regmatches(k,gregexpr(""*.(\\d+).*"",k))[[1]] [1] ""(123-456-789)"" ``` With suggestion from @Arun: ``` regmatches(k, gregexpr('(?<=\\()[^A-Z ]+(?=\\))', k, perl=TRUE))[[1]] ``` With suggestion from @akrun: ``` regmatches(k, gregexpr('[0-9-]+', k))[[1]] ```" 31292853,"Suppose I have a string like ""A B C (123-456-789)"", I'm wondering what's the best way to retrieve ""123-456-789"" from it. ``` strsplit(""A B C (123-456-789)"", ""\\("") [[1]] [1] ""A B C"" ""123-456-789)"" ```",2015/07/08,"['https://Stackoverflow.com/questions/31292853', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3015453/']","The capture groups in `sub` will target your desired output: ``` sub('.*\\((.*)\\).*', '\\1', str1) [1] ""123-456-789"" ``` Extra check to make sure I pass @akrun's extended example: ``` sub('.*\\((.*)\\).*', '\\1', str2) [1] ""123-425-478"" ""123-423-428"" ""123-423-498"" ""123-432-423"" ""124-233-848"" ```","You may try these gsub functions. ``` > gsub(""[^\\d-]"", """", x, perl=T) [1] ""123-456-789"" > gsub("".*\\(|\\)"", """", x) [1] ""123-456-789"" > gsub(""[^0-9-]"", """", x) [1] ""123-456-789"" ``` Few more... ``` > gsub(""[0-9-](*SKIP)(*F)|."", """", x, perl=T) [1] ""123-456-789"" > gsub(""(?:(?![0-9-]).)*"", """", x, perl=T) [1] ""123-456-789"" ```" 345177,"Just curious if the time you're stuck in a bury is the same for all attacks that cause you to be buried, or the amount of mashing needed to get out is the same? Examples include: * G&W down smash * KKR's down throw * DK's side special * Wii Fit trainer's neutral normal 3-hit combo * Pitfall items * etc.",2019/01/17,"['https://gaming.stackexchange.com/questions/345177', 'https://gaming.stackexchange.com', 'https://gaming.stackexchange.com/users/18916/']","If you haven't heard of [Beefy Smash Dudes](https://www.youtube.com/channel/UCeCEq4Sz1nNK4wn3Z4Ozk2w), I highly suggest checking them out. They have some amazing technical Smash content, and they're always my go to for keeping up with new Smash techniques. Not to mention they just [put out a video on Smash Ultimate buries](https://www.youtube.com/watch?v=fWsCApe4e94) 4 days ago! To sum up, each burying attack has a ""base duration."" In other words, **not all bury attacks are created equal.** From the video linked above, here are the base bury times (in seconds) for different moves at 0% without mashing: [![enter image description here](https://i.stack.imgur.com/b2mOH.jpg)](https://i.stack.imgur.com/b2mOH.jpg) The more percent a buried character has, the longer they'll stay buried. But just from this graphic it's clear that *some* buries are many times more powerful than others (looking at you, Inkling). Mashing will help to shorten the time, but different mashes will reduce the time different amounts. An input like `A`, `B`, `L` or `X` will reduce bury time by **.25 seconds** or 15 frames. Directional inputs on your control stick on the other hand, reduce the buy by half that of the buttons, or about **.13 seconds** or 8 frames (however, the game only counts the cardinal directions--up/down/left/right--as inputs on the stick). For more on the technicalities of mashing, see [Beefy's Smash 4 mashing video](https://www.youtube.com/watch?v=pwfXtDiQA24), since the mechanic has remained the same in Ultimate.","In previous games, bury time is purely based on knockback dealt (as in the amount of knockback that would have been applied if it weren't a bury attack). In Ultimate, it appears to also be based on current damage (though less so). The exact formula isn't known yet. Each input of mashing reduces bury time by 8 frames." 17735661,"I need to parse log files and get some values to variable. The log file will have a string ``` String logStr = ""21:19:03 -[ 8b4]- ERROR - Jhy AlarmOccure::OnAdd - Updated existing alarm: ID [StrValue1:StrValu2|StrValue3], Instance [4053], SetStatus [0], AckStatus [1], SetTime [DateValue4], ClearedTime [DateValue5]""; ``` I need to get StrValue1,StrValue2,StrValue3,DateValue4 and DateValue5 to varaibles these values are changing fields when ever there is an error. First i was trying to at least get StrValue1. But not getting the expected result. ``` Pattern twsPattern = Pattern.compile("".*?ID ?[([^]:]*):([^]|]*)|([^]]*)]"");//.*ID\\s$.([^]:]*.):.([^]|]*.)|.([^]]*.).] Matcher twsMatcher = twsPattern.matcher(logStr); if(twsMatcher.find()){ System.out.println(twsMatcher.start()); System.out.println(twsMatcher.group()); System.out.println(twsMatcher.end()); } ``` I am not able to understand the grouping stuff, in regex.",2013/07/18,"['https://Stackoverflow.com/questions/17735661', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/713328/']","Try regexp `([a-zA-z]+) \[([^\]]+)\]`. For string `21:19:03 -[ 8b4]- ERROR - Jhy AlarmOccure::OnAdd - Updated existing alarm: ID [StrValue1:StrValu2|StrValue3], Instance [4053], SetStatus [0], AckStatus [1], SetTime [DateValue4], ClearedTime [DateValue5]` it returns: * `ID` and `StrValue1:StrValu2|StrValue3` * `Instance` and `4053` * `SetStatus` and `0` * `AckStatus` and `1` * `SetTime` and `DateValue4` * `ClearedTime` and `DateValue5` You can test it [here](http://fiddle.re/tv12a).","I like more general solutions, but here is a very specific pattern you can use if it suits you. It will capture all of the values in a string as long as they are follow the same, very specific pattern. ``` ID (?:\[([^\]:]+):([^\]|]+)\|([^\]]+)\]).*?SetTime \[([^\]]+)\], ClearedTime \[([^\]]+)\] ``` Here is the result: ``` 1: ID [StrValue1:StrValu2|StrValue3], Instance [4053], SetStatus [0], AckStatus [1], SetTime [DateValue4], ClearedTime [DateValue5] [1]: StrValue1 [2]: StrValu2 [3]: StrValue3 [4]: DateValue4 [5]: DateValue5 ``` [Try it out](http://rey.gimenez.biz/s/gpqqpzcn) ----------------------------------------------- **Multiple Matches per line** This version will just match each instance in a string of ID, SetTime, or ClearedTime followed by a bracketed value. ``` (ID|SetTime|ClearedTime) \[([^\]]+)\ ``` Results ``` 1: ID [StrValue1:StrValu2|StrValue3] [1]: ID [2]: StrValue1:StrValu2|StrValue3 1: SetTime [DateValue4] [1]: SetTime [2]: DateValue4 1: ClearedTime [DateValue5] [1]: ClearedTime [2]: DateValue5 ``` [Try it out](http://rey.gimenez.biz/s/qz9s6fqb) -----------------------------------------------" 17735661,"I need to parse log files and get some values to variable. The log file will have a string ``` String logStr = ""21:19:03 -[ 8b4]- ERROR - Jhy AlarmOccure::OnAdd - Updated existing alarm: ID [StrValue1:StrValu2|StrValue3], Instance [4053], SetStatus [0], AckStatus [1], SetTime [DateValue4], ClearedTime [DateValue5]""; ``` I need to get StrValue1,StrValue2,StrValue3,DateValue4 and DateValue5 to varaibles these values are changing fields when ever there is an error. First i was trying to at least get StrValue1. But not getting the expected result. ``` Pattern twsPattern = Pattern.compile("".*?ID ?[([^]:]*):([^]|]*)|([^]]*)]"");//.*ID\\s$.([^]:]*.):.([^]|]*.)|.([^]]*.).] Matcher twsMatcher = twsPattern.matcher(logStr); if(twsMatcher.find()){ System.out.println(twsMatcher.start()); System.out.println(twsMatcher.group()); System.out.println(twsMatcher.end()); } ``` I am not able to understand the grouping stuff, in regex.",2013/07/18,"['https://Stackoverflow.com/questions/17735661', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/713328/']","Good on you for the attempt! You're actually doing quite well. You need to escape square brackets that you don't mean as character classes, *i.e.* ``` .*?ID ?\[ ^ ``` And hopefully you are aware that by `([^]:]*)` you are meaning, ""The longest possible string of characters *without* a closing square bracket or colon."" You probably also want to escape the `|`, as that is an alternation operator in regular expressions, *i.e.* ``` \| ```","I like more general solutions, but here is a very specific pattern you can use if it suits you. It will capture all of the values in a string as long as they are follow the same, very specific pattern. ``` ID (?:\[([^\]:]+):([^\]|]+)\|([^\]]+)\]).*?SetTime \[([^\]]+)\], ClearedTime \[([^\]]+)\] ``` Here is the result: ``` 1: ID [StrValue1:StrValu2|StrValue3], Instance [4053], SetStatus [0], AckStatus [1], SetTime [DateValue4], ClearedTime [DateValue5] [1]: StrValue1 [2]: StrValu2 [3]: StrValue3 [4]: DateValue4 [5]: DateValue5 ``` [Try it out](http://rey.gimenez.biz/s/gpqqpzcn) ----------------------------------------------- **Multiple Matches per line** This version will just match each instance in a string of ID, SetTime, or ClearedTime followed by a bracketed value. ``` (ID|SetTime|ClearedTime) \[([^\]]+)\ ``` Results ``` 1: ID [StrValue1:StrValu2|StrValue3] [1]: ID [2]: StrValue1:StrValu2|StrValue3 1: SetTime [DateValue4] [1]: SetTime [2]: DateValue4 1: ClearedTime [DateValue5] [1]: ClearedTime [2]: DateValue5 ``` [Try it out](http://rey.gimenez.biz/s/qz9s6fqb) -----------------------------------------------" 17735661,"I need to parse log files and get some values to variable. The log file will have a string ``` String logStr = ""21:19:03 -[ 8b4]- ERROR - Jhy AlarmOccure::OnAdd - Updated existing alarm: ID [StrValue1:StrValu2|StrValue3], Instance [4053], SetStatus [0], AckStatus [1], SetTime [DateValue4], ClearedTime [DateValue5]""; ``` I need to get StrValue1,StrValue2,StrValue3,DateValue4 and DateValue5 to varaibles these values are changing fields when ever there is an error. First i was trying to at least get StrValue1. But not getting the expected result. ``` Pattern twsPattern = Pattern.compile("".*?ID ?[([^]:]*):([^]|]*)|([^]]*)]"");//.*ID\\s$.([^]:]*.):.([^]|]*.)|.([^]]*.).] Matcher twsMatcher = twsPattern.matcher(logStr); if(twsMatcher.find()){ System.out.println(twsMatcher.start()); System.out.println(twsMatcher.group()); System.out.println(twsMatcher.end()); } ``` I am not able to understand the grouping stuff, in regex.",2013/07/18,"['https://Stackoverflow.com/questions/17735661', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/713328/']","Long story short, your regex lacks escaping some chars, like `[` and `|` (this one, if outside a character class - `[]`). So when you want to actually match the `[` char, you have to use `\[` (or `\\[` inside the java string). Also, the negation in the group `([^]:]*)` is not what it seems. You probably want just `([^:]*)`, which matches everything until a `:`. To make it work, then, you would simply use [`Matcher#group(int)`](http://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html#group%28int%29) to retrieve the values. This is the adapted code with the final regex: ``` String logStr = ""21:19:03 -[ 8b4]- ERROR - Jhy AlarmOccure::OnAdd - Updated existing alarm: ID [StrValue1:StrValu2|StrValue3], Instance [4053], SetStatus [0], AckStatus [1], SetTime [DateValue4], ClearedTime [DateValue5]""; Pattern twsPattern = Pattern.compile("".*?ID ?\\[([^:]*):([^|]*)\\|([^\\]]*)\\].*?SetTime ?\\[([^\\]]*)\\][^\\[]+\\[([^\\]]*)\\]""); Matcher twsMatcher = twsPattern.matcher(logStr); if (twsMatcher.find()){ System.out.println(twsMatcher.group(1)); // StrValue1 System.out.println(twsMatcher.group(2)); // StrValu2 System.out.println(twsMatcher.group(3)); // StrValue3 System.out.println(twsMatcher.group(4)); // DateValue4 System.out.println(twsMatcher.group(5)); // DateValue5 } ```","I like more general solutions, but here is a very specific pattern you can use if it suits you. It will capture all of the values in a string as long as they are follow the same, very specific pattern. ``` ID (?:\[([^\]:]+):([^\]|]+)\|([^\]]+)\]).*?SetTime \[([^\]]+)\], ClearedTime \[([^\]]+)\] ``` Here is the result: ``` 1: ID [StrValue1:StrValu2|StrValue3], Instance [4053], SetStatus [0], AckStatus [1], SetTime [DateValue4], ClearedTime [DateValue5] [1]: StrValue1 [2]: StrValu2 [3]: StrValue3 [4]: DateValue4 [5]: DateValue5 ``` [Try it out](http://rey.gimenez.biz/s/gpqqpzcn) ----------------------------------------------- **Multiple Matches per line** This version will just match each instance in a string of ID, SetTime, or ClearedTime followed by a bracketed value. ``` (ID|SetTime|ClearedTime) \[([^\]]+)\ ``` Results ``` 1: ID [StrValue1:StrValu2|StrValue3] [1]: ID [2]: StrValue1:StrValu2|StrValue3 1: SetTime [DateValue4] [1]: SetTime [2]: DateValue4 1: ClearedTime [DateValue5] [1]: ClearedTime [2]: DateValue5 ``` [Try it out](http://rey.gimenez.biz/s/qz9s6fqb) -----------------------------------------------" 64841086,"I am trying to below file operation using python input 1: unix shell cat command given below data file name: input1.txt ``` 11/13/2020 07:41:09 TREE count1: id1 green001 11/13/2020 07:43:09 TREE count1: id1 black001 11/13/2020 07:45:09 TREE count1: id2 black001 11/13/2020 07:45:09 PLAN count1: id3 green002 ``` Lookup data: file name: lookup.csv ``` ID,item,message id1,item1,message 1 id2,item2,message 2 id3,item3,message 3 ``` Need output like: where id field in [id1, id2, id3, etc ..in] input1 lookup in ID filed in lookup table.\ Output.txt ``` Time,Type,counts,id,item,message,colour 11/13/2020 07:41:09,TREE,count1,id1,item1,message 1,green001 11/13/2020 07:43:09,TREE,count1,id1,item1,message 1,black001 11/13/2020 07:45:09,TREE,count1,id2,item2,message 2,black001 11/13/2020 07:45:09,PLAN,count1,id3,item3,message 3,green002 ``` I've been trying to use this code, but I am getting errors. ``` r = pandas.read_csv(file1, sep=' ', index_col='ID') with open('/home/s/lookup.csv','r') as w: x = pandas.read_csv(w) # w is not indexable col = w['ID'] for line in w: # w is not a table. for col in w: for row in r: if row in col: print(line) ``` Any advice would be appreciated!",2020/11/15,"['https://Stackoverflow.com/questions/64841086', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14632454/']","Ok. Just for anyone wondering Just uninstalling and reinstalling the packages that were giving the error worked for me ``` pip uninstall matplotlib pip install matplotlib ```",Have you tried uninstalling it and reinstalling the latest python update and restarting you PC/Laptop? 64841086,"I am trying to below file operation using python input 1: unix shell cat command given below data file name: input1.txt ``` 11/13/2020 07:41:09 TREE count1: id1 green001 11/13/2020 07:43:09 TREE count1: id1 black001 11/13/2020 07:45:09 TREE count1: id2 black001 11/13/2020 07:45:09 PLAN count1: id3 green002 ``` Lookup data: file name: lookup.csv ``` ID,item,message id1,item1,message 1 id2,item2,message 2 id3,item3,message 3 ``` Need output like: where id field in [id1, id2, id3, etc ..in] input1 lookup in ID filed in lookup table.\ Output.txt ``` Time,Type,counts,id,item,message,colour 11/13/2020 07:41:09,TREE,count1,id1,item1,message 1,green001 11/13/2020 07:43:09,TREE,count1,id1,item1,message 1,black001 11/13/2020 07:45:09,TREE,count1,id2,item2,message 2,black001 11/13/2020 07:45:09,PLAN,count1,id3,item3,message 3,green002 ``` I've been trying to use this code, but I am getting errors. ``` r = pandas.read_csv(file1, sep=' ', index_col='ID') with open('/home/s/lookup.csv','r') as w: x = pandas.read_csv(w) # w is not indexable col = w['ID'] for line in w: # w is not a table. for col in w: for row in r: if row in col: print(line) ``` Any advice would be appreciated!",2020/11/15,"['https://Stackoverflow.com/questions/64841086', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14632454/']","I had the same issue - a Python program that was working fine before updating to Big Sur, and crashing with: ``` Segmentation fault: 11 ``` after updating. As previous responses have advised, just uninstalling and reinstalling the offending Python libraries fixed the problem. For me, that meant matplotlib: ``` pip uninstall matplotlib pip install matplotlib ``` Thank you!",Have you tried uninstalling it and reinstalling the latest python update and restarting you PC/Laptop? 64841086,"I am trying to below file operation using python input 1: unix shell cat command given below data file name: input1.txt ``` 11/13/2020 07:41:09 TREE count1: id1 green001 11/13/2020 07:43:09 TREE count1: id1 black001 11/13/2020 07:45:09 TREE count1: id2 black001 11/13/2020 07:45:09 PLAN count1: id3 green002 ``` Lookup data: file name: lookup.csv ``` ID,item,message id1,item1,message 1 id2,item2,message 2 id3,item3,message 3 ``` Need output like: where id field in [id1, id2, id3, etc ..in] input1 lookup in ID filed in lookup table.\ Output.txt ``` Time,Type,counts,id,item,message,colour 11/13/2020 07:41:09,TREE,count1,id1,item1,message 1,green001 11/13/2020 07:43:09,TREE,count1,id1,item1,message 1,black001 11/13/2020 07:45:09,TREE,count1,id2,item2,message 2,black001 11/13/2020 07:45:09,PLAN,count1,id3,item3,message 3,green002 ``` I've been trying to use this code, but I am getting errors. ``` r = pandas.read_csv(file1, sep=' ', index_col='ID') with open('/home/s/lookup.csv','r') as w: x = pandas.read_csv(w) # w is not indexable col = w['ID'] for line in w: # w is not a table. for col in w: for row in r: if row in col: print(line) ``` Any advice would be appreciated!",2020/11/15,"['https://Stackoverflow.com/questions/64841086', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14632454/']","Ok. Just for anyone wondering Just uninstalling and reinstalling the packages that were giving the error worked for me ``` pip uninstall matplotlib pip install matplotlib ```","I had the same issue - a Python program that was working fine before updating to Big Sur, and crashing with: ``` Segmentation fault: 11 ``` after updating. As previous responses have advised, just uninstalling and reinstalling the offending Python libraries fixed the problem. For me, that meant matplotlib: ``` pip uninstall matplotlib pip install matplotlib ``` Thank you!" 64841086,"I am trying to below file operation using python input 1: unix shell cat command given below data file name: input1.txt ``` 11/13/2020 07:41:09 TREE count1: id1 green001 11/13/2020 07:43:09 TREE count1: id1 black001 11/13/2020 07:45:09 TREE count1: id2 black001 11/13/2020 07:45:09 PLAN count1: id3 green002 ``` Lookup data: file name: lookup.csv ``` ID,item,message id1,item1,message 1 id2,item2,message 2 id3,item3,message 3 ``` Need output like: where id field in [id1, id2, id3, etc ..in] input1 lookup in ID filed in lookup table.\ Output.txt ``` Time,Type,counts,id,item,message,colour 11/13/2020 07:41:09,TREE,count1,id1,item1,message 1,green001 11/13/2020 07:43:09,TREE,count1,id1,item1,message 1,black001 11/13/2020 07:45:09,TREE,count1,id2,item2,message 2,black001 11/13/2020 07:45:09,PLAN,count1,id3,item3,message 3,green002 ``` I've been trying to use this code, but I am getting errors. ``` r = pandas.read_csv(file1, sep=' ', index_col='ID') with open('/home/s/lookup.csv','r') as w: x = pandas.read_csv(w) # w is not indexable col = w['ID'] for line in w: # w is not a table. for col in w: for row in r: if row in col: print(line) ``` Any advice would be appreciated!",2020/11/15,"['https://Stackoverflow.com/questions/64841086', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14632454/']","Ok. Just for anyone wondering Just uninstalling and reinstalling the packages that were giving the error worked for me ``` pip uninstall matplotlib pip install matplotlib ```","I also had the same issue: **Segmentation fault: 11** I guess, it is because of the statement line: **plt.show()** As stated above, uninstallation and reinstallation of matplotlib worked for me. Thank you!" 64841086,"I am trying to below file operation using python input 1: unix shell cat command given below data file name: input1.txt ``` 11/13/2020 07:41:09 TREE count1: id1 green001 11/13/2020 07:43:09 TREE count1: id1 black001 11/13/2020 07:45:09 TREE count1: id2 black001 11/13/2020 07:45:09 PLAN count1: id3 green002 ``` Lookup data: file name: lookup.csv ``` ID,item,message id1,item1,message 1 id2,item2,message 2 id3,item3,message 3 ``` Need output like: where id field in [id1, id2, id3, etc ..in] input1 lookup in ID filed in lookup table.\ Output.txt ``` Time,Type,counts,id,item,message,colour 11/13/2020 07:41:09,TREE,count1,id1,item1,message 1,green001 11/13/2020 07:43:09,TREE,count1,id1,item1,message 1,black001 11/13/2020 07:45:09,TREE,count1,id2,item2,message 2,black001 11/13/2020 07:45:09,PLAN,count1,id3,item3,message 3,green002 ``` I've been trying to use this code, but I am getting errors. ``` r = pandas.read_csv(file1, sep=' ', index_col='ID') with open('/home/s/lookup.csv','r') as w: x = pandas.read_csv(w) # w is not indexable col = w['ID'] for line in w: # w is not a table. for col in w: for row in r: if row in col: print(line) ``` Any advice would be appreciated!",2020/11/15,"['https://Stackoverflow.com/questions/64841086', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14632454/']","Ok. Just for anyone wondering Just uninstalling and reinstalling the packages that were giving the error worked for me ``` pip uninstall matplotlib pip install matplotlib ```","Reinstalling is the best option but you can also use: ``` import matplotlib as mpl mpl.use('MacOSX') import numpy as np import matplotlib.pyplot as plt ```" 64841086,"I am trying to below file operation using python input 1: unix shell cat command given below data file name: input1.txt ``` 11/13/2020 07:41:09 TREE count1: id1 green001 11/13/2020 07:43:09 TREE count1: id1 black001 11/13/2020 07:45:09 TREE count1: id2 black001 11/13/2020 07:45:09 PLAN count1: id3 green002 ``` Lookup data: file name: lookup.csv ``` ID,item,message id1,item1,message 1 id2,item2,message 2 id3,item3,message 3 ``` Need output like: where id field in [id1, id2, id3, etc ..in] input1 lookup in ID filed in lookup table.\ Output.txt ``` Time,Type,counts,id,item,message,colour 11/13/2020 07:41:09,TREE,count1,id1,item1,message 1,green001 11/13/2020 07:43:09,TREE,count1,id1,item1,message 1,black001 11/13/2020 07:45:09,TREE,count1,id2,item2,message 2,black001 11/13/2020 07:45:09,PLAN,count1,id3,item3,message 3,green002 ``` I've been trying to use this code, but I am getting errors. ``` r = pandas.read_csv(file1, sep=' ', index_col='ID') with open('/home/s/lookup.csv','r') as w: x = pandas.read_csv(w) # w is not indexable col = w['ID'] for line in w: # w is not a table. for col in w: for row in r: if row in col: print(line) ``` Any advice would be appreciated!",2020/11/15,"['https://Stackoverflow.com/questions/64841086', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14632454/']","Ok. Just for anyone wondering Just uninstalling and reinstalling the packages that were giving the error worked for me ``` pip uninstall matplotlib pip install matplotlib ```","i had to drop my dpi from 400 to 50 on the OSX machine. none of these other approaches worked. fwiw, my update was to Catalina, not Big Sur." 64841086,"I am trying to below file operation using python input 1: unix shell cat command given below data file name: input1.txt ``` 11/13/2020 07:41:09 TREE count1: id1 green001 11/13/2020 07:43:09 TREE count1: id1 black001 11/13/2020 07:45:09 TREE count1: id2 black001 11/13/2020 07:45:09 PLAN count1: id3 green002 ``` Lookup data: file name: lookup.csv ``` ID,item,message id1,item1,message 1 id2,item2,message 2 id3,item3,message 3 ``` Need output like: where id field in [id1, id2, id3, etc ..in] input1 lookup in ID filed in lookup table.\ Output.txt ``` Time,Type,counts,id,item,message,colour 11/13/2020 07:41:09,TREE,count1,id1,item1,message 1,green001 11/13/2020 07:43:09,TREE,count1,id1,item1,message 1,black001 11/13/2020 07:45:09,TREE,count1,id2,item2,message 2,black001 11/13/2020 07:45:09,PLAN,count1,id3,item3,message 3,green002 ``` I've been trying to use this code, but I am getting errors. ``` r = pandas.read_csv(file1, sep=' ', index_col='ID') with open('/home/s/lookup.csv','r') as w: x = pandas.read_csv(w) # w is not indexable col = w['ID'] for line in w: # w is not a table. for col in w: for row in r: if row in col: print(line) ``` Any advice would be appreciated!",2020/11/15,"['https://Stackoverflow.com/questions/64841086', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14632454/']","I had the same issue - a Python program that was working fine before updating to Big Sur, and crashing with: ``` Segmentation fault: 11 ``` after updating. As previous responses have advised, just uninstalling and reinstalling the offending Python libraries fixed the problem. For me, that meant matplotlib: ``` pip uninstall matplotlib pip install matplotlib ``` Thank you!","I also had the same issue: **Segmentation fault: 11** I guess, it is because of the statement line: **plt.show()** As stated above, uninstallation and reinstallation of matplotlib worked for me. Thank you!" 64841086,"I am trying to below file operation using python input 1: unix shell cat command given below data file name: input1.txt ``` 11/13/2020 07:41:09 TREE count1: id1 green001 11/13/2020 07:43:09 TREE count1: id1 black001 11/13/2020 07:45:09 TREE count1: id2 black001 11/13/2020 07:45:09 PLAN count1: id3 green002 ``` Lookup data: file name: lookup.csv ``` ID,item,message id1,item1,message 1 id2,item2,message 2 id3,item3,message 3 ``` Need output like: where id field in [id1, id2, id3, etc ..in] input1 lookup in ID filed in lookup table.\ Output.txt ``` Time,Type,counts,id,item,message,colour 11/13/2020 07:41:09,TREE,count1,id1,item1,message 1,green001 11/13/2020 07:43:09,TREE,count1,id1,item1,message 1,black001 11/13/2020 07:45:09,TREE,count1,id2,item2,message 2,black001 11/13/2020 07:45:09,PLAN,count1,id3,item3,message 3,green002 ``` I've been trying to use this code, but I am getting errors. ``` r = pandas.read_csv(file1, sep=' ', index_col='ID') with open('/home/s/lookup.csv','r') as w: x = pandas.read_csv(w) # w is not indexable col = w['ID'] for line in w: # w is not a table. for col in w: for row in r: if row in col: print(line) ``` Any advice would be appreciated!",2020/11/15,"['https://Stackoverflow.com/questions/64841086', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14632454/']","I had the same issue - a Python program that was working fine before updating to Big Sur, and crashing with: ``` Segmentation fault: 11 ``` after updating. As previous responses have advised, just uninstalling and reinstalling the offending Python libraries fixed the problem. For me, that meant matplotlib: ``` pip uninstall matplotlib pip install matplotlib ``` Thank you!","Reinstalling is the best option but you can also use: ``` import matplotlib as mpl mpl.use('MacOSX') import numpy as np import matplotlib.pyplot as plt ```" 64841086,"I am trying to below file operation using python input 1: unix shell cat command given below data file name: input1.txt ``` 11/13/2020 07:41:09 TREE count1: id1 green001 11/13/2020 07:43:09 TREE count1: id1 black001 11/13/2020 07:45:09 TREE count1: id2 black001 11/13/2020 07:45:09 PLAN count1: id3 green002 ``` Lookup data: file name: lookup.csv ``` ID,item,message id1,item1,message 1 id2,item2,message 2 id3,item3,message 3 ``` Need output like: where id field in [id1, id2, id3, etc ..in] input1 lookup in ID filed in lookup table.\ Output.txt ``` Time,Type,counts,id,item,message,colour 11/13/2020 07:41:09,TREE,count1,id1,item1,message 1,green001 11/13/2020 07:43:09,TREE,count1,id1,item1,message 1,black001 11/13/2020 07:45:09,TREE,count1,id2,item2,message 2,black001 11/13/2020 07:45:09,PLAN,count1,id3,item3,message 3,green002 ``` I've been trying to use this code, but I am getting errors. ``` r = pandas.read_csv(file1, sep=' ', index_col='ID') with open('/home/s/lookup.csv','r') as w: x = pandas.read_csv(w) # w is not indexable col = w['ID'] for line in w: # w is not a table. for col in w: for row in r: if row in col: print(line) ``` Any advice would be appreciated!",2020/11/15,"['https://Stackoverflow.com/questions/64841086', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14632454/']","I had the same issue - a Python program that was working fine before updating to Big Sur, and crashing with: ``` Segmentation fault: 11 ``` after updating. As previous responses have advised, just uninstalling and reinstalling the offending Python libraries fixed the problem. For me, that meant matplotlib: ``` pip uninstall matplotlib pip install matplotlib ``` Thank you!","i had to drop my dpi from 400 to 50 on the OSX machine. none of these other approaches worked. fwiw, my update was to Catalina, not Big Sur." 23687250,"I have this code: ``` protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); WebView siteViewer = (WebView) findViewById(R.id.webView); if(siteViewer != null) siteViewer.loadUrl(""http://www.website.com""); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, new PlaceholderFragment()) .commit(); } } ``` It's the default android app code, except: ``` WebView siteViewer = (WebView) findViewById(R.id.webView); if(siteViewer != null) siteViewer.loadUrl(""http://www.website.com""); ``` `siteViewer` is always `null`. If I don't use the `if()` statement, the app will crash immediately upon opening, otherwise it just skips `loadURL`. I found a similar bug here: Apparently some OS's don't allow it? I'm running it on 4.4.2 in an emulator. I also tried it on a Motorola Razr with 4.1.2 and I get the same result --- With the line `if(siteViewer != null)` commented out, this is the logcat: ``` 05-15 16:05:35.112: D/AndroidRuntime(1201): Shutting down VM 05-15 16:05:35.112: W/dalvikvm(1201): threadid=1: thread exiting with uncaught exception (group=0xada41ba8) 05-15 16:05:35.142: E/AndroidRuntime(1201): FATAL EXCEPTION: main 05-15 16:05:35.142: E/AndroidRuntime(1201): Process: com.example.webviewtest, PID: 1201 05-15 16:05:35.142: E/AndroidRuntime(1201): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.webviewtest/com.example.webviewtest.MainActivity}: java.lang.NullPointerException 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.access$800(ActivityThread.java:135) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.os.Handler.dispatchMessage(Handler.java:102) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.os.Looper.loop(Looper.java:136) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.main(ActivityThread.java:5017) 05-15 16:05:35.142: E/AndroidRuntime(1201): at java.lang.reflect.Method.invokeNative(Native Method) 05-15 16:05:35.142: E/AndroidRuntime(1201): at java.lang.reflect.Method.invoke(Method.java:515) 05-15 16:05:35.142: E/AndroidRuntime(1201): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 05-15 16:05:35.142: E/AndroidRuntime(1201): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 05-15 16:05:35.142: E/AndroidRuntime(1201): at dalvik.system.NativeStart.main(Native Method) 05-15 16:05:35.142: E/AndroidRuntime(1201): Caused by: java.lang.NullPointerException 05-15 16:05:35.142: E/AndroidRuntime(1201): at com.example.webviewtest.MainActivity.onCreate(MainActivity.java:25) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.Activity.performCreate(Activity.java:5231) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159) 05-15 16:05:35.142: E/AndroidRuntime(1201): ... 11 more ``` Here is `activity_main.xml`: ``` ``` Here is `fragment_main.xml`: ``` ``` --- Following the suggestion given, this is the PlaceHolderFragment code, with the WebView code included, that gives me the error `cannot make a static reference to the non-static method findViewById(int) from the type Activity`: ``` public static class PlaceholderFragment extends Fragment { public PlaceholderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); WebView siteViewer = (WebView) findViewById(R.id.webView); if(siteViewer != null) siteViewer.loadUrl(""http://www.website.com""); return rootView; } } ```",2014/05/15,"['https://Stackoverflow.com/questions/23687250', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2016196/']","`siteViewer` is `null`, because there is no such element with id = `webView` found at the `activity_main.xml`. Please double check that you've typed it correctly.","did you set the permission to access the internet in manifest file? ``` ```" 23687250,"I have this code: ``` protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); WebView siteViewer = (WebView) findViewById(R.id.webView); if(siteViewer != null) siteViewer.loadUrl(""http://www.website.com""); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, new PlaceholderFragment()) .commit(); } } ``` It's the default android app code, except: ``` WebView siteViewer = (WebView) findViewById(R.id.webView); if(siteViewer != null) siteViewer.loadUrl(""http://www.website.com""); ``` `siteViewer` is always `null`. If I don't use the `if()` statement, the app will crash immediately upon opening, otherwise it just skips `loadURL`. I found a similar bug here: Apparently some OS's don't allow it? I'm running it on 4.4.2 in an emulator. I also tried it on a Motorola Razr with 4.1.2 and I get the same result --- With the line `if(siteViewer != null)` commented out, this is the logcat: ``` 05-15 16:05:35.112: D/AndroidRuntime(1201): Shutting down VM 05-15 16:05:35.112: W/dalvikvm(1201): threadid=1: thread exiting with uncaught exception (group=0xada41ba8) 05-15 16:05:35.142: E/AndroidRuntime(1201): FATAL EXCEPTION: main 05-15 16:05:35.142: E/AndroidRuntime(1201): Process: com.example.webviewtest, PID: 1201 05-15 16:05:35.142: E/AndroidRuntime(1201): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.webviewtest/com.example.webviewtest.MainActivity}: java.lang.NullPointerException 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.access$800(ActivityThread.java:135) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.os.Handler.dispatchMessage(Handler.java:102) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.os.Looper.loop(Looper.java:136) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.main(ActivityThread.java:5017) 05-15 16:05:35.142: E/AndroidRuntime(1201): at java.lang.reflect.Method.invokeNative(Native Method) 05-15 16:05:35.142: E/AndroidRuntime(1201): at java.lang.reflect.Method.invoke(Method.java:515) 05-15 16:05:35.142: E/AndroidRuntime(1201): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 05-15 16:05:35.142: E/AndroidRuntime(1201): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 05-15 16:05:35.142: E/AndroidRuntime(1201): at dalvik.system.NativeStart.main(Native Method) 05-15 16:05:35.142: E/AndroidRuntime(1201): Caused by: java.lang.NullPointerException 05-15 16:05:35.142: E/AndroidRuntime(1201): at com.example.webviewtest.MainActivity.onCreate(MainActivity.java:25) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.Activity.performCreate(Activity.java:5231) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159) 05-15 16:05:35.142: E/AndroidRuntime(1201): ... 11 more ``` Here is `activity_main.xml`: ``` ``` Here is `fragment_main.xml`: ``` ``` --- Following the suggestion given, this is the PlaceHolderFragment code, with the WebView code included, that gives me the error `cannot make a static reference to the non-static method findViewById(int) from the type Activity`: ``` public static class PlaceholderFragment extends Fragment { public PlaceholderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); WebView siteViewer = (WebView) findViewById(R.id.webView); if(siteViewer != null) siteViewer.loadUrl(""http://www.website.com""); return rootView; } } ```",2014/05/15,"['https://Stackoverflow.com/questions/23687250', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2016196/']","In your Activity you are inflating main\_layout which doesn't contain a WebView at all. Therefore the findViewById won't find anything and siteViewer is null. Move your code to load the Url into your fragment. Since you'r using a PlaceHolderFragment I guess it will be replaced by a real one later. That's the place to put your code. You'll probably inflate your fragment\_main.xml in the fragments onCreateView and then you can load the Url in the fragment's onResume method. To find the WebView do the following: ``` @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); WebView siteViewer = (WebView) rootView.findViewById(R.id.webView); if(siteViewer != null) siteViewer.loadUrl(""http://www.website.com""); return rootView; } ``` Note the rootView.findViewById(R.id.webView) instead of the simple findViewById(R.id.webView). Fragments don't have a findViewById method but since you'r inflating the layout yourself you can use the View.findViewById.","`siteViewer` is `null`, because there is no such element with id = `webView` found at the `activity_main.xml`. Please double check that you've typed it correctly." 23687250,"I have this code: ``` protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); WebView siteViewer = (WebView) findViewById(R.id.webView); if(siteViewer != null) siteViewer.loadUrl(""http://www.website.com""); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, new PlaceholderFragment()) .commit(); } } ``` It's the default android app code, except: ``` WebView siteViewer = (WebView) findViewById(R.id.webView); if(siteViewer != null) siteViewer.loadUrl(""http://www.website.com""); ``` `siteViewer` is always `null`. If I don't use the `if()` statement, the app will crash immediately upon opening, otherwise it just skips `loadURL`. I found a similar bug here: Apparently some OS's don't allow it? I'm running it on 4.4.2 in an emulator. I also tried it on a Motorola Razr with 4.1.2 and I get the same result --- With the line `if(siteViewer != null)` commented out, this is the logcat: ``` 05-15 16:05:35.112: D/AndroidRuntime(1201): Shutting down VM 05-15 16:05:35.112: W/dalvikvm(1201): threadid=1: thread exiting with uncaught exception (group=0xada41ba8) 05-15 16:05:35.142: E/AndroidRuntime(1201): FATAL EXCEPTION: main 05-15 16:05:35.142: E/AndroidRuntime(1201): Process: com.example.webviewtest, PID: 1201 05-15 16:05:35.142: E/AndroidRuntime(1201): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.webviewtest/com.example.webviewtest.MainActivity}: java.lang.NullPointerException 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.access$800(ActivityThread.java:135) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.os.Handler.dispatchMessage(Handler.java:102) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.os.Looper.loop(Looper.java:136) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.main(ActivityThread.java:5017) 05-15 16:05:35.142: E/AndroidRuntime(1201): at java.lang.reflect.Method.invokeNative(Native Method) 05-15 16:05:35.142: E/AndroidRuntime(1201): at java.lang.reflect.Method.invoke(Method.java:515) 05-15 16:05:35.142: E/AndroidRuntime(1201): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 05-15 16:05:35.142: E/AndroidRuntime(1201): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 05-15 16:05:35.142: E/AndroidRuntime(1201): at dalvik.system.NativeStart.main(Native Method) 05-15 16:05:35.142: E/AndroidRuntime(1201): Caused by: java.lang.NullPointerException 05-15 16:05:35.142: E/AndroidRuntime(1201): at com.example.webviewtest.MainActivity.onCreate(MainActivity.java:25) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.Activity.performCreate(Activity.java:5231) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159) 05-15 16:05:35.142: E/AndroidRuntime(1201): ... 11 more ``` Here is `activity_main.xml`: ``` ``` Here is `fragment_main.xml`: ``` ``` --- Following the suggestion given, this is the PlaceHolderFragment code, with the WebView code included, that gives me the error `cannot make a static reference to the non-static method findViewById(int) from the type Activity`: ``` public static class PlaceholderFragment extends Fragment { public PlaceholderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); WebView siteViewer = (WebView) findViewById(R.id.webView); if(siteViewer != null) siteViewer.loadUrl(""http://www.website.com""); return rootView; } } ```",2014/05/15,"['https://Stackoverflow.com/questions/23687250', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2016196/']","I will answer from my knowledge since i didnt know the project heirarchy ... I) .suppose you have the activity in `package com.another.package` and your project package which is declared in the manifest is `com.main.package` now if you will try to access the webview using `R.id.webView` in package `com.another.package` it wont be available hence you will get null pointer exception so to fix that import com.main.package.R.\*; in the crashing activity. II). suppose the crashing activity is in the same package `com.main.package` then plz cross check dat whether webview named `webView` is present in the `activity_main`. III). may be u are casting other layout to webView like `webView` is id of other than webview ( but in this case you wont get null pointer exception just for info). Hope it helps ... Thx","did you set the permission to access the internet in manifest file? ``` ```" 23687250,"I have this code: ``` protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); WebView siteViewer = (WebView) findViewById(R.id.webView); if(siteViewer != null) siteViewer.loadUrl(""http://www.website.com""); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, new PlaceholderFragment()) .commit(); } } ``` It's the default android app code, except: ``` WebView siteViewer = (WebView) findViewById(R.id.webView); if(siteViewer != null) siteViewer.loadUrl(""http://www.website.com""); ``` `siteViewer` is always `null`. If I don't use the `if()` statement, the app will crash immediately upon opening, otherwise it just skips `loadURL`. I found a similar bug here: Apparently some OS's don't allow it? I'm running it on 4.4.2 in an emulator. I also tried it on a Motorola Razr with 4.1.2 and I get the same result --- With the line `if(siteViewer != null)` commented out, this is the logcat: ``` 05-15 16:05:35.112: D/AndroidRuntime(1201): Shutting down VM 05-15 16:05:35.112: W/dalvikvm(1201): threadid=1: thread exiting with uncaught exception (group=0xada41ba8) 05-15 16:05:35.142: E/AndroidRuntime(1201): FATAL EXCEPTION: main 05-15 16:05:35.142: E/AndroidRuntime(1201): Process: com.example.webviewtest, PID: 1201 05-15 16:05:35.142: E/AndroidRuntime(1201): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.webviewtest/com.example.webviewtest.MainActivity}: java.lang.NullPointerException 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.access$800(ActivityThread.java:135) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.os.Handler.dispatchMessage(Handler.java:102) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.os.Looper.loop(Looper.java:136) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.main(ActivityThread.java:5017) 05-15 16:05:35.142: E/AndroidRuntime(1201): at java.lang.reflect.Method.invokeNative(Native Method) 05-15 16:05:35.142: E/AndroidRuntime(1201): at java.lang.reflect.Method.invoke(Method.java:515) 05-15 16:05:35.142: E/AndroidRuntime(1201): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 05-15 16:05:35.142: E/AndroidRuntime(1201): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 05-15 16:05:35.142: E/AndroidRuntime(1201): at dalvik.system.NativeStart.main(Native Method) 05-15 16:05:35.142: E/AndroidRuntime(1201): Caused by: java.lang.NullPointerException 05-15 16:05:35.142: E/AndroidRuntime(1201): at com.example.webviewtest.MainActivity.onCreate(MainActivity.java:25) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.Activity.performCreate(Activity.java:5231) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159) 05-15 16:05:35.142: E/AndroidRuntime(1201): ... 11 more ``` Here is `activity_main.xml`: ``` ``` Here is `fragment_main.xml`: ``` ``` --- Following the suggestion given, this is the PlaceHolderFragment code, with the WebView code included, that gives me the error `cannot make a static reference to the non-static method findViewById(int) from the type Activity`: ``` public static class PlaceholderFragment extends Fragment { public PlaceholderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); WebView siteViewer = (WebView) findViewById(R.id.webView); if(siteViewer != null) siteViewer.loadUrl(""http://www.website.com""); return rootView; } } ```",2014/05/15,"['https://Stackoverflow.com/questions/23687250', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2016196/']","In your Activity you are inflating main\_layout which doesn't contain a WebView at all. Therefore the findViewById won't find anything and siteViewer is null. Move your code to load the Url into your fragment. Since you'r using a PlaceHolderFragment I guess it will be replaced by a real one later. That's the place to put your code. You'll probably inflate your fragment\_main.xml in the fragments onCreateView and then you can load the Url in the fragment's onResume method. To find the WebView do the following: ``` @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); WebView siteViewer = (WebView) rootView.findViewById(R.id.webView); if(siteViewer != null) siteViewer.loadUrl(""http://www.website.com""); return rootView; } ``` Note the rootView.findViewById(R.id.webView) instead of the simple findViewById(R.id.webView). Fragments don't have a findViewById method but since you'r inflating the layout yourself you can use the View.findViewById.","did you set the permission to access the internet in manifest file? ``` ```" 23687250,"I have this code: ``` protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); WebView siteViewer = (WebView) findViewById(R.id.webView); if(siteViewer != null) siteViewer.loadUrl(""http://www.website.com""); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, new PlaceholderFragment()) .commit(); } } ``` It's the default android app code, except: ``` WebView siteViewer = (WebView) findViewById(R.id.webView); if(siteViewer != null) siteViewer.loadUrl(""http://www.website.com""); ``` `siteViewer` is always `null`. If I don't use the `if()` statement, the app will crash immediately upon opening, otherwise it just skips `loadURL`. I found a similar bug here: Apparently some OS's don't allow it? I'm running it on 4.4.2 in an emulator. I also tried it on a Motorola Razr with 4.1.2 and I get the same result --- With the line `if(siteViewer != null)` commented out, this is the logcat: ``` 05-15 16:05:35.112: D/AndroidRuntime(1201): Shutting down VM 05-15 16:05:35.112: W/dalvikvm(1201): threadid=1: thread exiting with uncaught exception (group=0xada41ba8) 05-15 16:05:35.142: E/AndroidRuntime(1201): FATAL EXCEPTION: main 05-15 16:05:35.142: E/AndroidRuntime(1201): Process: com.example.webviewtest, PID: 1201 05-15 16:05:35.142: E/AndroidRuntime(1201): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.webviewtest/com.example.webviewtest.MainActivity}: java.lang.NullPointerException 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.access$800(ActivityThread.java:135) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.os.Handler.dispatchMessage(Handler.java:102) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.os.Looper.loop(Looper.java:136) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.main(ActivityThread.java:5017) 05-15 16:05:35.142: E/AndroidRuntime(1201): at java.lang.reflect.Method.invokeNative(Native Method) 05-15 16:05:35.142: E/AndroidRuntime(1201): at java.lang.reflect.Method.invoke(Method.java:515) 05-15 16:05:35.142: E/AndroidRuntime(1201): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 05-15 16:05:35.142: E/AndroidRuntime(1201): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 05-15 16:05:35.142: E/AndroidRuntime(1201): at dalvik.system.NativeStart.main(Native Method) 05-15 16:05:35.142: E/AndroidRuntime(1201): Caused by: java.lang.NullPointerException 05-15 16:05:35.142: E/AndroidRuntime(1201): at com.example.webviewtest.MainActivity.onCreate(MainActivity.java:25) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.Activity.performCreate(Activity.java:5231) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) 05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159) 05-15 16:05:35.142: E/AndroidRuntime(1201): ... 11 more ``` Here is `activity_main.xml`: ``` ``` Here is `fragment_main.xml`: ``` ``` --- Following the suggestion given, this is the PlaceHolderFragment code, with the WebView code included, that gives me the error `cannot make a static reference to the non-static method findViewById(int) from the type Activity`: ``` public static class PlaceholderFragment extends Fragment { public PlaceholderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); WebView siteViewer = (WebView) findViewById(R.id.webView); if(siteViewer != null) siteViewer.loadUrl(""http://www.website.com""); return rootView; } } ```",2014/05/15,"['https://Stackoverflow.com/questions/23687250', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2016196/']","In your Activity you are inflating main\_layout which doesn't contain a WebView at all. Therefore the findViewById won't find anything and siteViewer is null. Move your code to load the Url into your fragment. Since you'r using a PlaceHolderFragment I guess it will be replaced by a real one later. That's the place to put your code. You'll probably inflate your fragment\_main.xml in the fragments onCreateView and then you can load the Url in the fragment's onResume method. To find the WebView do the following: ``` @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); WebView siteViewer = (WebView) rootView.findViewById(R.id.webView); if(siteViewer != null) siteViewer.loadUrl(""http://www.website.com""); return rootView; } ``` Note the rootView.findViewById(R.id.webView) instead of the simple findViewById(R.id.webView). Fragments don't have a findViewById method but since you'r inflating the layout yourself you can use the View.findViewById.","I will answer from my knowledge since i didnt know the project heirarchy ... I) .suppose you have the activity in `package com.another.package` and your project package which is declared in the manifest is `com.main.package` now if you will try to access the webview using `R.id.webView` in package `com.another.package` it wont be available hence you will get null pointer exception so to fix that import com.main.package.R.\*; in the crashing activity. II). suppose the crashing activity is in the same package `com.main.package` then plz cross check dat whether webview named `webView` is present in the `activity_main`. III). may be u are casting other layout to webView like `webView` is id of other than webview ( but in this case you wont get null pointer exception just for info). Hope it helps ... Thx" 323637,"I would like to understand the best practices regarding nonce validation in REST APIs. I see a lot of people talking about `wp_rest` nonce for REST requests. But upon looking on WordPress core code, I saw that `wp_rest` is just a nonce to validate a logged in user status, if it's not present, it just runs the request as guest. That said, should I submit two nonces upon sending a POST request to a REST API? One for authentication `wp_rest` and another for the action `foo_action`? If so, how should I send `wp_rest` and `foo_action` nonce in JavaScript, and, in PHP, what's the correct place to validate those nonces? (I mean validate\_callback for a arg? permission\_callback?)",2018/12/22,"['https://wordpress.stackexchange.com/questions/323637', 'https://wordpress.stackexchange.com', 'https://wordpress.stackexchange.com/users/27278/']","You should pass the special `wp_rest` nonce as part of the request. Without it, the `global $current_user` object will not be available in your REST class. You can pass this from several ways, from $\_GET to $\_POST to headers. The action nonce is optional. If you add it, you can't use the REST endpoint from an external server, only from requests dispatched from within WordPress itself. The user can authenticate itself using [Basic Auth](https://github.com/WP-API/Basic-Auth), [OAuth2](https://github.com/WP-API/OAuth2), or [JWT](https://github.com/WP-API/jwt-auth) from an external server even without the `wp_rest` nonce, but if you add an action nonce as well, it won't work. So the action nonce is optional. Add it if you want the endpoint to work locally only. Example: ``` /** * First step, registering, localizing and enqueueing the JavaScript */ wp_register_script( 'main-js', get_template_directory_uri() . '/js/main.js', [ 'jquery' ] ); wp_localize_script( 'main-js', 'data', [ 'rest' => [ 'endpoints' => [ 'my_endpoint' => esc_url_raw( rest_url( 'my_plugin/v1/my_endpoint' ) ), ], 'timeout' => (int) apply_filters( ""my_plugin_rest_timeout"", 60 ), 'nonce' => wp_create_nonce( 'wp_rest' ), //'action_nonce' => wp_create_nonce( 'action_nonce' ), ], ] ); wp_enqueue_script( 'main-js' ); /** * Second step, the request on the JavaScript file */ jQuery(document).on('click', '#some_element', function () { let ajax_data = { 'some_value': jQuery( "".some_value"" ).val(), //'action_nonce': data.rest.action_nonce }; jQuery.ajax({ url: data.rest.endpoints.my_endpoint, method: ""GET"", dataType: ""json"", timeout: data.rest.timeout, data: ajax_data, beforeSend: function (xhr) { xhr.setRequestHeader('X-WP-Nonce', data.rest.nonce); } }).done(function (results) { console.log(results); alert(""Success!""); }).fail(function (xhr) { console.log(results); alert(""Error!""); }); }); /** * Third step, the REST endpoint itself */ class My_Endpoint { public function registerRoutes() { register_rest_route( 'my_plugin', 'v1/my_endpoint', [ 'methods' => WP_REST_Server::READABLE, 'callback' => [ $this, 'get_something' ], 'args' => [ 'some_value' => [ 'required' => true, ], ], 'permission_callback' => function ( WP_REST_Request $request ) { return true; }, ] ); } /** * @return WP_REST_Response */ private function get_something( WP_REST_Request $request ) { //if ( ! wp_verify_nonce( $request['nonce'], 'action_nonce' ) ) { // return false; //} $some_value = $request['some_value']; if ( strlen( $some_value ) < 5 ) { return new WP_REST_Response( 'Sorry, Some Value must be at least 5 characters long.', 400 ); } // Since we are passing the ""X-WP-Nonce"" header, this will work: $user = wp_get_current_user(); if ( $user instanceof WP_User ) { return new WP_REST_Response( 'Sorry, could not get the name.', 400 ); } else { return new WP_REST_Response( 'Your username name is: ' . $user->display_name, 200 ); } } } ```","Building on what @lucas-bustamante wrote (which helped me a ton!), once you have the X-WP-Nonce header setup in your custom routes you can do the following: ```php register_rest_route('v1', '/my_post', [ 'methods' => WP_REST_Server::CREATABLE, 'callback' => [$this, 'create_post'], 'args' => [ 'post_title' => [ 'required' => true, ], 'post_excerpt' => [ 'required' => true, ] ], 'permission_callback' => function ( ) { return current_user_can( 'publish_posts' ); }, ]); ``` Note that the `permission_callback` is on the root level not under args ([documented here](https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/#permissions-callback)) and I've removed the additional `nonce` check from `args` since checking the permission alone will fail if the nonce is invalid or not supplied (I've tested this extensively and can confirm I get an error when no nonce is supplied or it's invalid)." 323637,"I would like to understand the best practices regarding nonce validation in REST APIs. I see a lot of people talking about `wp_rest` nonce for REST requests. But upon looking on WordPress core code, I saw that `wp_rest` is just a nonce to validate a logged in user status, if it's not present, it just runs the request as guest. That said, should I submit two nonces upon sending a POST request to a REST API? One for authentication `wp_rest` and another for the action `foo_action`? If so, how should I send `wp_rest` and `foo_action` nonce in JavaScript, and, in PHP, what's the correct place to validate those nonces? (I mean validate\_callback for a arg? permission\_callback?)",2018/12/22,"['https://wordpress.stackexchange.com/questions/323637', 'https://wordpress.stackexchange.com', 'https://wordpress.stackexchange.com/users/27278/']","You should pass the special `wp_rest` nonce as part of the request. Without it, the `global $current_user` object will not be available in your REST class. You can pass this from several ways, from $\_GET to $\_POST to headers. The action nonce is optional. If you add it, you can't use the REST endpoint from an external server, only from requests dispatched from within WordPress itself. The user can authenticate itself using [Basic Auth](https://github.com/WP-API/Basic-Auth), [OAuth2](https://github.com/WP-API/OAuth2), or [JWT](https://github.com/WP-API/jwt-auth) from an external server even without the `wp_rest` nonce, but if you add an action nonce as well, it won't work. So the action nonce is optional. Add it if you want the endpoint to work locally only. Example: ``` /** * First step, registering, localizing and enqueueing the JavaScript */ wp_register_script( 'main-js', get_template_directory_uri() . '/js/main.js', [ 'jquery' ] ); wp_localize_script( 'main-js', 'data', [ 'rest' => [ 'endpoints' => [ 'my_endpoint' => esc_url_raw( rest_url( 'my_plugin/v1/my_endpoint' ) ), ], 'timeout' => (int) apply_filters( ""my_plugin_rest_timeout"", 60 ), 'nonce' => wp_create_nonce( 'wp_rest' ), //'action_nonce' => wp_create_nonce( 'action_nonce' ), ], ] ); wp_enqueue_script( 'main-js' ); /** * Second step, the request on the JavaScript file */ jQuery(document).on('click', '#some_element', function () { let ajax_data = { 'some_value': jQuery( "".some_value"" ).val(), //'action_nonce': data.rest.action_nonce }; jQuery.ajax({ url: data.rest.endpoints.my_endpoint, method: ""GET"", dataType: ""json"", timeout: data.rest.timeout, data: ajax_data, beforeSend: function (xhr) { xhr.setRequestHeader('X-WP-Nonce', data.rest.nonce); } }).done(function (results) { console.log(results); alert(""Success!""); }).fail(function (xhr) { console.log(results); alert(""Error!""); }); }); /** * Third step, the REST endpoint itself */ class My_Endpoint { public function registerRoutes() { register_rest_route( 'my_plugin', 'v1/my_endpoint', [ 'methods' => WP_REST_Server::READABLE, 'callback' => [ $this, 'get_something' ], 'args' => [ 'some_value' => [ 'required' => true, ], ], 'permission_callback' => function ( WP_REST_Request $request ) { return true; }, ] ); } /** * @return WP_REST_Response */ private function get_something( WP_REST_Request $request ) { //if ( ! wp_verify_nonce( $request['nonce'], 'action_nonce' ) ) { // return false; //} $some_value = $request['some_value']; if ( strlen( $some_value ) < 5 ) { return new WP_REST_Response( 'Sorry, Some Value must be at least 5 characters long.', 400 ); } // Since we are passing the ""X-WP-Nonce"" header, this will work: $user = wp_get_current_user(); if ( $user instanceof WP_User ) { return new WP_REST_Response( 'Sorry, could not get the name.', 400 ); } else { return new WP_REST_Response( 'Your username name is: ' . $user->display_name, 200 ); } } } ```","One thing to note about @Lucas Bustamante's answer is that the verification process described is user-based authentication. This means if you have an anonymous API end point which doesn't require a user, then by simply by not providing the `X-WP-NONCE` header you'll pass the described nonce check. Supplying an incorrect nonce will still throw an error. The reason for this is that the `rest_cookie_check_errors` which is what does the verification will simply set the `current_user` to empty if no nonce is provided. This works fine when a user is required, but not otherwise. (see: ) If you want to expand on Lucas' answer to also include annonymous end points, then you can add a manual nonce check to the start of your end point, like this: ``` if ( !$_SERVER['HTTP_X_WP_NONCE'] || !wp_verify_nonce( $_SERVER['HTTP_X_WP_NONCE'], 'wp_rest' ) ) { header('HTTP/1.0 403 Forbidden'); exit; } ```" 323637,"I would like to understand the best practices regarding nonce validation in REST APIs. I see a lot of people talking about `wp_rest` nonce for REST requests. But upon looking on WordPress core code, I saw that `wp_rest` is just a nonce to validate a logged in user status, if it's not present, it just runs the request as guest. That said, should I submit two nonces upon sending a POST request to a REST API? One for authentication `wp_rest` and another for the action `foo_action`? If so, how should I send `wp_rest` and `foo_action` nonce in JavaScript, and, in PHP, what's the correct place to validate those nonces? (I mean validate\_callback for a arg? permission\_callback?)",2018/12/22,"['https://wordpress.stackexchange.com/questions/323637', 'https://wordpress.stackexchange.com', 'https://wordpress.stackexchange.com/users/27278/']","Building on what @lucas-bustamante wrote (which helped me a ton!), once you have the X-WP-Nonce header setup in your custom routes you can do the following: ```php register_rest_route('v1', '/my_post', [ 'methods' => WP_REST_Server::CREATABLE, 'callback' => [$this, 'create_post'], 'args' => [ 'post_title' => [ 'required' => true, ], 'post_excerpt' => [ 'required' => true, ] ], 'permission_callback' => function ( ) { return current_user_can( 'publish_posts' ); }, ]); ``` Note that the `permission_callback` is on the root level not under args ([documented here](https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/#permissions-callback)) and I've removed the additional `nonce` check from `args` since checking the permission alone will fail if the nonce is invalid or not supplied (I've tested this extensively and can confirm I get an error when no nonce is supplied or it's invalid).","One thing to note about @Lucas Bustamante's answer is that the verification process described is user-based authentication. This means if you have an anonymous API end point which doesn't require a user, then by simply by not providing the `X-WP-NONCE` header you'll pass the described nonce check. Supplying an incorrect nonce will still throw an error. The reason for this is that the `rest_cookie_check_errors` which is what does the verification will simply set the `current_user` to empty if no nonce is provided. This works fine when a user is required, but not otherwise. (see: ) If you want to expand on Lucas' answer to also include annonymous end points, then you can add a manual nonce check to the start of your end point, like this: ``` if ( !$_SERVER['HTTP_X_WP_NONCE'] || !wp_verify_nonce( $_SERVER['HTTP_X_WP_NONCE'], 'wp_rest' ) ) { header('HTTP/1.0 403 Forbidden'); exit; } ```" 16801403,"I'm looking for information/documentation on creating a custom icon for a document type in my iOS app. I am sure I have seen some Apple developer guide with information about this, but I have been searching and cannot find it! In the app's Info.plist I have specified a custom document type, and a corresponding exported UTI (conforming to com.apple.package). Xcode makes it quite easy to specify images for these under the ""Info"" tab of the target settings, but I can't find the information regarding what sizes they should be, or in what situations the document icon will be visible. I believe that iOS automatically creates a 'default' document icon for you using the app icon (as per [this section](http://developer.apple.com/library/ios/#documentation/UserExperience/Conceptual/MobileHIG/IconsImages/IconsImages.html#//apple_ref/doc/uid/TP40006556-CH14-SW15) of the HIG), so if I made it possible for users to share the document via email, another user with the app installed on their iOS device would see this default document icon. Where else might this document icon be seen? Currently in iTunes file sharing the document appears as a directory with the custom file extension - presumably this would change if an icon was specified for the document? When viewing one of the documents in the OS X file system, it appears as a standard white document (i.e. looks like an unknown file type) - is there any way for this to appear with the proper icon, or would the user need a Mac app installed that specifies such a file type?",2013/05/28,"['https://Stackoverflow.com/questions/16801403', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/429427/']","You already found the HIG documentation. I'm not certain if document icons show up in iTunes, but I doubt it. I've never seen this from any other app. From the [Information Property List Key Reference](https://developer.apple.com/library/ios/documentation/general/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html#//apple_ref/doc/uid/TP40009249-SW9) (search for ""Document Icons""): **Document Icons** > > In iOS, the `CFBundleTypeIconFiles` key contains an array of strings with the names of the image files to use for the document icon. Table 3 lists the icon sizes you can include for each device type. You can name the image files however you want but the file names in your `Info.plist` file must match the image resource filenames exactly. (For iPhone and iPod touch, the usable area of your icon is actually much smaller.) For more information on how to create these icons, see *iOS Human Interface Guidelines*. > > > **Table 3** Document icon sizes for iOS ``` +-----------------------+----------------------------------+ | Device | Sizes | +-----------------------+----------------------------------+ | iPad | 64 x 64 pixels | | | 320 x 320 pixels | +-----------------------+----------------------------------+ | iPhone and iPod touch | 22 x 29 pixels | | | 44 x 58 pixels (high resolution) | +-----------------------+----------------------------------+ ```","Thanks @TomSwift for your answer help me a lot. I just add this if you have Xcode 6.3.2. You can not add icon files drag and drop or press ""+"" button inside info section, instead you must add the icon files names directly info.plist ![enter image description here](https://i.stack.imgur.com/aKGgS.png) You must add the fours icons as image above. Then you can see the icon inside Document Types. ![enter image description here](https://i.stack.imgur.com/YqC5L.png)" 59163378,"Suppose I have the following code: (which is too verbose) ``` function usePolicyFormRequirements(policy) { const [addresses, setAddresses] = React.useState([]); const [pools, setPools] = React.useState([]); const [schedules, setSchedules] = React.useState([]); const [services, setServices] = React.useState([]); const [tunnels, setTunnels] = React.useState([]); const [zones, setZones] = React.useState([]); const [groups, setGroups] = React.useState([]); const [advancedServices, setAdvancedServices] = React.useState([]); const [profiles, setProfiles] = React.useState([]); React.useEffect(() => { policiesService .getPolicyFormRequirements(policy) .then( ({ addresses, pools, schedules, services, tunnels, zones, groups, advancedServices, profiles, }) => { setAddresses(addresses); setPools(pools); setSchedules(schedules); setServices(services); setTunnels(tunnels); setZones(zones); setGroups(groups); setAdvancedServices(advancedServices); setProfiles(profiles); } ); }, [policy]); return { addresses, pools, schedules, services, tunnels, zones, groups, advancedServices, profiles, }; } ``` When I use this custom Hook inside of my function component, after `getPolicyFormRequirements` resolves, my function component re-renders `9` times (the count of all entities that I call `setState` on) I know the solution to this particular use case would be to aggregate them into one state and call `setState` on it once, but as I remember (correct me, if I'm wrong) on event handlers (e.g. `onClick`) if you call multiple consecutive `setState`s, only one re-render occurs after event handler finishes executing. **Isn't there any way I could tell `React`, or `React` would know itself, that, after this `setState` another `setState` is coming along, so skip re-render until you find a second to breath.** I'm not looking for performance-optimization tips, I'm looking to know the answer to the above (**Bold**) question! Or do you think I am thinking wrong? Thanks! -------------- -------------- --- **UPDATE** How I checked my component rendered 9 times? ``` export default function PolicyForm({ onSubmit, policy }) { const [formState, setFormState, formIsValid] = usePgForm(); const { addresses, pools, schedules, services, tunnels, zones, groups, advancedServices, profiles, actions, rejects, differentiatedServices, packetTypes, } = usePolicyFormRequirements(policy); console.log(' --- re-rendering'); // count of this return <>; } ```",2019/12/03,"['https://Stackoverflow.com/questions/59163378', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2908277/']","If the state changes are triggered asynchronously, `React` will not batch your multiple state updates. For eg, in your case since you are calling setState after resolving policiesService.getPolicyFormRequirements(policy), react won't be batching it. Instead if it is just the following way, React would have batched the setState calls and in this case there would be only 1 re-render. ``` React.useEffect(() => { setAddresses(addresses); setPools(pools); setSchedules(schedules); setServices(services); setTunnels(tunnels); setZones(zones); setGroups(groups); setAdvancedServices(advancedServices); setProfiles(profiles); }, []) ``` I have found the below codesandbox example online which demonstrates the above two behaviour. If you look at the console, when you hit the button “with promise”, it will first show a aa and b b, then a aa and b bb. In this case, it will not render aa - bb right away, each state change triggers a new render, there is no batching. However, when you click the button “without promise”, the console will show a aa and b bb right away. So in this case, React does batch the state changes and does one render for both together.","**REACT 18 UPDATE** ------------------- With React 18, all state updates occurring together are automatically batched into a single render. This means it is okay to split the state into as many separate variables as you like. Source: [React 18 Batching](https://reactjs.org/blog/2022/03/29/react-v18.html#new-feature-automatic-batching)" 59163378,"Suppose I have the following code: (which is too verbose) ``` function usePolicyFormRequirements(policy) { const [addresses, setAddresses] = React.useState([]); const [pools, setPools] = React.useState([]); const [schedules, setSchedules] = React.useState([]); const [services, setServices] = React.useState([]); const [tunnels, setTunnels] = React.useState([]); const [zones, setZones] = React.useState([]); const [groups, setGroups] = React.useState([]); const [advancedServices, setAdvancedServices] = React.useState([]); const [profiles, setProfiles] = React.useState([]); React.useEffect(() => { policiesService .getPolicyFormRequirements(policy) .then( ({ addresses, pools, schedules, services, tunnels, zones, groups, advancedServices, profiles, }) => { setAddresses(addresses); setPools(pools); setSchedules(schedules); setServices(services); setTunnels(tunnels); setZones(zones); setGroups(groups); setAdvancedServices(advancedServices); setProfiles(profiles); } ); }, [policy]); return { addresses, pools, schedules, services, tunnels, zones, groups, advancedServices, profiles, }; } ``` When I use this custom Hook inside of my function component, after `getPolicyFormRequirements` resolves, my function component re-renders `9` times (the count of all entities that I call `setState` on) I know the solution to this particular use case would be to aggregate them into one state and call `setState` on it once, but as I remember (correct me, if I'm wrong) on event handlers (e.g. `onClick`) if you call multiple consecutive `setState`s, only one re-render occurs after event handler finishes executing. **Isn't there any way I could tell `React`, or `React` would know itself, that, after this `setState` another `setState` is coming along, so skip re-render until you find a second to breath.** I'm not looking for performance-optimization tips, I'm looking to know the answer to the above (**Bold**) question! Or do you think I am thinking wrong? Thanks! -------------- -------------- --- **UPDATE** How I checked my component rendered 9 times? ``` export default function PolicyForm({ onSubmit, policy }) { const [formState, setFormState, formIsValid] = usePgForm(); const { addresses, pools, schedules, services, tunnels, zones, groups, advancedServices, profiles, actions, rejects, differentiatedServices, packetTypes, } = usePolicyFormRequirements(policy); console.log(' --- re-rendering'); // count of this return <>; } ```",2019/12/03,"['https://Stackoverflow.com/questions/59163378', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2908277/']","If the state changes are triggered asynchronously, `React` will not batch your multiple state updates. For eg, in your case since you are calling setState after resolving policiesService.getPolicyFormRequirements(policy), react won't be batching it. Instead if it is just the following way, React would have batched the setState calls and in this case there would be only 1 re-render. ``` React.useEffect(() => { setAddresses(addresses); setPools(pools); setSchedules(schedules); setServices(services); setTunnels(tunnels); setZones(zones); setGroups(groups); setAdvancedServices(advancedServices); setProfiles(profiles); }, []) ``` I have found the below codesandbox example online which demonstrates the above two behaviour. If you look at the console, when you hit the button “with promise”, it will first show a aa and b b, then a aa and b bb. In this case, it will not render aa - bb right away, each state change triggers a new render, there is no batching. However, when you click the button “without promise”, the console will show a aa and b bb right away. So in this case, React does batch the state changes and does one render for both together.","You can merge all states into one ``` function usePolicyFormRequirements(policy) { const [values, setValues] = useState({ addresses: [], pools: [], schedules: [], services: [], tunnels: [], zones: [], groups: [], advancedServices: [], profiles: [], }); React.useEffect(() => { policiesService .getPolicyFormRequirements(policy) .then(newValues) => setValues({ ...newValues })); }, [policy]); return values; } ```" 59163378,"Suppose I have the following code: (which is too verbose) ``` function usePolicyFormRequirements(policy) { const [addresses, setAddresses] = React.useState([]); const [pools, setPools] = React.useState([]); const [schedules, setSchedules] = React.useState([]); const [services, setServices] = React.useState([]); const [tunnels, setTunnels] = React.useState([]); const [zones, setZones] = React.useState([]); const [groups, setGroups] = React.useState([]); const [advancedServices, setAdvancedServices] = React.useState([]); const [profiles, setProfiles] = React.useState([]); React.useEffect(() => { policiesService .getPolicyFormRequirements(policy) .then( ({ addresses, pools, schedules, services, tunnels, zones, groups, advancedServices, profiles, }) => { setAddresses(addresses); setPools(pools); setSchedules(schedules); setServices(services); setTunnels(tunnels); setZones(zones); setGroups(groups); setAdvancedServices(advancedServices); setProfiles(profiles); } ); }, [policy]); return { addresses, pools, schedules, services, tunnels, zones, groups, advancedServices, profiles, }; } ``` When I use this custom Hook inside of my function component, after `getPolicyFormRequirements` resolves, my function component re-renders `9` times (the count of all entities that I call `setState` on) I know the solution to this particular use case would be to aggregate them into one state and call `setState` on it once, but as I remember (correct me, if I'm wrong) on event handlers (e.g. `onClick`) if you call multiple consecutive `setState`s, only one re-render occurs after event handler finishes executing. **Isn't there any way I could tell `React`, or `React` would know itself, that, after this `setState` another `setState` is coming along, so skip re-render until you find a second to breath.** I'm not looking for performance-optimization tips, I'm looking to know the answer to the above (**Bold**) question! Or do you think I am thinking wrong? Thanks! -------------- -------------- --- **UPDATE** How I checked my component rendered 9 times? ``` export default function PolicyForm({ onSubmit, policy }) { const [formState, setFormState, formIsValid] = usePgForm(); const { addresses, pools, schedules, services, tunnels, zones, groups, advancedServices, profiles, actions, rejects, differentiatedServices, packetTypes, } = usePolicyFormRequirements(policy); console.log(' --- re-rendering'); // count of this return <>; } ```",2019/12/03,"['https://Stackoverflow.com/questions/59163378', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2908277/']","I thought I'd post this answer here since it hasn't already been mentioned. There is a way to force the batching of state updates. See [this article](https://blog.logrocket.com/simplifying-state-management-in-react-apps-with-batched-updates/) for an explanation. Below is a fully functional component that only renders once, regardless of whether the setValues function is async or not. ``` import React, { useState, useEffect} from 'react' import {unstable_batchedUpdates} from 'react-dom' export default function SingleRender() { const [A, setA] = useState(0) const [B, setB] = useState(0) const [C, setC] = useState(0) const setValues = () => { unstable_batchedUpdates(() => { setA(5) setB(6) setC(7) }) } useEffect(() => { setValues() }, []) return (

{A}

{B}

{C}

) } ``` While the name ""unstable"" might be concerning, the React team has previously recommended the use of this API where appropriate, and I have found it very useful to cut down on the number of renders without clogging up my code.","You can merge all states into one ``` function usePolicyFormRequirements(policy) { const [values, setValues] = useState({ addresses: [], pools: [], schedules: [], services: [], tunnels: [], zones: [], groups: [], advancedServices: [], profiles: [], }); React.useEffect(() => { policiesService .getPolicyFormRequirements(policy) .then(newValues) => setValues({ ...newValues })); }, [policy]); return values; } ```" 59163378,"Suppose I have the following code: (which is too verbose) ``` function usePolicyFormRequirements(policy) { const [addresses, setAddresses] = React.useState([]); const [pools, setPools] = React.useState([]); const [schedules, setSchedules] = React.useState([]); const [services, setServices] = React.useState([]); const [tunnels, setTunnels] = React.useState([]); const [zones, setZones] = React.useState([]); const [groups, setGroups] = React.useState([]); const [advancedServices, setAdvancedServices] = React.useState([]); const [profiles, setProfiles] = React.useState([]); React.useEffect(() => { policiesService .getPolicyFormRequirements(policy) .then( ({ addresses, pools, schedules, services, tunnels, zones, groups, advancedServices, profiles, }) => { setAddresses(addresses); setPools(pools); setSchedules(schedules); setServices(services); setTunnels(tunnels); setZones(zones); setGroups(groups); setAdvancedServices(advancedServices); setProfiles(profiles); } ); }, [policy]); return { addresses, pools, schedules, services, tunnels, zones, groups, advancedServices, profiles, }; } ``` When I use this custom Hook inside of my function component, after `getPolicyFormRequirements` resolves, my function component re-renders `9` times (the count of all entities that I call `setState` on) I know the solution to this particular use case would be to aggregate them into one state and call `setState` on it once, but as I remember (correct me, if I'm wrong) on event handlers (e.g. `onClick`) if you call multiple consecutive `setState`s, only one re-render occurs after event handler finishes executing. **Isn't there any way I could tell `React`, or `React` would know itself, that, after this `setState` another `setState` is coming along, so skip re-render until you find a second to breath.** I'm not looking for performance-optimization tips, I'm looking to know the answer to the above (**Bold**) question! Or do you think I am thinking wrong? Thanks! -------------- -------------- --- **UPDATE** How I checked my component rendered 9 times? ``` export default function PolicyForm({ onSubmit, policy }) { const [formState, setFormState, formIsValid] = usePgForm(); const { addresses, pools, schedules, services, tunnels, zones, groups, advancedServices, profiles, actions, rejects, differentiatedServices, packetTypes, } = usePolicyFormRequirements(policy); console.log(' --- re-rendering'); // count of this return <>; } ```",2019/12/03,"['https://Stackoverflow.com/questions/59163378', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2908277/']","If the state changes are triggered asynchronously, `React` will not batch your multiple state updates. For eg, in your case since you are calling setState after resolving policiesService.getPolicyFormRequirements(policy), react won't be batching it. Instead if it is just the following way, React would have batched the setState calls and in this case there would be only 1 re-render. ``` React.useEffect(() => { setAddresses(addresses); setPools(pools); setSchedules(schedules); setServices(services); setTunnels(tunnels); setZones(zones); setGroups(groups); setAdvancedServices(advancedServices); setProfiles(profiles); }, []) ``` I have found the below codesandbox example online which demonstrates the above two behaviour. If you look at the console, when you hit the button “with promise”, it will first show a aa and b b, then a aa and b bb. In this case, it will not render aa - bb right away, each state change triggers a new render, there is no batching. However, when you click the button “without promise”, the console will show a aa and b bb right away. So in this case, React does batch the state changes and does one render for both together.","> > Isn't there any way I could tell React, or React would know itself, that, after this setState another setState is coming along, so skip re-render until you find a second to breath. > > > You can't, React batches (as for React 17) state updates only on event handlers and lifecycle methods, therefore batching in promise like it your case is not possible. To solve it, you need to reduce the hook state to a single source. From React 18 you have [automatic batching even in promises](https://github.com/reactwg/react-18/discussions/21)." 59163378,"Suppose I have the following code: (which is too verbose) ``` function usePolicyFormRequirements(policy) { const [addresses, setAddresses] = React.useState([]); const [pools, setPools] = React.useState([]); const [schedules, setSchedules] = React.useState([]); const [services, setServices] = React.useState([]); const [tunnels, setTunnels] = React.useState([]); const [zones, setZones] = React.useState([]); const [groups, setGroups] = React.useState([]); const [advancedServices, setAdvancedServices] = React.useState([]); const [profiles, setProfiles] = React.useState([]); React.useEffect(() => { policiesService .getPolicyFormRequirements(policy) .then( ({ addresses, pools, schedules, services, tunnels, zones, groups, advancedServices, profiles, }) => { setAddresses(addresses); setPools(pools); setSchedules(schedules); setServices(services); setTunnels(tunnels); setZones(zones); setGroups(groups); setAdvancedServices(advancedServices); setProfiles(profiles); } ); }, [policy]); return { addresses, pools, schedules, services, tunnels, zones, groups, advancedServices, profiles, }; } ``` When I use this custom Hook inside of my function component, after `getPolicyFormRequirements` resolves, my function component re-renders `9` times (the count of all entities that I call `setState` on) I know the solution to this particular use case would be to aggregate them into one state and call `setState` on it once, but as I remember (correct me, if I'm wrong) on event handlers (e.g. `onClick`) if you call multiple consecutive `setState`s, only one re-render occurs after event handler finishes executing. **Isn't there any way I could tell `React`, or `React` would know itself, that, after this `setState` another `setState` is coming along, so skip re-render until you find a second to breath.** I'm not looking for performance-optimization tips, I'm looking to know the answer to the above (**Bold**) question! Or do you think I am thinking wrong? Thanks! -------------- -------------- --- **UPDATE** How I checked my component rendered 9 times? ``` export default function PolicyForm({ onSubmit, policy }) { const [formState, setFormState, formIsValid] = usePgForm(); const { addresses, pools, schedules, services, tunnels, zones, groups, advancedServices, profiles, actions, rejects, differentiatedServices, packetTypes, } = usePolicyFormRequirements(policy); console.log(' --- re-rendering'); // count of this return <>; } ```",2019/12/03,"['https://Stackoverflow.com/questions/59163378', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2908277/']","I thought I'd post this answer here since it hasn't already been mentioned. There is a way to force the batching of state updates. See [this article](https://blog.logrocket.com/simplifying-state-management-in-react-apps-with-batched-updates/) for an explanation. Below is a fully functional component that only renders once, regardless of whether the setValues function is async or not. ``` import React, { useState, useEffect} from 'react' import {unstable_batchedUpdates} from 'react-dom' export default function SingleRender() { const [A, setA] = useState(0) const [B, setB] = useState(0) const [C, setC] = useState(0) const setValues = () => { unstable_batchedUpdates(() => { setA(5) setB(6) setC(7) }) } useEffect(() => { setValues() }, []) return (

{A}

{B}

{C}

) } ``` While the name ""unstable"" might be concerning, the React team has previously recommended the use of this API where appropriate, and I have found it very useful to cut down on the number of renders without clogging up my code.","> > Isn't there any way I could tell React, or React would know itself, that, after this setState another setState is coming along, so skip re-render until you find a second to breath. > > > You can't, React batches (as for React 17) state updates only on event handlers and lifecycle methods, therefore batching in promise like it your case is not possible. To solve it, you need to reduce the hook state to a single source. From React 18 you have [automatic batching even in promises](https://github.com/reactwg/react-18/discussions/21)." 59163378,"Suppose I have the following code: (which is too verbose) ``` function usePolicyFormRequirements(policy) { const [addresses, setAddresses] = React.useState([]); const [pools, setPools] = React.useState([]); const [schedules, setSchedules] = React.useState([]); const [services, setServices] = React.useState([]); const [tunnels, setTunnels] = React.useState([]); const [zones, setZones] = React.useState([]); const [groups, setGroups] = React.useState([]); const [advancedServices, setAdvancedServices] = React.useState([]); const [profiles, setProfiles] = React.useState([]); React.useEffect(() => { policiesService .getPolicyFormRequirements(policy) .then( ({ addresses, pools, schedules, services, tunnels, zones, groups, advancedServices, profiles, }) => { setAddresses(addresses); setPools(pools); setSchedules(schedules); setServices(services); setTunnels(tunnels); setZones(zones); setGroups(groups); setAdvancedServices(advancedServices); setProfiles(profiles); } ); }, [policy]); return { addresses, pools, schedules, services, tunnels, zones, groups, advancedServices, profiles, }; } ``` When I use this custom Hook inside of my function component, after `getPolicyFormRequirements` resolves, my function component re-renders `9` times (the count of all entities that I call `setState` on) I know the solution to this particular use case would be to aggregate them into one state and call `setState` on it once, but as I remember (correct me, if I'm wrong) on event handlers (e.g. `onClick`) if you call multiple consecutive `setState`s, only one re-render occurs after event handler finishes executing. **Isn't there any way I could tell `React`, or `React` would know itself, that, after this `setState` another `setState` is coming along, so skip re-render until you find a second to breath.** I'm not looking for performance-optimization tips, I'm looking to know the answer to the above (**Bold**) question! Or do you think I am thinking wrong? Thanks! -------------- -------------- --- **UPDATE** How I checked my component rendered 9 times? ``` export default function PolicyForm({ onSubmit, policy }) { const [formState, setFormState, formIsValid] = usePgForm(); const { addresses, pools, schedules, services, tunnels, zones, groups, advancedServices, profiles, actions, rejects, differentiatedServices, packetTypes, } = usePolicyFormRequirements(policy); console.log(' --- re-rendering'); // count of this return <>; } ```",2019/12/03,"['https://Stackoverflow.com/questions/59163378', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2908277/']","If the state changes are triggered asynchronously, `React` will not batch your multiple state updates. For eg, in your case since you are calling setState after resolving policiesService.getPolicyFormRequirements(policy), react won't be batching it. Instead if it is just the following way, React would have batched the setState calls and in this case there would be only 1 re-render. ``` React.useEffect(() => { setAddresses(addresses); setPools(pools); setSchedules(schedules); setServices(services); setTunnels(tunnels); setZones(zones); setGroups(groups); setAdvancedServices(advancedServices); setProfiles(profiles); }, []) ``` I have found the below codesandbox example online which demonstrates the above two behaviour. If you look at the console, when you hit the button “with promise”, it will first show a aa and b b, then a aa and b bb. In this case, it will not render aa - bb right away, each state change triggers a new render, there is no batching. However, when you click the button “without promise”, the console will show a aa and b bb right away. So in this case, React does batch the state changes and does one render for both together.","By the way, I just found out React 18 adds automatic update-batching out of the box. Read more: " 59163378,"Suppose I have the following code: (which is too verbose) ``` function usePolicyFormRequirements(policy) { const [addresses, setAddresses] = React.useState([]); const [pools, setPools] = React.useState([]); const [schedules, setSchedules] = React.useState([]); const [services, setServices] = React.useState([]); const [tunnels, setTunnels] = React.useState([]); const [zones, setZones] = React.useState([]); const [groups, setGroups] = React.useState([]); const [advancedServices, setAdvancedServices] = React.useState([]); const [profiles, setProfiles] = React.useState([]); React.useEffect(() => { policiesService .getPolicyFormRequirements(policy) .then( ({ addresses, pools, schedules, services, tunnels, zones, groups, advancedServices, profiles, }) => { setAddresses(addresses); setPools(pools); setSchedules(schedules); setServices(services); setTunnels(tunnels); setZones(zones); setGroups(groups); setAdvancedServices(advancedServices); setProfiles(profiles); } ); }, [policy]); return { addresses, pools, schedules, services, tunnels, zones, groups, advancedServices, profiles, }; } ``` When I use this custom Hook inside of my function component, after `getPolicyFormRequirements` resolves, my function component re-renders `9` times (the count of all entities that I call `setState` on) I know the solution to this particular use case would be to aggregate them into one state and call `setState` on it once, but as I remember (correct me, if I'm wrong) on event handlers (e.g. `onClick`) if you call multiple consecutive `setState`s, only one re-render occurs after event handler finishes executing. **Isn't there any way I could tell `React`, or `React` would know itself, that, after this `setState` another `setState` is coming along, so skip re-render until you find a second to breath.** I'm not looking for performance-optimization tips, I'm looking to know the answer to the above (**Bold**) question! Or do you think I am thinking wrong? Thanks! -------------- -------------- --- **UPDATE** How I checked my component rendered 9 times? ``` export default function PolicyForm({ onSubmit, policy }) { const [formState, setFormState, formIsValid] = usePgForm(); const { addresses, pools, schedules, services, tunnels, zones, groups, advancedServices, profiles, actions, rejects, differentiatedServices, packetTypes, } = usePolicyFormRequirements(policy); console.log(' --- re-rendering'); // count of this return <>; } ```",2019/12/03,"['https://Stackoverflow.com/questions/59163378', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2908277/']","I thought I'd post this answer here since it hasn't already been mentioned. There is a way to force the batching of state updates. See [this article](https://blog.logrocket.com/simplifying-state-management-in-react-apps-with-batched-updates/) for an explanation. Below is a fully functional component that only renders once, regardless of whether the setValues function is async or not. ``` import React, { useState, useEffect} from 'react' import {unstable_batchedUpdates} from 'react-dom' export default function SingleRender() { const [A, setA] = useState(0) const [B, setB] = useState(0) const [C, setC] = useState(0) const setValues = () => { unstable_batchedUpdates(() => { setA(5) setB(6) setC(7) }) } useEffect(() => { setValues() }, []) return (

{A}

{B}

{C}

) } ``` While the name ""unstable"" might be concerning, the React team has previously recommended the use of this API where appropriate, and I have found it very useful to cut down on the number of renders without clogging up my code.","By the way, I just found out React 18 adds automatic update-batching out of the box. Read more: " 59163378,"Suppose I have the following code: (which is too verbose) ``` function usePolicyFormRequirements(policy) { const [addresses, setAddresses] = React.useState([]); const [pools, setPools] = React.useState([]); const [schedules, setSchedules] = React.useState([]); const [services, setServices] = React.useState([]); const [tunnels, setTunnels] = React.useState([]); const [zones, setZones] = React.useState([]); const [groups, setGroups] = React.useState([]); const [advancedServices, setAdvancedServices] = React.useState([]); const [profiles, setProfiles] = React.useState([]); React.useEffect(() => { policiesService .getPolicyFormRequirements(policy) .then( ({ addresses, pools, schedules, services, tunnels, zones, groups, advancedServices, profiles, }) => { setAddresses(addresses); setPools(pools); setSchedules(schedules); setServices(services); setTunnels(tunnels); setZones(zones); setGroups(groups); setAdvancedServices(advancedServices); setProfiles(profiles); } ); }, [policy]); return { addresses, pools, schedules, services, tunnels, zones, groups, advancedServices, profiles, }; } ``` When I use this custom Hook inside of my function component, after `getPolicyFormRequirements` resolves, my function component re-renders `9` times (the count of all entities that I call `setState` on) I know the solution to this particular use case would be to aggregate them into one state and call `setState` on it once, but as I remember (correct me, if I'm wrong) on event handlers (e.g. `onClick`) if you call multiple consecutive `setState`s, only one re-render occurs after event handler finishes executing. **Isn't there any way I could tell `React`, or `React` would know itself, that, after this `setState` another `setState` is coming along, so skip re-render until you find a second to breath.** I'm not looking for performance-optimization tips, I'm looking to know the answer to the above (**Bold**) question! Or do you think I am thinking wrong? Thanks! -------------- -------------- --- **UPDATE** How I checked my component rendered 9 times? ``` export default function PolicyForm({ onSubmit, policy }) { const [formState, setFormState, formIsValid] = usePgForm(); const { addresses, pools, schedules, services, tunnels, zones, groups, advancedServices, profiles, actions, rejects, differentiatedServices, packetTypes, } = usePolicyFormRequirements(policy); console.log(' --- re-rendering'); // count of this return <>; } ```",2019/12/03,"['https://Stackoverflow.com/questions/59163378', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2908277/']","I thought I'd post this answer here since it hasn't already been mentioned. There is a way to force the batching of state updates. See [this article](https://blog.logrocket.com/simplifying-state-management-in-react-apps-with-batched-updates/) for an explanation. Below is a fully functional component that only renders once, regardless of whether the setValues function is async or not. ``` import React, { useState, useEffect} from 'react' import {unstable_batchedUpdates} from 'react-dom' export default function SingleRender() { const [A, setA] = useState(0) const [B, setB] = useState(0) const [C, setC] = useState(0) const setValues = () => { unstable_batchedUpdates(() => { setA(5) setB(6) setC(7) }) } useEffect(() => { setValues() }, []) return (

{A}

{B}

{C}

) } ``` While the name ""unstable"" might be concerning, the React team has previously recommended the use of this API where appropriate, and I have found it very useful to cut down on the number of renders without clogging up my code.","If the state changes are triggered asynchronously, `React` will not batch your multiple state updates. For eg, in your case since you are calling setState after resolving policiesService.getPolicyFormRequirements(policy), react won't be batching it. Instead if it is just the following way, React would have batched the setState calls and in this case there would be only 1 re-render. ``` React.useEffect(() => { setAddresses(addresses); setPools(pools); setSchedules(schedules); setServices(services); setTunnels(tunnels); setZones(zones); setGroups(groups); setAdvancedServices(advancedServices); setProfiles(profiles); }, []) ``` I have found the below codesandbox example online which demonstrates the above two behaviour. If you look at the console, when you hit the button “with promise”, it will first show a aa and b b, then a aa and b bb. In this case, it will not render aa - bb right away, each state change triggers a new render, there is no batching. However, when you click the button “without promise”, the console will show a aa and b bb right away. So in this case, React does batch the state changes and does one render for both together." 59163378,"Suppose I have the following code: (which is too verbose) ``` function usePolicyFormRequirements(policy) { const [addresses, setAddresses] = React.useState([]); const [pools, setPools] = React.useState([]); const [schedules, setSchedules] = React.useState([]); const [services, setServices] = React.useState([]); const [tunnels, setTunnels] = React.useState([]); const [zones, setZones] = React.useState([]); const [groups, setGroups] = React.useState([]); const [advancedServices, setAdvancedServices] = React.useState([]); const [profiles, setProfiles] = React.useState([]); React.useEffect(() => { policiesService .getPolicyFormRequirements(policy) .then( ({ addresses, pools, schedules, services, tunnels, zones, groups, advancedServices, profiles, }) => { setAddresses(addresses); setPools(pools); setSchedules(schedules); setServices(services); setTunnels(tunnels); setZones(zones); setGroups(groups); setAdvancedServices(advancedServices); setProfiles(profiles); } ); }, [policy]); return { addresses, pools, schedules, services, tunnels, zones, groups, advancedServices, profiles, }; } ``` When I use this custom Hook inside of my function component, after `getPolicyFormRequirements` resolves, my function component re-renders `9` times (the count of all entities that I call `setState` on) I know the solution to this particular use case would be to aggregate them into one state and call `setState` on it once, but as I remember (correct me, if I'm wrong) on event handlers (e.g. `onClick`) if you call multiple consecutive `setState`s, only one re-render occurs after event handler finishes executing. **Isn't there any way I could tell `React`, or `React` would know itself, that, after this `setState` another `setState` is coming along, so skip re-render until you find a second to breath.** I'm not looking for performance-optimization tips, I'm looking to know the answer to the above (**Bold**) question! Or do you think I am thinking wrong? Thanks! -------------- -------------- --- **UPDATE** How I checked my component rendered 9 times? ``` export default function PolicyForm({ onSubmit, policy }) { const [formState, setFormState, formIsValid] = usePgForm(); const { addresses, pools, schedules, services, tunnels, zones, groups, advancedServices, profiles, actions, rejects, differentiatedServices, packetTypes, } = usePolicyFormRequirements(policy); console.log(' --- re-rendering'); // count of this return <>; } ```",2019/12/03,"['https://Stackoverflow.com/questions/59163378', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2908277/']","You can merge all states into one ``` function usePolicyFormRequirements(policy) { const [values, setValues] = useState({ addresses: [], pools: [], schedules: [], services: [], tunnels: [], zones: [], groups: [], advancedServices: [], profiles: [], }); React.useEffect(() => { policiesService .getPolicyFormRequirements(policy) .then(newValues) => setValues({ ...newValues })); }, [policy]); return values; } ```","**REACT 18 UPDATE** ------------------- With React 18, all state updates occurring together are automatically batched into a single render. This means it is okay to split the state into as many separate variables as you like. Source: [React 18 Batching](https://reactjs.org/blog/2022/03/29/react-v18.html#new-feature-automatic-batching)" 59163378,"Suppose I have the following code: (which is too verbose) ``` function usePolicyFormRequirements(policy) { const [addresses, setAddresses] = React.useState([]); const [pools, setPools] = React.useState([]); const [schedules, setSchedules] = React.useState([]); const [services, setServices] = React.useState([]); const [tunnels, setTunnels] = React.useState([]); const [zones, setZones] = React.useState([]); const [groups, setGroups] = React.useState([]); const [advancedServices, setAdvancedServices] = React.useState([]); const [profiles, setProfiles] = React.useState([]); React.useEffect(() => { policiesService .getPolicyFormRequirements(policy) .then( ({ addresses, pools, schedules, services, tunnels, zones, groups, advancedServices, profiles, }) => { setAddresses(addresses); setPools(pools); setSchedules(schedules); setServices(services); setTunnels(tunnels); setZones(zones); setGroups(groups); setAdvancedServices(advancedServices); setProfiles(profiles); } ); }, [policy]); return { addresses, pools, schedules, services, tunnels, zones, groups, advancedServices, profiles, }; } ``` When I use this custom Hook inside of my function component, after `getPolicyFormRequirements` resolves, my function component re-renders `9` times (the count of all entities that I call `setState` on) I know the solution to this particular use case would be to aggregate them into one state and call `setState` on it once, but as I remember (correct me, if I'm wrong) on event handlers (e.g. `onClick`) if you call multiple consecutive `setState`s, only one re-render occurs after event handler finishes executing. **Isn't there any way I could tell `React`, or `React` would know itself, that, after this `setState` another `setState` is coming along, so skip re-render until you find a second to breath.** I'm not looking for performance-optimization tips, I'm looking to know the answer to the above (**Bold**) question! Or do you think I am thinking wrong? Thanks! -------------- -------------- --- **UPDATE** How I checked my component rendered 9 times? ``` export default function PolicyForm({ onSubmit, policy }) { const [formState, setFormState, formIsValid] = usePgForm(); const { addresses, pools, schedules, services, tunnels, zones, groups, advancedServices, profiles, actions, rejects, differentiatedServices, packetTypes, } = usePolicyFormRequirements(policy); console.log(' --- re-rendering'); // count of this return <>; } ```",2019/12/03,"['https://Stackoverflow.com/questions/59163378', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2908277/']","I thought I'd post this answer here since it hasn't already been mentioned. There is a way to force the batching of state updates. See [this article](https://blog.logrocket.com/simplifying-state-management-in-react-apps-with-batched-updates/) for an explanation. Below is a fully functional component that only renders once, regardless of whether the setValues function is async or not. ``` import React, { useState, useEffect} from 'react' import {unstable_batchedUpdates} from 'react-dom' export default function SingleRender() { const [A, setA] = useState(0) const [B, setB] = useState(0) const [C, setC] = useState(0) const setValues = () => { unstable_batchedUpdates(() => { setA(5) setB(6) setC(7) }) } useEffect(() => { setValues() }, []) return (

{A}

{B}

{C}

) } ``` While the name ""unstable"" might be concerning, the React team has previously recommended the use of this API where appropriate, and I have found it very useful to cut down on the number of renders without clogging up my code.","**REACT 18 UPDATE** ------------------- With React 18, all state updates occurring together are automatically batched into a single render. This means it is okay to split the state into as many separate variables as you like. Source: [React 18 Batching](https://reactjs.org/blog/2022/03/29/react-v18.html#new-feature-automatic-batching)" 69247371,"devs, I'm trying to deploy a simple cloud function to the firebase console, everything working very well (installation of npm & configuration & other stuff...). then I wrote a simple function in the **index.js** file : ``` 'use strict' const functions = require(""firebase-functions""); const admin = require('firebase-admin'); admin.initializeApp(functions.config().firebase); exports.sendNotification = functions.database.ref('/notififcation/{user_id}/{notififcation_id}').onWrite( event => { const user_id = event.params.user_id; const notififcation_id = event.params.notififcation_id; console.log('this id is the ' , user_id); } ): ``` then, when I wanna deploy it to firebase with this command **firebase deploy**, This error keeps appearing, this is the error : --- ``` C:\Users\nasro\Desktop\oussamaproject\notifyfun\functions\index.js 14:2 error Parsing error: Unexpected token : ? 1 problem (1 error, 0 warnings) npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! functions@ lint: `eslint .` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the functions@ lint script. npm ERR! This is probably not a problem with npm. There is likely additional l ging output above. npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\nasro\AppData\Roaming\npm-cache\_logs\2021-09-19T21_28_2 892Z-debug.log events.js:292 throw er; // Unhandled 'error' event ^ Error: spawn npm --prefix ""C:\Users\nasro\Desktop\oussamaproject\notifyfun\fun ions"" run lint ENOENT at notFoundError (C:\Users\nasro\AppData\Roaming\npm\node_modules\firebase ools\node_modules\cross-env\node_modules\cross-spawn\lib\enoent.js:6:26) at verifyENOENT (C:\Users\nasro\AppData\Roaming\npm\node_modules\firebase- ols\node_modules\cross-env\node_modules\cross-spawn\lib\enoent.js:40:16) at ChildProcess.cp.emit (C:\Users\nasro\AppData\Roaming\npm\node_modules\f ebase-tools\node_modules\cross-env\node_modules\cross-spawn\lib\enoent.js:27:2 at Process.ChildProcess._handle.onexit (internal/child_process.js:275:12) Emitted 'error' event on ChildProcess instance at: at ChildProcess.cp.emit (C:\Users\nasro\AppData\Roaming\npm\node_modules\f ebase-tools\node_modules\cross-env\node_modules\cross-spawn\lib\enoent.js:30:3 at Process.ChildProcess._handle.onexit (internal/child_process.js:275:12) code: 'ENOENT', errno: 'ENOENT', syscall: 'spawn npm --prefix ""C:\\Users\\nasro\\Desktop\\oussamaproject\\not yfun\\functions"" run lint', path: 'npm --prefix ""C:\\Users\\nasro\\Desktop\\oussamaproject\\notifyfun\\f ctions"" run lint', spawnargs: [] } Error: functions predeploy error: Command terminated with non-zero exit code1 ``` so after searching for a solution in firebase documentation and articles, I tried those solutions **solution one:** in **firebase.json** by default: ``` ""predeploy"": [ ""npm --prefix \""$RESOURCE_DIR\"" run lint"" ] ``` i Modified it to: ``` ""predeploy"": [ ""npm --prefix \""%RESOURCE_DIR%\"" run lint"" ] ``` the error keeps appearing again with the same error message, so I tried solution 2 **Solution two** I modified again the file **firebase.json** to : ``` ""predeploy"": [ ""npm --prefix \""%RESOURCE_DIR%\"" run lint"", ""npm --prefix \""%RESOURCE_DIR%\"" run build"" ] ``` and the error keeps appearing again and again with the same error message (**btw** I'm using windows7) So any solution or suggestions for this error ..",2021/09/19,"['https://Stackoverflow.com/questions/69247371', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15094547/']","try this ``` List prices = new List(); decimal price=0; int count=0; do { count++; Console.WriteLine(""Item {0}"", count); Console.WriteLine("" Enter Price: $ ""); price = Convert.ToDecimal(Console.ReadLine()); prices.Add(price); } while ( price != -1); Console.WriteLine (""Price history:""); foreach(var item in prices) { Console.WriteLine(item.ToString()); } ```","I would store your prices in a dictionary as to ensure that prices for the same item have not been added. Here is a fiddle with an example: ``` public static void Main() { Dictionary prices = new Dictionary(); int count = 0; bool finished = false; do { Console.Write(""Item {0}:\tEnter Price: $"", count); var price = Console.ReadLine(); var convertedPrice = Convert.ToDecimal(price); if(convertedPrice != -1) { prices.Add(count, convertedPrice); count++; } else { finished = true; } } while(!finished); Console.WriteLine(""Price History""); foreach(var price in prices) { Console.WriteLine(""Item {0}:\tPrice: ${1}"", price.Key, price.Value); } } ```" 8074168,"I am basically trying to convert a string similar to this one: ""`2011-11-9 18:24:12.3`"" into a format that I can insert into a database table claiming this particular column to be of the ""datetime"" type. I figured I could do something along the lines of `preparedStatement.setTimestamp(...)`, but I can't seem to get a Timestamp created correctly. Can anyone suggest the easiest way to convert a string like the one above to either a Timestamp or some other type which is compatible with MySQL's ""datetime"" type? Any help would be appreciated. Thus far, I've tried doing something like this: ``` String strDateTime = ""2011-11-9 18:24:12.3""; Timestamp timeStamp = new Timestamp((new Date(strDateTime)).getTime()); preparedStatement.setTimestamp(1, timeStamp); ```",2011/11/10,"['https://Stackoverflow.com/questions/8074168', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/967968/']","Ah, so, the problem is most likely not with the datetime of mysql but with the date. The `Date(Strings s)` constructor is [currently deprecated](http://download.oracle.com/javase/6/docs/api/java/util/Date.html#Date%28java.lang.String%29) and is recommended to use a [SimpleDateFormat](http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html) which would let you use any format you want.","Have you tried splitting and making it into a format you can use? This assumes that this is in the same format all the time. Create a new string that takes apart a split of the old string and rearranges it in a useful way. If this is a string provided by the end-user, you may have to validate it first and check to make sure it is usable." 56815600,"I am using POM in automation and in the test I have 3 classes. let's say `test1, test2 and test3` tester is providing a class name in property file so if tester provide like `test1` in a property file, I have put conditions in java code to run class based on what tester provide in property file. But now I want to set up the same thing from Jenkins using a single build. I do not want to create 3 builds for 3 classes, So if in property file tester provide value `test1`, it should run class `test1` from jenkins. I did check for conditional build steps but seems could not satisfy my need.",2019/06/29,"['https://Stackoverflow.com/questions/56815600', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4213132/']","Using the `includeFile` property of the Maven surefire plugin, you can explicitly say which Test classes should be run. You can provide this file from the command line (e.g. in Jenkins) by using an expression like `-Dsurefire.includesFile={yourfile}`.","You can proceed as before and let the tester provide the test class names in a file. That file is either already available on your system, or it can be uploaded by the tester when the Jenkins job builds. For that you have to parameterize the Jenkins job, and define a file upload parameter. See [Jenkins Wiki](https://wiki.jenkins.io/plugins/servlet/mobile?contentId=34930782#content/view/34930782) for a start point, and these two Stackoverflow questions: [How to upload a generic file into a Jenkins job?](https://stackoverflow.com/questions/27491789/how-to-upload-a-generic-file-into-a-jenkins-job) and [How to use file parameter in jenkins](https://stackoverflow.com/questions/42224691/how-to-use-file-parameter-in-jenkins/42242113) Now, this file upload is tedious for the testers. Why not change the job parameter to a input field respectively a text field, and provide at job build the tests class names as comma separated string respectively multi line text?" 32862638,"Is there a `MIN` constant for `datetime`? I need it to represent the expiration date of a resource, and I want to have a `datetime` that represents ""always expires"" as default value (instead of `None` so I can use the same expiration comparison no matter what). So right now I'm using `datetime.datetime(datetime.MINYEAR,1,1,0,0,tzusc())` as my `MIN datetime` but I wonder if there is some other way to represents ""the lowest possible time"" (even if it's not a `datetime`).",2015/09/30,"['https://Stackoverflow.com/questions/32862638', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/90580/']","You can try - [`datetime.datetime.min`](https://docs.python.org/2/library/datetime.html#datetime.datetime.min) . According to [documentation](https://docs.python.org/2/library/datetime.html#datetime.datetime.min) - > > **`datetime.min`** > > > The earliest representable datetime, datetime(MINYEAR, 1, 1, tzinfo=None). > > >","You could use `time.gmtime(0)` which is the epoch. [Time Documentation](https://docs.python.org/2/library/time.html) > > The epoch is the point where the time starts. On January 1st of that year, at 0 hours, the “time since the epoch” is zero. For Unix, the epoch is 1970. To find out what the epoch is, look at gmtime(0). > > >" 32862638,"Is there a `MIN` constant for `datetime`? I need it to represent the expiration date of a resource, and I want to have a `datetime` that represents ""always expires"" as default value (instead of `None` so I can use the same expiration comparison no matter what). So right now I'm using `datetime.datetime(datetime.MINYEAR,1,1,0,0,tzusc())` as my `MIN datetime` but I wonder if there is some other way to represents ""the lowest possible time"" (even if it's not a `datetime`).",2015/09/30,"['https://Stackoverflow.com/questions/32862638', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/90580/']","You can try - [`datetime.datetime.min`](https://docs.python.org/2/library/datetime.html#datetime.datetime.min) . According to [documentation](https://docs.python.org/2/library/datetime.html#datetime.datetime.min) - > > **`datetime.min`** > > > The earliest representable datetime, datetime(MINYEAR, 1, 1, tzinfo=None). > > >","`datetime.datetime.fromtimestamp(0)` it will gives you: ``` datetime.datetime(1970, 1, 1, 1, 0) ``` > > Return the local date corresponding to the POSIX timestamp, such as is > returned by time.time(). This may raise ValueError, if the timestamp > is out of the range of values supported by the platform C localtime() > function. It’s common for this to be restricted to years from 1970 > through 2038. Note that on non-POSIX systems that include leap seconds > in their notion of a timestamp, leap seconds are ignored by > fromtimestamp(). > > >" 63563,"I am confused in the difference between one to one function and one to one correspondence. Please help me out to distinguish between the two. Thanks",2011/09/11,"['https://math.stackexchange.com/questions/63563', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']",a one to one function can be injective or bijective but a one to one correspondence can only be bijective,"I would say (hand waveingly) a one to one function is a mapping from A to B that puts A & B into one-to-one correspondence with each other, for one to one and function as defined in your previous questions." 63563,"I am confused in the difference between one to one function and one to one correspondence. Please help me out to distinguish between the two. Thanks",2011/09/11,"['https://math.stackexchange.com/questions/63563', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']","Hope this helps you understand things a bit better. I too had the same question a while ago... **Types of Mappings/Functions** a. **Injective mapping (injection)**: **one-to-one mapping** = is a function that preserves distinctness: it never maps distinct elements of its domain to the same element of its codomain. b. **Surjection**: onto mapping = a function f from a set X to a set Y is surjective (or onto), or a surjection, if for every element y in the codomain Y of f there is at least one element x in the domain X of f such that f(x) = y. It is not required that x be unique; the function f may map one or more elements of X to the same element of Y. c. **Bijective mapping (bijection)**: one-to-one and onto mapping = **one-to-one correspondence** [NOTE: bijectivity (one-to-one **correspondence**) is a necessary condition for functions to have inverses, whereas injectivity (one-to-one **mapping**) solely will not help in guaranteeing inverses]. [![Pictorial representations of these mappings](https://i.stack.imgur.com/QdE2r.png)](https://i.stack.imgur.com/QdE2r.png)","I would say (hand waveingly) a one to one function is a mapping from A to B that puts A & B into one-to-one correspondence with each other, for one to one and function as defined in your previous questions." 63563,"I am confused in the difference between one to one function and one to one correspondence. Please help me out to distinguish between the two. Thanks",2011/09/11,"['https://math.stackexchange.com/questions/63563', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']","I would say (hand waveingly) a one to one function is a mapping from A to B that puts A & B into one-to-one correspondence with each other, for one to one and function as defined in your previous questions.","1. one to one means injective (a mapping $f$ which maps distinct elements of its domain to distinct elements of its codomain, i.e. $f(x) \neq f(y)$ whenever $x \neq y$ ) 2. one to one correspondence means bijective (a mapping $f$ which is injective AND for every element $y$ in the codomain of $f$, there exists an element of $x$ in the domain of $f$ such that $f(x) = y$ )" 63563,"I am confused in the difference between one to one function and one to one correspondence. Please help me out to distinguish between the two. Thanks",2011/09/11,"['https://math.stackexchange.com/questions/63563', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']",a one to one function can be injective or bijective but a one to one correspondence can only be bijective,"1. one to one means injective (a mapping $f$ which maps distinct elements of its domain to distinct elements of its codomain, i.e. $f(x) \neq f(y)$ whenever $x \neq y$ ) 2. one to one correspondence means bijective (a mapping $f$ which is injective AND for every element $y$ in the codomain of $f$, there exists an element of $x$ in the domain of $f$ such that $f(x) = y$ )" 63563,"I am confused in the difference between one to one function and one to one correspondence. Please help me out to distinguish between the two. Thanks",2011/09/11,"['https://math.stackexchange.com/questions/63563', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']","Hope this helps you understand things a bit better. I too had the same question a while ago... **Types of Mappings/Functions** a. **Injective mapping (injection)**: **one-to-one mapping** = is a function that preserves distinctness: it never maps distinct elements of its domain to the same element of its codomain. b. **Surjection**: onto mapping = a function f from a set X to a set Y is surjective (or onto), or a surjection, if for every element y in the codomain Y of f there is at least one element x in the domain X of f such that f(x) = y. It is not required that x be unique; the function f may map one or more elements of X to the same element of Y. c. **Bijective mapping (bijection)**: one-to-one and onto mapping = **one-to-one correspondence** [NOTE: bijectivity (one-to-one **correspondence**) is a necessary condition for functions to have inverses, whereas injectivity (one-to-one **mapping**) solely will not help in guaranteeing inverses]. [![Pictorial representations of these mappings](https://i.stack.imgur.com/QdE2r.png)](https://i.stack.imgur.com/QdE2r.png)","1. one to one means injective (a mapping $f$ which maps distinct elements of its domain to distinct elements of its codomain, i.e. $f(x) \neq f(y)$ whenever $x \neq y$ ) 2. one to one correspondence means bijective (a mapping $f$ which is injective AND for every element $y$ in the codomain of $f$, there exists an element of $x$ in the domain of $f$ such that $f(x) = y$ )" 145334,"One of the players of the oneshot campaign that I'm writing chose the feat **Pierce Magical Concealment** (Complete Arcane, p.81), as a DM I'm not sure how it would work in an encounter I am planning. The manual states about the Pierce Magical Concealment feat: > > You ignore the miss chance provided by certain magical effects. > > > Your fierce contempt for magic allows you to disregard the miss chance granted by spells or spell-like abilities such as *darkness*, *blur*, *invisibility*, *obscuring mist*, *ghostform* (see page 109), and spells when used to create concealment effects (such as a wizard using *permanent image* to fill a corridor with illusory fire and smoke). In addition, when facing a creature protected by *mirror image*, you can immediately pick out the real creature from its figments. Your ability to ignore the miss chance granted by magical concealment doesn't grant you any ability to ignore nonmagical concealment (so you would still have a 20% miss chance against an invisible creature hiding in fog, for example). > > > This doesn't specify if a character with this feat can actually **see** an enemy that is, for example, under the effect of the spell **Invisibility** (Player's Handbook, p. 245). I am planning an encounter in which the party will be invited by a wizard for dinner, an assassin under the effect of invisibility will pretend to be an **Unseen Servant** (Player's Handbook, p. 297) until the wizard gives him the signal to attack the party. Will the character that has the **Pierce Magical Concealment** feat be able to see the assassin, or at least have any advantage in noticing he is not an Unseen Servant?",2019/04/17,"['https://rpg.stackexchange.com/questions/145334', 'https://rpg.stackexchange.com', 'https://rpg.stackexchange.com/users/51527/']","The feat indeed doesn't specify if the character can or cannot see its target and the final decision would be up to the GM. However we still have some pieces of information to use to try to find a more satisfying answer. If you proceed logically, the 50% miss chance when attacking an invisible target results from the Total Concealment, which implies that the character doesn't attack directly the creature, but the square it occupies : > > You can’t attack an opponent that has total concealment, though you > can attack into a square that you think he occupies. A successful > attack into a square occupied by an enemy with total concealment has a > 50% miss chance > > > Therefore ignoring these 50% miss chance would imply that the character doesn't attack the square anymore but directly the creature and so has a way to distinguish it. Note that being able to distinguish the invisible creature doesn't necessarily involve that it can see it properly. For your example, the character could be able to see the assassin as a shapeless form, being enough to target it if he wants to attack him, but not enough to be able to say if it really is an Unseen servant or not (especially as the Unseen servant is described as a *shapeless force*). By this way, you can create a clear difference between this feat and other features that are clearly designed to allow to see the invisible like the See Invisibility spell, avoiding to make such features obsolete because of this feat.","No. You can negate the miss chance for concealment, but that doesn't mean you can see invisibility. It is not explained how this works, so there is no textual basis for believing you could distinguish between an unseen servant and an assassin. Perhaps you can see a glowing interface layer, perhaps there is some distortion at the creature boundary, perhaps you're mildly precognitive. On the other hand, you probably do need opposed disguise/spot checks for the assassin to imitate an invisible stalker (likely with a very large bonus for the assassin). Were I running that game, I would be inclined to allow a generic circumstance bonus to those spot checks for the ability to Pierce Magical Concealment." 25353460,"I have set up a query and a cursor. My problem is my cursor seems to be moving 1 column at a time. my table is set up with first column as the description string, second column is the grade value and the third column is the weight value. this is my query: ``` String[] columns = {Calc_db.COLUMN_GRADE_VALUE, Calc_db.COLUMN_WEIGHT_VALUE}; Cursor cursor = openClass.getBd().query(Calc_db.TABLE_NAME, columns, null, null, null, null, null); ``` I am trying to retrieve the grade and weight value so I can put them in a list. ``` cursor.moveToFirst(); while (cursor.moveToNext()){ Double dbGrade = cursor.getDouble(cursor.getColumnIndex(Calc_db.COLUMN_GRADE_VALUE)); //cursor.moveToNext(); Double dbWeight = cursor.getDouble(cursor.getColumnIndex(Calc_db.COLUMN_WEIGHT_VALUE)); gradeWeightList.add(dbGrade); gradeWeightList.add(dbWeight); ``` My problem is the cursor is going through 1 column at a time for each loop iteration. It is also going through all 3 columns even though I am only selecting for the second 2 (grade and weight). example: If i input : description, 0.7, 0.5 (row 1) decript, 0.6, 0.4 (row 2) I receive: loop 1: grade = 0.7, weight = 0.0 loop 2: grade = 0.7, weight = 0.5 loop 3: grade = 0.7, weight = 0.5 loop 4: grade = 0.6, weight = 0.5 loop 5: grade = 0.6, weight = 0.4 What I want is for loop 1: grade = 0.7, weight = 0.5 loop 2: grade = 0.6, weight = 0.4",2014/08/17,"['https://Stackoverflow.com/questions/25353460', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3943131/']","I see some bugs in your code. **First bug**: ``` cursor.moveToFirst(); while (cursor.moveToNext()) { ... } ``` This code will skip the first row. You are moving to the first row with `moveToFirst`, then you are moving to the second row with `moveToNext` when the `while` loop condition is evaluated. In general, I prefer to iterate over a cursor using a `for` loop like so: ``` for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { ... } ``` This code will work no matter what position the cursor was at before the `for` loop started. **Second bug**: ``` Double dbGrade = cursor.getDouble(...); Double dbWeight = cursor.getDouble(...); gradeWeightList.add(dbGrade); gradeWeightList.add(dbWeight); ``` Notice you are adding both doubles to the same list (which you call `gradeWeightList`). I presume you have different lists for the grades and weights? While you could simply change the line that is incorrect, you might want to consider making a class that encapsulates the grade data, e.g. ``` public class GradeData { double grade; double gradeWeight; /* constructors and methods omitted */ } ``` ... and use a single list of this type of object. For each row, make a new instance of this class, set its properties, and add it to your list. That way you aren't trying to manage disparate lists and keep them all in sync, especially if you decide that your grade data needs more attributes (which in your current implementation would mean adding a third list).","You first go in to the first row by `moveToFirst` and then in the if statement you move the cursor to the second row. You should do something like this: ``` if(cursor.moveToFirst) { do { // Your Code } while (cursor.moveToNext()) } ```" 25353460,"I have set up a query and a cursor. My problem is my cursor seems to be moving 1 column at a time. my table is set up with first column as the description string, second column is the grade value and the third column is the weight value. this is my query: ``` String[] columns = {Calc_db.COLUMN_GRADE_VALUE, Calc_db.COLUMN_WEIGHT_VALUE}; Cursor cursor = openClass.getBd().query(Calc_db.TABLE_NAME, columns, null, null, null, null, null); ``` I am trying to retrieve the grade and weight value so I can put them in a list. ``` cursor.moveToFirst(); while (cursor.moveToNext()){ Double dbGrade = cursor.getDouble(cursor.getColumnIndex(Calc_db.COLUMN_GRADE_VALUE)); //cursor.moveToNext(); Double dbWeight = cursor.getDouble(cursor.getColumnIndex(Calc_db.COLUMN_WEIGHT_VALUE)); gradeWeightList.add(dbGrade); gradeWeightList.add(dbWeight); ``` My problem is the cursor is going through 1 column at a time for each loop iteration. It is also going through all 3 columns even though I am only selecting for the second 2 (grade and weight). example: If i input : description, 0.7, 0.5 (row 1) decript, 0.6, 0.4 (row 2) I receive: loop 1: grade = 0.7, weight = 0.0 loop 2: grade = 0.7, weight = 0.5 loop 3: grade = 0.7, weight = 0.5 loop 4: grade = 0.6, weight = 0.5 loop 5: grade = 0.6, weight = 0.4 What I want is for loop 1: grade = 0.7, weight = 0.5 loop 2: grade = 0.6, weight = 0.4",2014/08/17,"['https://Stackoverflow.com/questions/25353460', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3943131/']","I see some bugs in your code. **First bug**: ``` cursor.moveToFirst(); while (cursor.moveToNext()) { ... } ``` This code will skip the first row. You are moving to the first row with `moveToFirst`, then you are moving to the second row with `moveToNext` when the `while` loop condition is evaluated. In general, I prefer to iterate over a cursor using a `for` loop like so: ``` for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { ... } ``` This code will work no matter what position the cursor was at before the `for` loop started. **Second bug**: ``` Double dbGrade = cursor.getDouble(...); Double dbWeight = cursor.getDouble(...); gradeWeightList.add(dbGrade); gradeWeightList.add(dbWeight); ``` Notice you are adding both doubles to the same list (which you call `gradeWeightList`). I presume you have different lists for the grades and weights? While you could simply change the line that is incorrect, you might want to consider making a class that encapsulates the grade data, e.g. ``` public class GradeData { double grade; double gradeWeight; /* constructors and methods omitted */ } ``` ... and use a single list of this type of object. For each row, make a new instance of this class, set its properties, and add it to your list. That way you aren't trying to manage disparate lists and keep them all in sync, especially if you decide that your grade data needs more attributes (which in your current implementation would mean adding a third list).","For those of interested this is how I fixed my problem: (Thanks for the advice Karakuri) ``` public List populateList(){ List gradeWeightList = new ArrayList(); Cursor cursor = data.getBd().query(Calc_db.TABLE_NAME, null, null, null, null, null, null); for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { String dbDescript = cursor.getString(cursor.getColumnIndex(Calc_db.COLUMN_DESCRIPTION_VALUE)); Double dbGrade = cursor.getDouble(cursor.getColumnIndex(Calc_db.COLUMN_GRADE_VALUE)); Double dbWeight = cursor.getDouble(cursor.getColumnIndex(Calc_db.COLUMN_WEIGHT_VALUE)); Entry e1 = new Entry (dbDescript, dbGrade, dbWeight); gradeWeightList.add(e1); } cursor.close(); return gradeWeightList; } ``` Entry Class ``` public class Entry { private double GRADE; private double WEIGHT; private String DESCRIPT; public Entry(){ GRADE = 0; WEIGHT = 0; DESCRIPT = "" ""; } public Entry(String description, double grade, double weight){ GRADE = grade; WEIGHT = weight; DESCRIPT = description; } public String getDESCRIPT(){ return DESCRIPT; } public double getGRADE(){ return GRADE; } public double getWEIGHT(){ return WEIGHT; } public void setDESCRIPT(String description){ DESCRIPT = description; } public void setGRADE(double grade){ GRADE = grade; } public void setWEIGHT(double weight){ WEIGHT = weight; } ``` }" 25353460,"I have set up a query and a cursor. My problem is my cursor seems to be moving 1 column at a time. my table is set up with first column as the description string, second column is the grade value and the third column is the weight value. this is my query: ``` String[] columns = {Calc_db.COLUMN_GRADE_VALUE, Calc_db.COLUMN_WEIGHT_VALUE}; Cursor cursor = openClass.getBd().query(Calc_db.TABLE_NAME, columns, null, null, null, null, null); ``` I am trying to retrieve the grade and weight value so I can put them in a list. ``` cursor.moveToFirst(); while (cursor.moveToNext()){ Double dbGrade = cursor.getDouble(cursor.getColumnIndex(Calc_db.COLUMN_GRADE_VALUE)); //cursor.moveToNext(); Double dbWeight = cursor.getDouble(cursor.getColumnIndex(Calc_db.COLUMN_WEIGHT_VALUE)); gradeWeightList.add(dbGrade); gradeWeightList.add(dbWeight); ``` My problem is the cursor is going through 1 column at a time for each loop iteration. It is also going through all 3 columns even though I am only selecting for the second 2 (grade and weight). example: If i input : description, 0.7, 0.5 (row 1) decript, 0.6, 0.4 (row 2) I receive: loop 1: grade = 0.7, weight = 0.0 loop 2: grade = 0.7, weight = 0.5 loop 3: grade = 0.7, weight = 0.5 loop 4: grade = 0.6, weight = 0.5 loop 5: grade = 0.6, weight = 0.4 What I want is for loop 1: grade = 0.7, weight = 0.5 loop 2: grade = 0.6, weight = 0.4",2014/08/17,"['https://Stackoverflow.com/questions/25353460', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3943131/']","You first go in to the first row by `moveToFirst` and then in the if statement you move the cursor to the second row. You should do something like this: ``` if(cursor.moveToFirst) { do { // Your Code } while (cursor.moveToNext()) } ```","For those of interested this is how I fixed my problem: (Thanks for the advice Karakuri) ``` public List populateList(){ List gradeWeightList = new ArrayList(); Cursor cursor = data.getBd().query(Calc_db.TABLE_NAME, null, null, null, null, null, null); for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { String dbDescript = cursor.getString(cursor.getColumnIndex(Calc_db.COLUMN_DESCRIPTION_VALUE)); Double dbGrade = cursor.getDouble(cursor.getColumnIndex(Calc_db.COLUMN_GRADE_VALUE)); Double dbWeight = cursor.getDouble(cursor.getColumnIndex(Calc_db.COLUMN_WEIGHT_VALUE)); Entry e1 = new Entry (dbDescript, dbGrade, dbWeight); gradeWeightList.add(e1); } cursor.close(); return gradeWeightList; } ``` Entry Class ``` public class Entry { private double GRADE; private double WEIGHT; private String DESCRIPT; public Entry(){ GRADE = 0; WEIGHT = 0; DESCRIPT = "" ""; } public Entry(String description, double grade, double weight){ GRADE = grade; WEIGHT = weight; DESCRIPT = description; } public String getDESCRIPT(){ return DESCRIPT; } public double getGRADE(){ return GRADE; } public double getWEIGHT(){ return WEIGHT; } public void setDESCRIPT(String description){ DESCRIPT = description; } public void setGRADE(double grade){ GRADE = grade; } public void setWEIGHT(double weight){ WEIGHT = weight; } ``` }" 61611313,"I have a dropdown and a button, how would I go on about making the dropdown the same size as the button? ```css :root { --navbarbgc: rgb(83, 79, 79); --dropwidth: 100px; } body { margin: 0; } ul { list-style: none; } .navbar { background-color: var(--navbarbgc); } .navbar>ul>li>button { width: var(--dropwidth); } #navdrop { position: absolute; background-color: var(--navbarbgc); justify-content: center; } ``` ```html
    • Option1
    • Option2
    • Option3
    • Option4
    • Option5
    • Option6
    • Option7
``` I tried making a variable and then putting the same size to them but that didn't work.",2020/05/05,"['https://Stackoverflow.com/questions/61611313', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13124037/']","What I did Added class `button-li` to the `li` element which has `button` And added this css ``` #navdrop { position: absolute; background-color: var(--navbarbgc); justify-content: center; padding: 0; width: 100%; } .button-li { display: inline-block; position: relative; } ``` Fiddle ","Here I gave **button** **width** of **100px**, removed **padding** from **#navdrop** and gave **width** of **100px** to **#navdrop** (same as button) then I just centered the text using **text-align**. you should **NOT** be using **justify-content** because it does nothing for you right now. use **justify-content** with Flex ``` #navdrop { position: absolute; background-color: var(--navbarbgc); width: 100px; padding-left: 0px; text-align: center; } #navdropbutton { width: 100px; } ``` **Fiddle**: " 61611313,"I have a dropdown and a button, how would I go on about making the dropdown the same size as the button? ```css :root { --navbarbgc: rgb(83, 79, 79); --dropwidth: 100px; } body { margin: 0; } ul { list-style: none; } .navbar { background-color: var(--navbarbgc); } .navbar>ul>li>button { width: var(--dropwidth); } #navdrop { position: absolute; background-color: var(--navbarbgc); justify-content: center; } ``` ```html
    • Option1
    • Option2
    • Option3
    • Option4
    • Option5
    • Option6
    • Option7
``` I tried making a variable and then putting the same size to them but that didn't work.",2020/05/05,"['https://Stackoverflow.com/questions/61611313', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13124037/']","What I did Added class `button-li` to the `li` element which has `button` And added this css ``` #navdrop { position: absolute; background-color: var(--navbarbgc); justify-content: center; padding: 0; width: 100%; } .button-li { display: inline-block; position: relative; } ``` Fiddle ","you can add w-100 to the dropdown-menu class part ``` ```" 61611313,"I have a dropdown and a button, how would I go on about making the dropdown the same size as the button? ```css :root { --navbarbgc: rgb(83, 79, 79); --dropwidth: 100px; } body { margin: 0; } ul { list-style: none; } .navbar { background-color: var(--navbarbgc); } .navbar>ul>li>button { width: var(--dropwidth); } #navdrop { position: absolute; background-color: var(--navbarbgc); justify-content: center; } ``` ```html
    • Option1
    • Option2
    • Option3
    • Option4
    • Option5
    • Option6
    • Option7
``` I tried making a variable and then putting the same size to them but that didn't work.",2020/05/05,"['https://Stackoverflow.com/questions/61611313', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13124037/']","Here I gave **button** **width** of **100px**, removed **padding** from **#navdrop** and gave **width** of **100px** to **#navdrop** (same as button) then I just centered the text using **text-align**. you should **NOT** be using **justify-content** because it does nothing for you right now. use **justify-content** with Flex ``` #navdrop { position: absolute; background-color: var(--navbarbgc); width: 100px; padding-left: 0px; text-align: center; } #navdropbutton { width: 100px; } ``` **Fiddle**: ","you can add w-100 to the dropdown-menu class part ``` ```" 424696,"I need to write a very simple shell script that will check if the system is configured to enforce multi-factor authentication. To verify that the system is configured to enforce multi-factor authentication, run the following commands: ``` /usr/sbin/system_profiler SPConfigurationProfileDataType | /usr/bin/grep enforceSmartCard ``` If the results do not show ""**enforceSmartCard=1**"", this is a finding. I created this very simple script, but I am pretty sure there is a more effective, elegant and efficient way to achieve the same result. Basically if it was you, what kind of modifications would you apply to the script below to achieve the same results? Thank you so much in advance for your help. ``` #!/bin/zsh myVAR=`/usr/sbin/system_profiler SPConfigurationProfileDataType | /usr/bin/grep enforceSmartCard` if [ $myVAR = ""enforceSmartCard=1"" ] then echo ""The system is configured to enforce multi-factor authentication"" else echo ""The system is not configured to enforce multi-factor authentication"" fi ```",2021/07/27,"['https://apple.stackexchange.com/questions/424696', 'https://apple.stackexchange.com', 'https://apple.stackexchange.com/users/219530/']","This might be a little more elegant, not necessarily *simpler*: I'm wrapping the parts of the pipeline in their own functions ```bsh profile () { /usr/sbin/system_profiler SPConfigurationProfileDataType; } enforces2fa () { /usr/bin/grep -F -q 'enforceSmartCard=1'; } if profile | enforces2fa; then echo ""The system is configured to enforce multi-factor authentication"" else echo ""The system is not configured to enforce multi-factor authentication"" fi ``` Some notes * prefer `$(...)` over ``...`` for command substitution: it's easier to read. * `if` takes a *command* and branches based on the command's *exit status*. At a bash prompt, enter `help if` for more details. + `[` is a bash builtin command, not just syntax. * if ""enforceSmartCard=1"" is the only text on the line, add `-x` to the grep options. Additionally, you can modify the PATH in your script to streamline the functions ```bsh PATH=$(getconf PATH) # /usr/bin:/bin:/usr/sbin:/sbin profile () { system_profiler SPConfigurationProfileDataType; } enforces2fa () { grep -F -q 'enforceSmartCard=1'; } ``` This is only in effect for the duration of the running script, and will not affect your interactive shell.","I'd be inclined to read the value of the **`enforceSmartCard`** key directly from the *`com.apple.security.smartcard.plist`* file located in the *`/Library/Preferences`* folder. This can be done using the `defaults` command-line tool, which will be significantly faster than the `system_profiler`, and you won't need to `grep` its output: **``` defaults read /Library/Preferences/com.apple.security.smartcard enforceSmartCard ```** Here are the possible outputs for the `system_profiler | grep` and `defaults` commands, together with their meaning: | `system_profiler | grep` | `defaults` | | | --- | --- | --- | | `enforceSmartCard=0` | 0 | The `enforceSmartCard` key is set,and its value is `false` | | `enforceSmartCard=1` | 1 | The `enforceSmartCard` key is set,and its value is `true` | | *non-zero exit status* | *Error message* and*non-zero exit status* | The `enforceSmartCard` key is *not*set, **or** (`defaults` only) the propertylist does not exist | The default value for `enforceSmartCard` is `false`, therefore a non-zero exit status is essentially equivalent in meaning—for our purposes—to `enforceSmartCard=0`. In the case of the `defaults` command, an error message is also printed that looks something like this: ``` The domain/default pair of (/Library/Preferences/com.apple.security.smartcard, enforceSmartCard) does not exist ``` so, provided there isn't a typographical error when you issue the command, then either the file */Library/Preferences/com.apple.security.smartcard.plist* does not exist, or it does and the `enforceSmartCard` key is not set. Either way, the error message is of little value, so this can be suppressed by redirecting *`stderr`* into the void: ``` defaults read /Library/Preferences/com.apple.security.smartcard enforceSmartCard 2>/dev/null ``` Thus, the predicate we discriminate upon will be whether or not this command outputs `""1""` (without quotes): if it does, then a user must authenticate using their smart card (in addition to whatever other form of authentication would be required); any other result (either an output of `""0""`, or a non-zero exit status with no output) infers that a user may authenticate without using a smart card. Here's the final script that should be equivalent to yours: ``` #!/usr/bin/env zsh plist=/Library/Preferences/com.apple.security.smartcard (( $( defaults read ""$plist"" \ enforceSmartCard 2>/dev/null ) )) && i=1 _not= || i=2 _not=not printf '%s ' The system is ${_not} configured to \ enforce multi-factor authentication \ >/dev/fd/$i ```" 17317465,"I found that jQuery change event on a textbox doesn't fire until I click outside the textbox. HTML: ``` ``` JS: ``` $(""#textbox"").change(function() {alert(""Change detected!"");}); ``` See [demo on JSFiddle](http://jsfiddle.net/K682b/) My application requires the event to be fired on every character change in the textbox. I even tried using keyup instead... ``` $(""#textbox"").keyup(function() {alert(""Keyup detected!"");}); ``` ...but it's a known fact that the keyup event isn't fired on right-click-and-paste. Any workaround? Is having both listeners going to cause any problems?",2013/06/26,"['https://Stackoverflow.com/questions/17317465', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/979621/']","Try this: ``` $(""#textbox"").bind('paste',function() {alert(""Change detected!"");}); ``` See [demo on JSFiddle](http://jsfiddle.net/K682b/3/).","Reading your comments took me to a dirty fix. This is not a right way, I know, but can be a work around. ``` $(function() { $( ""#inputFieldId"" ).autocomplete({ source: function( event, ui ) { alert(""do your functions here""); return false; } }); }); ```" 17317465,"I found that jQuery change event on a textbox doesn't fire until I click outside the textbox. HTML: ``` ``` JS: ``` $(""#textbox"").change(function() {alert(""Change detected!"");}); ``` See [demo on JSFiddle](http://jsfiddle.net/K682b/) My application requires the event to be fired on every character change in the textbox. I even tried using keyup instead... ``` $(""#textbox"").keyup(function() {alert(""Keyup detected!"");}); ``` ...but it's a known fact that the keyup event isn't fired on right-click-and-paste. Any workaround? Is having both listeners going to cause any problems?",2013/06/26,"['https://Stackoverflow.com/questions/17317465', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/979621/']","On modern browsers, you can use [the `input` event](https://developer.mozilla.org/en-US/docs/Web/Events/input): [DEMO](http://jsfiddle.net/K682b/6/) ``` $(""#textbox"").on('input',function() {alert(""Change detected!"");}); ```","``` if you write anything in your textbox, the event gets fired. code as follows : ``` HTML: ``` ``` JS: ``` ```" 17317465,"I found that jQuery change event on a textbox doesn't fire until I click outside the textbox. HTML: ``` ``` JS: ``` $(""#textbox"").change(function() {alert(""Change detected!"");}); ``` See [demo on JSFiddle](http://jsfiddle.net/K682b/) My application requires the event to be fired on every character change in the textbox. I even tried using keyup instead... ``` $(""#textbox"").keyup(function() {alert(""Keyup detected!"");}); ``` ...but it's a known fact that the keyup event isn't fired on right-click-and-paste. Any workaround? Is having both listeners going to cause any problems?",2013/06/26,"['https://Stackoverflow.com/questions/17317465', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/979621/']","On modern browsers, you can use [the `input` event](https://developer.mozilla.org/en-US/docs/Web/Events/input): [DEMO](http://jsfiddle.net/K682b/6/) ``` $(""#textbox"").on('input',function() {alert(""Change detected!"");}); ```","Try this: ``` $(""#textbox"").bind('paste',function() {alert(""Change detected!"");}); ``` See [demo on JSFiddle](http://jsfiddle.net/K682b/3/)." 17317465,"I found that jQuery change event on a textbox doesn't fire until I click outside the textbox. HTML: ``` ``` JS: ``` $(""#textbox"").change(function() {alert(""Change detected!"");}); ``` See [demo on JSFiddle](http://jsfiddle.net/K682b/) My application requires the event to be fired on every character change in the textbox. I even tried using keyup instead... ``` $(""#textbox"").keyup(function() {alert(""Keyup detected!"");}); ``` ...but it's a known fact that the keyup event isn't fired on right-click-and-paste. Any workaround? Is having both listeners going to cause any problems?",2013/06/26,"['https://Stackoverflow.com/questions/17317465', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/979621/']","On modern browsers, you can use [the `input` event](https://developer.mozilla.org/en-US/docs/Web/Events/input): [DEMO](http://jsfiddle.net/K682b/6/) ``` $(""#textbox"").on('input',function() {alert(""Change detected!"");}); ```","Try the below Code: ``` $(""#textbox"").on('change keypress paste', function() { console.log(""Handler for .keypress() called.""); }); ```" 17317465,"I found that jQuery change event on a textbox doesn't fire until I click outside the textbox. HTML: ``` ``` JS: ``` $(""#textbox"").change(function() {alert(""Change detected!"");}); ``` See [demo on JSFiddle](http://jsfiddle.net/K682b/) My application requires the event to be fired on every character change in the textbox. I even tried using keyup instead... ``` $(""#textbox"").keyup(function() {alert(""Keyup detected!"");}); ``` ...but it's a known fact that the keyup event isn't fired on right-click-and-paste. Any workaround? Is having both listeners going to cause any problems?",2013/06/26,"['https://Stackoverflow.com/questions/17317465', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/979621/']","``` $(this).bind('input propertychange', function() { //your code here }); ``` This is works for typing, paste, right click mouse paste etc.","Try the below Code: ``` $(""#textbox"").on('change keypress paste', function() { console.log(""Handler for .keypress() called.""); }); ```" 17317465,"I found that jQuery change event on a textbox doesn't fire until I click outside the textbox. HTML: ``` ``` JS: ``` $(""#textbox"").change(function() {alert(""Change detected!"");}); ``` See [demo on JSFiddle](http://jsfiddle.net/K682b/) My application requires the event to be fired on every character change in the textbox. I even tried using keyup instead... ``` $(""#textbox"").keyup(function() {alert(""Keyup detected!"");}); ``` ...but it's a known fact that the keyup event isn't fired on right-click-and-paste. Any workaround? Is having both listeners going to cause any problems?",2013/06/26,"['https://Stackoverflow.com/questions/17317465', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/979621/']","Binding to both events is the typical way to do it. You can also bind to the paste event. You can bind to multiple events like this: ``` $(""#textbox"").on('change keyup paste', function() { console.log('I am pretty sure the text box changed'); }); ``` If you wanted to be pedantic about it, you should also bind to mouseup to cater for dragging text around, and add a `lastValue` variable to ensure that the text actually did change: ``` var lastValue = ''; $(""#textbox"").on('change keyup paste mouseup', function() { if ($(this).val() != lastValue) { lastValue = $(this).val(); console.log('The text box really changed this time'); } }); ``` And if you want to be `super duper` pedantic then you should use an interval timer to cater for auto fill, plugins, etc: ``` var lastValue = ''; setInterval(function() { if ($(""#textbox"").val() != lastValue) { lastValue = $(""#textbox"").val(); console.log('I am definitely sure the text box realy realy changed this time'); } }, 500); ```","Reading your comments took me to a dirty fix. This is not a right way, I know, but can be a work around. ``` $(function() { $( ""#inputFieldId"" ).autocomplete({ source: function( event, ui ) { alert(""do your functions here""); return false; } }); }); ```" 17317465,"I found that jQuery change event on a textbox doesn't fire until I click outside the textbox. HTML: ``` ``` JS: ``` $(""#textbox"").change(function() {alert(""Change detected!"");}); ``` See [demo on JSFiddle](http://jsfiddle.net/K682b/) My application requires the event to be fired on every character change in the textbox. I even tried using keyup instead... ``` $(""#textbox"").keyup(function() {alert(""Keyup detected!"");}); ``` ...but it's a known fact that the keyup event isn't fired on right-click-and-paste. Any workaround? Is having both listeners going to cause any problems?",2013/06/26,"['https://Stackoverflow.com/questions/17317465', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/979621/']","``` if you write anything in your textbox, the event gets fired. code as follows : ``` HTML: ``` ``` JS: ``` ```","Try the below Code: ``` $(""#textbox"").on('change keypress paste', function() { console.log(""Handler for .keypress() called.""); }); ```" 17317465,"I found that jQuery change event on a textbox doesn't fire until I click outside the textbox. HTML: ``` ``` JS: ``` $(""#textbox"").change(function() {alert(""Change detected!"");}); ``` See [demo on JSFiddle](http://jsfiddle.net/K682b/) My application requires the event to be fired on every character change in the textbox. I even tried using keyup instead... ``` $(""#textbox"").keyup(function() {alert(""Keyup detected!"");}); ``` ...but it's a known fact that the keyup event isn't fired on right-click-and-paste. Any workaround? Is having both listeners going to cause any problems?",2013/06/26,"['https://Stackoverflow.com/questions/17317465', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/979621/']","Binding to both events is the typical way to do it. You can also bind to the paste event. You can bind to multiple events like this: ``` $(""#textbox"").on('change keyup paste', function() { console.log('I am pretty sure the text box changed'); }); ``` If you wanted to be pedantic about it, you should also bind to mouseup to cater for dragging text around, and add a `lastValue` variable to ensure that the text actually did change: ``` var lastValue = ''; $(""#textbox"").on('change keyup paste mouseup', function() { if ($(this).val() != lastValue) { lastValue = $(this).val(); console.log('The text box really changed this time'); } }); ``` And if you want to be `super duper` pedantic then you should use an interval timer to cater for auto fill, plugins, etc: ``` var lastValue = ''; setInterval(function() { if ($(""#textbox"").val() != lastValue) { lastValue = $(""#textbox"").val(); console.log('I am definitely sure the text box realy realy changed this time'); } }, 500); ```","``` if you write anything in your textbox, the event gets fired. code as follows : ``` HTML: ``` ``` JS: ``` ```" 17317465,"I found that jQuery change event on a textbox doesn't fire until I click outside the textbox. HTML: ``` ``` JS: ``` $(""#textbox"").change(function() {alert(""Change detected!"");}); ``` See [demo on JSFiddle](http://jsfiddle.net/K682b/) My application requires the event to be fired on every character change in the textbox. I even tried using keyup instead... ``` $(""#textbox"").keyup(function() {alert(""Keyup detected!"");}); ``` ...but it's a known fact that the keyup event isn't fired on right-click-and-paste. Any workaround? Is having both listeners going to cause any problems?",2013/06/26,"['https://Stackoverflow.com/questions/17317465', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/979621/']","``` if you write anything in your textbox, the event gets fired. code as follows : ``` HTML: ``` ``` JS: ``` ```","Reading your comments took me to a dirty fix. This is not a right way, I know, but can be a work around. ``` $(function() { $( ""#inputFieldId"" ).autocomplete({ source: function( event, ui ) { alert(""do your functions here""); return false; } }); }); ```" 17317465,"I found that jQuery change event on a textbox doesn't fire until I click outside the textbox. HTML: ``` ``` JS: ``` $(""#textbox"").change(function() {alert(""Change detected!"");}); ``` See [demo on JSFiddle](http://jsfiddle.net/K682b/) My application requires the event to be fired on every character change in the textbox. I even tried using keyup instead... ``` $(""#textbox"").keyup(function() {alert(""Keyup detected!"");}); ``` ...but it's a known fact that the keyup event isn't fired on right-click-and-paste. Any workaround? Is having both listeners going to cause any problems?",2013/06/26,"['https://Stackoverflow.com/questions/17317465', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/979621/']","On modern browsers, you can use [the `input` event](https://developer.mozilla.org/en-US/docs/Web/Events/input): [DEMO](http://jsfiddle.net/K682b/6/) ``` $(""#textbox"").on('input',function() {alert(""Change detected!"");}); ```","Reading your comments took me to a dirty fix. This is not a right way, I know, but can be a work around. ``` $(function() { $( ""#inputFieldId"" ).autocomplete({ source: function( event, ui ) { alert(""do your functions here""); return false; } }); }); ```" 46257191,"I'm not getting the response I expect. This is the controller code for a Location web-service request: ``` validate( array( 'name' => 'required|alpha_num', 'user_id' => 'required|integer', ), array( 'name.required' => 'Name is required', 'name.string' => 'Name must be alphanumeric', 'user_id.required' => 'Curator User Id is required', 'user_id.required' => 'Curator User Id must be an integer', ) ); } catch (\Exception $ex) { $arrResponse = array( 'result' => 0, 'reason' => $ex->getMessage(), 'data' => array(), 'statusCode' => 404 ); } finally { return response()->json($arrResponse); } } } ``` The request is !^ The response reason I expect is: { ""result"": 0, ""reason"": ""Name must be alphanumeric"", ""data"": [], ""statusCode"": 404 } The actual response I get instead is: { ""result"": 0, ""reason"": ""The given data was invalid."", ""data"": [], ""statusCode"": 404 } Please help. This is bugging me.",2017/09/16,"['https://Stackoverflow.com/questions/46257191', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3125602/']","I've finally discovered why this isn't working. It's not an issue of errors in the implementing code or Laravel, but one of either: (i). writing good PHP code to handle the self-evident result, which clearly I didn't do; (ii). insufficient documentation within Laravel on how to actually use the validation error response. Take your pick. Laravel's validation throws a Illuminate\Validation\ValidationError. Believe it or not, this actually defaults the error message to ""The given data was invalid."", so when you catch an \Exception and retrieve its $e->getMessage(), this default error-message is what you (correctly) get. What you need to do is capture the \Illuminate\Validation\ValidationError - which I should've done originally, duh! - and then use its methods to help you distill the error messages from it. Here's the solution I've come up with: ``` 'required|alpha_num', 'user_id' => 'required|integer', ); $p_oRequest->validate( $arrValid, array( 'name.required' => 'Name is missing', 'name.alpha_num' => 'Name must be alphanumeric', 'user_id.required' => 'User Id is missing', 'user_id.integer' => 'User Id must be an integer', ) ); } catch (\Illuminate\Validation\ValidationException $e ) { /** * Validation failed * Tell the end-user why */ $arrError = $e->errors(); // Useful method - thank you Laravel /** * Compile a string of error-messages */ foreach ($arrValid as $key=>$value ) { $arrImplode[] = implode( ', ', $arrError[$key] ); } $message = implode(', ', $arrImplode); /** * Populate the respose array for the JSON */ $arrResponse = array( 'result' => 0, 'reason' => $message, 'data' => array(), 'statusCode' => $e->status, ); } catch (\Exception $ex) { $arrResponse = array( 'result' => 0, 'reason' => $ex->getMessage(), 'data' => array(), 'statusCode' => 404 ); } finally { return response()->json($arrResponse); } } } ``` So, indeed, Laravel was supplying the correct response, and did what it said on the side of the tin, but I wasn't applying it correctly. Regardless, as a help to future me and other lost PHP-mariners at Laravel-sea, I provide the solution. In addition, thanks to Marcin for pointing out my buggy coding, which would've caused a problem even if I had implemented the above solution.","Your messages should be validation rules, so instead of: ``` 'name.required' => 'Name is required', 'name.string' => 'Name must be alphanumeric', 'user_id.required' => 'Curator User Id is required', 'user_id.required' => 'Curator User Id must be an integer', ``` you should have: ``` 'name.required' => 'Name is required', 'name.alpha_num' => 'Name must be alphanumeric', 'user_id.required' => 'Curator User Id is required', 'user_id.integer' => 'Curator User Id must be an integer', ```" 46257191,"I'm not getting the response I expect. This is the controller code for a Location web-service request: ``` validate( array( 'name' => 'required|alpha_num', 'user_id' => 'required|integer', ), array( 'name.required' => 'Name is required', 'name.string' => 'Name must be alphanumeric', 'user_id.required' => 'Curator User Id is required', 'user_id.required' => 'Curator User Id must be an integer', ) ); } catch (\Exception $ex) { $arrResponse = array( 'result' => 0, 'reason' => $ex->getMessage(), 'data' => array(), 'statusCode' => 404 ); } finally { return response()->json($arrResponse); } } } ``` The request is !^ The response reason I expect is: { ""result"": 0, ""reason"": ""Name must be alphanumeric"", ""data"": [], ""statusCode"": 404 } The actual response I get instead is: { ""result"": 0, ""reason"": ""The given data was invalid."", ""data"": [], ""statusCode"": 404 } Please help. This is bugging me.",2017/09/16,"['https://Stackoverflow.com/questions/46257191', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3125602/']","The problem is probably that Laravel's default Exception handler is not prepared to relay detailed validation info back to the user. Instead, it hides Exception details from the user, which is normally the right thing to do because it might form a security risk for other Exceptions than validation ones. In other words; if the Exception Handler's `render` function (implemented in `/app/Exceptions/Handler.php`) catches your validation errors, they will be interpreted as a general application Exception and the general error message relaid to the user will always read 'The given data was invalid'. Make sure the `render` method ignores instances of `\Illuminate\Validation\ValidationException`, and you should get the response you expect: ``` public function render($request, Exception $exception) { if (! $exception instanceof \Illuminate\Validation\ValidationException)) { // ... render code for other Exceptions here } } ``` Another way to make the Exception Handler relay ValidationException details with the response would be to do something like this in the `render` method: ``` if ($exception instanceof ValidationException && $request->expectsJson()) { return response()->json(['message' => 'The given data was invalid.', 'errors' => $exception->validator->getMessageBag()], 422); } ``` Background ========== Laravel is basically (ab)using Exceptions here. Normally an Exception indicates a (runtime) problem in the code, but Laravel uses them as a mechanism to facilitate request validation and supply feedback to the user. That's why, in this case, it would be incorrect to let your Exception Handler handle the Exception -- it's not an application Exception, it's info meant for the user. The code in the answer supplied by OP works, because he catches the ValidationException himself, preventing it to be caught by the application's Exception Handler. There is no scenario in which I think that would be wanted as it's a clear mix of concerns and makes for horribly long and unreadable code. Simply ignoring ValidationExceptions or treating them differently in the Exception Handler like I showed above should do the trick just fine.","Your messages should be validation rules, so instead of: ``` 'name.required' => 'Name is required', 'name.string' => 'Name must be alphanumeric', 'user_id.required' => 'Curator User Id is required', 'user_id.required' => 'Curator User Id must be an integer', ``` you should have: ``` 'name.required' => 'Name is required', 'name.alpha_num' => 'Name must be alphanumeric', 'user_id.required' => 'Curator User Id is required', 'user_id.integer' => 'Curator User Id must be an integer', ```" 46257191,"I'm not getting the response I expect. This is the controller code for a Location web-service request: ``` validate( array( 'name' => 'required|alpha_num', 'user_id' => 'required|integer', ), array( 'name.required' => 'Name is required', 'name.string' => 'Name must be alphanumeric', 'user_id.required' => 'Curator User Id is required', 'user_id.required' => 'Curator User Id must be an integer', ) ); } catch (\Exception $ex) { $arrResponse = array( 'result' => 0, 'reason' => $ex->getMessage(), 'data' => array(), 'statusCode' => 404 ); } finally { return response()->json($arrResponse); } } } ``` The request is !^ The response reason I expect is: { ""result"": 0, ""reason"": ""Name must be alphanumeric"", ""data"": [], ""statusCode"": 404 } The actual response I get instead is: { ""result"": 0, ""reason"": ""The given data was invalid."", ""data"": [], ""statusCode"": 404 } Please help. This is bugging me.",2017/09/16,"['https://Stackoverflow.com/questions/46257191', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3125602/']","I've only just seen this but all you need to do is move the validate call **before** the try/catch ``` $p_oRequest->validate( [ 'name' => 'required|alpha_num', 'user_id' => 'required|integer', ], [ 'name.required' => 'Name is required', 'name.string' => 'Name must be alphanumeric', 'user_id.required' => 'Curator User Id is required', 'user_id.required' => 'Curator User Id must be an integer', ] ); try { ... } catch(\Exception $e) { return back()->withErrors($e->getMessage())->withInput(); } ``` Because Laravel catches the validation exception automatically and returns you back with old input and an array of errors which you can output like ``` @if ($errors->any())
    @foreach ($errors->all() as $error)
  • {{ $error }}
  • @endforeach
@endif ```","Your messages should be validation rules, so instead of: ``` 'name.required' => 'Name is required', 'name.string' => 'Name must be alphanumeric', 'user_id.required' => 'Curator User Id is required', 'user_id.required' => 'Curator User Id must be an integer', ``` you should have: ``` 'name.required' => 'Name is required', 'name.alpha_num' => 'Name must be alphanumeric', 'user_id.required' => 'Curator User Id is required', 'user_id.integer' => 'Curator User Id must be an integer', ```" 46257191,"I'm not getting the response I expect. This is the controller code for a Location web-service request: ``` validate( array( 'name' => 'required|alpha_num', 'user_id' => 'required|integer', ), array( 'name.required' => 'Name is required', 'name.string' => 'Name must be alphanumeric', 'user_id.required' => 'Curator User Id is required', 'user_id.required' => 'Curator User Id must be an integer', ) ); } catch (\Exception $ex) { $arrResponse = array( 'result' => 0, 'reason' => $ex->getMessage(), 'data' => array(), 'statusCode' => 404 ); } finally { return response()->json($arrResponse); } } } ``` The request is !^ The response reason I expect is: { ""result"": 0, ""reason"": ""Name must be alphanumeric"", ""data"": [], ""statusCode"": 404 } The actual response I get instead is: { ""result"": 0, ""reason"": ""The given data was invalid."", ""data"": [], ""statusCode"": 404 } Please help. This is bugging me.",2017/09/16,"['https://Stackoverflow.com/questions/46257191', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3125602/']","I've finally discovered why this isn't working. It's not an issue of errors in the implementing code or Laravel, but one of either: (i). writing good PHP code to handle the self-evident result, which clearly I didn't do; (ii). insufficient documentation within Laravel on how to actually use the validation error response. Take your pick. Laravel's validation throws a Illuminate\Validation\ValidationError. Believe it or not, this actually defaults the error message to ""The given data was invalid."", so when you catch an \Exception and retrieve its $e->getMessage(), this default error-message is what you (correctly) get. What you need to do is capture the \Illuminate\Validation\ValidationError - which I should've done originally, duh! - and then use its methods to help you distill the error messages from it. Here's the solution I've come up with: ``` 'required|alpha_num', 'user_id' => 'required|integer', ); $p_oRequest->validate( $arrValid, array( 'name.required' => 'Name is missing', 'name.alpha_num' => 'Name must be alphanumeric', 'user_id.required' => 'User Id is missing', 'user_id.integer' => 'User Id must be an integer', ) ); } catch (\Illuminate\Validation\ValidationException $e ) { /** * Validation failed * Tell the end-user why */ $arrError = $e->errors(); // Useful method - thank you Laravel /** * Compile a string of error-messages */ foreach ($arrValid as $key=>$value ) { $arrImplode[] = implode( ', ', $arrError[$key] ); } $message = implode(', ', $arrImplode); /** * Populate the respose array for the JSON */ $arrResponse = array( 'result' => 0, 'reason' => $message, 'data' => array(), 'statusCode' => $e->status, ); } catch (\Exception $ex) { $arrResponse = array( 'result' => 0, 'reason' => $ex->getMessage(), 'data' => array(), 'statusCode' => 404 ); } finally { return response()->json($arrResponse); } } } ``` So, indeed, Laravel was supplying the correct response, and did what it said on the side of the tin, but I wasn't applying it correctly. Regardless, as a help to future me and other lost PHP-mariners at Laravel-sea, I provide the solution. In addition, thanks to Marcin for pointing out my buggy coding, which would've caused a problem even if I had implemented the above solution.","The problem is probably that Laravel's default Exception handler is not prepared to relay detailed validation info back to the user. Instead, it hides Exception details from the user, which is normally the right thing to do because it might form a security risk for other Exceptions than validation ones. In other words; if the Exception Handler's `render` function (implemented in `/app/Exceptions/Handler.php`) catches your validation errors, they will be interpreted as a general application Exception and the general error message relaid to the user will always read 'The given data was invalid'. Make sure the `render` method ignores instances of `\Illuminate\Validation\ValidationException`, and you should get the response you expect: ``` public function render($request, Exception $exception) { if (! $exception instanceof \Illuminate\Validation\ValidationException)) { // ... render code for other Exceptions here } } ``` Another way to make the Exception Handler relay ValidationException details with the response would be to do something like this in the `render` method: ``` if ($exception instanceof ValidationException && $request->expectsJson()) { return response()->json(['message' => 'The given data was invalid.', 'errors' => $exception->validator->getMessageBag()], 422); } ``` Background ========== Laravel is basically (ab)using Exceptions here. Normally an Exception indicates a (runtime) problem in the code, but Laravel uses them as a mechanism to facilitate request validation and supply feedback to the user. That's why, in this case, it would be incorrect to let your Exception Handler handle the Exception -- it's not an application Exception, it's info meant for the user. The code in the answer supplied by OP works, because he catches the ValidationException himself, preventing it to be caught by the application's Exception Handler. There is no scenario in which I think that would be wanted as it's a clear mix of concerns and makes for horribly long and unreadable code. Simply ignoring ValidationExceptions or treating them differently in the Exception Handler like I showed above should do the trick just fine." 46257191,"I'm not getting the response I expect. This is the controller code for a Location web-service request: ``` validate( array( 'name' => 'required|alpha_num', 'user_id' => 'required|integer', ), array( 'name.required' => 'Name is required', 'name.string' => 'Name must be alphanumeric', 'user_id.required' => 'Curator User Id is required', 'user_id.required' => 'Curator User Id must be an integer', ) ); } catch (\Exception $ex) { $arrResponse = array( 'result' => 0, 'reason' => $ex->getMessage(), 'data' => array(), 'statusCode' => 404 ); } finally { return response()->json($arrResponse); } } } ``` The request is !^ The response reason I expect is: { ""result"": 0, ""reason"": ""Name must be alphanumeric"", ""data"": [], ""statusCode"": 404 } The actual response I get instead is: { ""result"": 0, ""reason"": ""The given data was invalid."", ""data"": [], ""statusCode"": 404 } Please help. This is bugging me.",2017/09/16,"['https://Stackoverflow.com/questions/46257191', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3125602/']","I've finally discovered why this isn't working. It's not an issue of errors in the implementing code or Laravel, but one of either: (i). writing good PHP code to handle the self-evident result, which clearly I didn't do; (ii). insufficient documentation within Laravel on how to actually use the validation error response. Take your pick. Laravel's validation throws a Illuminate\Validation\ValidationError. Believe it or not, this actually defaults the error message to ""The given data was invalid."", so when you catch an \Exception and retrieve its $e->getMessage(), this default error-message is what you (correctly) get. What you need to do is capture the \Illuminate\Validation\ValidationError - which I should've done originally, duh! - and then use its methods to help you distill the error messages from it. Here's the solution I've come up with: ``` 'required|alpha_num', 'user_id' => 'required|integer', ); $p_oRequest->validate( $arrValid, array( 'name.required' => 'Name is missing', 'name.alpha_num' => 'Name must be alphanumeric', 'user_id.required' => 'User Id is missing', 'user_id.integer' => 'User Id must be an integer', ) ); } catch (\Illuminate\Validation\ValidationException $e ) { /** * Validation failed * Tell the end-user why */ $arrError = $e->errors(); // Useful method - thank you Laravel /** * Compile a string of error-messages */ foreach ($arrValid as $key=>$value ) { $arrImplode[] = implode( ', ', $arrError[$key] ); } $message = implode(', ', $arrImplode); /** * Populate the respose array for the JSON */ $arrResponse = array( 'result' => 0, 'reason' => $message, 'data' => array(), 'statusCode' => $e->status, ); } catch (\Exception $ex) { $arrResponse = array( 'result' => 0, 'reason' => $ex->getMessage(), 'data' => array(), 'statusCode' => 404 ); } finally { return response()->json($arrResponse); } } } ``` So, indeed, Laravel was supplying the correct response, and did what it said on the side of the tin, but I wasn't applying it correctly. Regardless, as a help to future me and other lost PHP-mariners at Laravel-sea, I provide the solution. In addition, thanks to Marcin for pointing out my buggy coding, which would've caused a problem even if I had implemented the above solution.","I've only just seen this but all you need to do is move the validate call **before** the try/catch ``` $p_oRequest->validate( [ 'name' => 'required|alpha_num', 'user_id' => 'required|integer', ], [ 'name.required' => 'Name is required', 'name.string' => 'Name must be alphanumeric', 'user_id.required' => 'Curator User Id is required', 'user_id.required' => 'Curator User Id must be an integer', ] ); try { ... } catch(\Exception $e) { return back()->withErrors($e->getMessage())->withInput(); } ``` Because Laravel catches the validation exception automatically and returns you back with old input and an array of errors which you can output like ``` @if ($errors->any())
    @foreach ($errors->all() as $error)
  • {{ $error }}
  • @endforeach
@endif ```" 46257191,"I'm not getting the response I expect. This is the controller code for a Location web-service request: ``` validate( array( 'name' => 'required|alpha_num', 'user_id' => 'required|integer', ), array( 'name.required' => 'Name is required', 'name.string' => 'Name must be alphanumeric', 'user_id.required' => 'Curator User Id is required', 'user_id.required' => 'Curator User Id must be an integer', ) ); } catch (\Exception $ex) { $arrResponse = array( 'result' => 0, 'reason' => $ex->getMessage(), 'data' => array(), 'statusCode' => 404 ); } finally { return response()->json($arrResponse); } } } ``` The request is !^ The response reason I expect is: { ""result"": 0, ""reason"": ""Name must be alphanumeric"", ""data"": [], ""statusCode"": 404 } The actual response I get instead is: { ""result"": 0, ""reason"": ""The given data was invalid."", ""data"": [], ""statusCode"": 404 } Please help. This is bugging me.",2017/09/16,"['https://Stackoverflow.com/questions/46257191', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3125602/']","I've finally discovered why this isn't working. It's not an issue of errors in the implementing code or Laravel, but one of either: (i). writing good PHP code to handle the self-evident result, which clearly I didn't do; (ii). insufficient documentation within Laravel on how to actually use the validation error response. Take your pick. Laravel's validation throws a Illuminate\Validation\ValidationError. Believe it or not, this actually defaults the error message to ""The given data was invalid."", so when you catch an \Exception and retrieve its $e->getMessage(), this default error-message is what you (correctly) get. What you need to do is capture the \Illuminate\Validation\ValidationError - which I should've done originally, duh! - and then use its methods to help you distill the error messages from it. Here's the solution I've come up with: ``` 'required|alpha_num', 'user_id' => 'required|integer', ); $p_oRequest->validate( $arrValid, array( 'name.required' => 'Name is missing', 'name.alpha_num' => 'Name must be alphanumeric', 'user_id.required' => 'User Id is missing', 'user_id.integer' => 'User Id must be an integer', ) ); } catch (\Illuminate\Validation\ValidationException $e ) { /** * Validation failed * Tell the end-user why */ $arrError = $e->errors(); // Useful method - thank you Laravel /** * Compile a string of error-messages */ foreach ($arrValid as $key=>$value ) { $arrImplode[] = implode( ', ', $arrError[$key] ); } $message = implode(', ', $arrImplode); /** * Populate the respose array for the JSON */ $arrResponse = array( 'result' => 0, 'reason' => $message, 'data' => array(), 'statusCode' => $e->status, ); } catch (\Exception $ex) { $arrResponse = array( 'result' => 0, 'reason' => $ex->getMessage(), 'data' => array(), 'statusCode' => 404 ); } finally { return response()->json($arrResponse); } } } ``` So, indeed, Laravel was supplying the correct response, and did what it said on the side of the tin, but I wasn't applying it correctly. Regardless, as a help to future me and other lost PHP-mariners at Laravel-sea, I provide the solution. In addition, thanks to Marcin for pointing out my buggy coding, which would've caused a problem even if I had implemented the above solution.","Put the response in a variable and use dd() to print it. You will find it on the ""messages"" method. Worked for me. `dd($response);`" 46257191,"I'm not getting the response I expect. This is the controller code for a Location web-service request: ``` validate( array( 'name' => 'required|alpha_num', 'user_id' => 'required|integer', ), array( 'name.required' => 'Name is required', 'name.string' => 'Name must be alphanumeric', 'user_id.required' => 'Curator User Id is required', 'user_id.required' => 'Curator User Id must be an integer', ) ); } catch (\Exception $ex) { $arrResponse = array( 'result' => 0, 'reason' => $ex->getMessage(), 'data' => array(), 'statusCode' => 404 ); } finally { return response()->json($arrResponse); } } } ``` The request is !^ The response reason I expect is: { ""result"": 0, ""reason"": ""Name must be alphanumeric"", ""data"": [], ""statusCode"": 404 } The actual response I get instead is: { ""result"": 0, ""reason"": ""The given data was invalid."", ""data"": [], ""statusCode"": 404 } Please help. This is bugging me.",2017/09/16,"['https://Stackoverflow.com/questions/46257191', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3125602/']","The problem is probably that Laravel's default Exception handler is not prepared to relay detailed validation info back to the user. Instead, it hides Exception details from the user, which is normally the right thing to do because it might form a security risk for other Exceptions than validation ones. In other words; if the Exception Handler's `render` function (implemented in `/app/Exceptions/Handler.php`) catches your validation errors, they will be interpreted as a general application Exception and the general error message relaid to the user will always read 'The given data was invalid'. Make sure the `render` method ignores instances of `\Illuminate\Validation\ValidationException`, and you should get the response you expect: ``` public function render($request, Exception $exception) { if (! $exception instanceof \Illuminate\Validation\ValidationException)) { // ... render code for other Exceptions here } } ``` Another way to make the Exception Handler relay ValidationException details with the response would be to do something like this in the `render` method: ``` if ($exception instanceof ValidationException && $request->expectsJson()) { return response()->json(['message' => 'The given data was invalid.', 'errors' => $exception->validator->getMessageBag()], 422); } ``` Background ========== Laravel is basically (ab)using Exceptions here. Normally an Exception indicates a (runtime) problem in the code, but Laravel uses them as a mechanism to facilitate request validation and supply feedback to the user. That's why, in this case, it would be incorrect to let your Exception Handler handle the Exception -- it's not an application Exception, it's info meant for the user. The code in the answer supplied by OP works, because he catches the ValidationException himself, preventing it to be caught by the application's Exception Handler. There is no scenario in which I think that would be wanted as it's a clear mix of concerns and makes for horribly long and unreadable code. Simply ignoring ValidationExceptions or treating them differently in the Exception Handler like I showed above should do the trick just fine.","I've only just seen this but all you need to do is move the validate call **before** the try/catch ``` $p_oRequest->validate( [ 'name' => 'required|alpha_num', 'user_id' => 'required|integer', ], [ 'name.required' => 'Name is required', 'name.string' => 'Name must be alphanumeric', 'user_id.required' => 'Curator User Id is required', 'user_id.required' => 'Curator User Id must be an integer', ] ); try { ... } catch(\Exception $e) { return back()->withErrors($e->getMessage())->withInput(); } ``` Because Laravel catches the validation exception automatically and returns you back with old input and an array of errors which you can output like ``` @if ($errors->any())
    @foreach ($errors->all() as $error)
  • {{ $error }}
  • @endforeach
@endif ```" 46257191,"I'm not getting the response I expect. This is the controller code for a Location web-service request: ``` validate( array( 'name' => 'required|alpha_num', 'user_id' => 'required|integer', ), array( 'name.required' => 'Name is required', 'name.string' => 'Name must be alphanumeric', 'user_id.required' => 'Curator User Id is required', 'user_id.required' => 'Curator User Id must be an integer', ) ); } catch (\Exception $ex) { $arrResponse = array( 'result' => 0, 'reason' => $ex->getMessage(), 'data' => array(), 'statusCode' => 404 ); } finally { return response()->json($arrResponse); } } } ``` The request is !^ The response reason I expect is: { ""result"": 0, ""reason"": ""Name must be alphanumeric"", ""data"": [], ""statusCode"": 404 } The actual response I get instead is: { ""result"": 0, ""reason"": ""The given data was invalid."", ""data"": [], ""statusCode"": 404 } Please help. This is bugging me.",2017/09/16,"['https://Stackoverflow.com/questions/46257191', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3125602/']","The problem is probably that Laravel's default Exception handler is not prepared to relay detailed validation info back to the user. Instead, it hides Exception details from the user, which is normally the right thing to do because it might form a security risk for other Exceptions than validation ones. In other words; if the Exception Handler's `render` function (implemented in `/app/Exceptions/Handler.php`) catches your validation errors, they will be interpreted as a general application Exception and the general error message relaid to the user will always read 'The given data was invalid'. Make sure the `render` method ignores instances of `\Illuminate\Validation\ValidationException`, and you should get the response you expect: ``` public function render($request, Exception $exception) { if (! $exception instanceof \Illuminate\Validation\ValidationException)) { // ... render code for other Exceptions here } } ``` Another way to make the Exception Handler relay ValidationException details with the response would be to do something like this in the `render` method: ``` if ($exception instanceof ValidationException && $request->expectsJson()) { return response()->json(['message' => 'The given data was invalid.', 'errors' => $exception->validator->getMessageBag()], 422); } ``` Background ========== Laravel is basically (ab)using Exceptions here. Normally an Exception indicates a (runtime) problem in the code, but Laravel uses them as a mechanism to facilitate request validation and supply feedback to the user. That's why, in this case, it would be incorrect to let your Exception Handler handle the Exception -- it's not an application Exception, it's info meant for the user. The code in the answer supplied by OP works, because he catches the ValidationException himself, preventing it to be caught by the application's Exception Handler. There is no scenario in which I think that would be wanted as it's a clear mix of concerns and makes for horribly long and unreadable code. Simply ignoring ValidationExceptions or treating them differently in the Exception Handler like I showed above should do the trick just fine.","Put the response in a variable and use dd() to print it. You will find it on the ""messages"" method. Worked for me. `dd($response);`" 46257191,"I'm not getting the response I expect. This is the controller code for a Location web-service request: ``` validate( array( 'name' => 'required|alpha_num', 'user_id' => 'required|integer', ), array( 'name.required' => 'Name is required', 'name.string' => 'Name must be alphanumeric', 'user_id.required' => 'Curator User Id is required', 'user_id.required' => 'Curator User Id must be an integer', ) ); } catch (\Exception $ex) { $arrResponse = array( 'result' => 0, 'reason' => $ex->getMessage(), 'data' => array(), 'statusCode' => 404 ); } finally { return response()->json($arrResponse); } } } ``` The request is !^ The response reason I expect is: { ""result"": 0, ""reason"": ""Name must be alphanumeric"", ""data"": [], ""statusCode"": 404 } The actual response I get instead is: { ""result"": 0, ""reason"": ""The given data was invalid."", ""data"": [], ""statusCode"": 404 } Please help. This is bugging me.",2017/09/16,"['https://Stackoverflow.com/questions/46257191', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3125602/']","I've only just seen this but all you need to do is move the validate call **before** the try/catch ``` $p_oRequest->validate( [ 'name' => 'required|alpha_num', 'user_id' => 'required|integer', ], [ 'name.required' => 'Name is required', 'name.string' => 'Name must be alphanumeric', 'user_id.required' => 'Curator User Id is required', 'user_id.required' => 'Curator User Id must be an integer', ] ); try { ... } catch(\Exception $e) { return back()->withErrors($e->getMessage())->withInput(); } ``` Because Laravel catches the validation exception automatically and returns you back with old input and an array of errors which you can output like ``` @if ($errors->any())
    @foreach ($errors->all() as $error)
  • {{ $error }}
  • @endforeach
@endif ```","Put the response in a variable and use dd() to print it. You will find it on the ""messages"" method. Worked for me. `dd($response);`" 38156908,"I am working on windows Universal platform(Universal app-UWP). I have issue regarding Responsiveness of the Grid Control. How to design a grid which is responsive for all view. I am designed a grid this way: Code: ``` ``` I designed this way but the Grid not properly work responsiveness as per the view so, If there are any solution which make it easily responsive so provide a solution.",2016/07/02,"['https://Stackoverflow.com/questions/38156908', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5997390/']","We can provide a width of listview in code behind (c#) through the managing all visual state. Code: ``` if (PageSizeStatesGroup.CurrentState == WideState) //Desktop Devie { } else if (PageSizeStatesGroup.CurrentState == MediumState) // // //tablate state { lstorderdetail.Width = 650; } else if (PageSizeStatesGroup.CurrentState == MobileState) { } else { lstorderdetail.Width = 1200; new InvalidOperationException(); } ``` Use PageSizeStatesGroup to manage the visual state and then provide a width as per your scrrn requirement.","Please tell more about your current problem (at which view size it has problem ? What is your desired result ?). Depend on your view port / device requirements, you can chose one or combine the following solutions: * Use difference XAML for each device family * Use VisualState to change the size/flow of content of the view * Check the conditions in code behind and adjust the view accordingly * Programmatically build your UI from code behind" 38156908,"I am working on windows Universal platform(Universal app-UWP). I have issue regarding Responsiveness of the Grid Control. How to design a grid which is responsive for all view. I am designed a grid this way: Code: ``` ``` I designed this way but the Grid not properly work responsiveness as per the view so, If there are any solution which make it easily responsive so provide a solution.",2016/07/02,"['https://Stackoverflow.com/questions/38156908', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5997390/']","We can provide a width of listview in code behind (c#) through the managing all visual state. Code: ``` if (PageSizeStatesGroup.CurrentState == WideState) //Desktop Devie { } else if (PageSizeStatesGroup.CurrentState == MediumState) // // //tablate state { lstorderdetail.Width = 650; } else if (PageSizeStatesGroup.CurrentState == MobileState) { } else { lstorderdetail.Width = 1200; new InvalidOperationException(); } ``` Use PageSizeStatesGroup to manage the visual state and then provide a width as per your scrrn requirement.","The best thing you could do is to use State Triggers which automatically resize based on the Screen size. Check this [example](http://www.wintellect.com/devcenter/jprosise/using-adaptivetrigger-to-build-adaptive-uis-in-windows-10)" 40935127,"I am getting an error when executing following `.prototxt` and I have absolutely no idea why I get an error there: ``` layer { name: ""conv"" type: ""Convolution"" bottom: ""image"" top: ""conv"" convolution_param { num_output: 2 kernel_size: 5 pad: 2 stride: 1 weight_filler { type: ""xavier"" } bias_filler { type: ""constant"" value: 0 } } } ``` This is the error output. As I have seen in the latest `caffe-master-branch` it should be possible to use `5D-Blobs`. ``` I1202 14:54:58.617269 2393 hdf5_data_layer.cpp:93] Number of HDF5 files: 9 I1202 14:54:58.631134 2393 hdf5.cpp:35] Datatype class: H5T_INTEGER I1202 14:54:59.159739 2393 net.cpp:150] Setting up train-data I1202 14:54:59.159760 2393 net.cpp:157] Top shape: 1 1 1 128 128 (16384) I1202 14:54:59.159765 2393 net.cpp:157] Top shape: 1 1 8 128 128 (131072) I1202 14:54:59.159766 2393 net.cpp:165] Memory required for data: 589824 I1202 14:54:59.159773 2393 layer_factory.hpp:77] Creating layer down_level_0_conv I1202 14:54:59.159790 2393 net.cpp:100] Creating Layer down_level_0_conv I1202 14:54:59.159795 2393 net.cpp:434] down_level_0_conv <- image I1202 14:54:59.159804 2393 net.cpp:408] down_level_0_conv -> down_level_0_conv F1202 14:54:59.159915 2393 blob.hpp:140] Check failed: num_axes() <= 4 (5 vs. 4) Cannot use legacy accessors on Blobs with > 4 axes. ``` Do I need to go to a certain branch? I just pulled from `caffe-master-branch` again to make sure it is the newest version. I then made a make clean make all command and it still does not work.",2016/12/02,"['https://Stackoverflow.com/questions/40935127', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']","AFAIK, this error comes from the `""Xavier""` filler: this filler computes the ratio between the input and output channels. If you replace it with a different filler you should be Okay with ND blob.","When I remove the check in `line 140 blob.hpp` it does work. This is one way to solve it, not the best one though. (But this cannot be the proper solution. Is there anything else?)" 40935127,"I am getting an error when executing following `.prototxt` and I have absolutely no idea why I get an error there: ``` layer { name: ""conv"" type: ""Convolution"" bottom: ""image"" top: ""conv"" convolution_param { num_output: 2 kernel_size: 5 pad: 2 stride: 1 weight_filler { type: ""xavier"" } bias_filler { type: ""constant"" value: 0 } } } ``` This is the error output. As I have seen in the latest `caffe-master-branch` it should be possible to use `5D-Blobs`. ``` I1202 14:54:58.617269 2393 hdf5_data_layer.cpp:93] Number of HDF5 files: 9 I1202 14:54:58.631134 2393 hdf5.cpp:35] Datatype class: H5T_INTEGER I1202 14:54:59.159739 2393 net.cpp:150] Setting up train-data I1202 14:54:59.159760 2393 net.cpp:157] Top shape: 1 1 1 128 128 (16384) I1202 14:54:59.159765 2393 net.cpp:157] Top shape: 1 1 8 128 128 (131072) I1202 14:54:59.159766 2393 net.cpp:165] Memory required for data: 589824 I1202 14:54:59.159773 2393 layer_factory.hpp:77] Creating layer down_level_0_conv I1202 14:54:59.159790 2393 net.cpp:100] Creating Layer down_level_0_conv I1202 14:54:59.159795 2393 net.cpp:434] down_level_0_conv <- image I1202 14:54:59.159804 2393 net.cpp:408] down_level_0_conv -> down_level_0_conv F1202 14:54:59.159915 2393 blob.hpp:140] Check failed: num_axes() <= 4 (5 vs. 4) Cannot use legacy accessors on Blobs with > 4 axes. ``` Do I need to go to a certain branch? I just pulled from `caffe-master-branch` again to make sure it is the newest version. I then made a make clean make all command and it still does not work.",2016/12/02,"['https://Stackoverflow.com/questions/40935127', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']","As a complement of [Shai's answer](https://stackoverflow.com/a/40956354/6281477), in order to be compatible with the `ND Convolution` and `InnerProduct` layer, the ""`Xavier`"" filler [code](https://github.com/BVLC/caffe/blob/master/include/caffe/filler.hpp#L144) ``` virtual void Fill(Blob* blob) { ... int fan_in = blob->count() / blob->num(); int fan_out = blob->count() / blob->channels(); Dtype n = fan_in; // default to fan_in ... Dtype scale = sqrt(Dtype(3) / n); caffe_rng_uniform(blob->count(), -scale, scale, blob->mutable_cpu_data()); CHECK_EQ(this->filler_param_.sparse(), -1) << ""Sparsity not supported by this Filler.""; } ``` in caffe, should be more like this: ``` ... int fan_in = blob->count() / blob->shape(0); int fan_out = blob->num_axis() == 2 ? blob->shape(0) : blob->count() / blob->shape(1); ...//original stuff ``` This little change should also make your prototxt work.","When I remove the check in `line 140 blob.hpp` it does work. This is one way to solve it, not the best one though. (But this cannot be the proper solution. Is there anything else?)" 40935127,"I am getting an error when executing following `.prototxt` and I have absolutely no idea why I get an error there: ``` layer { name: ""conv"" type: ""Convolution"" bottom: ""image"" top: ""conv"" convolution_param { num_output: 2 kernel_size: 5 pad: 2 stride: 1 weight_filler { type: ""xavier"" } bias_filler { type: ""constant"" value: 0 } } } ``` This is the error output. As I have seen in the latest `caffe-master-branch` it should be possible to use `5D-Blobs`. ``` I1202 14:54:58.617269 2393 hdf5_data_layer.cpp:93] Number of HDF5 files: 9 I1202 14:54:58.631134 2393 hdf5.cpp:35] Datatype class: H5T_INTEGER I1202 14:54:59.159739 2393 net.cpp:150] Setting up train-data I1202 14:54:59.159760 2393 net.cpp:157] Top shape: 1 1 1 128 128 (16384) I1202 14:54:59.159765 2393 net.cpp:157] Top shape: 1 1 8 128 128 (131072) I1202 14:54:59.159766 2393 net.cpp:165] Memory required for data: 589824 I1202 14:54:59.159773 2393 layer_factory.hpp:77] Creating layer down_level_0_conv I1202 14:54:59.159790 2393 net.cpp:100] Creating Layer down_level_0_conv I1202 14:54:59.159795 2393 net.cpp:434] down_level_0_conv <- image I1202 14:54:59.159804 2393 net.cpp:408] down_level_0_conv -> down_level_0_conv F1202 14:54:59.159915 2393 blob.hpp:140] Check failed: num_axes() <= 4 (5 vs. 4) Cannot use legacy accessors on Blobs with > 4 axes. ``` Do I need to go to a certain branch? I just pulled from `caffe-master-branch` again to make sure it is the newest version. I then made a make clean make all command and it still does not work.",2016/12/02,"['https://Stackoverflow.com/questions/40935127', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']","AFAIK, this error comes from the `""Xavier""` filler: this filler computes the ratio between the input and output channels. If you replace it with a different filler you should be Okay with ND blob.","As a complement of [Shai's answer](https://stackoverflow.com/a/40956354/6281477), in order to be compatible with the `ND Convolution` and `InnerProduct` layer, the ""`Xavier`"" filler [code](https://github.com/BVLC/caffe/blob/master/include/caffe/filler.hpp#L144) ``` virtual void Fill(Blob* blob) { ... int fan_in = blob->count() / blob->num(); int fan_out = blob->count() / blob->channels(); Dtype n = fan_in; // default to fan_in ... Dtype scale = sqrt(Dtype(3) / n); caffe_rng_uniform(blob->count(), -scale, scale, blob->mutable_cpu_data()); CHECK_EQ(this->filler_param_.sparse(), -1) << ""Sparsity not supported by this Filler.""; } ``` in caffe, should be more like this: ``` ... int fan_in = blob->count() / blob->shape(0); int fan_out = blob->num_axis() == 2 ? blob->shape(0) : blob->count() / blob->shape(1); ...//original stuff ``` This little change should also make your prototxt work." 9104620,"I have this code to check if a span is hidden or visible depending on the value it will show or hide, the event is triggered when a user clicks a button: ``` $('form').on('click', '#agregar', function(){ // var p = $('#panel'); //var a = $('#agregar'); if($('#panel').is(':visible')){ $('#panel').hide(); $('#agregar').val('Mostrar Forma'); alert('ocultar'); }else { //if($('#panel').is(':hidden')){ $('#panel').show(); $('#agregar').val('Ocultar Forma'); alert('mostrar'); } }); ``` the problem is that even if its visible it will never hide it and the alert('mostrar') will always show so the conditional is always false, why is this? is my code wrong? my span is like this: ``` a fieldset and a form here ``` The css is on a external stylesheet and it's like ``` #panel{ display: none;} ``` Any help is greatly apreciated don't mind any code that's commented I was just trying different forms to see any changes",2012/02/01,"['https://Stackoverflow.com/questions/9104620', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1079232/']","try doing this if( $(""#panel"").css(""display"") != ""none"" )","Try this extension to see if this helps you. ``` jQuery.extend( jQuery.expr[ "":"" ], { reallyvisible : function (a) { return !(jQuery(a).is(':hidden') || jQuery(a).parents(':hidden').length); }} ); ```" 7923033,"I am running some unit tests on my code, and for this I had to download the selenium server. Now, one of the examples selenium includes is called GoogleTest. I had this copied to my C:\ folder, and tried to run it. At first, i had an error trying to open firefox. Seems that selenium hasn't been updated for quite some time, since it supports up till Firefox version 3.5. Found [this](http://geekswithblogs.net/thomasweller/archive/2010/02/14/making-selenium-1.0.1-work-with-firefox-3.6.aspx) helpful blog that helped me (changing 3.5.\* for 7.0.\*). Now, I have a new problem. It seems selenium hasn't updated its docs either, and the GoogleTest hangs when executed ([this](https://stackoverflow.com/questions/3652235/selenium-rc-waitforpagetoload-hangs) post explains why). When using AJAX type operations, the operation waitForPageToLoad hangs. Now, I need an equivalent to this operation but when dealing with AJAX operations.. anybody knows of an alternative? Thanks",2011/10/27,"['https://Stackoverflow.com/questions/7923033', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/775205/']","Did you tried with [QAF formerly ISFW](https://qmetry.github.io/qaf/)? It internally waits for element as well as provides wait functionality for ajax to complete for may of the js toolkit like dojo, extjs, prototype etc for example if the AUT uses extjs then you can use like ``` waitService.waitForAjaxToComplete(JsToolkit.EXTJS); ```","There is no waitforajaxtoreturn function in Selenium. The way AJAX changes are handled are by using the `WebDriverWait` class to wait for a specific condition to become true when the AJAX call returns. So for example, for the Google test, the `WebDriverWait` could wait for the search container to appear. In essence, you have to know what you are waiting for in order to continue the test." 7923033,"I am running some unit tests on my code, and for this I had to download the selenium server. Now, one of the examples selenium includes is called GoogleTest. I had this copied to my C:\ folder, and tried to run it. At first, i had an error trying to open firefox. Seems that selenium hasn't been updated for quite some time, since it supports up till Firefox version 3.5. Found [this](http://geekswithblogs.net/thomasweller/archive/2010/02/14/making-selenium-1.0.1-work-with-firefox-3.6.aspx) helpful blog that helped me (changing 3.5.\* for 7.0.\*). Now, I have a new problem. It seems selenium hasn't updated its docs either, and the GoogleTest hangs when executed ([this](https://stackoverflow.com/questions/3652235/selenium-rc-waitforpagetoload-hangs) post explains why). When using AJAX type operations, the operation waitForPageToLoad hangs. Now, I need an equivalent to this operation but when dealing with AJAX operations.. anybody knows of an alternative? Thanks",2011/10/27,"['https://Stackoverflow.com/questions/7923033', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/775205/']","Did you tried with [QAF formerly ISFW](https://qmetry.github.io/qaf/)? It internally waits for element as well as provides wait functionality for ajax to complete for may of the js toolkit like dojo, extjs, prototype etc for example if the AUT uses extjs then you can use like ``` waitService.waitForAjaxToComplete(JsToolkit.EXTJS); ```","I am testing some ajax and JS heavy pages and I have been facing exactly the same problem. I have used implicit waits to to pause for the ajax code to execute and load the new content to DOM . Here is a python sample from my code : ``` from selenium import webdriver browserHandle = webdriver.Firefox() browserHandle.implicitly_wait(10) ## assuming dom object loads in 10 seconds ## clear implicit wait browserHandle.implicitly_wait(0) ```" 12851933,"when i try to run this code : ``` ``` the output is `Patty O'Furniture` but when i try to run this code(upload data into database table) ``` 0) { //get the csv file $file = $_FILES[csv][tmp_name]; $handle = fopen($file,""r""); //loop through the csv file and insert into database do { if ($data[0]) { if(get_magic_quotes_gpc()) mysql_query(""INSERT INTO sms_recipient (store_id, recipient_name, recipient_phone) VALUES ( '"".$login_id.""', '"".stripslashes($data[0]).""', '"".stripslashes($data[1]).""' ) ""); } } while ($data = fgetcsv($handle,1000,"","",""'"")); // } ?> ``` the output only `Patty O` . (see screenshot) ![enter image description here](https://i.stack.imgur.com/zEjQu.jpg) i'm not sure why when i try to save data into database using function `stripslashes` it's not working.",2012/10/12,"['https://Stackoverflow.com/questions/12851933', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1530536/']","Because you're undoing what [magic\_quotes](http://www.php.net/manual/en/info.configuration.php#ini.magic-quotes-gpc) is trying to do. > > When magic\_quotes are on, all ' (single-quote), "" (double quote), \ > (backslash) and NUL's are escaped with a backslash automatically. > > > So you're removing the backslashes via `stripslashes` that are being added, and shorting the query when it hits the `'` in `O'Furniture`","use [`mysql_real_escape_string()`](http://php.net/manual/en/function.mysql-real-escape-string.php) function instead of `stripslashes()` or Try to avoid `mysql_*` functions, Try to use [`mysqli`](http://www.php.net/manual/en/book.mysqli.php) or `PDO`" 12851933,"when i try to run this code : ``` ``` the output is `Patty O'Furniture` but when i try to run this code(upload data into database table) ``` 0) { //get the csv file $file = $_FILES[csv][tmp_name]; $handle = fopen($file,""r""); //loop through the csv file and insert into database do { if ($data[0]) { if(get_magic_quotes_gpc()) mysql_query(""INSERT INTO sms_recipient (store_id, recipient_name, recipient_phone) VALUES ( '"".$login_id.""', '"".stripslashes($data[0]).""', '"".stripslashes($data[1]).""' ) ""); } } while ($data = fgetcsv($handle,1000,"","",""'"")); // } ?> ``` the output only `Patty O` . (see screenshot) ![enter image description here](https://i.stack.imgur.com/zEjQu.jpg) i'm not sure why when i try to save data into database using function `stripslashes` it's not working.",2012/10/12,"['https://Stackoverflow.com/questions/12851933', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1530536/']","Because you're undoing what [magic\_quotes](http://www.php.net/manual/en/info.configuration.php#ini.magic-quotes-gpc) is trying to do. > > When magic\_quotes are on, all ' (single-quote), "" (double quote), \ > (backslash) and NUL's are escaped with a backslash automatically. > > > So you're removing the backslashes via `stripslashes` that are being added, and shorting the query when it hits the `'` in `O'Furniture`","What you are seeing is the basis for [SQL Injection](http://en.wikipedia.org/wiki/SQL_injection). Your input is not escaped at all once you remove the slashes. Imagine what would happen if an attacker provided an input string that closed your query and began a new one with `'; UPDATE users SET password WHERE username=""admin""`? At the very least, you need to escape your input with `mysql_real_escape_string`, but really you need to stop using the `mysql` extension. Use prepared statements of the `mysqli` extension instead." 24359324,"This is my php code to get user information using google plus api. I had unset the access token in case user click logout but still logout don't works. Once i got the information of any user, then after logging out and connecting again i still got the same user information and no option to sign in with different email id. ``` setClientId($client_id); $client->setClientSecret($client_secret); $client->setRedirectUri($redirect_uri); $client->setDeveloperKey('AIzaSyCWdr3JGvgOZ0lPX9R6hJP4Y00J-R2Ksgg'); $plus = new Google_Service_Plus($client); $google_oauthV2 = new Google_Service_Oauth2($client); $client->setScopes('https://www.googleapis.com/auth/plus.login'); $client->setScopes('email'); /************************************************ If we're logging out we just need to clear our local access token in this case ************************************************/ if (isset($_REQUEST['logout'])) { unset($_SESSION['access_token']); } /************************************************ If we have a code back from the OAuth 2.0 flow, we need to exchange that with the authenticate() function. We store the resultant access token bundle in the session, and redirect to ourself. ************************************************/ if (isset($_GET['code'])) { $client->authenticate($_GET['code']); $_SESSION['access_token'] = $client->getAccessToken(); $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']; header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL)); } /************************************************ If we have an access token, we can make requests, else we generate an authentication URL. ************************************************/ if (isset($_SESSION['access_token']) && $_SESSION['access_token']) { $client->setAccessToken($_SESSION['access_token']); } else { $authUrl = $client->createAuthUrl(); } /************************************************ If we're signed in we can go ahead and retrieve the ID token, which is part of the bundle of data that is exchange in the authenticate step - we only need to do a network call if we have to retrieve the Google certificate to verify it, and that can be cached. ************************************************/ if ($client->getAccessToken()) { $_SESSION['access_token'] = $client->getAccessToken(); $token_data = $client->verifyIdToken()->getAttributes(); $user = $google_oauthV2->userinfo->get(); $me = $plus->people->get('me'); } echo pageHeader(""GOOGLE+ API for Information Retrival""); if ( $client_id == ' ' || $client_secret == ' ' || $redirect_uri == ' ') { echo missingClientSecretsWarning(); } ?> ```",2014/06/23,"['https://Stackoverflow.com/questions/24359324', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/734371/']","How about this? ``` if (isset($_REQUEST['logout'])) { unset($_SESSION['access_token']); header('Location: https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue=http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']); } ```","And how about this? ``` if (isset($_REQUEST['logout'])) { $client->revokeToken($_SESSION['access_token']); unset($_SESSION['access_token']); } ```" 15535398,"Im trying to add a checkbox to a specific datagridview column header, I found some code online to help but it's not aligning properly and I'm not really sure how to fix it. Below is an image of the problem and the code, any help would be greatly appreciated! P.S. I think it might be something to do with properties but I've played around with them but not been successful. ![enter image description here](https://i.stack.imgur.com/1hNdW.png) ``` Private checkboxHeader231 As CheckBox Private Sub show_chkBox() Dim rect As Rectangle = DataGridView1.GetCellDisplayRectangle(columnIndexOfCheckBox, -1, True) ' set checkbox header to center of header cell. +1 pixel to position rect.Y = 3 rect.X = rect.Location.X + 8 + (rect.Width / 4) checkboxHeader231 = New CheckBox() With checkboxHeader231 .BackColor = Color.Transparent End With checkboxHeader231.Name = ""checkboxHeader1"" checkboxHeader231.Size = New Size(18, 18) checkboxHeader231.Location = rect.Location AddHandler checkboxHeader231.CheckedChanged, AddressOf checkboxHeader231_CheckedChanged DataGridView1.Controls.Add(checkboxHeader231) End Sub Private Sub checkboxHeader231_CheckedChanged(sender As System.Object, e As System.EventArgs) Dim headerBox As CheckBox = DirectCast(DataGridView1.Controls.Find(""checkboxHeader1"", True)(0), CheckBox) For Each row As DataGridViewRow In DataGridView1.Rows row.Cells(columnIndexOfCheckBox).Value = headerBox.Checked Next End Sub ```",2013/03/20,"['https://Stackoverflow.com/questions/15535398', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2058444/']","This is my first entry, but I think this is what youre looking for. I tested it and it worked on my datagrid. You were using the width for the rectangle, youll need it for the column width instead. I set the column header to 4, but you would replace the 4 with your column you want to use I put it in two ways, one with a four loop, the other just as single lines. Tell me if this worked for you: ``` Dim rect As Rectangle = DataGridView1.GetCellDisplayRectangle(4, -1, True) ' replace 4 rect.Y = 3 Dim sum = DataGridView1.Columns(0).Width 'for this area write a for loop to find the width of each column except for the last line which you manually do ' ' 'For i As Integer = 1 To 4 - 1 Step 1 ' replace 4 'sum = sum + DataGridView1.Columns(i).Width 'Next sum = sum + DataGridView1.Columns(1).Width sum = sum + DataGridView1.Columns(2).Width sum = sum + DataGridView1.Columns(3).Width ' stop here and add the last line by hand here sum = sum + (DataGridView1.Columns(4).Width / 2) + 35 ' used in both cases ' replace 4 rect.X = sum checkboxHeader231 = New CheckBox() With checkboxHeader231 .BackColor = Color.Transparent End With checkboxHeader231.Name = ""checkboxHeader1"" checkboxHeader231.Size = New Size(18, 18) checkboxHeader231.Location = rect.Location AddHandler checkboxHeader231.CheckedChanged, AddressOf checkboxHeader231_CheckedChanged DataGridView1.Controls.Add(checkboxHeader231) ```","``` Private headerBox As CheckBox Private Sub show_checkBox() Dim checkboxHeader As CheckBox = New CheckBox() Dim rect As Rectangle = PendingApprovalServiceListingDataGridView.GetCellDisplayRectangle(4, -1, True) rect.X = 20 rect.Y = 12 With checkboxHeader .BackColor = Color.Transparent End With checkboxHeader.Name = ""checkboxHeader"" checkboxHeader.Size = New Size(14, 14) checkboxHeader.Location = rect.Location AddHandler checkboxHeader.CheckedChanged, AddressOf checkboxHeader_CheckedChanged PendingApprovalServiceListingDataGridView.Controls.Add(checkboxHeader) End Sub Private Sub checkboxHeader_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs) headerBox = DirectCast(PendingApprovalServiceListingDataGridView.Controls.Find(""checkboxHeader"", True)(0), CheckBox) For Each row As DataGridViewRow In PendingApprovalServiceListingDataGridView.Rows row.Cells(0).Value = headerBox.Checked Next End Sub ```" 73963231,"I know that `document.getElementById()` won't work with several ids. So I tried this: ``` document.getElementsByClassName(""circle""); ``` But that also doesn't work at all. But if I use just the `document.getElementById()` it works with that one id. Here is my code: ```js let toggle = () => { let circle = document.getElementsByClassName(""circle""); let hidden = circle.getAttribute(""hidden""); if (hidden) { circle.removeAttribute(""hidden""); } else { circle.setAttribute(""hidden"", ""hidden""); } } ```",2022/10/05,"['https://Stackoverflow.com/questions/73963231', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/20168544/']","`document.getElementsByClassName()` returns a `NodeList`, and to convert it to an array of elements, use `Array.from()`. this will return an array containing all of the elements with the class name `circle` Here is an example, which changes each element with the `circle` class: ```js const items = document.getElementsByClassName('circle') const output = Array.from(items) function change() { output.forEach(i => { var current = i.innerText.split(' ') current[1] = 'hate' current = current[0] + ' ' + current[1] + ' ' + current[2] i.innerText = current }) } ``` ```html

I love cats!

I love dogs!

I love green!

I love waffles!

I love javascript!

I love tea!

```","You can try this. ``` const selectedIds = document.querySelectorAll('#id1, #id12, #id3'); console.log(selectedIds); //Will log [element#id1, element#id2, element#id3] ``` Then you can do something like this: ``` for(const element of selectedIds){ //Do something with element //Example: element.style.color = ""red"" } ```" 21608613,"I was trying to solve a problem which is to verify that if there exist a sub sequence whose sum is equal to a given number. I found this thread [Distinct sub sequences summing to given number in an array](https://stackoverflow.com/questions/17125536/distinct-sub-sequences-summing-to-given-number-in-an-array). I don't have to solve it for all the possible sub sequence I just need is to verify. What is the most optimal algorithm to verify it. e.g. `a[]={8,1,2,5,4,7,6,3} and num=18` ``` 8+2+5+3 = 18 ```",2014/02/06,"['https://Stackoverflow.com/questions/21608613', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1763475/']","You're trying to solve the [subset sum problem](http://en.wikipedia.org/wiki/Subset_sum_problem) which is known to be NP-complete. Hence there's no known optimal polynomial algorithm. However if your problem permits certain constraints then it may be possible to solve it elegantly with one of the algorithms provided in the Wikipedia article.","There is a pseudo polynomial Dynamic Programming solution similar to knapsack problem using following analogy :- > > 1. Knapsack capacity W = num > 2. Item i's weight and cost is same as arr[i] > 3. Maximize Profit > 4. if MaxProfit == W then there exists subsequence else no subsequence possible. > 5. Recontruct solution using DP values > > > **Note:** So as this can be reduced to knapsack problem hence there is no polynomial time solution yet found." 167409,"I have to evaluate: $$\int\_{0}^{\pi/2}\frac{\sqrt{\sin x}}{\sqrt{\sin x}+\sqrt{\cos x}}\, \mathrm{d}x. $$ I can't get the right answer! So please help me out!",2012/07/06,"['https://math.stackexchange.com/questions/167409', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/27579/']","Let $I$ denote the integral and consider the substitution $u= \frac{\pi }{2} - x.$ Then $I = \displaystyle\int\_0^{\frac{\pi }{2}} \frac{\sqrt{\cos u}}{\sqrt{\cos u } + \sqrt{\sin u }} du$ and $2I = \displaystyle\int\_0^{\frac{\pi }{2}} \frac{\sqrt{\cos u} + \sqrt{\sin u }}{\sqrt{\cos u } + \sqrt{\sin u }} du = \frac{\pi }{2}.$ Hence $I = \frac{\pi }{4}.$ In general, $ \displaystyle\int\_0^a f(x) dx = \displaystyle\int\_0^a f(a-x) $ $dx$ whenever $f$ is integrable, and $\displaystyle\int\_0^{\frac{\pi }{2}} \frac{\cos^a x}{\cos^a x + \sin^a x } dx = \displaystyle\int\_0^{\frac{\pi }{2}} \frac{\sin^a x}{\cos^a x + \sin^a x } dx = \frac{\pi }{4}$ for $a>0$ (same trick.)","Note that $\sin(\pi/2-x)=\cos x$ and $\cos(\pi/2-x)=\sin x$. The answer will exploit the symmetry. Break up the original integral into two parts, (i) from $0$ to $\pi/4$ and (ii) from $\pi/4$ to $\pi/2$. So our first integral is $$\int\_{x=0}^{\pi/4} \frac{\sqrt{\sin x}}{\sqrt{\sin x}+\sqrt{\cos x}}\,dx.\tag{$1$} $$ For the second integral, make the change of variable $u=\pi/2-x$. Using the fact that $\sin x=\sin(\pi/2-u)=\cos u$ and $\cos x=\cos(\pi/2-u)=\sin u$, and the fact that $dx=-du$, we get after not much work $$\int\_{u=\pi/4}^{0} -\frac{\sqrt{\cos u}}{\sqrt{\cos u}+\sqrt{\sin u}}\,du$$ Change the dummy variable of integration variable to the **name** $x$. Also, do the integration in the ""right"" order, $0$ to $\pi/4$. That changes the sign, so our second integral is equal to $$\int\_{x=0}^{\pi/4} \frac{\sqrt{\cos x}}{\sqrt{\cos x}+\sqrt{\sin x}}\,dx.\tag{$2$}$$ Our original integral is the **sum** of the integrals $(1)$ and $(2)$. Add, and note the beautiful cancellation $\frac{\sqrt{\sin x}}{\sqrt{\sin x}+\sqrt{\cos x}}+ \frac{\sqrt{\cos x}}{\sqrt{\cos x}+\sqrt{\sin x}}=1$. Thus our original integral is equal to $$\int\_0^{\pi/4}1\,dx.$$ This is trivial to compute: the answer is $\pi/4$. **Remark:** Let $f(x)$ and $g(x)$ be any reasonably nice functions such that $g(x)=f(a-x)$. Exactly the same argument shows that $$\int\_0^a\frac{f(x)}{f(x)+g(x)}\,dx=\frac{a}{2}.$$" 40102726,"I am working on building an app. Earlier I have used Xcode 7.1 at that time everything was working fine. Recently I have installed Xcode 8.0 as well and I have both the setups installed into in two different directories Xcode\_7, Xcode\_8 and I renamed the setup files as well. Everything was working fine but lately I am getting the following error while working with Xcode 8. **""An internal error occurred. Editing functionality may be limited ""** and the storyboard view objects are all gone empty like shown in the image but I am able to click on a specific view and still can see their properties defined through attributes inspector but nothing shows up in storyboard still I am able to build the project successfully but while loading it in simulator it says **Unable to boot the iOS simulator** I have followed few tips like reinstalling the Xcode , trashing the derived data from preferences. Nothing helped so far. Please let me know if anyone resolved this issue. [Storyboard file ViewObjects all gone empty](https://i.stack.imgur.com/GtOrZ.png) **UPDATE** I have found the fix with the help of apple forums here [Visit](https://forums.developer.apple.com/message/189283)!. **Disabling the SIP (System Integrity Protection)** in my iMac which runs on El Capitan solved the issue however not sure disabling it will raise any further errors. :)",2016/10/18,"['https://Stackoverflow.com/questions/40102726', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4134597/']","Try This > > Go to Xcode -> Preferences -> Locations -> Derived Data -> click the > arrow to open in Finder -> And delete the content of that folder. > > > [![enter image description here](https://i.stack.imgur.com/0j0EO.png)](https://i.stack.imgur.com/0j0EO.png) Hope it helps!","Restart your mac, press cmd+R and open in recovery mode. Open terminal and type command --> csrutil disable restart mac.. open terminal--> sudo chmod 0777 / private / tmp  then run your xcode, simulator will work fine :)" 40102726,"I am working on building an app. Earlier I have used Xcode 7.1 at that time everything was working fine. Recently I have installed Xcode 8.0 as well and I have both the setups installed into in two different directories Xcode\_7, Xcode\_8 and I renamed the setup files as well. Everything was working fine but lately I am getting the following error while working with Xcode 8. **""An internal error occurred. Editing functionality may be limited ""** and the storyboard view objects are all gone empty like shown in the image but I am able to click on a specific view and still can see their properties defined through attributes inspector but nothing shows up in storyboard still I am able to build the project successfully but while loading it in simulator it says **Unable to boot the iOS simulator** I have followed few tips like reinstalling the Xcode , trashing the derived data from preferences. Nothing helped so far. Please let me know if anyone resolved this issue. [Storyboard file ViewObjects all gone empty](https://i.stack.imgur.com/GtOrZ.png) **UPDATE** I have found the fix with the help of apple forums here [Visit](https://forums.developer.apple.com/message/189283)!. **Disabling the SIP (System Integrity Protection)** in my iMac which runs on El Capitan solved the issue however not sure disabling it will raise any further errors. :)",2016/10/18,"['https://Stackoverflow.com/questions/40102726', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4134597/']","Try This > > Go to Xcode -> Preferences -> Locations -> Derived Data -> click the > arrow to open in Finder -> And delete the content of that folder. > > > [![enter image description here](https://i.stack.imgur.com/0j0EO.png)](https://i.stack.imgur.com/0j0EO.png) Hope it helps!","To all you Xcode 8 users out there: Make sure you are running mac os sierra! It isn't said that being on el capitan will cause this problem. But I have updated to Sierra and everything works fine now!" 40102726,"I am working on building an app. Earlier I have used Xcode 7.1 at that time everything was working fine. Recently I have installed Xcode 8.0 as well and I have both the setups installed into in two different directories Xcode\_7, Xcode\_8 and I renamed the setup files as well. Everything was working fine but lately I am getting the following error while working with Xcode 8. **""An internal error occurred. Editing functionality may be limited ""** and the storyboard view objects are all gone empty like shown in the image but I am able to click on a specific view and still can see their properties defined through attributes inspector but nothing shows up in storyboard still I am able to build the project successfully but while loading it in simulator it says **Unable to boot the iOS simulator** I have followed few tips like reinstalling the Xcode , trashing the derived data from preferences. Nothing helped so far. Please let me know if anyone resolved this issue. [Storyboard file ViewObjects all gone empty](https://i.stack.imgur.com/GtOrZ.png) **UPDATE** I have found the fix with the help of apple forums here [Visit](https://forums.developer.apple.com/message/189283)!. **Disabling the SIP (System Integrity Protection)** in my iMac which runs on El Capitan solved the issue however not sure disabling it will raise any further errors. :)",2016/10/18,"['https://Stackoverflow.com/questions/40102726', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4134597/']","Restart your mac, press cmd+R and open in recovery mode. Open terminal and type command --> csrutil disable restart mac.. open terminal--> sudo chmod 0777 / private / tmp  then run your xcode, simulator will work fine :)","To all you Xcode 8 users out there: Make sure you are running mac os sierra! It isn't said that being on el capitan will cause this problem. But I have updated to Sierra and everything works fine now!" 101120,"I have a Google App Engine Java web app that I have setup with a custom domain from GoDaddy. The site can currently be reached at domain.com and www.domain.com. I am trying to have a 301 redirect occur whenever someone tries to access domain.com instead of www.domain.com. I have tried to use domain forwarding via GoDaddy, without success. How can I achieve this goal? Here is my Google App Engine setup. I have added all of these records to the GoDaddy DNS Manger. [![](https://i.stack.imgur.com/alc3w.png)](https://i.stack.imgur.com/alc3w.png) Here is the domain forwarding information I tried: [![enter image description here](https://i.stack.imgur.com/TeeiC.png)](https://i.stack.imgur.com/TeeiC.png)",2016/11/15,"['https://webmasters.stackexchange.com/questions/101120', 'https://webmasters.stackexchange.com', 'https://webmasters.stackexchange.com/users/71988/']","Update: There are 3 ways to do this. 1. htaccess 2. php to yaml with redirect 3. Within Google itself. > > **Specify the domain and subdomains you want to map.** > > > Note: The naked domain and www subdomain are pre populated in the > form. A naked domain, such as example.com, maps to . > A subdomain, such as www, maps to . Click Submit > mappings to create the desired mapping. In the final step of the Add > new custom domain form, note the resource records listed along with > their type and canonical name. > > > [Full article on Google](https://cloud.google.com/appengine/docs/python/console/using-custom-domains-and-ssl?hl=en) [Link to Custom Domains Login on Google](https://console.cloud.google.com/appengine/settings/domains?_ga=1.59431789.139328086.1479124615) **HTACCESS** Assuming you are on their Apache server you want to add this to your .htaccess file. This is for both, choose one. Replace example with your domain name. ``` #Force www: RewriteEngine on RewriteCond %{HTTP_HOST} ^example.com [NC] RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301,NC] ``` --- ``` #Force non-www: RewriteEngine on RewriteCond %{HTTP_HOST} ^www\.example\.com [NC] RewriteRule ^(.*)$ http://example.com/$1 [L,R=301] ```","Google does not support htaccess file. They support app.yaml file, which have different [mod rewrite rule](https://cloud.google.com/appengine/docs/php/config/appref), but as far I know It will applicable only to one CNAME, it means if you have set www.example.com then those rewrite rules will not applicable to example.com. You can use wildcard `*` in CNAME, which redirect all of your subdomain to your perferred domain name. For example if people access example.com/directory/ then it will automatically redirect to www.example.com/directory/ . The main drawback of wildcard is, it applied to all of your subdomain, it means you can't add any of content like images and blog in your subdomain, for example blog.example.com will redirect to www.example.com and images.example.com/puppy.jpg will redirect to www.example.com/puppy.jpg(Which may trigger 404 error). But If you don't have placed any of thing in your subdomain then wildcard will solve your problem. And, If you just want to redirect example.com to www.example.com and not other subdirectory then you can use [meta refresh tag](https://www.w3.org/TR/WCAG20-TECHS/H76.html) which is client side solution. Or you can host your naked domain somwehere else(Github Pages, Firebase are free solution) and do 301 redirection." 3018,"In my view the life begins at the time of forming zygote inside the mother's womb. My question is that what is the view of Hinduism about ""the beginning of a life""?",2014/09/04,"['https://hinduism.stackexchange.com/questions/3018', 'https://hinduism.stackexchange.com', 'https://hinduism.stackexchange.com/users/187/']","**Scientifically:** You are correct. **By Hinduism:** Its a soul,which is going to change a body like clothes, leaving off the old one and wearing newones.[see this](http://www.eaglespace.com/spirit/gita_reincarnation.php) > > vaasaa.nsi jiirNaani yathaa vihaaya navaani gRRihNaati naro.aparaaNi. > > > tathaa shariiraaNi vihaaya jiirNaanyanyaani sa.nyaati navaani dehii.. > B.G. II-22 > > > वासांसि जीर्णानि यथा विहाय नवानि गृह्णाति नरोऽपराणि। > > > तथा शरीराणि विहाय जीर्णान्यन्यानि संयाति नवानि देही।। > > > **That is:** The life of your **body** begins when Zygote was formed in mother's womb, but there is no life of your **soul** (and no death either).","*Krishna* says in the *Bhagavad Gita* that the soul is eternal i.e. life neither begins nor ends. Ofcourse, the body if formed again and again as mentioned in *nobalG's* answer. TEXT 2.12 > > na tv evaham jatu nasam na tvam neme janadhipah na caiva na > bhavisyamah sarve vayam atah param > > > SYNONYMS > > na—never; tu—but; eva—certainly; aham—I; jātu—become; na—never; > āsam—existed; na—it is not so; tvam—yourself; na—not; ime—all these; > janādhipāḥ—kings; na—never; ca—also; eva—certainly; na—not like that; > bhaviṣyāmaḥ—shall exist; sarve—all of us; vayam—we; ataḥ > param—hereafter. > > > TRANSLATION > > Never was there a time when I did not exist, nor you, nor all these > kings; nor in the future shall any of us cease to be. > > > " 3018,"In my view the life begins at the time of forming zygote inside the mother's womb. My question is that what is the view of Hinduism about ""the beginning of a life""?",2014/09/04,"['https://hinduism.stackexchange.com/questions/3018', 'https://hinduism.stackexchange.com', 'https://hinduism.stackexchange.com/users/187/']","**Scientifically:** You are correct. **By Hinduism:** Its a soul,which is going to change a body like clothes, leaving off the old one and wearing newones.[see this](http://www.eaglespace.com/spirit/gita_reincarnation.php) > > vaasaa.nsi jiirNaani yathaa vihaaya navaani gRRihNaati naro.aparaaNi. > > > tathaa shariiraaNi vihaaya jiirNaanyanyaani sa.nyaati navaani dehii.. > B.G. II-22 > > > वासांसि जीर्णानि यथा विहाय नवानि गृह्णाति नरोऽपराणि। > > > तथा शरीराणि विहाय जीर्णान्यन्यानि संयाति नवानि देही।। > > > **That is:** The life of your **body** begins when Zygote was formed in mother's womb, but there is no life of your **soul** (and no death either).","My SatGuru says human life (i.e., in physical form) starts when the sperm fuses with the Ova. However, it is not that simple.The incoming spirit permeates through both the Ova and the sperm even before they fuse. Answer is taken from this video: " 3018,"In my view the life begins at the time of forming zygote inside the mother's womb. My question is that what is the view of Hinduism about ""the beginning of a life""?",2014/09/04,"['https://hinduism.stackexchange.com/questions/3018', 'https://hinduism.stackexchange.com', 'https://hinduism.stackexchange.com/users/187/']","*Krishna* says in the *Bhagavad Gita* that the soul is eternal i.e. life neither begins nor ends. Ofcourse, the body if formed again and again as mentioned in *nobalG's* answer. TEXT 2.12 > > na tv evaham jatu nasam na tvam neme janadhipah na caiva na > bhavisyamah sarve vayam atah param > > > SYNONYMS > > na—never; tu—but; eva—certainly; aham—I; jātu—become; na—never; > āsam—existed; na—it is not so; tvam—yourself; na—not; ime—all these; > janādhipāḥ—kings; na—never; ca—also; eva—certainly; na—not like that; > bhaviṣyāmaḥ—shall exist; sarve—all of us; vayam—we; ataḥ > param—hereafter. > > > TRANSLATION > > Never was there a time when I did not exist, nor you, nor all these > kings; nor in the future shall any of us cease to be. > > > ","My SatGuru says human life (i.e., in physical form) starts when the sperm fuses with the Ova. However, it is not that simple.The incoming spirit permeates through both the Ova and the sperm even before they fuse. Answer is taken from this video: " 37899964,"I am a total scrub with the node http module and having some trouble. The ultimate goal here is to take a huge list of urls, figure out which are valid and then scrape those pages for certain data. So step one is figuring out if a URL is valid and this simple exercise is baffling me. say we have an array allURLs: ``` [""www.yahoo.com"", ""www.stackoverflow.com"", ""www.sdfhksdjfksjdhg.net""] ``` The goal is to iterate this array, make a get request to each and if a response comes in, add the link to a list of workingURLs (for now just another array), else it goes to a list brokenURLs. ``` var workingURLs = []; var brokenURLs = []; for (var i = 0; i < allURLs.length; i++) { var url = allURLs[i]; var req = http.get(url, function (res) { if (res) { workingURLs.push(?????); // How to derive URL from response? } }); req.on('error', function (e) { brokenURLs.push(e.host); }); } ``` what I don't know is how to properly obtain the url from the request/ response object itself, or really how to structure this kind of async code - because again, I am a nodejs scrub :( For most websites using res.headers.location works, but there are times when the headers do not have this property and that will cause problems for me later on. Also I've tried console logging the response object itself and that was a messy and fruitless endeavor I have tried pushing the url variable to workingURLs, but by the time any response comes back that would trigger the push, the for loop is already over and url is forever pointing to the final element of the allURLs array. Thanks to anyone who can help",2016/06/18,"['https://Stackoverflow.com/questions/37899964', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6062473/']","You need to closure url value to have access to it and protect it from changes on next loop iteration. For example: ``` (function(url){ // use url here })(allUrls[i]); ``` Most simple solution for this is use `forEach` instead of `for`. ``` allURLs.forEach(function(url){ //.... }); ``` Promisified solution allows you to get a moment when work is done: ``` var http = require('http'); var allURLs = [ ""http://www.yahoo.com/"", ""http://www.stackoverflow.com/"", ""http://www.sdfhksdjfksjdhg.net/"" ]; var workingURLs = []; var brokenURLs = []; var promises = allURLs.map(url => validateUrl(url) .then(res => (res?workingURLs:brokenURLs).push(url))); Promise.all(promises).then(() => { console.log(workingURLs, brokenURLs); }); // ---- function validateUrl(url) { return new Promise((ok, fail) => { http.get(url, res => return ok(res.statusCode == 200)) .on('error', e => ok(false)); }); } // Prevent nodejs from exit, don't need if any server listen. var t = setTimeout(() => { console.log('Time is over'); }, 1000).ref(); ```","You can use something like this (Not tested): ``` const arr = ["""", ""/a"", """", """"]; Promise.all(arr.map(fetch) .then(responses=>responses.filter(res=> res.ok).map(res=>res.url)) .then(workingUrls=>{ console.log(workingUrls); console.log(arr.filter(url=> workingUrls.indexOf(url) == -1 )) }); ``` **EDITED** [Working fiddle](https://jsfiddle.net/joherro3/x9mg92xf/2/) (Note that you can't do request to another site in the browser because of Cross domain). **UPDATED with @vp\_arth suggestions** ``` const arr = [""/"", ""/a"", ""/"", ""/""]; let working=[], notWorking=[], find = url=> fetch(url) .then(res=> res.ok ? working.push(res.url) && res : notWorking.push(res.url) && res); Promise.all(arr.map(find)) .then(responses=>{ console.log('woking', working, 'notWorking', notWorking); /* Do whatever with the responses if needed */ }); ``` [Fiddle](https://jsfiddle.net/joherro3/x9mg92xf/3/)" 47712861,"I have Three queries execute at the same time and its declared one object $sql. In result ""Product"" Array Actually Four Record display only one Record,Three Record is not Display. In ""total"" Array Percentage Value Display null. I have need this Result ``` {""success"":1,""product"":[{""std_Name"":""VIVEK SANAPARA"",""Standard"":""12-SCI-CE"",""Division"":""A"",""ExamDate"":{""date"":""2016-10-06 00:00:00.000000"",""timezone_type"":3,""timezone"":""UTC""},""subject"":""MATHS"",""ExamName"":""WT"",""Marks"":""30.00"",""TotalMarks"":""30.00"",""PassingMarks"":""10""},{""std_Name"":""VIVEK SANAPARA"",""Standard"":""12-SCI-CE"",""Division"":""A"",""ExamDate"":{""date"":""2016-10-07 00:00:00.000000"",""timezone_type"":3,""timezone"":""Asia\/Kolkata""},""subject"":""PHYSICS"",""ExamName"":""WT"",""Marks"":""15.00"",""TotalMarks"":""30.00"",""PassingMarks"":""10""},{""std_Name"":""VIVEK SANAPARA"",""Standard"":""12-SCI-CE"",""Division"":""A"",""ExamDate"":{""date"":""2016-10-08 00:00:00.000000"",""timezone_type"":3,""timezone"":""Asia\/Kolkata""},""subject"":""PHYSICS"",""ExamName"":""WT"",""Marks"":""25.00"",""TotalMarks"":""30.00"",""PassingMarks"":""10""},{""std_Name"":""VIVEK SANAPARA"",""Standard"":""12-SCI-CE"",""Division"":""A"",""ExamDate"":{""date"":""2016-11-22 00:00:00.000000"",""timezone_type"":3,""timezone"":""Asia\/Kolkata""},""subject"":""PHYSICS"",""ExamName"":""WT"",""Marks"":""25.00"",""TotalMarks"":""30.00"",""PassingMarks"":""10""},],""total"":[{""Marks"":""30.00"",""TotalMarks"":""30.00"",""Percentage"":""79.166600""}],""exam"":[{""ExamName"":""WT""}]} ``` I have show Error Image below the Code. In image only one record display but in above resulr Four Record and Percentage Value Display null in image. Marks.php ``` if(isset($_REQUEST[""insert""])) { $reg = $_GET['reg']; $sql = ""select b.std_Name,d.Standard,e.Division,a.ExamDate,f.subject,a.ExamName,a.Marks,a.TotalMarks,a.PassingMarks from Marks_mas a inner join std_reg b on a.regno=b.regno INNER JOIN Subject_mas as f ON a.Subject_ID = f.Subject_ID inner join StandardMaster d on a.standard = d.STDID inner join DivisionMaster e on a.Division = e.DivisionID where a.RegNo= '$reg' order by a.ExamDate; select sum(a.Marks) as Marks,sum(a.TotalMarks) as TotalMarks, sum(a.Marks)/sum(a.TotalMarks) * 100 as Percentage from Marks_mas a where a.RegNo= '$reg'; select distinct ExamName From Marks_mas;""; $stmt = sqlsrv_query($conn, $sql); $result = array(); if (!empty($stmt)) { // check for empty result if (sqlsrv_has_rows($stmt) > 0) { $stmt = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC); $product = array(); $product[""std_Name""] = $stmt[""std_Name""]; $product[""Standard""] = $stmt[""Standard""]; $product[""Division""] = $stmt[""Division""]; $product[""ExamDate""] = $stmt[""ExamDate""]; $product[""subject""] = $stmt[""subject""]; $product[""ExamName""] = $stmt[""ExamName""]; $product[""Marks""] = $stmt[""Marks""]; $product[""TotalMarks""] = $stmt[""TotalMarks""]; $product[""PassingMarks""] = $stmt[""PassingMarks""]; $total = array(); $total[""Marks""] = $stmt[""Marks""]; $total[""TotalMarks""] = $stmt[""TotalMarks""]; $total[""Percentage""] = $stmt[""Percentage""]; $exam = array(); $exam[""ExamName""] = $stmt[""ExamName""]; // success $result[""success""] = 1; // user node $result[""product""] = array(); $result[""total""] = array(); $result[""exam""] = array(); array_push($result[""product""],$product); array_push($result[""total""],$total); array_push($result[""exam""],$exam); // echoing JSON response echo json_encode($result); } else { // no product found $result[""success""] = 0; $result[""message""] = ""No product found""; // echo no users JSON echo json_encode($result); } //sqlsrv_free_stmt($stmt); sqlsrv_close($conn); //Close the connnection first } } ``` This is Error: [enter image description here](https://i.stack.imgur.com/fHsXV.png)",2017/12/08,"['https://Stackoverflow.com/questions/47712861', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8841544/']","You could do it with just a little CSS but it does leave a gap: ``` .week-name th:nth-child(7), .month1 tbody tr td:nth-child(7) { display: none; } ``` Hope this helps a little.","You can also do it by setting a custom css class and use it in `beforeShowDay` like below ``` .hideSunDay{ display:none; } beforeShowDay: function(t) { var valid = t.getDay() !== 0; //disable sunday var _class = t.getDay() !== 0 ? '' : 'hideSunDay'; // var _tooltip = valid ? '' : 'weekends are disabled'; return [valid, _class]; } ``` But it only hides the sundays beginning from current day. Here is a working fiddle " 47712861,"I have Three queries execute at the same time and its declared one object $sql. In result ""Product"" Array Actually Four Record display only one Record,Three Record is not Display. In ""total"" Array Percentage Value Display null. I have need this Result ``` {""success"":1,""product"":[{""std_Name"":""VIVEK SANAPARA"",""Standard"":""12-SCI-CE"",""Division"":""A"",""ExamDate"":{""date"":""2016-10-06 00:00:00.000000"",""timezone_type"":3,""timezone"":""UTC""},""subject"":""MATHS"",""ExamName"":""WT"",""Marks"":""30.00"",""TotalMarks"":""30.00"",""PassingMarks"":""10""},{""std_Name"":""VIVEK SANAPARA"",""Standard"":""12-SCI-CE"",""Division"":""A"",""ExamDate"":{""date"":""2016-10-07 00:00:00.000000"",""timezone_type"":3,""timezone"":""Asia\/Kolkata""},""subject"":""PHYSICS"",""ExamName"":""WT"",""Marks"":""15.00"",""TotalMarks"":""30.00"",""PassingMarks"":""10""},{""std_Name"":""VIVEK SANAPARA"",""Standard"":""12-SCI-CE"",""Division"":""A"",""ExamDate"":{""date"":""2016-10-08 00:00:00.000000"",""timezone_type"":3,""timezone"":""Asia\/Kolkata""},""subject"":""PHYSICS"",""ExamName"":""WT"",""Marks"":""25.00"",""TotalMarks"":""30.00"",""PassingMarks"":""10""},{""std_Name"":""VIVEK SANAPARA"",""Standard"":""12-SCI-CE"",""Division"":""A"",""ExamDate"":{""date"":""2016-11-22 00:00:00.000000"",""timezone_type"":3,""timezone"":""Asia\/Kolkata""},""subject"":""PHYSICS"",""ExamName"":""WT"",""Marks"":""25.00"",""TotalMarks"":""30.00"",""PassingMarks"":""10""},],""total"":[{""Marks"":""30.00"",""TotalMarks"":""30.00"",""Percentage"":""79.166600""}],""exam"":[{""ExamName"":""WT""}]} ``` I have show Error Image below the Code. In image only one record display but in above resulr Four Record and Percentage Value Display null in image. Marks.php ``` if(isset($_REQUEST[""insert""])) { $reg = $_GET['reg']; $sql = ""select b.std_Name,d.Standard,e.Division,a.ExamDate,f.subject,a.ExamName,a.Marks,a.TotalMarks,a.PassingMarks from Marks_mas a inner join std_reg b on a.regno=b.regno INNER JOIN Subject_mas as f ON a.Subject_ID = f.Subject_ID inner join StandardMaster d on a.standard = d.STDID inner join DivisionMaster e on a.Division = e.DivisionID where a.RegNo= '$reg' order by a.ExamDate; select sum(a.Marks) as Marks,sum(a.TotalMarks) as TotalMarks, sum(a.Marks)/sum(a.TotalMarks) * 100 as Percentage from Marks_mas a where a.RegNo= '$reg'; select distinct ExamName From Marks_mas;""; $stmt = sqlsrv_query($conn, $sql); $result = array(); if (!empty($stmt)) { // check for empty result if (sqlsrv_has_rows($stmt) > 0) { $stmt = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC); $product = array(); $product[""std_Name""] = $stmt[""std_Name""]; $product[""Standard""] = $stmt[""Standard""]; $product[""Division""] = $stmt[""Division""]; $product[""ExamDate""] = $stmt[""ExamDate""]; $product[""subject""] = $stmt[""subject""]; $product[""ExamName""] = $stmt[""ExamName""]; $product[""Marks""] = $stmt[""Marks""]; $product[""TotalMarks""] = $stmt[""TotalMarks""]; $product[""PassingMarks""] = $stmt[""PassingMarks""]; $total = array(); $total[""Marks""] = $stmt[""Marks""]; $total[""TotalMarks""] = $stmt[""TotalMarks""]; $total[""Percentage""] = $stmt[""Percentage""]; $exam = array(); $exam[""ExamName""] = $stmt[""ExamName""]; // success $result[""success""] = 1; // user node $result[""product""] = array(); $result[""total""] = array(); $result[""exam""] = array(); array_push($result[""product""],$product); array_push($result[""total""],$total); array_push($result[""exam""],$exam); // echoing JSON response echo json_encode($result); } else { // no product found $result[""success""] = 0; $result[""message""] = ""No product found""; // echo no users JSON echo json_encode($result); } //sqlsrv_free_stmt($stmt); sqlsrv_close($conn); //Close the connnection first } } ``` This is Error: [enter image description here](https://i.stack.imgur.com/fHsXV.png)",2017/12/08,"['https://Stackoverflow.com/questions/47712861', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8841544/']","I finally ended up by letting the Sundays appear (but completely disabling them). These questions inspired me : * [Moment.js - Get all mondays between a date range](https://stackoverflow.com/questions/44909662/moment-js-get-all-mondays-between-a-date-range) * [Moment.js: Date between dates](https://stackoverflow.com/questions/14897571/moment-js-date-between-dates) So I created a function as follows which returns an array that contains the ""sundays"" (or whatever day you provide as `dayNumber` parameter) in the date range you selected: ``` function getDayInRange(dayNumber, startDate, endDate, inclusiveNextDay) { var start = moment(startDate), end = moment(endDate), arr = []; // Get ""next"" given day where 1 is monday and 7 is sunday let tmp = start.clone().day(dayNumber); if (!!inclusiveNextDay && tmp.isAfter(start, 'd')) { arr.push(tmp.format('YYYY-MM-DD')); } while (tmp.isBefore(end)) { tmp.add(7, 'days'); arr.push(tmp.format('YYYY-MM-DD')); } // If last day matches the given dayNumber, add it. if (end.isoWeekday() === dayNumber) { arr.push(end.format('YYYY-MM-DD')); } return arr; } ``` Then I call this function in my code like that: ``` $('#daterange-2') .dateRangePicker(configObject2) .bind('datepicker-change', function(event, obj) { var sundays = getDayInRange(7, moment(obj.date1), moment(obj.date1).add(selectedDatesCount, 'd')); console.log(sundays); $('#daterange-2') .data('dateRangePicker') .setDateRange(obj.value, moment(obj.date1) .add(selectedDatesCount + sundays.length, 'd') .format('YYYY-MM-DD'), true); }); ``` This way, I retrieve the amount of sundays in the date range I selected. For example, if there's two sundays in my selection (with `sundays.length`), I know I have to set two additional workdays to the user selection (in the second date range picker). Here's the working result: [![working result](https://i.stack.imgur.com/PYa56.png)](https://i.stack.imgur.com/PYa56.png) With the above screenshot, you can see the user selected 4 workdays (5 with sunday but we don't count it). Then he click on the second calendar and the 4 workdays automatically apply. Here's the result if the period apply over a sunday (we add one supplementary day and `X`for `X` sundays in the period): [![other working result](https://i.stack.imgur.com/L6yR8.png)](https://i.stack.imgur.com/L6yR8.png) **Finally, here's the working fiddle: ** I want to thank any person that helped me. The question was hard to explain and to understand.","You could do it with just a little CSS but it does leave a gap: ``` .week-name th:nth-child(7), .month1 tbody tr td:nth-child(7) { display: none; } ``` Hope this helps a little." 47712861,"I have Three queries execute at the same time and its declared one object $sql. In result ""Product"" Array Actually Four Record display only one Record,Three Record is not Display. In ""total"" Array Percentage Value Display null. I have need this Result ``` {""success"":1,""product"":[{""std_Name"":""VIVEK SANAPARA"",""Standard"":""12-SCI-CE"",""Division"":""A"",""ExamDate"":{""date"":""2016-10-06 00:00:00.000000"",""timezone_type"":3,""timezone"":""UTC""},""subject"":""MATHS"",""ExamName"":""WT"",""Marks"":""30.00"",""TotalMarks"":""30.00"",""PassingMarks"":""10""},{""std_Name"":""VIVEK SANAPARA"",""Standard"":""12-SCI-CE"",""Division"":""A"",""ExamDate"":{""date"":""2016-10-07 00:00:00.000000"",""timezone_type"":3,""timezone"":""Asia\/Kolkata""},""subject"":""PHYSICS"",""ExamName"":""WT"",""Marks"":""15.00"",""TotalMarks"":""30.00"",""PassingMarks"":""10""},{""std_Name"":""VIVEK SANAPARA"",""Standard"":""12-SCI-CE"",""Division"":""A"",""ExamDate"":{""date"":""2016-10-08 00:00:00.000000"",""timezone_type"":3,""timezone"":""Asia\/Kolkata""},""subject"":""PHYSICS"",""ExamName"":""WT"",""Marks"":""25.00"",""TotalMarks"":""30.00"",""PassingMarks"":""10""},{""std_Name"":""VIVEK SANAPARA"",""Standard"":""12-SCI-CE"",""Division"":""A"",""ExamDate"":{""date"":""2016-11-22 00:00:00.000000"",""timezone_type"":3,""timezone"":""Asia\/Kolkata""},""subject"":""PHYSICS"",""ExamName"":""WT"",""Marks"":""25.00"",""TotalMarks"":""30.00"",""PassingMarks"":""10""},],""total"":[{""Marks"":""30.00"",""TotalMarks"":""30.00"",""Percentage"":""79.166600""}],""exam"":[{""ExamName"":""WT""}]} ``` I have show Error Image below the Code. In image only one record display but in above resulr Four Record and Percentage Value Display null in image. Marks.php ``` if(isset($_REQUEST[""insert""])) { $reg = $_GET['reg']; $sql = ""select b.std_Name,d.Standard,e.Division,a.ExamDate,f.subject,a.ExamName,a.Marks,a.TotalMarks,a.PassingMarks from Marks_mas a inner join std_reg b on a.regno=b.regno INNER JOIN Subject_mas as f ON a.Subject_ID = f.Subject_ID inner join StandardMaster d on a.standard = d.STDID inner join DivisionMaster e on a.Division = e.DivisionID where a.RegNo= '$reg' order by a.ExamDate; select sum(a.Marks) as Marks,sum(a.TotalMarks) as TotalMarks, sum(a.Marks)/sum(a.TotalMarks) * 100 as Percentage from Marks_mas a where a.RegNo= '$reg'; select distinct ExamName From Marks_mas;""; $stmt = sqlsrv_query($conn, $sql); $result = array(); if (!empty($stmt)) { // check for empty result if (sqlsrv_has_rows($stmt) > 0) { $stmt = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC); $product = array(); $product[""std_Name""] = $stmt[""std_Name""]; $product[""Standard""] = $stmt[""Standard""]; $product[""Division""] = $stmt[""Division""]; $product[""ExamDate""] = $stmt[""ExamDate""]; $product[""subject""] = $stmt[""subject""]; $product[""ExamName""] = $stmt[""ExamName""]; $product[""Marks""] = $stmt[""Marks""]; $product[""TotalMarks""] = $stmt[""TotalMarks""]; $product[""PassingMarks""] = $stmt[""PassingMarks""]; $total = array(); $total[""Marks""] = $stmt[""Marks""]; $total[""TotalMarks""] = $stmt[""TotalMarks""]; $total[""Percentage""] = $stmt[""Percentage""]; $exam = array(); $exam[""ExamName""] = $stmt[""ExamName""]; // success $result[""success""] = 1; // user node $result[""product""] = array(); $result[""total""] = array(); $result[""exam""] = array(); array_push($result[""product""],$product); array_push($result[""total""],$total); array_push($result[""exam""],$exam); // echoing JSON response echo json_encode($result); } else { // no product found $result[""success""] = 0; $result[""message""] = ""No product found""; // echo no users JSON echo json_encode($result); } //sqlsrv_free_stmt($stmt); sqlsrv_close($conn); //Close the connnection first } } ``` This is Error: [enter image description here](https://i.stack.imgur.com/fHsXV.png)",2017/12/08,"['https://Stackoverflow.com/questions/47712861', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8841544/']","You need do changes in two functions in your daterangepicker.js file: 1. createMonthHTML() ``` function createMonthHTML(d) { var days = []; d.setDate(1); var lastMonth = new Date(d.getTime() - 86400000); var now = new Date(); var dayOfWeek = d.getDay(); if ((dayOfWeek === 0) && (opt.startOfWeek === 'monday')) { // add one week dayOfWeek = 7; } var today, valid; if (dayOfWeek > 0) { for (var i = dayOfWeek; i > 0; i--) { var day = new Date(d.getTime() - 86400000 * i); valid = isValidTime(day.getTime()); if (opt.startDate && compare_day(day, opt.startDate) < 0) valid = false; if (opt.endDate && compare_day(day, opt.endDate) > 0) valid = false; days.push({ date: day, type: 'lastMonth', day: day.getDate(), time: day.getTime(), valid: valid }); } } var toMonth = d.getMonth(); for (var i = 0; i < 40; i++) { today = moment(d).add(i, 'days').toDate(); valid = isValidTime(today.getTime()); if (opt.startDate && compare_day(today, opt.startDate) < 0) valid = false; if (opt.endDate && compare_day(today, opt.endDate) > 0) valid = false; days.push({ date: today, type: today.getMonth() == toMonth ? 'toMonth' : 'nextMonth', day: today.getDate(), time: today.getTime(), valid: valid }); } var html = []; for (var week = 0; week < 6; week++) { if (days[week * 7].type == 'nextMonth') break; html.push(''); for (var day = 0; day < 7; day++) { var _day = (opt.startOfWeek == 'monday') ? day + 1 : day; today = days[week * 7 + _day]; var highlightToday = moment(today.time).format('L') == moment(now).format('L'); today.extraClass = ''; today.tooltip = ''; if (today.valid && opt.beforeShowDay && typeof opt.beforeShowDay == 'function') { var _r = opt.beforeShowDay(moment(today.time).toDate()); today.valid = _r[0]; today.extraClass = _r[1] || ''; today.tooltip = _r[2] || ''; if (today.tooltip !== '') today.extraClass += ' has-tooltip '; } var todayDivAttr = { time: today.time, 'data-tooltip': today.tooltip, 'class': 'day ' + today.type + ' ' + today.extraClass + ' ' + (today.valid ? 'valid' : 'invalid') + ' ' + (highlightToday ? 'real-today' : '') }; if (day === 0 && opt.showWeekNumbers) { html.push('
' + opt.getWeekNumber(today.date) + '
'); } if(day == 0){ html.push('
' + showDayHTML(today.time, today.day) + '
'); }else{ html.push('
' + showDayHTML(today.time, today.day) + '
'); } } html.push(''); } return html.join(''); } ``` In this function i have added class `hideSunday` while pushing the element. The 2nd function is getWeekHead(): ``` function getWeekHead() { var prepend = opt.showWeekNumbers ? '' + translate('week-number') + '' : ''; if (opt.startOfWeek == 'monday') { return prepend + '' + translate('week-1') + '' + '' + translate('week-2') + '' + '' + translate('week-3') + '' + '' + translate('week-4') + '' + '' + translate('week-5') + '' + '' + translate('week-6') + '' + '' + translate('week-7') + ''; } else { return prepend + '' + translate('week-7') + '' + '' + translate('week-1') + '' + '' + translate('week-2') + '' + '' + translate('week-3') + '' + '' + translate('week-4') + '' + '' + translate('week-5') + '' + '' + translate('week-6') + ''; } } ``` In this file, I have added class to week-7 header. CSS: ``` .hideSunday{display:none;} ``` Please note, I have not checked all the scenario but it will do trick for you.","You can also do it by setting a custom css class and use it in `beforeShowDay` like below ``` .hideSunDay{ display:none; } beforeShowDay: function(t) { var valid = t.getDay() !== 0; //disable sunday var _class = t.getDay() !== 0 ? '' : 'hideSunDay'; // var _tooltip = valid ? '' : 'weekends are disabled'; return [valid, _class]; } ``` But it only hides the sundays beginning from current day. Here is a working fiddle " 47712861,"I have Three queries execute at the same time and its declared one object $sql. In result ""Product"" Array Actually Four Record display only one Record,Three Record is not Display. In ""total"" Array Percentage Value Display null. I have need this Result ``` {""success"":1,""product"":[{""std_Name"":""VIVEK SANAPARA"",""Standard"":""12-SCI-CE"",""Division"":""A"",""ExamDate"":{""date"":""2016-10-06 00:00:00.000000"",""timezone_type"":3,""timezone"":""UTC""},""subject"":""MATHS"",""ExamName"":""WT"",""Marks"":""30.00"",""TotalMarks"":""30.00"",""PassingMarks"":""10""},{""std_Name"":""VIVEK SANAPARA"",""Standard"":""12-SCI-CE"",""Division"":""A"",""ExamDate"":{""date"":""2016-10-07 00:00:00.000000"",""timezone_type"":3,""timezone"":""Asia\/Kolkata""},""subject"":""PHYSICS"",""ExamName"":""WT"",""Marks"":""15.00"",""TotalMarks"":""30.00"",""PassingMarks"":""10""},{""std_Name"":""VIVEK SANAPARA"",""Standard"":""12-SCI-CE"",""Division"":""A"",""ExamDate"":{""date"":""2016-10-08 00:00:00.000000"",""timezone_type"":3,""timezone"":""Asia\/Kolkata""},""subject"":""PHYSICS"",""ExamName"":""WT"",""Marks"":""25.00"",""TotalMarks"":""30.00"",""PassingMarks"":""10""},{""std_Name"":""VIVEK SANAPARA"",""Standard"":""12-SCI-CE"",""Division"":""A"",""ExamDate"":{""date"":""2016-11-22 00:00:00.000000"",""timezone_type"":3,""timezone"":""Asia\/Kolkata""},""subject"":""PHYSICS"",""ExamName"":""WT"",""Marks"":""25.00"",""TotalMarks"":""30.00"",""PassingMarks"":""10""},],""total"":[{""Marks"":""30.00"",""TotalMarks"":""30.00"",""Percentage"":""79.166600""}],""exam"":[{""ExamName"":""WT""}]} ``` I have show Error Image below the Code. In image only one record display but in above resulr Four Record and Percentage Value Display null in image. Marks.php ``` if(isset($_REQUEST[""insert""])) { $reg = $_GET['reg']; $sql = ""select b.std_Name,d.Standard,e.Division,a.ExamDate,f.subject,a.ExamName,a.Marks,a.TotalMarks,a.PassingMarks from Marks_mas a inner join std_reg b on a.regno=b.regno INNER JOIN Subject_mas as f ON a.Subject_ID = f.Subject_ID inner join StandardMaster d on a.standard = d.STDID inner join DivisionMaster e on a.Division = e.DivisionID where a.RegNo= '$reg' order by a.ExamDate; select sum(a.Marks) as Marks,sum(a.TotalMarks) as TotalMarks, sum(a.Marks)/sum(a.TotalMarks) * 100 as Percentage from Marks_mas a where a.RegNo= '$reg'; select distinct ExamName From Marks_mas;""; $stmt = sqlsrv_query($conn, $sql); $result = array(); if (!empty($stmt)) { // check for empty result if (sqlsrv_has_rows($stmt) > 0) { $stmt = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC); $product = array(); $product[""std_Name""] = $stmt[""std_Name""]; $product[""Standard""] = $stmt[""Standard""]; $product[""Division""] = $stmt[""Division""]; $product[""ExamDate""] = $stmt[""ExamDate""]; $product[""subject""] = $stmt[""subject""]; $product[""ExamName""] = $stmt[""ExamName""]; $product[""Marks""] = $stmt[""Marks""]; $product[""TotalMarks""] = $stmt[""TotalMarks""]; $product[""PassingMarks""] = $stmt[""PassingMarks""]; $total = array(); $total[""Marks""] = $stmt[""Marks""]; $total[""TotalMarks""] = $stmt[""TotalMarks""]; $total[""Percentage""] = $stmt[""Percentage""]; $exam = array(); $exam[""ExamName""] = $stmt[""ExamName""]; // success $result[""success""] = 1; // user node $result[""product""] = array(); $result[""total""] = array(); $result[""exam""] = array(); array_push($result[""product""],$product); array_push($result[""total""],$total); array_push($result[""exam""],$exam); // echoing JSON response echo json_encode($result); } else { // no product found $result[""success""] = 0; $result[""message""] = ""No product found""; // echo no users JSON echo json_encode($result); } //sqlsrv_free_stmt($stmt); sqlsrv_close($conn); //Close the connnection first } } ``` This is Error: [enter image description here](https://i.stack.imgur.com/fHsXV.png)",2017/12/08,"['https://Stackoverflow.com/questions/47712861', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8841544/']","I finally ended up by letting the Sundays appear (but completely disabling them). These questions inspired me : * [Moment.js - Get all mondays between a date range](https://stackoverflow.com/questions/44909662/moment-js-get-all-mondays-between-a-date-range) * [Moment.js: Date between dates](https://stackoverflow.com/questions/14897571/moment-js-date-between-dates) So I created a function as follows which returns an array that contains the ""sundays"" (or whatever day you provide as `dayNumber` parameter) in the date range you selected: ``` function getDayInRange(dayNumber, startDate, endDate, inclusiveNextDay) { var start = moment(startDate), end = moment(endDate), arr = []; // Get ""next"" given day where 1 is monday and 7 is sunday let tmp = start.clone().day(dayNumber); if (!!inclusiveNextDay && tmp.isAfter(start, 'd')) { arr.push(tmp.format('YYYY-MM-DD')); } while (tmp.isBefore(end)) { tmp.add(7, 'days'); arr.push(tmp.format('YYYY-MM-DD')); } // If last day matches the given dayNumber, add it. if (end.isoWeekday() === dayNumber) { arr.push(end.format('YYYY-MM-DD')); } return arr; } ``` Then I call this function in my code like that: ``` $('#daterange-2') .dateRangePicker(configObject2) .bind('datepicker-change', function(event, obj) { var sundays = getDayInRange(7, moment(obj.date1), moment(obj.date1).add(selectedDatesCount, 'd')); console.log(sundays); $('#daterange-2') .data('dateRangePicker') .setDateRange(obj.value, moment(obj.date1) .add(selectedDatesCount + sundays.length, 'd') .format('YYYY-MM-DD'), true); }); ``` This way, I retrieve the amount of sundays in the date range I selected. For example, if there's two sundays in my selection (with `sundays.length`), I know I have to set two additional workdays to the user selection (in the second date range picker). Here's the working result: [![working result](https://i.stack.imgur.com/PYa56.png)](https://i.stack.imgur.com/PYa56.png) With the above screenshot, you can see the user selected 4 workdays (5 with sunday but we don't count it). Then he click on the second calendar and the 4 workdays automatically apply. Here's the result if the period apply over a sunday (we add one supplementary day and `X`for `X` sundays in the period): [![other working result](https://i.stack.imgur.com/L6yR8.png)](https://i.stack.imgur.com/L6yR8.png) **Finally, here's the working fiddle: ** I want to thank any person that helped me. The question was hard to explain and to understand.","You can also do it by setting a custom css class and use it in `beforeShowDay` like below ``` .hideSunDay{ display:none; } beforeShowDay: function(t) { var valid = t.getDay() !== 0; //disable sunday var _class = t.getDay() !== 0 ? '' : 'hideSunDay'; // var _tooltip = valid ? '' : 'weekends are disabled'; return [valid, _class]; } ``` But it only hides the sundays beginning from current day. Here is a working fiddle " 47712861,"I have Three queries execute at the same time and its declared one object $sql. In result ""Product"" Array Actually Four Record display only one Record,Three Record is not Display. In ""total"" Array Percentage Value Display null. I have need this Result ``` {""success"":1,""product"":[{""std_Name"":""VIVEK SANAPARA"",""Standard"":""12-SCI-CE"",""Division"":""A"",""ExamDate"":{""date"":""2016-10-06 00:00:00.000000"",""timezone_type"":3,""timezone"":""UTC""},""subject"":""MATHS"",""ExamName"":""WT"",""Marks"":""30.00"",""TotalMarks"":""30.00"",""PassingMarks"":""10""},{""std_Name"":""VIVEK SANAPARA"",""Standard"":""12-SCI-CE"",""Division"":""A"",""ExamDate"":{""date"":""2016-10-07 00:00:00.000000"",""timezone_type"":3,""timezone"":""Asia\/Kolkata""},""subject"":""PHYSICS"",""ExamName"":""WT"",""Marks"":""15.00"",""TotalMarks"":""30.00"",""PassingMarks"":""10""},{""std_Name"":""VIVEK SANAPARA"",""Standard"":""12-SCI-CE"",""Division"":""A"",""ExamDate"":{""date"":""2016-10-08 00:00:00.000000"",""timezone_type"":3,""timezone"":""Asia\/Kolkata""},""subject"":""PHYSICS"",""ExamName"":""WT"",""Marks"":""25.00"",""TotalMarks"":""30.00"",""PassingMarks"":""10""},{""std_Name"":""VIVEK SANAPARA"",""Standard"":""12-SCI-CE"",""Division"":""A"",""ExamDate"":{""date"":""2016-11-22 00:00:00.000000"",""timezone_type"":3,""timezone"":""Asia\/Kolkata""},""subject"":""PHYSICS"",""ExamName"":""WT"",""Marks"":""25.00"",""TotalMarks"":""30.00"",""PassingMarks"":""10""},],""total"":[{""Marks"":""30.00"",""TotalMarks"":""30.00"",""Percentage"":""79.166600""}],""exam"":[{""ExamName"":""WT""}]} ``` I have show Error Image below the Code. In image only one record display but in above resulr Four Record and Percentage Value Display null in image. Marks.php ``` if(isset($_REQUEST[""insert""])) { $reg = $_GET['reg']; $sql = ""select b.std_Name,d.Standard,e.Division,a.ExamDate,f.subject,a.ExamName,a.Marks,a.TotalMarks,a.PassingMarks from Marks_mas a inner join std_reg b on a.regno=b.regno INNER JOIN Subject_mas as f ON a.Subject_ID = f.Subject_ID inner join StandardMaster d on a.standard = d.STDID inner join DivisionMaster e on a.Division = e.DivisionID where a.RegNo= '$reg' order by a.ExamDate; select sum(a.Marks) as Marks,sum(a.TotalMarks) as TotalMarks, sum(a.Marks)/sum(a.TotalMarks) * 100 as Percentage from Marks_mas a where a.RegNo= '$reg'; select distinct ExamName From Marks_mas;""; $stmt = sqlsrv_query($conn, $sql); $result = array(); if (!empty($stmt)) { // check for empty result if (sqlsrv_has_rows($stmt) > 0) { $stmt = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC); $product = array(); $product[""std_Name""] = $stmt[""std_Name""]; $product[""Standard""] = $stmt[""Standard""]; $product[""Division""] = $stmt[""Division""]; $product[""ExamDate""] = $stmt[""ExamDate""]; $product[""subject""] = $stmt[""subject""]; $product[""ExamName""] = $stmt[""ExamName""]; $product[""Marks""] = $stmt[""Marks""]; $product[""TotalMarks""] = $stmt[""TotalMarks""]; $product[""PassingMarks""] = $stmt[""PassingMarks""]; $total = array(); $total[""Marks""] = $stmt[""Marks""]; $total[""TotalMarks""] = $stmt[""TotalMarks""]; $total[""Percentage""] = $stmt[""Percentage""]; $exam = array(); $exam[""ExamName""] = $stmt[""ExamName""]; // success $result[""success""] = 1; // user node $result[""product""] = array(); $result[""total""] = array(); $result[""exam""] = array(); array_push($result[""product""],$product); array_push($result[""total""],$total); array_push($result[""exam""],$exam); // echoing JSON response echo json_encode($result); } else { // no product found $result[""success""] = 0; $result[""message""] = ""No product found""; // echo no users JSON echo json_encode($result); } //sqlsrv_free_stmt($stmt); sqlsrv_close($conn); //Close the connnection first } } ``` This is Error: [enter image description here](https://i.stack.imgur.com/fHsXV.png)",2017/12/08,"['https://Stackoverflow.com/questions/47712861', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8841544/']","I finally ended up by letting the Sundays appear (but completely disabling them). These questions inspired me : * [Moment.js - Get all mondays between a date range](https://stackoverflow.com/questions/44909662/moment-js-get-all-mondays-between-a-date-range) * [Moment.js: Date between dates](https://stackoverflow.com/questions/14897571/moment-js-date-between-dates) So I created a function as follows which returns an array that contains the ""sundays"" (or whatever day you provide as `dayNumber` parameter) in the date range you selected: ``` function getDayInRange(dayNumber, startDate, endDate, inclusiveNextDay) { var start = moment(startDate), end = moment(endDate), arr = []; // Get ""next"" given day where 1 is monday and 7 is sunday let tmp = start.clone().day(dayNumber); if (!!inclusiveNextDay && tmp.isAfter(start, 'd')) { arr.push(tmp.format('YYYY-MM-DD')); } while (tmp.isBefore(end)) { tmp.add(7, 'days'); arr.push(tmp.format('YYYY-MM-DD')); } // If last day matches the given dayNumber, add it. if (end.isoWeekday() === dayNumber) { arr.push(end.format('YYYY-MM-DD')); } return arr; } ``` Then I call this function in my code like that: ``` $('#daterange-2') .dateRangePicker(configObject2) .bind('datepicker-change', function(event, obj) { var sundays = getDayInRange(7, moment(obj.date1), moment(obj.date1).add(selectedDatesCount, 'd')); console.log(sundays); $('#daterange-2') .data('dateRangePicker') .setDateRange(obj.value, moment(obj.date1) .add(selectedDatesCount + sundays.length, 'd') .format('YYYY-MM-DD'), true); }); ``` This way, I retrieve the amount of sundays in the date range I selected. For example, if there's two sundays in my selection (with `sundays.length`), I know I have to set two additional workdays to the user selection (in the second date range picker). Here's the working result: [![working result](https://i.stack.imgur.com/PYa56.png)](https://i.stack.imgur.com/PYa56.png) With the above screenshot, you can see the user selected 4 workdays (5 with sunday but we don't count it). Then he click on the second calendar and the 4 workdays automatically apply. Here's the result if the period apply over a sunday (we add one supplementary day and `X`for `X` sundays in the period): [![other working result](https://i.stack.imgur.com/L6yR8.png)](https://i.stack.imgur.com/L6yR8.png) **Finally, here's the working fiddle: ** I want to thank any person that helped me. The question was hard to explain and to understand.","You need do changes in two functions in your daterangepicker.js file: 1. createMonthHTML() ``` function createMonthHTML(d) { var days = []; d.setDate(1); var lastMonth = new Date(d.getTime() - 86400000); var now = new Date(); var dayOfWeek = d.getDay(); if ((dayOfWeek === 0) && (opt.startOfWeek === 'monday')) { // add one week dayOfWeek = 7; } var today, valid; if (dayOfWeek > 0) { for (var i = dayOfWeek; i > 0; i--) { var day = new Date(d.getTime() - 86400000 * i); valid = isValidTime(day.getTime()); if (opt.startDate && compare_day(day, opt.startDate) < 0) valid = false; if (opt.endDate && compare_day(day, opt.endDate) > 0) valid = false; days.push({ date: day, type: 'lastMonth', day: day.getDate(), time: day.getTime(), valid: valid }); } } var toMonth = d.getMonth(); for (var i = 0; i < 40; i++) { today = moment(d).add(i, 'days').toDate(); valid = isValidTime(today.getTime()); if (opt.startDate && compare_day(today, opt.startDate) < 0) valid = false; if (opt.endDate && compare_day(today, opt.endDate) > 0) valid = false; days.push({ date: today, type: today.getMonth() == toMonth ? 'toMonth' : 'nextMonth', day: today.getDate(), time: today.getTime(), valid: valid }); } var html = []; for (var week = 0; week < 6; week++) { if (days[week * 7].type == 'nextMonth') break; html.push(''); for (var day = 0; day < 7; day++) { var _day = (opt.startOfWeek == 'monday') ? day + 1 : day; today = days[week * 7 + _day]; var highlightToday = moment(today.time).format('L') == moment(now).format('L'); today.extraClass = ''; today.tooltip = ''; if (today.valid && opt.beforeShowDay && typeof opt.beforeShowDay == 'function') { var _r = opt.beforeShowDay(moment(today.time).toDate()); today.valid = _r[0]; today.extraClass = _r[1] || ''; today.tooltip = _r[2] || ''; if (today.tooltip !== '') today.extraClass += ' has-tooltip '; } var todayDivAttr = { time: today.time, 'data-tooltip': today.tooltip, 'class': 'day ' + today.type + ' ' + today.extraClass + ' ' + (today.valid ? 'valid' : 'invalid') + ' ' + (highlightToday ? 'real-today' : '') }; if (day === 0 && opt.showWeekNumbers) { html.push('
' + opt.getWeekNumber(today.date) + '
'); } if(day == 0){ html.push('
' + showDayHTML(today.time, today.day) + '
'); }else{ html.push('
' + showDayHTML(today.time, today.day) + '
'); } } html.push(''); } return html.join(''); } ``` In this function i have added class `hideSunday` while pushing the element. The 2nd function is getWeekHead(): ``` function getWeekHead() { var prepend = opt.showWeekNumbers ? '' + translate('week-number') + '' : ''; if (opt.startOfWeek == 'monday') { return prepend + '' + translate('week-1') + '' + '' + translate('week-2') + '' + '' + translate('week-3') + '' + '' + translate('week-4') + '' + '' + translate('week-5') + '' + '' + translate('week-6') + '' + '' + translate('week-7') + ''; } else { return prepend + '' + translate('week-7') + '' + '' + translate('week-1') + '' + '' + translate('week-2') + '' + '' + translate('week-3') + '' + '' + translate('week-4') + '' + '' + translate('week-5') + '' + '' + translate('week-6') + ''; } } ``` In this file, I have added class to week-7 header. CSS: ``` .hideSunday{display:none;} ``` Please note, I have not checked all the scenario but it will do trick for you." 46977956,"Any ideas how to create like this animation on iOS using Swift ? Thanks [![enter image description here](https://i.stack.imgur.com/h49Hi.gif)](https://i.stack.imgur.com/h49Hi.gif)",2017/10/27,"['https://Stackoverflow.com/questions/46977956', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5718563/']","There are three ways to achieve this (probably more than three): 1. Create a custom header and listen to your table view Scroll, then update the header based on the offset. 2. Use a third party library like this one: * 3. Follow a tutorial (there are many of them): Sometimes it is better to do that by yourself, but in this case, I think a framework could help you.",I think it's not the UINavigationBar. You could change nav bar alpha then add custom view to table view or collection view and create animation that you need when scrolling. 46977956,"Any ideas how to create like this animation on iOS using Swift ? Thanks [![enter image description here](https://i.stack.imgur.com/h49Hi.gif)](https://i.stack.imgur.com/h49Hi.gif)",2017/10/27,"['https://Stackoverflow.com/questions/46977956', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5718563/']","There are three ways to achieve this (probably more than three): 1. Create a custom header and listen to your table view Scroll, then update the header based on the offset. 2. Use a third party library like this one: * 3. Follow a tutorial (there are many of them): Sometimes it is better to do that by yourself, but in this case, I think a framework could help you.",Custom Collection view flow layout or ScrollView with UIScrollViewDelegate adjusting the header height when content offset is changing. 9347,"In the rules it is recommended for the first games to use side A of the wonders only. After these first games (if I understand the rules correctly) players play the side that is *at the top* of the wonder card they draw. So some would play side A and some side B (probably). This question discusses [if the two sides are balanced](https://boardgames.stackexchange.com/questions/5310/are-the-a-sides-and-b-sides-of-the-wonder-boards-really-balanced). I wonder if this is really the best way? I see several possibilities how to handle which side to play: 1. randomly drawn wonder cards, but all players use side A (recommended for the first games) 2. randomly drawn wonder cards, but all players use side B 3. randomly drawn wonder cards, all players use the side that is at the top when the card is revealed (the normal rule) 4. randomly drawn wonder cards, all players use the side they like more I feel like variant 4 would be the best (each player may select the side) for a casual playing group, as otherwise some side A players might feel that the side B players have an ""unfair"" advantage (as the special abilites on B *seem* to be better). Would it be problematic/unbalanced to use variant 4? How does the side get selected in tournaments? --- EDIT: The rules also allow that players (if all agree) can choose which *wonder* to play. In this case, variant 4 is probably used (variants 1 and 2 would be possible, too), while variant 3 would be rather pointless (you'd select a wonder yourself but randomize which side to play). Anyhow, this question is about randomly chosen wonders.",2012/11/23,"['https://boardgames.stackexchange.com/questions/9347', 'https://boardgames.stackexchange.com', 'https://boardgames.stackexchange.com/users/3532/']","This is a tricky one. The rulebook makes seems to specify option #3 pretty specifically: > > Shuffle the 7 Wonder cards, face down, and hand one to each player. The card **and its facing** determine the Wonders board given to each player, as well as the side to be used during the game. > > > However, when I demoed the Leaders expansion from Asmodee at a convention, option #4 was used; the cards were dealt randomly but players were allowed to choose their own sides. This was the first I had seen this rule, but it seemed to work well and I immediately started using it in casual games as well. Not only do players get to choose the board they like better, but there's no worry about making sure to maintain the orientation on the Wonder card when revealing it. I encountered the same rule at GenCon 2012, when I played (with little success, sadly) in a tournament.","The sides are pretty imbalanced - with about one exception (I forget which, and depends on Leaders expansion) B is far stronger. In general it's a poorly balanced game but forcing some players to side A and some to side B only exacerbates this." 7324767,"Look at the Twitter sign up page at Even when you click on first input field ""Full name"" placeholder stays there until I start typing something. That is awesome. Does anyone know of a good jQuery plugin that comes close to that?",2011/09/06,"['https://Stackoverflow.com/questions/7324767', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/796723/']",One possible problem could be that the web server is running out of memory and forcing the app pool to recycle. This would flush the InProc Session memory. You could try using Sql Session State instead and see if that resolves the problem. Try monitoring the web server processes and see if they're recycling quickly.,"You can place a ``` if(Session.IsNew) ``` check in your code and redirect/stop code execution appropriately." 7324767,"Look at the Twitter sign up page at Even when you click on first input field ""Full name"" placeholder stays there until I start typing something. That is awesome. Does anyone know of a good jQuery plugin that comes close to that?",2011/09/06,"['https://Stackoverflow.com/questions/7324767', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/796723/']",One possible problem could be that the web server is running out of memory and forcing the app pool to recycle. This would flush the InProc Session memory. You could try using Sql Session State instead and see if that resolves the problem. Try monitoring the web server processes and see if they're recycling quickly.,"I would check the Performance tab in IIS to see whether a bandwidth threshold is set. 1. Right click on website in IIS 2. Performance tab 3. Check ""Bandwidth throttling"" limit If a treshold is set you might be hitting the maximum bandwidth (KB per second) limit. Either disable bandwidth throttling, or increase the limit." 79016,"Given the case that a user is presented a modal dialog that displays an installation process (or something similar). If the process would normally take a few seconds but can potentially take longer, should I offer a ""Cancel"" button to give the user full control? I've seen installers that disable the Cancel button and others that can do a rollback after Cancel is clicked. But what if one does not have the option of a full rollback? Should I ... * trap the user in the dialog until the process is completed or a timeout is reached * offer the Cancel button anyways, with the drawback of possibly generating data garbage or an invalid installation",2015/05/20,"['https://ux.stackexchange.com/questions/79016', 'https://ux.stackexchange.com', 'https://ux.stackexchange.com/users/19337/']","It very much depends on the type of your application the operation it is doing. Ideally user should always be in control, but there are situations when you will want to keep control when you are making critical changes. Firstly, you must inform user that a following operation might take X amount of time and that she may not be able to use the system. ![enter image description here](https://i.stack.imgur.com/mYfVN.jpg) When you tell such a thing, this puts a certain amount of stress on the user. You should try your best to alleviate that stress. Best way is to show the time left, and what exactly is the action you are performing. While doing so, your messages should avoid jargon and meet the target audience's vocabulary. A windows update may not be an precise example for this situation but it does tell you how Microsoft handled it in Windows 7. ![enter image description here](https://i.stack.imgur.com/jqnOo.png) Although here Windows can not estimate the time required, it tries to break up the operation in steps so that user has some tangible progress to hold on to. This is very essential for many reasons. I have seen vague progress bars which just run to oblivion without offering any solace to users. You must avoid that. *Considering your use case, after user feedback, you might want to push the message of delay when the operation does not complete in threshold time. I agree that users would already have started the process, but if most of the times the operation is going to take few seconds, there is no reason to always show a message that they can't use the system. After a few seconds you can pop up and mention this seems to be taking longer than usual. You might need a users opinion on this.*","If there is no safe way for the user to leave the process then you really should make them wait until it is complete. Leaving them with a faulty system is potentially more damaging to the software's reputation than making them wait for an extra 20 minutes for a correct and perfect instal. However, I assume that they've gone through some sort of process to get to that point (agree to EULA, select instal location, etc), that would be that time to clearly tell them how much time it is expected to take in the worst cases (this will also add a little expectation management giving users who don't experience worst case a pleasant surprise when the process completes more quickly than expected). If you must offer a ""cancel at any cost"" option then you will need to clearly message the user about the cost to their system (bad data, disk errors, failing software, etc) with an ""Are you sure?"" dialogue so that they can make an informed choice. You might also need to include a legal disclaimer depending on the amount of damage you could potentially do to their system." 79016,"Given the case that a user is presented a modal dialog that displays an installation process (or something similar). If the process would normally take a few seconds but can potentially take longer, should I offer a ""Cancel"" button to give the user full control? I've seen installers that disable the Cancel button and others that can do a rollback after Cancel is clicked. But what if one does not have the option of a full rollback? Should I ... * trap the user in the dialog until the process is completed or a timeout is reached * offer the Cancel button anyways, with the drawback of possibly generating data garbage or an invalid installation",2015/05/20,"['https://ux.stackexchange.com/questions/79016', 'https://ux.stackexchange.com', 'https://ux.stackexchange.com/users/19337/']","If there is no safe way for the user to leave the process then you really should make them wait until it is complete. Leaving them with a faulty system is potentially more damaging to the software's reputation than making them wait for an extra 20 minutes for a correct and perfect instal. However, I assume that they've gone through some sort of process to get to that point (agree to EULA, select instal location, etc), that would be that time to clearly tell them how much time it is expected to take in the worst cases (this will also add a little expectation management giving users who don't experience worst case a pleasant surprise when the process completes more quickly than expected). If you must offer a ""cancel at any cost"" option then you will need to clearly message the user about the cost to their system (bad data, disk errors, failing software, etc) with an ""Are you sure?"" dialogue so that they can make an informed choice. You might also need to include a legal disclaimer depending on the amount of damage you could potentially do to their system.","If possible, present the user with a ""Finish Later"" option on the dialog, instead of ""Cancel"". If the install takes longer than they want right now, or they have something important they need to do right now that the install process is interfering with, they can choose that option and then you let them continue the next time the install process is initiated." 79016,"Given the case that a user is presented a modal dialog that displays an installation process (or something similar). If the process would normally take a few seconds but can potentially take longer, should I offer a ""Cancel"" button to give the user full control? I've seen installers that disable the Cancel button and others that can do a rollback after Cancel is clicked. But what if one does not have the option of a full rollback? Should I ... * trap the user in the dialog until the process is completed or a timeout is reached * offer the Cancel button anyways, with the drawback of possibly generating data garbage or an invalid installation",2015/05/20,"['https://ux.stackexchange.com/questions/79016', 'https://ux.stackexchange.com', 'https://ux.stackexchange.com/users/19337/']","It very much depends on the type of your application the operation it is doing. Ideally user should always be in control, but there are situations when you will want to keep control when you are making critical changes. Firstly, you must inform user that a following operation might take X amount of time and that she may not be able to use the system. ![enter image description here](https://i.stack.imgur.com/mYfVN.jpg) When you tell such a thing, this puts a certain amount of stress on the user. You should try your best to alleviate that stress. Best way is to show the time left, and what exactly is the action you are performing. While doing so, your messages should avoid jargon and meet the target audience's vocabulary. A windows update may not be an precise example for this situation but it does tell you how Microsoft handled it in Windows 7. ![enter image description here](https://i.stack.imgur.com/jqnOo.png) Although here Windows can not estimate the time required, it tries to break up the operation in steps so that user has some tangible progress to hold on to. This is very essential for many reasons. I have seen vague progress bars which just run to oblivion without offering any solace to users. You must avoid that. *Considering your use case, after user feedback, you might want to push the message of delay when the operation does not complete in threshold time. I agree that users would already have started the process, but if most of the times the operation is going to take few seconds, there is no reason to always show a message that they can't use the system. After a few seconds you can pop up and mention this seems to be taking longer than usual. You might need a users opinion on this.*","I believe the correct action would be to explain to the user before going through with the irreversible action, that the action is irreversible. `""Doing this is permanent / This action is un-doable / You can not roll back this change"" -> OK /cancel` Or something like that depending on what kind of users you have and what jargon they do or don't know. Don't trap a user on a load screen if avoidable. If the load time really is so high that you have to expect the user to want to cancel out of it; then we can now acknowledge that the load time is very high. So let's make the user prepared for this long, irreversible load time and at least give them the option to start it in their own time. Presenting junk data would only be okay if CRUD'ing / manipulating data was normal/easy/expected/not a hassel. But it usually is considering we as UX designers should value every single click we cost on the user." 79016,"Given the case that a user is presented a modal dialog that displays an installation process (or something similar). If the process would normally take a few seconds but can potentially take longer, should I offer a ""Cancel"" button to give the user full control? I've seen installers that disable the Cancel button and others that can do a rollback after Cancel is clicked. But what if one does not have the option of a full rollback? Should I ... * trap the user in the dialog until the process is completed or a timeout is reached * offer the Cancel button anyways, with the drawback of possibly generating data garbage or an invalid installation",2015/05/20,"['https://ux.stackexchange.com/questions/79016', 'https://ux.stackexchange.com', 'https://ux.stackexchange.com/users/19337/']","I believe the correct action would be to explain to the user before going through with the irreversible action, that the action is irreversible. `""Doing this is permanent / This action is un-doable / You can not roll back this change"" -> OK /cancel` Or something like that depending on what kind of users you have and what jargon they do or don't know. Don't trap a user on a load screen if avoidable. If the load time really is so high that you have to expect the user to want to cancel out of it; then we can now acknowledge that the load time is very high. So let's make the user prepared for this long, irreversible load time and at least give them the option to start it in their own time. Presenting junk data would only be okay if CRUD'ing / manipulating data was normal/easy/expected/not a hassel. But it usually is considering we as UX designers should value every single click we cost on the user.","If possible, present the user with a ""Finish Later"" option on the dialog, instead of ""Cancel"". If the install takes longer than they want right now, or they have something important they need to do right now that the install process is interfering with, they can choose that option and then you let them continue the next time the install process is initiated." 79016,"Given the case that a user is presented a modal dialog that displays an installation process (or something similar). If the process would normally take a few seconds but can potentially take longer, should I offer a ""Cancel"" button to give the user full control? I've seen installers that disable the Cancel button and others that can do a rollback after Cancel is clicked. But what if one does not have the option of a full rollback? Should I ... * trap the user in the dialog until the process is completed or a timeout is reached * offer the Cancel button anyways, with the drawback of possibly generating data garbage or an invalid installation",2015/05/20,"['https://ux.stackexchange.com/questions/79016', 'https://ux.stackexchange.com', 'https://ux.stackexchange.com/users/19337/']","It very much depends on the type of your application the operation it is doing. Ideally user should always be in control, but there are situations when you will want to keep control when you are making critical changes. Firstly, you must inform user that a following operation might take X amount of time and that she may not be able to use the system. ![enter image description here](https://i.stack.imgur.com/mYfVN.jpg) When you tell such a thing, this puts a certain amount of stress on the user. You should try your best to alleviate that stress. Best way is to show the time left, and what exactly is the action you are performing. While doing so, your messages should avoid jargon and meet the target audience's vocabulary. A windows update may not be an precise example for this situation but it does tell you how Microsoft handled it in Windows 7. ![enter image description here](https://i.stack.imgur.com/jqnOo.png) Although here Windows can not estimate the time required, it tries to break up the operation in steps so that user has some tangible progress to hold on to. This is very essential for many reasons. I have seen vague progress bars which just run to oblivion without offering any solace to users. You must avoid that. *Considering your use case, after user feedback, you might want to push the message of delay when the operation does not complete in threshold time. I agree that users would already have started the process, but if most of the times the operation is going to take few seconds, there is no reason to always show a message that they can't use the system. After a few seconds you can pop up and mention this seems to be taking longer than usual. You might need a users opinion on this.*","If possible, present the user with a ""Finish Later"" option on the dialog, instead of ""Cancel"". If the install takes longer than they want right now, or they have something important they need to do right now that the install process is interfering with, they can choose that option and then you let them continue the next time the install process is initiated." 48201091,"I have made .net core 2.0 web app. I have added Entity Framework 6.2.0 using NUGET and then I get this error > > Package 'EntityFramework 6.2.0' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework '.NETCoreApp,Version=v2.0'. This package may not be fully compatible with your project. > > > How do I fix this?",2018/01/11,"['https://Stackoverflow.com/questions/48201091', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2613439/']","The problem is your entity version is confused with `.NetFramework` and `.NetCore`. Your application target framework is `Asp.Net Core`. So You should install package related with `Asp.net Core` In your case `'EntityFramework 6.2.0'` is supports by `.NETFramework,Version=v4.6.1'` not by `'.NETCoreApp,Version=v2.0'`. So use this below version of entity framework instead of yours. ``` PM> Install-Package Microsoft.EntityFrameworkCore -Version 2.0.1 ``` ### 3rd party If Nuget is not installed this command should do it ``` dotnet add package Microsoft.EntityFrameworkCore ```","Change your project to `.NETFramework,Version=v4.6.1` or choose an Entity Framework nuget that supports `.NETCoreApp,Version=v2.0`" 48201091,"I have made .net core 2.0 web app. I have added Entity Framework 6.2.0 using NUGET and then I get this error > > Package 'EntityFramework 6.2.0' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework '.NETCoreApp,Version=v2.0'. This package may not be fully compatible with your project. > > > How do I fix this?",2018/01/11,"['https://Stackoverflow.com/questions/48201091', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2613439/']","Alternatively you can change your target framework to net461 as below. ``` net461 ``` By changing your target framework to net461 makes you available to use .net core and full .net frameworks. I think that for this period of time, this approach is better. Because EF Core still hasn't got some main features like [many to many relationship](https://learn.microsoft.com/en-us/ef/core/modeling/relationships) and some others. Sure it depends on your needs and expectations from an ORM tool.","Change your project to `.NETFramework,Version=v4.6.1` or choose an Entity Framework nuget that supports `.NETCoreApp,Version=v2.0`" 48201091,"I have made .net core 2.0 web app. I have added Entity Framework 6.2.0 using NUGET and then I get this error > > Package 'EntityFramework 6.2.0' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework '.NETCoreApp,Version=v2.0'. This package may not be fully compatible with your project. > > > How do I fix this?",2018/01/11,"['https://Stackoverflow.com/questions/48201091', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2613439/']","In my case, my project was Core 2.2. I installed (NuGet) Microsoft.EntityFrameworkCore v2.2.4 first and all built fine. Then I ACCIDENTALLY installed Microsoft.AspNet.Identity rather than Microsoft.AspNetCore.Idendity (v2.2.0). Once my eyes spotted the missing 'Core' in the .Identity package and I fixed it by uninstalling the wrong and installing the right, then the warnings went away. I expect I'm not the only one that went a little fast on the Nuget installations on a new project :)","Change your project to `.NETFramework,Version=v4.6.1` or choose an Entity Framework nuget that supports `.NETCoreApp,Version=v2.0`" 48201091,"I have made .net core 2.0 web app. I have added Entity Framework 6.2.0 using NUGET and then I get this error > > Package 'EntityFramework 6.2.0' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework '.NETCoreApp,Version=v2.0'. This package may not be fully compatible with your project. > > > How do I fix this?",2018/01/11,"['https://Stackoverflow.com/questions/48201091', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2613439/']","The problem is your entity version is confused with `.NetFramework` and `.NetCore`. Your application target framework is `Asp.Net Core`. So You should install package related with `Asp.net Core` In your case `'EntityFramework 6.2.0'` is supports by `.NETFramework,Version=v4.6.1'` not by `'.NETCoreApp,Version=v2.0'`. So use this below version of entity framework instead of yours. ``` PM> Install-Package Microsoft.EntityFrameworkCore -Version 2.0.1 ``` ### 3rd party If Nuget is not installed this command should do it ``` dotnet add package Microsoft.EntityFrameworkCore ```","Alternatively you can change your target framework to net461 as below. ``` net461 ``` By changing your target framework to net461 makes you available to use .net core and full .net frameworks. I think that for this period of time, this approach is better. Because EF Core still hasn't got some main features like [many to many relationship](https://learn.microsoft.com/en-us/ef/core/modeling/relationships) and some others. Sure it depends on your needs and expectations from an ORM tool." 48201091,"I have made .net core 2.0 web app. I have added Entity Framework 6.2.0 using NUGET and then I get this error > > Package 'EntityFramework 6.2.0' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework '.NETCoreApp,Version=v2.0'. This package may not be fully compatible with your project. > > > How do I fix this?",2018/01/11,"['https://Stackoverflow.com/questions/48201091', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2613439/']","The problem is your entity version is confused with `.NetFramework` and `.NetCore`. Your application target framework is `Asp.Net Core`. So You should install package related with `Asp.net Core` In your case `'EntityFramework 6.2.0'` is supports by `.NETFramework,Version=v4.6.1'` not by `'.NETCoreApp,Version=v2.0'`. So use this below version of entity framework instead of yours. ``` PM> Install-Package Microsoft.EntityFrameworkCore -Version 2.0.1 ``` ### 3rd party If Nuget is not installed this command should do it ``` dotnet add package Microsoft.EntityFrameworkCore ```","I had the same problem, and was introduced by altering my solution to use a new TargetFramework. ``` netcoreapp2.2 ``` After the Update I tried to add the Identity Framework but failed with a warning as described. By Adding the packages in this sequence solved it for me: ``` Microsoft.EntityFrameworkCore Microsoft.AspNetCore.Identity ```" 48201091,"I have made .net core 2.0 web app. I have added Entity Framework 6.2.0 using NUGET and then I get this error > > Package 'EntityFramework 6.2.0' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework '.NETCoreApp,Version=v2.0'. This package may not be fully compatible with your project. > > > How do I fix this?",2018/01/11,"['https://Stackoverflow.com/questions/48201091', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2613439/']","The problem is your entity version is confused with `.NetFramework` and `.NetCore`. Your application target framework is `Asp.Net Core`. So You should install package related with `Asp.net Core` In your case `'EntityFramework 6.2.0'` is supports by `.NETFramework,Version=v4.6.1'` not by `'.NETCoreApp,Version=v2.0'`. So use this below version of entity framework instead of yours. ``` PM> Install-Package Microsoft.EntityFrameworkCore -Version 2.0.1 ``` ### 3rd party If Nuget is not installed this command should do it ``` dotnet add package Microsoft.EntityFrameworkCore ```","In my case, my project was Core 2.2. I installed (NuGet) Microsoft.EntityFrameworkCore v2.2.4 first and all built fine. Then I ACCIDENTALLY installed Microsoft.AspNet.Identity rather than Microsoft.AspNetCore.Idendity (v2.2.0). Once my eyes spotted the missing 'Core' in the .Identity package and I fixed it by uninstalling the wrong and installing the right, then the warnings went away. I expect I'm not the only one that went a little fast on the Nuget installations on a new project :)" 48201091,"I have made .net core 2.0 web app. I have added Entity Framework 6.2.0 using NUGET and then I get this error > > Package 'EntityFramework 6.2.0' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework '.NETCoreApp,Version=v2.0'. This package may not be fully compatible with your project. > > > How do I fix this?",2018/01/11,"['https://Stackoverflow.com/questions/48201091', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2613439/']","Alternatively you can change your target framework to net461 as below. ``` net461 ``` By changing your target framework to net461 makes you available to use .net core and full .net frameworks. I think that for this period of time, this approach is better. Because EF Core still hasn't got some main features like [many to many relationship](https://learn.microsoft.com/en-us/ef/core/modeling/relationships) and some others. Sure it depends on your needs and expectations from an ORM tool.","I had the same problem, and was introduced by altering my solution to use a new TargetFramework. ``` netcoreapp2.2 ``` After the Update I tried to add the Identity Framework but failed with a warning as described. By Adding the packages in this sequence solved it for me: ``` Microsoft.EntityFrameworkCore Microsoft.AspNetCore.Identity ```" 48201091,"I have made .net core 2.0 web app. I have added Entity Framework 6.2.0 using NUGET and then I get this error > > Package 'EntityFramework 6.2.0' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework '.NETCoreApp,Version=v2.0'. This package may not be fully compatible with your project. > > > How do I fix this?",2018/01/11,"['https://Stackoverflow.com/questions/48201091', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2613439/']","Alternatively you can change your target framework to net461 as below. ``` net461 ``` By changing your target framework to net461 makes you available to use .net core and full .net frameworks. I think that for this period of time, this approach is better. Because EF Core still hasn't got some main features like [many to many relationship](https://learn.microsoft.com/en-us/ef/core/modeling/relationships) and some others. Sure it depends on your needs and expectations from an ORM tool.","In my case, my project was Core 2.2. I installed (NuGet) Microsoft.EntityFrameworkCore v2.2.4 first and all built fine. Then I ACCIDENTALLY installed Microsoft.AspNet.Identity rather than Microsoft.AspNetCore.Idendity (v2.2.0). Once my eyes spotted the missing 'Core' in the .Identity package and I fixed it by uninstalling the wrong and installing the right, then the warnings went away. I expect I'm not the only one that went a little fast on the Nuget installations on a new project :)" 48201091,"I have made .net core 2.0 web app. I have added Entity Framework 6.2.0 using NUGET and then I get this error > > Package 'EntityFramework 6.2.0' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework '.NETCoreApp,Version=v2.0'. This package may not be fully compatible with your project. > > > How do I fix this?",2018/01/11,"['https://Stackoverflow.com/questions/48201091', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2613439/']","In my case, my project was Core 2.2. I installed (NuGet) Microsoft.EntityFrameworkCore v2.2.4 first and all built fine. Then I ACCIDENTALLY installed Microsoft.AspNet.Identity rather than Microsoft.AspNetCore.Idendity (v2.2.0). Once my eyes spotted the missing 'Core' in the .Identity package and I fixed it by uninstalling the wrong and installing the right, then the warnings went away. I expect I'm not the only one that went a little fast on the Nuget installations on a new project :)","I had the same problem, and was introduced by altering my solution to use a new TargetFramework. ``` netcoreapp2.2 ``` After the Update I tried to add the Identity Framework but failed with a warning as described. By Adding the packages in this sequence solved it for me: ``` Microsoft.EntityFrameworkCore Microsoft.AspNetCore.Identity ```" 54096270,"I do not understand why one IEnumerable.Contains() is faster than the other in the following snippet, even though they are identical. ``` public class Group { public static Dictionary groups = new Dictionary(); // Members, user and groups public List Users = new List(); public List GroupIds = new List(); public IEnumerable AggregateUsers() { IEnumerable aggregatedUsers = Users.AsEnumerable(); foreach (int id in GroupIds) aggregatedUsers = aggregatedUsers.Concat(groups[id].AggregateUsers()); return aggregatedUsers; } } static void Main(string[] args) { for (int i = 0; i < 1000; i++) Group.groups.TryAdd(i, new Group()); for (int i = 0; i < 999; i++) Group.groups[i + 1].GroupIds.Add(i); for (int i = 0; i < 10000; i++) Group.groups[i/10].Users.Add($""user{i}""); IEnumerable users = Group.groups[999].AggregateUsers(); Stopwatch stopwatch = Stopwatch.StartNew(); bool contains1 = users.Contains(""user0""); Console.WriteLine($""Search through IEnumerable from recursive function was {contains1} and took {stopwatch.ElapsedMilliseconds} ms""); users = Enumerable.Empty(); foreach (Group group in Group.groups.Values.Reverse()) users = users.Concat(group.Users); stopwatch = Stopwatch.StartNew(); bool contains2 = users.Contains(""user0""); Console.WriteLine($""Search through IEnumerable from foreach was {contains2} and took {stopwatch.ElapsedMilliseconds} ms""); Console.Read(); } ``` Here is the output obtained by executing this snippet: ``` Search through IEnumerable from recursive function was True and took 40 ms Search through IEnumerable from foreach was True and took 3 ms ``` The snippet simulates 10,000 users distributed in 1,000 groups of 10 users each. Each group can have 2 types of members, users (a string), or other groups (an int representing the ID of that group). Each group has the previous group as a member. So group 0 has 10 users, group1 has 10 users and users from group 0, group 2 has 10 users and users of group 1 .. and here begins the recursion. The purpose of the search is to determine if user ""user0"" (which is close to the end of the List) is a member of the group 999 (which through group relation contains all 10,000 users). The question is, why is the search taking only 3 ms for the search through the IEnumerable constructed with foreach, and 10 times more, for the same IEnumerable constructed with the recursive method ?",2019/01/08,"['https://Stackoverflow.com/questions/54096270', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5550961/']","An interesting question. When I compiled it in .NET Framework, the execution times were about the same (I had to change the TryAdd Dictionary method to Add). In .NET Core I've got the same result as you observed. I believe the answer is deferred execution. You can see in the debugger, that the ``` IEnumerable users = Group.groups[999].AggregateUsers(); ``` assignment to users variable will result in Concat2Iterator instance and the second one ``` users = Enumerable.Empty(); foreach (Group group in Group.groups.Values.Reverse()) users = users.Concat(group.Users); ``` will result in ConcatNIterator. From the documentation of concat: > > This method is implemented by using deferred execution. The immediate > return value is an object that stores all the information that is > required to perform the action. The query represented by this method > is not executed until the object is enumerated either by calling its > GetEnumerator method directly or by using foreach in Visual C# or For > Each in Visual Basic. > > > You can check out the code of concat [here](https://github.com/dotnet/corefx/blob/master/src/System.Linq/src/System/Linq/Concat.cs). The implementations of GetEnumerable for ConcatNIterator and Concat2Iterator are different. So my guess is that the first query takes longer to evaluate because of the way you build the query using concat. If you try using ToList() on one of the enumerables like this: ``` IEnumerable users = Group.groups[999].AggregateUsers().ToList(); ``` you will see that the time elapsed will come down almost to 0 ms.","I figured out how to overcome the problem after reading Mikołaj's answer and Servy's comment. Thanks! ``` public class Group { public static Dictionary groups = new Dictionary(); // Members, user and groups public List Users = new List(); public List GroupIds = new List(); public IEnumerable AggregateUsers() { IEnumerable aggregatedUsers = Users.AsEnumerable(); foreach (int id in GroupIds) aggregatedUsers = aggregatedUsers.Concat(groups[id].AggregateUsers()); return aggregatedUsers; } public IEnumerable AggregateUsers(List> aggregatedUsers = null) { bool topStack = false; if (aggregatedUsers == null) { topStack = true; aggregatedUsers = new List>(); } aggregatedUsers.Add(Users.AsEnumerable()); foreach (int id in GroupIds) groups[id].AggregateUsers(aggregatedUsers); if (topStack) return aggregatedUsers.SelectMany(i => i); else return null; } } static void Main(string[] args) { for (int i = 0; i < 1000; i++) Group.groups.TryAdd(i, new Group()); for (int i = 0; i < 999; i++) Group.groups[i + 1].GroupIds.Add(i); for (int i = 0; i < 10000; i++) Group.groups[i / 10].Users.Add($""user{i}""); Stopwatch stopwatch = Stopwatch.StartNew(); IEnumerable users = Group.groups[999].AggregateUsers(); Console.WriteLine($""Aggregation via nested concatenation took {stopwatch.ElapsedMilliseconds} ms""); stopwatch = Stopwatch.StartNew(); bool contains = users.Contains(""user0""); Console.WriteLine($""Search through IEnumerable from nested concatenation was {contains} and took {stopwatch.ElapsedMilliseconds} ms""); stopwatch = Stopwatch.StartNew(); users = Group.groups[999].AggregateUsers(null); Console.WriteLine($""Aggregation via SelectMany took {stopwatch.ElapsedMilliseconds} ms""); stopwatch = Stopwatch.StartNew(); contains = users.Contains(""user0""); Console.WriteLine($""Search through IEnumerable from SelectMany was {contains} and took {stopwatch.ElapsedMilliseconds} ms""); stopwatch = Stopwatch.StartNew(); users = Enumerable.Empty(); foreach (Group group in Group.groups.Values.Reverse()) users = users.Concat(group.Users); Console.WriteLine($""Aggregation via flat concatenation took {stopwatch.ElapsedMilliseconds} ms""); stopwatch = Stopwatch.StartNew(); contains = users.Contains(""user0""); Console.WriteLine($""Search through IEnumerable from flat concatenation was {contains} and took {stopwatch.ElapsedMilliseconds} ms""); Console.Read(); } ``` Here are the results: ``` Aggregation via nested concatenation took 0 ms Search through IEnumerable from nested concatenation was True and took 43 ms Aggregation via SelectMany took 1 ms Search through IEnumerable from SelectMany was True and took 0 ms Aggregation via foreach concatenation took 0 ms Search through IEnumerable from foreach concatenation was True and took 2 ms ```" 5234749,"I have infinite number of divs of a 100px width, which can fit into a 250px width parent. Regardless of height, I need the divs to be displayed in rows, as shown in the image. I've tried resolving this, but the div height seems to be screwing it up. ![enter image description here](https://i.stack.imgur.com/J5D3J.jpg) I'd really appreciate your help. Thanks :) ```
1
2
3
4
``` Here is the [jsfiddle](http://jsfiddle.net/XFX55/) Here is what I did and achieved using javascript ",2011/03/08,"['https://Stackoverflow.com/questions/5234749', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/504617/']","on the assumption that your needs are more like your colored example code then: ``` .box:nth-child(odd){ clear:both; } ``` if it's going to be 3 rows then `nth-child(3n+1)`","This may not be the exact solution for everybody but I find that (quite literally) thinking outside the box works for many cases: in stead of displaying the the boxes from left to right, in many cases you can fill the left column first, than go to the middle, fill that with boxes and finally fill the right column with boxes. Your image would then be: [![order of filling ](https://i.stack.imgur.com/WTxhS.jpg)](https://i.stack.imgur.com/WTxhS.jpg): If you are using a scripting language like php you can also fill the columns from left to right by adding a new box to it and outputting when all columns are filled. eg (untested php code): ``` $col1 = '
box1
'; $col2 = '
box2
'; $col3 = '
box3
'; $col1 .= '
box4
'; //last
closes the col1 div $col2 .= '
box5
'; $col3 .= '
box6
'; echo $col1.$col2.$col3; ``` $col1, $col2 and $col3 can have float:left and width: 33%, set the boxes inside the div to full width and no float. Obviously if you are using javascript / jquery to load the boxes dynamically you are better of styling them this way as well, as explained in other answers to this thread." 5234749,"I have infinite number of divs of a 100px width, which can fit into a 250px width parent. Regardless of height, I need the divs to be displayed in rows, as shown in the image. I've tried resolving this, but the div height seems to be screwing it up. ![enter image description here](https://i.stack.imgur.com/J5D3J.jpg) I'd really appreciate your help. Thanks :) ```
1
2
3
4
``` Here is the [jsfiddle](http://jsfiddle.net/XFX55/) Here is what I did and achieved using javascript ",2011/03/08,"['https://Stackoverflow.com/questions/5234749', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/504617/']","To my knowledge, there's no way to fix this problem with pure CSS (that works in all common browsers): * Floats [don't work](http://jsfiddle.net/bCgea/). * `display: inline-block` [doesn't work](http://jsfiddle.net/bCgea/1/). * `position: relative` with `position: absolute` requires [manual pixel tuning](http://jsfiddle.net/bCgea/2/). If you're using a server-side language, and you're working with images (or something with predictable height), you can handle the pixel tuning ""automatically"" with server-side code. Instead, use [***jQuery Masonry***](http://masonry.desandro.com/).","With a little help from this comment ([CSS Block float left](https://stackoverflow.com/questions/4889230/css-block-float-left)) I figured out the answer. On every ""row"" that I make, I add a class name `left`. On every other ""row"" that I make, I add a class name `right`. Then I float left and float right for each of these class names! The only complication is that my content order is reversed on the ""right"" rows, but that can be resolved using PHP. Thanks for your help folks! ```css #holder{ width:200px; border:1px dotted blue; display:inline-block; } .box{ width:100px; height:150px; background-color:#CCC; float:left; text-align:center; font-size:45px; } .one{ background-color:#0F0; height:200px; } .two{ background-color:#0FF; } .three{ background-color:#00F; float:right; } .four{ background-color:#FF0; float:right; } .left{float:left;} .right{float:right;} ``` ```html
1
2
4
3
```" 5234749,"I have infinite number of divs of a 100px width, which can fit into a 250px width parent. Regardless of height, I need the divs to be displayed in rows, as shown in the image. I've tried resolving this, but the div height seems to be screwing it up. ![enter image description here](https://i.stack.imgur.com/J5D3J.jpg) I'd really appreciate your help. Thanks :) ```
1
2
3
4
``` Here is the [jsfiddle](http://jsfiddle.net/XFX55/) Here is what I did and achieved using javascript ",2011/03/08,"['https://Stackoverflow.com/questions/5234749', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/504617/']","As has been rightly pointed out, this is impossible with CSS alone... thankfully, I've now found a solution in It seems to solve the problem fully.","Thanks to thirtydot, I have realised my previous answer did not properly resolve the problem. Here is my second attempt, which utilizes JQuery as a CSS only solution appears impossible: ```
1
2
3
4
5
6
``` The only problem that remains for my solution is, what happens when a box is two-box-widths instead of just one. I'm still working on this solution. I'll post when complete." 5234749,"I have infinite number of divs of a 100px width, which can fit into a 250px width parent. Regardless of height, I need the divs to be displayed in rows, as shown in the image. I've tried resolving this, but the div height seems to be screwing it up. ![enter image description here](https://i.stack.imgur.com/J5D3J.jpg) I'd really appreciate your help. Thanks :) ```
1
2
3
4
``` Here is the [jsfiddle](http://jsfiddle.net/XFX55/) Here is what I did and achieved using javascript ",2011/03/08,"['https://Stackoverflow.com/questions/5234749', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/504617/']","I'm providing this answer because even when there are good ones which do provide a solution([using Masonry](http://masonry.desandro.com/)) still isn't crystal clear why it isn't possible to achieve this by using floats. (this is important - **#1**). > > A floated element will move as far to the left or right as it can **in > the position where it was originally** > > > So put it in this way: We have 2 div ```
div5
div6
.div-blue{ width:100px; height:100px; background: blue; } .div-red{ width:50px; height:50px; background: red; } ``` without `float` they'll be one below the other ![enter image description here](https://i.stack.imgur.com/5ilLh.png) If we `float: right` the `div5`, the `div6` is positioned on the line where the `div5` was , `/*the lines are just for illustrate*/` ![enter image description here](https://i.stack.imgur.com/nExmb.png) So if now we `float: left` the `div6` it will move as far to the left as it can, ""**in this line**"" (see #1 above), so if `div5` changes its line, `div6` will follow it. Now let's add other div into the equation ```
div4
div5
div6
.div-gree{ width:150px; height:150px; background: green; float:right; } ``` We have this ![enter image description here](https://i.stack.imgur.com/FljU8.png) If we set `clear: right` to the `div5`, we are forcing it to take the line bellow `div4` ![enter image description here](https://i.stack.imgur.com/Xy5yF.png) and `div6` will float in this new line wether to the right or to the left. Now lets use as example the question that brought me here due to a duplicate [Forcing div stack from left to right](https://stackoverflow.com/questions/32102623/forcing-div-stack-from-left-to-right#32102623) Here the snippet to test it: ```css div{ width:24%; margin-right: 1%; float: left; margin-top:5px; color: #fff; font-size: 24px; text-align: center; } .one{ background-color:red; height: 50px; } .two{ background-color:green; height:40px; } .three{ background-color:orange; height:55px; } .four{ background-color:magenta; height:25px; } .five{ background-color:black; height:55px; } ``` ```html
1
2
3
4
5
1*
2*
3*
4*
5*
``` [![enter image description here](https://i.stack.imgur.com/MQfyh.jpg)](https://i.stack.imgur.com/MQfyh.jpg) In the above image you can see how `div.5` is stocked just next to `div.3` that is because in its line (defined by the line box of `div.4`) that is as far it can go, `div.1*`, `div.2*`, etc, also float left of `div.5` but as they don't fit in that line they go to the line bellow (defined by the line box of `div.5`) Now notice that when we reduce the height of `div.2*` enough to be less than `div.4*` how it let pass to `div.5*`: [![enter image description here](https://i.stack.imgur.com/UZSkC.jpg)](https://i.stack.imgur.com/UZSkC.jpg) I hope this helps to clarify why this can not be achieved using floats. I only clarify using floats (not inline-block) because of the title ""*CSS Floating Divs At Variable Heights*"" and because right now the answer is quite long.","As has been rightly pointed out, this is impossible with CSS alone... thankfully, I've now found a solution in It seems to solve the problem fully." 5234749,"I have infinite number of divs of a 100px width, which can fit into a 250px width parent. Regardless of height, I need the divs to be displayed in rows, as shown in the image. I've tried resolving this, but the div height seems to be screwing it up. ![enter image description here](https://i.stack.imgur.com/J5D3J.jpg) I'd really appreciate your help. Thanks :) ```
1
2
3
4
``` Here is the [jsfiddle](http://jsfiddle.net/XFX55/) Here is what I did and achieved using javascript ",2011/03/08,"['https://Stackoverflow.com/questions/5234749', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/504617/']","on the assumption that your needs are more like your colored example code then: ``` .box:nth-child(odd){ clear:both; } ``` if it's going to be 3 rows then `nth-child(3n+1)`","On modern browsers you can simply do: ``` display: inline-block; vertical-align: top; ```" 5234749,"I have infinite number of divs of a 100px width, which can fit into a 250px width parent. Regardless of height, I need the divs to be displayed in rows, as shown in the image. I've tried resolving this, but the div height seems to be screwing it up. ![enter image description here](https://i.stack.imgur.com/J5D3J.jpg) I'd really appreciate your help. Thanks :) ```
1
2
3
4
``` Here is the [jsfiddle](http://jsfiddle.net/XFX55/) Here is what I did and achieved using javascript ",2011/03/08,"['https://Stackoverflow.com/questions/5234749', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/504617/']","With a little help from this comment ([CSS Block float left](https://stackoverflow.com/questions/4889230/css-block-float-left)) I figured out the answer. On every ""row"" that I make, I add a class name `left`. On every other ""row"" that I make, I add a class name `right`. Then I float left and float right for each of these class names! The only complication is that my content order is reversed on the ""right"" rows, but that can be resolved using PHP. Thanks for your help folks! ```css #holder{ width:200px; border:1px dotted blue; display:inline-block; } .box{ width:100px; height:150px; background-color:#CCC; float:left; text-align:center; font-size:45px; } .one{ background-color:#0F0; height:200px; } .two{ background-color:#0FF; } .three{ background-color:#00F; float:right; } .four{ background-color:#FF0; float:right; } .left{float:left;} .right{float:right;} ``` ```html
1
2
4
3
```","This may not be the exact solution for everybody but I find that (quite literally) thinking outside the box works for many cases: in stead of displaying the the boxes from left to right, in many cases you can fill the left column first, than go to the middle, fill that with boxes and finally fill the right column with boxes. Your image would then be: [![order of filling ](https://i.stack.imgur.com/WTxhS.jpg)](https://i.stack.imgur.com/WTxhS.jpg): If you are using a scripting language like php you can also fill the columns from left to right by adding a new box to it and outputting when all columns are filled. eg (untested php code): ``` $col1 = '
box1
'; $col2 = '
box2
'; $col3 = '
box3
'; $col1 .= '
box4
'; //last
closes the col1 div $col2 .= '
box5
'; $col3 .= '
box6
'; echo $col1.$col2.$col3; ``` $col1, $col2 and $col3 can have float:left and width: 33%, set the boxes inside the div to full width and no float. Obviously if you are using javascript / jquery to load the boxes dynamically you are better of styling them this way as well, as explained in other answers to this thread." 5234749,"I have infinite number of divs of a 100px width, which can fit into a 250px width parent. Regardless of height, I need the divs to be displayed in rows, as shown in the image. I've tried resolving this, but the div height seems to be screwing it up. ![enter image description here](https://i.stack.imgur.com/J5D3J.jpg) I'd really appreciate your help. Thanks :) ```
1
2
3
4
``` Here is the [jsfiddle](http://jsfiddle.net/XFX55/) Here is what I did and achieved using javascript ",2011/03/08,"['https://Stackoverflow.com/questions/5234749', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/504617/']","I'm providing this answer because even when there are good ones which do provide a solution([using Masonry](http://masonry.desandro.com/)) still isn't crystal clear why it isn't possible to achieve this by using floats. (this is important - **#1**). > > A floated element will move as far to the left or right as it can **in > the position where it was originally** > > > So put it in this way: We have 2 div ```
div5
div6
.div-blue{ width:100px; height:100px; background: blue; } .div-red{ width:50px; height:50px; background: red; } ``` without `float` they'll be one below the other ![enter image description here](https://i.stack.imgur.com/5ilLh.png) If we `float: right` the `div5`, the `div6` is positioned on the line where the `div5` was , `/*the lines are just for illustrate*/` ![enter image description here](https://i.stack.imgur.com/nExmb.png) So if now we `float: left` the `div6` it will move as far to the left as it can, ""**in this line**"" (see #1 above), so if `div5` changes its line, `div6` will follow it. Now let's add other div into the equation ```
div4
div5
div6
.div-gree{ width:150px; height:150px; background: green; float:right; } ``` We have this ![enter image description here](https://i.stack.imgur.com/FljU8.png) If we set `clear: right` to the `div5`, we are forcing it to take the line bellow `div4` ![enter image description here](https://i.stack.imgur.com/Xy5yF.png) and `div6` will float in this new line wether to the right or to the left. Now lets use as example the question that brought me here due to a duplicate [Forcing div stack from left to right](https://stackoverflow.com/questions/32102623/forcing-div-stack-from-left-to-right#32102623) Here the snippet to test it: ```css div{ width:24%; margin-right: 1%; float: left; margin-top:5px; color: #fff; font-size: 24px; text-align: center; } .one{ background-color:red; height: 50px; } .two{ background-color:green; height:40px; } .three{ background-color:orange; height:55px; } .four{ background-color:magenta; height:25px; } .five{ background-color:black; height:55px; } ``` ```html
1
2
3
4
5
1*
2*
3*
4*
5*
``` [![enter image description here](https://i.stack.imgur.com/MQfyh.jpg)](https://i.stack.imgur.com/MQfyh.jpg) In the above image you can see how `div.5` is stocked just next to `div.3` that is because in its line (defined by the line box of `div.4`) that is as far it can go, `div.1*`, `div.2*`, etc, also float left of `div.5` but as they don't fit in that line they go to the line bellow (defined by the line box of `div.5`) Now notice that when we reduce the height of `div.2*` enough to be less than `div.4*` how it let pass to `div.5*`: [![enter image description here](https://i.stack.imgur.com/UZSkC.jpg)](https://i.stack.imgur.com/UZSkC.jpg) I hope this helps to clarify why this can not be achieved using floats. I only clarify using floats (not inline-block) because of the title ""*CSS Floating Divs At Variable Heights*"" and because right now the answer is quite long.","Thanks to thirtydot, I have realised my previous answer did not properly resolve the problem. Here is my second attempt, which utilizes JQuery as a CSS only solution appears impossible: ```
1
2
3
4
5
6
``` The only problem that remains for my solution is, what happens when a box is two-box-widths instead of just one. I'm still working on this solution. I'll post when complete." 5234749,"I have infinite number of divs of a 100px width, which can fit into a 250px width parent. Regardless of height, I need the divs to be displayed in rows, as shown in the image. I've tried resolving this, but the div height seems to be screwing it up. ![enter image description here](https://i.stack.imgur.com/J5D3J.jpg) I'd really appreciate your help. Thanks :) ```
1
2
3
4
``` Here is the [jsfiddle](http://jsfiddle.net/XFX55/) Here is what I did and achieved using javascript ",2011/03/08,"['https://Stackoverflow.com/questions/5234749', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/504617/']","on the assumption that your needs are more like your colored example code then: ``` .box:nth-child(odd){ clear:both; } ``` if it's going to be 3 rows then `nth-child(3n+1)`","With a little help from this comment ([CSS Block float left](https://stackoverflow.com/questions/4889230/css-block-float-left)) I figured out the answer. On every ""row"" that I make, I add a class name `left`. On every other ""row"" that I make, I add a class name `right`. Then I float left and float right for each of these class names! The only complication is that my content order is reversed on the ""right"" rows, but that can be resolved using PHP. Thanks for your help folks! ```css #holder{ width:200px; border:1px dotted blue; display:inline-block; } .box{ width:100px; height:150px; background-color:#CCC; float:left; text-align:center; font-size:45px; } .one{ background-color:#0F0; height:200px; } .two{ background-color:#0FF; } .three{ background-color:#00F; float:right; } .four{ background-color:#FF0; float:right; } .left{float:left;} .right{float:right;} ``` ```html
1
2
4
3
```" 5234749,"I have infinite number of divs of a 100px width, which can fit into a 250px width parent. Regardless of height, I need the divs to be displayed in rows, as shown in the image. I've tried resolving this, but the div height seems to be screwing it up. ![enter image description here](https://i.stack.imgur.com/J5D3J.jpg) I'd really appreciate your help. Thanks :) ```
1
2
3
4
``` Here is the [jsfiddle](http://jsfiddle.net/XFX55/) Here is what I did and achieved using javascript ",2011/03/08,"['https://Stackoverflow.com/questions/5234749', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/504617/']","I'm providing this answer because even when there are good ones which do provide a solution([using Masonry](http://masonry.desandro.com/)) still isn't crystal clear why it isn't possible to achieve this by using floats. (this is important - **#1**). > > A floated element will move as far to the left or right as it can **in > the position where it was originally** > > > So put it in this way: We have 2 div ```
div5
div6
.div-blue{ width:100px; height:100px; background: blue; } .div-red{ width:50px; height:50px; background: red; } ``` without `float` they'll be one below the other ![enter image description here](https://i.stack.imgur.com/5ilLh.png) If we `float: right` the `div5`, the `div6` is positioned on the line where the `div5` was , `/*the lines are just for illustrate*/` ![enter image description here](https://i.stack.imgur.com/nExmb.png) So if now we `float: left` the `div6` it will move as far to the left as it can, ""**in this line**"" (see #1 above), so if `div5` changes its line, `div6` will follow it. Now let's add other div into the equation ```
div4
div5
div6
.div-gree{ width:150px; height:150px; background: green; float:right; } ``` We have this ![enter image description here](https://i.stack.imgur.com/FljU8.png) If we set `clear: right` to the `div5`, we are forcing it to take the line bellow `div4` ![enter image description here](https://i.stack.imgur.com/Xy5yF.png) and `div6` will float in this new line wether to the right or to the left. Now lets use as example the question that brought me here due to a duplicate [Forcing div stack from left to right](https://stackoverflow.com/questions/32102623/forcing-div-stack-from-left-to-right#32102623) Here the snippet to test it: ```css div{ width:24%; margin-right: 1%; float: left; margin-top:5px; color: #fff; font-size: 24px; text-align: center; } .one{ background-color:red; height: 50px; } .two{ background-color:green; height:40px; } .three{ background-color:orange; height:55px; } .four{ background-color:magenta; height:25px; } .five{ background-color:black; height:55px; } ``` ```html
1
2
3
4
5
1*
2*
3*
4*
5*
``` [![enter image description here](https://i.stack.imgur.com/MQfyh.jpg)](https://i.stack.imgur.com/MQfyh.jpg) In the above image you can see how `div.5` is stocked just next to `div.3` that is because in its line (defined by the line box of `div.4`) that is as far it can go, `div.1*`, `div.2*`, etc, also float left of `div.5` but as they don't fit in that line they go to the line bellow (defined by the line box of `div.5`) Now notice that when we reduce the height of `div.2*` enough to be less than `div.4*` how it let pass to `div.5*`: [![enter image description here](https://i.stack.imgur.com/UZSkC.jpg)](https://i.stack.imgur.com/UZSkC.jpg) I hope this helps to clarify why this can not be achieved using floats. I only clarify using floats (not inline-block) because of the title ""*CSS Floating Divs At Variable Heights*"" and because right now the answer is quite long.","With a little help from this comment ([CSS Block float left](https://stackoverflow.com/questions/4889230/css-block-float-left)) I figured out the answer. On every ""row"" that I make, I add a class name `left`. On every other ""row"" that I make, I add a class name `right`. Then I float left and float right for each of these class names! The only complication is that my content order is reversed on the ""right"" rows, but that can be resolved using PHP. Thanks for your help folks! ```css #holder{ width:200px; border:1px dotted blue; display:inline-block; } .box{ width:100px; height:150px; background-color:#CCC; float:left; text-align:center; font-size:45px; } .one{ background-color:#0F0; height:200px; } .two{ background-color:#0FF; } .three{ background-color:#00F; float:right; } .four{ background-color:#FF0; float:right; } .left{float:left;} .right{float:right;} ``` ```html
1
2
4
3
```" 5234749,"I have infinite number of divs of a 100px width, which can fit into a 250px width parent. Regardless of height, I need the divs to be displayed in rows, as shown in the image. I've tried resolving this, but the div height seems to be screwing it up. ![enter image description here](https://i.stack.imgur.com/J5D3J.jpg) I'd really appreciate your help. Thanks :) ```
1
2
3
4
``` Here is the [jsfiddle](http://jsfiddle.net/XFX55/) Here is what I did and achieved using javascript ",2011/03/08,"['https://Stackoverflow.com/questions/5234749', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/504617/']","To my knowledge, there's no way to fix this problem with pure CSS (that works in all common browsers): * Floats [don't work](http://jsfiddle.net/bCgea/). * `display: inline-block` [doesn't work](http://jsfiddle.net/bCgea/1/). * `position: relative` with `position: absolute` requires [manual pixel tuning](http://jsfiddle.net/bCgea/2/). If you're using a server-side language, and you're working with images (or something with predictable height), you can handle the pixel tuning ""automatically"" with server-side code. Instead, use [***jQuery Masonry***](http://masonry.desandro.com/).","On modern browsers you can simply do: ``` display: inline-block; vertical-align: top; ```" 15722072,"I have created a singup button as follows: ``` signupButton = [[UIButton alloc] initWithFrame:CGRectMake(10,(facebookLoginButton.bounds.size.height + 40),300,50)]; signupButton.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin; UIImage *signupButtonImage = [[UIImage imageNamed:@""Signup""] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 10, 0, 10)]; [signupButton setBackgroundImage:signupButtonImage forState:UIControlStateNormal]; ``` The frame for the button is 300x50 per the above. I have created an image (for Retina devices) as 22(w)x100(h)px. The image is 22 pixels which includes 10px rounded corners and 2px which are for the repeatable middle section. I have tried to implement the stretch per the above code with insets as 0,10,0,10 but this does not stretch as expected. ![enter image description here](https://i.stack.imgur.com/5aiBT.png) ![Actual image](https://i.stack.imgur.com/MiNNJ.png) Can someone explain what the insets should be? Also how to work these out, I cannot find any useful information on how to actually calculate what the insets should be? I have read the Apple documentation on this, but I do not understand how to work these out.",2013/03/30,"['https://Stackoverflow.com/questions/15722072', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1523603/']","You don't need the starting and trailing `.*`, but you do need to escape the `$` as it has the special meaning of the zero-width end of the string. ``` \\$_POST\\['[a-zA-Z0-9]*'\\] ```","Use this: ``` ""\\$_POST\\['([a-zA-Z0-9]*)'\\]"" ``` Symbols like `$`have particular meanings in regex. Therefore, you need to prefix them with `\`" 15722072,"I have created a singup button as follows: ``` signupButton = [[UIButton alloc] initWithFrame:CGRectMake(10,(facebookLoginButton.bounds.size.height + 40),300,50)]; signupButton.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin; UIImage *signupButtonImage = [[UIImage imageNamed:@""Signup""] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 10, 0, 10)]; [signupButton setBackgroundImage:signupButtonImage forState:UIControlStateNormal]; ``` The frame for the button is 300x50 per the above. I have created an image (for Retina devices) as 22(w)x100(h)px. The image is 22 pixels which includes 10px rounded corners and 2px which are for the repeatable middle section. I have tried to implement the stretch per the above code with insets as 0,10,0,10 but this does not stretch as expected. ![enter image description here](https://i.stack.imgur.com/5aiBT.png) ![Actual image](https://i.stack.imgur.com/MiNNJ.png) Can someone explain what the insets should be? Also how to work these out, I cannot find any useful information on how to actually calculate what the insets should be? I have read the Apple documentation on this, but I do not understand how to work these out.",2013/03/30,"['https://Stackoverflow.com/questions/15722072', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1523603/']","You don't need the starting and trailing `.*`, but you do need to escape the `$` as it has the special meaning of the zero-width end of the string. ``` \\$_POST\\['[a-zA-Z0-9]*'\\] ```","You can use the regex pattern given as a String with the [matches(...) method](http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#matches%28java.lang.String%29) of the [String class](http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#matches%28java.lang.String%29). It returns a `boolean`. ``` String a = ""Hello, world! $_POST['something'] Test!""; String b = ""Hello, world! $_POST['special!!!char'] Test!""; String c = ""Hey there $_GET['something'] foo bar""; String pattern = "".*\\$_POST\\['[A-Za-z0-9]+'\\].*""; System.out.println (""a matches? "" + Boolean.toString(a.matches(pattern))); System.out.println (""b matches? "" + Boolean.toString(b.matches(pattern))); System.out.println (""c matches? "" + Boolean.toString(c.matches(pattern))); ``` You can also use a [Pattern](http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html) and a Matcher object to reuse the pattern for multiple uses: ``` String[] array = { ""Hello, world! $_POST['something'] Test!"", ""Hello, world! $_POST['special!!!char'] Test!"", ""Hey there $_GET['something'] foo bar"" }; String strPattern = "".*\\$_POST\\['[A-Za-z0-9]+'\\].*""; Pattern p = Pattern.compile(strPattern); for (int i=0; i Matches? "" + Boolean.toString(m.matches())); System.out.println(""""); } ``` outputs: ``` Expression: Hello, world! $_POST['something'] Test! -> Matches? true Expression: Hello, world! $_POST['special!!!char'] Test! -> Matches? false Expression: Hey there $_GET['something'] foo bar -> Matches? false ```" 72120789,"I'm trying to figure out a way to detect where the cursor is in a certain range. This would be the sort of thing I'm looking for: ``` if ('bla bla bla' && Input.mousePosition == (in between x1 and x2, in between y1. and y2)) ``` Is this possible in unity, because I can't figure it out :( Thanks for any help!",2022/05/05,"['https://Stackoverflow.com/questions/72120789', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16430718/']","also you can use `Rect.Contains` for Prevent dublication: ``` var InRect = new Rect(0, 0, Screen.width/2, Screen.height).Contains(Input.mousePosition); UnityEngine.Debug.Log(InRect); ```","``` Vector2 mousePos = Input.mousePosition; ``` This returns a `Vector2` with the coordinates `x` and `y` of the mouse position. To check if this point with the coordinates `mousePos.x` and `mousePos.y` lies in the range `x1` and `x2`; `y1` and `y2`, we can write ``` if((mousePos.x >= x1 && mousePos.x <= x2) && (mousePos.y >= y1 && mousePos.y <= y2)) { // do something } ``` Alternatively, ``` if(mousePos >= new Vector2(x1, y1) && mousePos <= new Vector2(x2, y2)) { // do something } ```" 10650165,"I'm working on a scripting language and would like to write a compiler / interpreter for my language. I've desited to do the compiler in standart ML My question now is, is there a ""pattern"" for doing this sorta design process? I've written a java-compiler from scratch as a part of a computerscience course, but that was sorta cheating, since the language was given, meaning that there was reference implementations and syntax, grammars and other specs given. If starting from scratch, only having a problem domain how does one get started? I'm looking for a book or a tutorial on the subject.",2012/05/18,"['https://Stackoverflow.com/questions/10650165', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/750186/']","The classic books on modern compiler construction in functional languages are: * [Modern Compiler Implementation in ML](http://www.cs.princeton.edu/~appel/modern/ml/) * [Types and Programming Languages](http://www.cis.upenn.edu/~bcpierce/tapl/) * [Implementing Functional Languages](http://research.microsoft.com/en-us/um/people/simonpj/papers/pj-lester-book/) * [Practical Foundations of Programming Languages](http://www.cs.cmu.edu/~rwh/plbook/book.pdf)","[Concepts, Techniques and Models of Computer Programming](https://rads.stackoverflow.com/amzn/click/com/0262220695). This book is not directly about how to design a language, but it is an in-depth exploration of the features of one interesting language (Oz), how they interact, and how they enable various usage patterns and features. It is excellent for giving a sense of what the implications of various design decisions and capabilities are. Reading a few such books, observing the resulting languages, and synthesizing from them is a decent way to go about learning how to design a language. Similarly, but a lot more pragmatically, [Programming Scala](https://rads.stackoverflow.com/amzn/click/com/0981531644) does a great job of explaining how language features enable style. A lot of language design is ultimately taste and good sense. Reading in-depth explorations of existing languages is a good way to develop and hone such taste." 24808853,"I have several lists and I need to do something with each possible combination of these list items. In the case of two lists, I can do: ``` for a in alist: for b in blist: # do something with a and b ``` However, if there are more lists, say 6 or 7 lists, this method seems reluctant. Is there any way to elegantly implement this iteration?",2014/07/17,"['https://Stackoverflow.com/questions/24808853', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1150462/']","You could use `itertools.product` to make all possible combinations from your lists. The result will be one long list of `tuple` with an element from each list in the order you passed the list in. ``` >>> a = [1,2,3] >>> b = ['a', 'b', 'c'] >>> c = [4,5,6] >>> import itertools >>> list(itertools.product(a,b,c)) [(1, 'a', 4), (1, 'a', 5), (1, 'a', 6), (1, 'b', 4), (1, 'b', 5), (1, 'b', 6), (1, 'c', 4), (1, 'c', 5), (1, 'c', 6), (2, 'a', 4), (2, 'a', 5), (2, 'a', 6), (2, 'b', 4), (2, 'b', 5), (2, 'b', 6), (2, 'c', 4), (2, 'c', 5), (2, 'c', 6), (3, 'a', 4), (3, 'a', 5), (3, 'a', 6), (3, 'b', 4), (3, 'b', 5), (3, 'b', 6), (3, 'c', 4), (3, 'c', 5), (3, 'c', 6)] ``` For example ``` for ai, bi, ci in itertools.product(a,b,c): print ai, bi, ci ``` Output ``` 1 a 4 1 a 5 1 a 6 ... etc ```","If there are in fact 6 or 7 lists, it's probably worth going to `itertools.product` for readability. But for simple cases it's straightforward to use a [list comprehension](https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions), and it requires no imports. For example: ``` alist = [1, 2, 3] blist = ['A', 'B', 'C'] clist = ['.', ',', '?'] abc = [(a,b,c) for a in alist for b in blist for c in clist] for e in abc: print(""{}{}{} "".format(e[0],e[1],e[2])), # 1A. 1A, 1A? 1B. 1B, 1B? 1C. 1C, 1C? 2A. 2A, 2A? 2B. 2B, 2B? 2C. 2C, 2C? 3A. 3A, 3A? 3B. 3B, 3B? 3C. 3C, 3C? ```" 556808,"I have a table like this (the `C` column is blank): ``` A B C 1 19:30 23:00 (3.50) 2 14:15 18:30 (4.25) ``` I need to calculate the time difference in each row between column `A` and column `B` (always `B` - `A`), and put it in column `C` as a decimal number (as shown inside the parentheses). Which formula should I use? Is it possible to generate a general formula, so I won't have to change the row number every time (maybe `INDIRECT`)?",2013/02/24,"['https://superuser.com/questions/556808', 'https://superuser.com', 'https://superuser.com/users/165729/']","If you use MOD that will also work when the times cross midnight, e.g. in C2 `=MOD(B2-A2,1)*24` copy formula down column and the row numbers will change automaticaly for each row","This will do the job: ``` =(B1-A1)*24 ``` You might need to format the cell as number, not time!" 67169129,"I want to exclude only If ColumnA = 'SA' exclude ColumnB not like '%Prev%' and ColumnB not like '%old%'. If columnA = 'BA' I want to keep them. exp: > > > ``` > select columnA > from Table > where columnA ='SA' and ColumnB not like '%Prev%' and ColumnB not like '%old%' > > ``` > >",2021/04/19,"['https://Stackoverflow.com/questions/67169129', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5661085/']","You are trying to perform Integer operation on a list. 'lengths' is an ArrayList and operation % is non applicable to it. Also, I think you shouldn't use cloning here and just iterate over `list` and check if each element is odd - print it or add to another list if it is.","modify lengths methods ``` public static void main(String []args){ ArrayList list = new ArrayList(); list.add(""yoy""); list.add(""lmao""); list.add(""lol""); list.add(""kk""); list.add(""bbb""); ArrayList lengths = lengths(list); System.out.println(lengths.toString()); } public static ArrayList lengths(ArrayList list) { ArrayList lengthList = new ArrayList(); for (String s : list) if(s.length() % 2 != 0) lengthList.add(s); return lengthList; } ```" 67169129,"I want to exclude only If ColumnA = 'SA' exclude ColumnB not like '%Prev%' and ColumnB not like '%old%'. If columnA = 'BA' I want to keep them. exp: > > > ``` > select columnA > from Table > where columnA ='SA' and ColumnB not like '%Prev%' and ColumnB not like '%old%' > > ``` > >",2021/04/19,"['https://Stackoverflow.com/questions/67169129', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5661085/']","It's better to implement a separate method that copies the strings with odd length: ```java public static List oddLengths(List list) { List result = new ArrayList<>(); for (String s : list) { if (s.length() % 2 != 0) { result.add(s); } } return result; } ``` Then just call this method in `main` method: ```java List list = new ArrayList<>(); list.add(""yoy""); list.add(""lmao""); list.add(""lol""); list.add(""kk""); list.add(""bbb""); List oddList = oddLengths(list); System.out.println(""Strings with odd length are: "" + oddList); ``` Less efficient approach would be to copy the initial list and then remove all strings with *even* length using `removeIf` operation: ```java List oddList2 = new ArrayList<>(list); // no need to use clone oddList2.removeIf(s -> s.length() % 2 == 0); // removing all strings with even length System.out.println(""Strings with odd length are: "" + oddList2); ``` --- It is convenient to use Stream API with filter operation to achieve the same result: ```java public static List oddLengths(List list) { return list.stream() .filter(s -> s.length() % 2 != 0) .collect(Collectors.toList()); } ```","modify lengths methods ``` public static void main(String []args){ ArrayList list = new ArrayList(); list.add(""yoy""); list.add(""lmao""); list.add(""lol""); list.add(""kk""); list.add(""bbb""); ArrayList lengths = lengths(list); System.out.println(lengths.toString()); } public static ArrayList lengths(ArrayList list) { ArrayList lengthList = new ArrayList(); for (String s : list) if(s.length() % 2 != 0) lengthList.add(s); return lengthList; } ```" 865774,"I am trapping a `KeyDown` event and I need to be able to check whether the current keys pressed down are : `Ctrl` + `Shift` + `M` ? --- I know I need to use the `e.KeyData` from the `KeyEventArgs`, the `Keys` enum and something with Enum Flags and bits but I'm not sure on how to check for the combination.",2009/05/14,"['https://Stackoverflow.com/questions/865774', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/44084/']","You need to use the [Modifiers](http://msdn.microsoft.com/en-us/library/system.windows.forms.keyeventargs.modifiers.aspx) property of the KeyEventArgs class. Something like: ``` //asumming e is of type KeyEventArgs (such as it is // on a KeyDown event handler // .. bool ctrlShiftM; //will be true if the combination Ctrl + Shift + M is pressed, false otherwise ctrlShiftM = ((e.KeyCode == Keys.M) && // test for M pressed ((e.Modifiers & Keys.Shift) != 0) && // test for Shift modifier ((e.Modifiers & Keys.Control) != 0)); // test for Ctrl modifier if (ctrlShiftM == true) { Console.WriteLine(""[Ctrl] + [Shift] + M was pressed""); } ```","You can check using a technique similar to the following: ``` if(Control.ModifierKeys == Keys.Control && Control.ModifierKeys == Keys.Shift) ``` This in combination with the normal key checks will give you the answer you seek." 865774,"I am trapping a `KeyDown` event and I need to be able to check whether the current keys pressed down are : `Ctrl` + `Shift` + `M` ? --- I know I need to use the `e.KeyData` from the `KeyEventArgs`, the `Keys` enum and something with Enum Flags and bits but I'm not sure on how to check for the combination.",2009/05/14,"['https://Stackoverflow.com/questions/865774', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/44084/']","You need to use the [Modifiers](http://msdn.microsoft.com/en-us/library/system.windows.forms.keyeventargs.modifiers.aspx) property of the KeyEventArgs class. Something like: ``` //asumming e is of type KeyEventArgs (such as it is // on a KeyDown event handler // .. bool ctrlShiftM; //will be true if the combination Ctrl + Shift + M is pressed, false otherwise ctrlShiftM = ((e.KeyCode == Keys.M) && // test for M pressed ((e.Modifiers & Keys.Shift) != 0) && // test for Shift modifier ((e.Modifiers & Keys.Control) != 0)); // test for Ctrl modifier if (ctrlShiftM == true) { Console.WriteLine(""[Ctrl] + [Shift] + M was pressed""); } ```","I think its easiest to use this: `if(e.KeyData == (Keys.Control | Keys.G))`" 865774,"I am trapping a `KeyDown` event and I need to be able to check whether the current keys pressed down are : `Ctrl` + `Shift` + `M` ? --- I know I need to use the `e.KeyData` from the `KeyEventArgs`, the `Keys` enum and something with Enum Flags and bits but I'm not sure on how to check for the combination.",2009/05/14,"['https://Stackoverflow.com/questions/865774', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/44084/']","I think its easiest to use this: `if(e.KeyData == (Keys.Control | Keys.G))`","You can check using a technique similar to the following: ``` if(Control.ModifierKeys == Keys.Control && Control.ModifierKeys == Keys.Shift) ``` This in combination with the normal key checks will give you the answer you seek." 17608853,"I would like a for loop in jquery using `.html()` like this: ``` .html(''); ``` In Java's for each loop list it uses an object of `java.util.ArrayList`. Here the `.html();` function will call when we click on add button. Here my question is it possible to write jsp scriplet code in .html() of jquery.",2013/07/12,"['https://Stackoverflow.com/questions/17608853', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2147478/']","``` ``` ![enter image description here](https://i.stack.imgur.com/tmiYx.png)","I hope you are using this code in single.php from where the whole of the post is displayed. For displaying the links (Next/Prev), you need to check the function. ``` get_template_part() in the same file (Single.php of your theme). In my case function in single.php has been passes parameters like So, you will open the ""content-single.php"" according to the parameters specified in the function and paste the same code
', 'no'); ?>
``` ``` ', 'no'); ?> below

``` I hope this will solve your problem." 64634372,"I develop an Angular app based on ASP.NET Core and there is some settings in `launchSettings.json` in order to run the app with the given ports as shown below: ``` ""profiles"": { ""IIS Express"": { ""commandName"": ""IISExpress"", ""launchBrowser"": true, ""environmentVariables"": { ""DOTNET_ENVIRONMENT"": ""Development"" } }, ""EmployeeProject.WebUI"": { ""commandName"": ""Project"", ""launchBrowser"": true, ""applicationUrl"": ""http://localhost:6000;https://localhost:6001"", ""environmentVariables"": { ""DOTNET_ENVIRONMENT"": ""Development"" } } } ``` However, I heard that these settings is **ignored** when using **VS Code** and when running the frontend and backend at the same time using `dotnet watch run` the app starts by using random ports in every run. So, how can I make the app starts using the same ports (6000 or 6001) via `dotnet run` or `dotnet watch run` in VS Code?",2020/11/01,"['https://Stackoverflow.com/questions/64634372', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/836018/']","If you want to do this the VS Code way, as long as you use F5 (or the Run > ""Start Debugging"" command), it's as simple as changing the `launch.json` file from this: ```json ... ""env"": { ""ASPNETCORE_ENVIRONMENT"": ""Development"" }, ... ``` to this: ```json ... ""env"": { ""ASPNETCORE_ENVIRONMENT"": ""Development"", ""ASPNETCORE_URLS"": ""http://localhost:5001"" }, ... ``` Otherwise, if you use the IIS Express profile, edit your `launchSettings.json` file to specify the port: ```json ""iisSettings"": { ""iisExpress"": { ""applicationUrl"": ""http://localhost:6000"", } }, ""profiles"" : { ... } ```","Running from command line execute `Kastrel` server not `IIS`. In that case probably configuration `appsettings.json` is use. You can put in this configuration section to control port: ``` ""Kestrel"": { ""Endpoints"": { ""HTTP"": { ""Url"": ""http://localhost:6000"" } } }, ```" 26085466,"How can I shorten this function, so I don't need any of these `if`? ``` function showhide(element) { $('body').on('click', '#'+element, function() { if(element == 'export') { $('.chat-export').toggle(); $('.chat-settings').hide(); $('.chat-users').hide(); } else if(element == 'settings') { $('.chat-export').hide(); $('.chat-settings').toggle(); $('.chat-users').hide(); } else if(element == 'users') { $('.chat-export').hide(); $('.chat-settings').hide(); $('.chat-users').toggle(); } }); } ```",2014/09/28,"['https://Stackoverflow.com/questions/26085466', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/718990/']","Just do this: ``` $('[class^=chat]').each(function(){ if($(this).attr(""class"").indexOf(element) > -1){ $(this).toggle(); } else { $(this).hide(); } }); ``` PS. The problem with my early code and antyrat's code is that when we hide everything, the toggle works unexpectedly. [**DEMO**](http://jsfiddle.net/f3avLu2o/1/)","You can avoid this using this [`regex`](http://james.padolsey.com/javascript/regex-selector-for-jquery/) selector snippet for example: ``` $( 'div:regex(class, .chat-*)' ).hide(); $( '.chat-' + element ).toggle(); ```"