text
stringlengths
70
452k
dataset
stringclasses
2 values
Should a Product Owner (PO) be part of the Engineering team or Product team? Our start-up is currently build this way: Engineering Team which contains the following resources: Director of Engineering Mobile, front-end and back-end developers Quality Assurance Infrastructure engineer Product Owner (PO) Product Team: Director of Product Product designers Business Analyst Product Manager Other Teams such as sales, operations, etc We are currently having some discussions whether the PO should be part of the engineering team or the product team and we can't figure it out. My opinion is that it should be part of the same department as the whole scrum team but some people think otherwise. What would be the real logic needed to answer this question objectively? why does it matter which team a specific role falls into? I think only your company can answer these types of questions about your internal company structure, or you'll need to expand a lot more into how the team dynamics on your company works. It's a matter of opinion. Both ways can work well. And other ways can work well. it depends on how your teams and company operate. OP does not ask for opinions on this organisational question related to software engineering, but is on contrary, is looking for a logic (i.e. a model, a procedure, a criteria) that could help to answer it. It therefore calls for objectivity. I've added "objectively" to reinforce the call for a "logic". Furthermore it addresses a common organisational issue that is often addressed ad-hoc in an opinion based way and without clear analysis because related to power games. I therefore think this question is useful and worth to be reopened. Where should the PO be ? As you are a startup, there could be a confusion between team structure and organisation structure. What might look somewhat opinion based at first sight, becomes much more objective when you look at both dimensions separately: In the logic of the team, the product owner should of course be part of the scrum team, together with a lot of people from engineering. But that doesn't make him part of the engineering team. In the logic of the organisational structure, according to roles and responsibilities, the product owner should belong to the product organisation and report to the product manager. Otherwise stated: while the PO shall work closely together with engineering in a (cross-functional) scrum team, he/she shall be committed primarily to the customers interestest and therefore represent the product management in the team. This is fully compatible with the Scrum guide's definition: The Product Owner is responsible for maximizing the value of the product resulting from work of the Development Team. How this is done may vary widely across organizations, Scrum Teams, and individuals. What if PO would belong to engineering? First of all, depending on the people, their motivation and their ethics, this could very well work. But let's look at the consequences: How can the product manager manage the products if she/he has no control on the ownership of the product ? What will happen if (when?) engineering does not deliver according to product management expectations ? If the PO belongs to engineering, the product manager will immediatly questions his/her choices. And this is bad, since The Scrum guide says: The Product Owner is the sole person responsible for managing the Product Backlog. (...) For the Product Owner to succeed, the entire organization must respect his or her decisions. So this situation might create unnecessary tensions or even conflicts between departments, that could otherwise be avoided if both departments are represented in the team and find therein a negociated agreement (in a team spirit). Its depend of the technicals skills own by the Product Owner. I m currently working in a big company with multiple product owner. One of them is part of the enginering team where i am, because he can directly work on the projet, or at least, investigate on technicals problems, bugs or regressions in the code or in the infrastructure. But most other product owner, didn't have any skill in tech, and so are part of the marketing teams. In my opinion, Product Owner should be close as possible of his products (and product's customer), as possible he can act directly on the product. if your are in a startup, this is normal, that the product owner is parf ot the whole scrum.
common-pile/stackexchange_filtered
Pythonic way of splitting loop over list in two parts with one iterator I am processing a text file with an irregular structure that consists of a header and of data in different sections. What I aim to do is walk through a list and jump to the next section once a certain character is encountered. I made a simple example below. What is the elegant way of dealing with this problem? lines = ['a','b','c','$', 1, 2, 3] for line in lines: if line == '$': print("FOUND END OF HEADER") break else: print("Reading letters") # Here, I start again, but I would like to continue with the actual # state of the iterator, in order to only read the remaining elements. for line in lines: print("Reading numbers") can't you just call lines.index('$') to get the separator position? The use case is more complex than that, I am just searching for a general way of doing this. it would be productive if you post your real problem rather than this trivial one then The real problem has first a header, seperator and then an set of arbitrary sections with case specific number of lines. You actually can have one iterator for both loops by creating your line iterator outside the for loop with the builtin function iter. This way it will be partially exhausted in the first loop and reusable in the next loop. lines = ['a','b','c','$', 1, 2, 3] iter_lines = iter(lines) # This creates and iterator on lines for line in iter_lines : if line == '$': print("FOUND END OF HEADER") break else: print("Reading letters") for line in iter_lines: print("Reading numbers") The above prints this result. Reading letters Reading letters Reading letters FOUND END OF HEADER Reading numbers Reading numbers Reading numbers This is the most python answer. +1 This is exactly what I was looking for You could use enumerate to keep track of where you are in the iteration: lines = ['a','b','c','$', 1, 2, 3] for i, line in enumerate(lines): if line == '$': print("FOUND END OF HEADER") break else: print("Reading letters") print(lines[i+1:]) #prints [1,2,3] But, unless you actually need to process the header portion, the idea of @EdChum to simply use index is probably better. A simpler way and maybe more pythonic: lines = ['a','b','c','$', 1, 2, 3] print([i for i in lines[lines.index('$')+1:]]) # [1, 2, 3] If you want to read each element after $ to different variables, try this: lines = ['a','b','c','$', 1, 2, 3] a, b, c = [i for i in lines[lines.index('$')+1:]] print(a, b, c) # 1 2 3 Or if you are unaware of how many elements follow $, you could do something like this: lines = ['a','b','c','$', 1, 2, 3, 4, 5, 6] a, *b = [i for i in lines[lines.index('$')+1:]] print(a, *b) # 1 2 3 4 5 6 If you have more that one kind of separators, the most generic solution would be to built a mini-state machine to parse your data: def state0(line): pass # processing function for state0 def state1(line): pass # processing function for state1 # and so on... states = (state0, state1, ...) # tuple grouping all processing functions separators = {'$':1, '#':2, ...} # linking separators and states state = 0 # initial state for line in text: if line in separators: print('Found separator', line) state = separators[line] # change state else: states[state](line) # process line with associated function This solution is able to correctly process arbitrary number of separators in arbitrary order with arbitrary number of repetitions. The only constraint is that a given separator is always followed by the same kind of data, that can be process by its associated function.
common-pile/stackexchange_filtered
Constructing a warped image given optical flow gradients I have gradients for optical flow in the x and y direction, and I am wondering how to transform an image according to those gradients: The arrow points to the direction of the gradient calculated What would be the best way to construct the image for a given time-step along the gradients? Use a sane warping strategy, preferably based on interpolation. In matlab, use of "interp2" works well. Matlab example: s = 40; %size of data t = 1; %time offset [x,y] = meshgrid(1:s,1:s); binIm = (x-(s/2)).^2 +((y-(s/2)).^2)*10 <((s/3))^2; subplot(2,2,1); imagesc(binIm); colormap gray;axis image; title('eliptical mask'); %some rotational flow (curl) Ur = 10*(y-(s/2))/(s/2); Vr = -10*(x-(s/2))/(s/2); %some zooming flow (divergent) Uz = 10*(x-(s/2))/(s/2); Vz = 10*(y-(s/2))/(s/2); binImR = interp2(double(binIm),x-t*Ur,y-t*Vr); subplot(2,2,3); imagesc(binImR); axis image;colormap gray; hold on; quiver(Ur,Vr); title('rotational flow'); binImZ = interp2(double(binIm),x-t*Uz,y-t*Vz); subplot(2,2,4); imagesc(binImZ); axis image;colormap gray; hold on; quiver(Uz,Vz); title('zooming flow'); Note that the bigger you make "t", the worse the approximation will become, especially for rotational motion. -For each pixel, interpolate its gradient using proximity and magnitude of the 4 nearest optical flow values. -Then apply the time step to the interpolated gradient value to generate a destination location. -Since the resulting position will not be directly on grid, I would probably calculate a Gaussian centered on the destination based on the origin pixel's intensity. Then use that Gaussian to add intensity values into the nearby cells in the output image. Alternately, you could take the intensity (of the original pixel) and do a weighted split of that intensity into the 4 nearest cell centers about the destination location. (i feel like this may blur your image less than a Gaussian)
common-pile/stackexchange_filtered
Letter "E" Stopped Working - Linux Mint Can't login to my Linux Min 19 Cinnamon Laptop because I singular key stopped working! Any ideas around this? Plug in a keyboard. @Wildcard I'm literally on vacation in the middle of nowhere and didn't bring one ughh lol Login and change the keyboard layout. (But how to login). Or is there an onscreen keyboard option on the login screen, that can be activated via the mouse. Use your fingerprint sensor if you have one (and configured). Use ssh from your smartphone to login and change configuration as necessary. (You do have ssh on your smartphone, don't you?) If you can break in at the grub prompt (or other bootloader, but most people use grub) then append init=/bin/bash to the boot command. When the system boots, run mount -o remount,rw / to make the disk partition writeable, and then run passwd darria or whatever the user name is to change the password. @icarus remount has an e in it. @AnonymousDarria How did you type in the es in your question? Do you have access to another machine? @Sparhawk indeed it does. At this stage however he can do things like X=$\\x65`to make${X}a lower case e. so then he can typemount -o r${X}mount,rw /` @icarus Nice one. You should write that up as an answer. As noted in the comments, the simplest solution is to just connect an external keyboard, which might be via USB, bluetooth, or an onscreen one operated by a mouse. The OP says that he doesn't have another keyboard available. If it is possible to break in at the grub prompt (or whatever bootloader is being used) then you can append init=/bin/bash to the command line, and continue the boot. The system will continue and will end up with a shell prompt in a sort of half booted stage. At this stage we want to create a new password without the letter e so it can be entered with the faulty keyboard. However, the disk is in a read-only state, so can't store an updated password. Type X=$'\x65' mount -o r${X}mount,rw / to remount the / partition without needing the letter e. $'\xNN' is bash syntax which allows you input a character by hex digits, $'\x45' is E and $'\x65' is e. Then change the password for the user passwd darria to chnage the password of the user darria. Save all the changes to disk by running sync and waiting a few seconds, then reboot the machine (the power button for 10 seconds may be your best option), and log in with the new password.
common-pile/stackexchange_filtered
How to use "q" Query parameter in Bitbucket REST API? So I am aware of the fact that you can get the files in a repository by using https://api.bitbucket.org/2.0/repositories/{workspace}/{repo_slug} API. The API also supports the q parameter where you can query the resulting json object based on various fields in it. I wanted to know if one can use this query parameter to fetch the files based on certain extensions? Like the JSON object also contains a field "mimetype" which defines the mime type of the files. I did use the following API call https://api.bitbucket.org/2.0/repositories/{workspace}/openapi/src/master/?max_depth=100&q=path+%7E+%22.js%22&pagelen=100 To fetch all the files which contain the string ".js" in the path parameter. But while querying the mimetype parameter I was not able to do the same using https://api.bitbucket.org/2.0/repositories/{workspace}/openapi/src/master/?max_depth=100&q=mimetype+%3D+%22application%2Fjavascript%22&pagelen=100 This call returned error. Can anybody let me know how can you query based on mimetype or if possible fetch the files based on extension Note: I know about the Code search API but that is not an option as it has large limitations.
common-pile/stackexchange_filtered
How do I derive Pauli's exclusion principle with path integrals? I am trying to prove Pauli's exclusion principle using path integrals. My starting point is the configuration space $\mathcal{C}$ for two indistinguishable particles in 3D: $$ \mathcal{C} = \{ \{x_1,x_2\}:x_i \in \mathbb{R}^3,x_1 \neq x_2 \} $$ The fundamental group $\pi_1 (\mathcal{C})$ is defined as the set of equivalence classes of paths $\gamma :[0,1] \rightarrow \mathcal{C} $ where two paths are equivalent if they are homotopic. I can deduce that for my configuration space $$ \pi_1(\mathcal{C}) \cong \mathbb{Z}_2 $$ which correspond to the two classes of paths where the particles exchange positions and those that don't. Now I have been told that this implies the existence of two species of particles, namely fermions and bosons. I am unsure why but I continue anyway. The propagator is defined as $$ \langle \mathbf{x}_f,t_f|\mathbf{x}_i,t_i \rangle = \sum_{\alpha \in \pi_1(\mathcal{C})}\rho(\alpha) K(\alpha)$$ where $\mathbf{x}_{i,f}$ are the initial and final configurations in $ \mathcal{C}$, $\rho(\alpha)$ is a representation of the homotopy class $\alpha \in \pi_1(\mathcal{C})$ and $K(\alpha)$ is the usual Feynman path integral over all paths within the $\alpha$ homotopy class. I take my initial and final configurations as $ \mathbf{x}_{i,f}= \{ x_1,x_2 \}$, and choose the paths $\alpha $ such that they interchange the particles with a representation $\rho(\alpha) = -1$, therefore the propagator above becomes $$ \langle \mathbf{x}_f,t_f|\mathbf{x}_i,t_i \rangle = - K(\alpha)$$ I am unsure what this is telling me. There is a minus sign but is this equivalent to the usual result in terms of state vectors $$ |\psi(x_1,x_2) \rangle = - |\psi(x_2,x_1 )\rangle?$$ How would I go from the propagator to Pauli's exlusion principle? I explicity stated that my configuration space does not include instances where $x_1 = x_2$, so I cannot use this to see what happens when both particles are at the same position. Any help would be much appreciated. write the amplitude of $\langle x_1,x_2|U|x_1,x_2 \rangle$ as a path integral in first quantized picture. Then if you choose a specific path for exmaple one particle encircles the other, you will find that therw ill be a phase. With this method you can calculate the corresponding phase of exchange and braiding. I am not sure if you can proove pep. Notice that the classical configuration space you wrote is simply connected. What you want to consider is $\mathcal C / S_2$, where $S_2$ acts on $\mathcal C$ as $(x_1,x_2)\to (x_2,x_1)$. @pppqqq I explicitly defined $ \mathcal{C} $ in terms of sets and not ordered pairs, so what I have written is not simply connected Oh. Anyway, you may try to have look at these notes http://www.sissa.it/tpp/phdsection/download.php?ID=3349&filename=Instantons.pdf
common-pile/stackexchange_filtered
How to use Caret to tell which line it is in from JTextPane? (Java) Problem: I have CaretListener and DocumentListener listening on a JTextPane. I need an algorithm that is able to tell which line is the caret at in a JTextPane, here's an illustrative example: Result: 3rd line Result: 2nd line Result: 4th line and if the algorithm can tell which line the caret is in the JTextPane, it should be fairly easy to substring whatever that is in between the parentheses as the picture (caret is at character m of metadata): -- This is how I divide the entire text that I retrieved from the JTextPane into sentences: String[] lines = textPane.getText().split("\r?\n|\r", -1); The sentences in the textPane is separated with \n. Problem is, how can I manipulate the caret to let me know at which position and which line it is in? I know the dot of the caret says at which position it is, but I can't tell which line it is at. Assuming if I know which line the caret is, then I can just do lines[<line number>] and manipulate the string from there. In Short: How do I use CaretListener and/or DocumentListener to know which line the caret is currently at, and retrieve the line for further string manipulation? Please help. Thanks. Do let me know if further clarification is needed. Thanks for your time. Here is the source code you requested : static int getLineOfOffset(JTextComponent comp, int offset) throws BadLocationException { Document doc = comp.getDocument(); if (offset < 0) { throw new BadLocationException("Can't translate offset to line", -1); } else if (offset > doc.getLength()) { throw new BadLocationException("Can't translate offset to line", doc.getLength() + 1); } else { Element map = doc.getDefaultRootElement(); return map.getElementIndex(offset); } } static int getLineStartOffset(JTextComponent comp, int line) throws BadLocationException { Element map = comp.getDocument().getDefaultRootElement(); if (line < 0) { throw new BadLocationException("Negative line", -1); } else if (line >= map.getElementCount()) { throw new BadLocationException("No such line", comp.getDocument().getLength() + 1); } else { Element lineElem = map.getElement(line); return lineElem.getStartOffset(); } } ... public void caretUpdate(CaretEvent e) { int dot = e.getDot(); int line = getLineOfOffset(textComponent, dot); int positionInLine = dot - getLineStartOffset(textComponent, line); ... } @joppux: Wow thanks! Can you please explain a bit of your code? Text component document model (subclass of Document) consists of Elements (class javax.swing.text.Element). For most Documents Elements are lines of text, so working with Elements is working with lines. Most of the code is simply checking for wrong arguments, and the rest is simple. Well, I looked in docs, so it seems that it works only for PlainDocument, more complex documents (as DefaultStyledDocument or HTMLDocument) need more complex code. @joppux: Eh? I am using StyledDocument instance of AbstractDocument and it worked. Hmm. Use the notion of paragraph in in the StyledDocument with JTextPane.getStyledDocument. With the position of cursor, you know the current paragraph with StyledDocument.getParagraph(pos). Then you iterate throw the paragraphs from StyledDocument.getRootElements and children, to search the number of current paragraph, so the number of current line. Sorry for my english. @Istao: It's alright, thanks for trying to answer. English is not my native language as well. =) I can't find a definition of a paragraph. It's supposed to be an abstract concept in the interface StyledDocument and abstract class AbstractDocument (whose documentation says: "...Sub-classes must define for themselves what exactly constitutes a paragraph...."), but DefaultStyledDocument is a concrete class. The closest it comes to a definition is "...A paragraph consists of at least one child Element, which is usually a leaf....". AbstractDocument seems to guarantee that paragraphs must start/end only at \n, but I can't locate any guarantee that they won't have embedded \ns. This is how I divide the entire text that I retrieved from the JTextPane into sentences: Your solution is not very efficient. First of all only a "\n" is ever stored in a Document not matter what OS is being used. So you can simplify the regex. However, there is no need to use a regex to parse the entire Document since you only care about 1 line in the Document. Now that you know about the Element interface you can make the code more efficient. a) get the line as demonstrated previously b) now you can get the Element represented by that line, from the root Element c) now you can use the start/end offsets and the getText(...) method to get only the text for that particular line. @camickr: I'm sorry I'm not well versed with the Element, especially on (b) that you're pointing out. Do you mind clarifying by giving an example? Well, start by reading the API. The start/end offset methods are in the Element class and the getText() method as you know is in the Document class. Regarding an example you already have a working example. joppux already showed you how to get the start offset. So its 2 more lines of code to get the end offset and then use the start and end offset extract the text using the getText() method. If you have a problem then post your SSCCE: http://sscce.org. You learn more by trying and making mistakes then by just copying code. Take the time to understand how the code you copy works. Oh. I was thinking how am I supposed to retrieve the text from Element, hence the question. I think I got the endOffset correct, however using what you'd suggested breaks my current implementation. I'll stick to my old code till I figure out what is wrong. Anyway, thanks.
common-pile/stackexchange_filtered
Feature-selection and prediction from sklearn.feature_selection import RFECV from sklearn.metrics import accuracy_score from sklearn.model_selection import cross_val_predict, KFold from sklearn.preprocessing import StandardScaler from sklearn.ensemble import RandomForestClassifier from sklearn.pipeline import Pipeline from sklearn.datasets import load_iris I have X and Y data. data = load_iris() X = data.data Y = data.target I would like to implement RFECV feature selection and prediction with k-fold validation approach. code corrected from the answer @ https://stackoverflow.com/users/3374996/vivek-kumar clf = RandomForestClassifier() kf = KFold(n_splits=2, shuffle=True, random_state=0) estimators = [('standardize' , StandardScaler()), ('clf', clf)] class Mypipeline(Pipeline): @property def coef_(self): return self._final_estimator.coef_ @property def feature_importances_(self): return self._final_estimator.feature_importances_ pipeline = Mypipeline(estimators) rfecv = RFECV(estimator=pipeline, cv=kf, scoring='accuracy', verbose=10) rfecv_data = rfecv.fit(X, Y) print ('no. of selected features =', rfecv_data.n_features_) EDIT (for small remaining): X_new = rfecv.transform(X) print X_new.shape y_predicts = cross_val_predict(clf, X_new, Y, cv=kf) accuracy = accuracy_score(Y, y_predicts) print ('accuracy =', accuracy) Instead of wrapping StandardScaler and RFECV in a same pipeline, do that for StandardScaler and RandomForestClassifier and pass that pipeline to the RFECV as an estimator. In this no traininf info will be leaked. estimators = [('standardize' , StandardScaler()), ('clf', RandomForestClassifier())] pipeline = Pipeline(estimators) rfecv = RFECV(estimator=pipeline, scoring='accuracy') rfecv_data = rfecv.fit(X, Y) Update: About the error 'RuntimeError: The classifier does not expose "coef_" or "feature_importances_" attributes' Yes thats a known issue in scikit-learn pipeline. You can look at my other answer here for more details and use the new pipeline I created there. Define a custom pipeline like this: class Mypipeline(Pipeline): @property def coef_(self): return self._final_estimator.coef_ @property def feature_importances_(self): return self._final_estimator.feature_importances_ And use that: pipeline = Mypipeline(estimators) rfecv = RFECV(estimator=pipeline, scoring='accuracy') rfecv_data = rfecv.fit(X, Y) Update 2: @brute, For your data and code, the algorithms completes within a minute on my PC. This is the complete code I use: import numpy as np import glob from sklearn.utils import resample files = glob.glob('/home/Downloads/Untitled Folder/*') outs = [] for fi in files: data = np.genfromtxt(fi, delimiter='|', dtype=float) data = data[~np.isnan(data).any(axis=1)] data = resample(data, replace=False, n_samples=1800, random_state=0) outs.append(data) X = np.vstack(outs) print X.shape Y = np.repeat([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 1800) print Y.shape #from sklearn.utils import shuffle #X, Y = shuffle(X, Y, random_state=0) from sklearn.feature_selection import RFECV from sklearn.model_selection import KFold from sklearn.preprocessing import StandardScaler from sklearn.ensemble import RandomForestClassifier from sklearn.pipeline import Pipeline clf = RandomForestClassifier() kf = KFold(n_splits=10, shuffle=True, random_state=0) estimators = [('standardize' , StandardScaler()), ('clf', RandomForestClassifier())] class Mypipeline(Pipeline): @property def coef_(self): return self._final_estimator.coef_ @property def feature_importances_(self): return self._final_estimator.feature_importances_ pipeline = Mypipeline(estimators) rfecv = RFECV(estimator=pipeline, scoring='accuracy', verbose=10) rfecv_data = rfecv.fit(X, Y) print ('no. of selected features =', rfecv_data.n_features_) Update 3: For cross_val_predict X_new = rfecv.transform(X) print X_new.shape # Here change clf to pipeline, # because RFECV has found features according to scaled data, # which is not present when you pass clf y_predicts = cross_val_predict(pipeline, X_new, Y, cv=kf) accuracy = accuracy_score(Y, y_predicts) print ('accuracy =', accuracy) This is an overly complex and un-necessary hack IMHO. @EkabaBisong Maybe its a little complex, but not un-necessary. This is done to prevent data leakage. Here's how we'll do it: Fit on the training set from sklearn.feature_selection import RFECV from sklearn.metrics import accuracy_score from sklearn.model_selection import cross_val_predict, KFold from sklearn.preprocessing import StandardScaler from sklearn.ensemble import RandomForestClassifier from sklearn.pipeline import Pipeline from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split data = load_iris() X = data.data, Y = data.target # split into train and test sets X_train, X_test, y_train, y_test = train_test_split(X, Y, shuffle=True) # create model clf = RandomForestClassifier() # instantiate K-Fold kf = KFold(n_splits=10, shuffle=True, random_state=0) # pipeline estimators estimators = [('standardize' , StandardScaler()), ('rfecv', RFECV(estimator=clf, cv=kf, scoring='accuracy'))] # instantiate pipeline pipeline = Pipeline(estimators) # fit rfecv to train model rfecv_model = rfecv_model = pipeline.fit(X_train, y_train) # print number of selected features print ('no. of selected features =', pipeline.named_steps['rfecv'].n_features_) # print feature ranking print ('ranking =', pipeline.named_steps['rfecv'].ranking_) 'Output': no. of selected features = 3 ranking = [1 2 1 1] Predict on the test set # make predictions on the test set predictions = rfecv_model.predict(X_test) # evaluate the model performance using accuracy metric print("Accuracy on test set: ", accuracy_score(y_test, predictions)) 'Output': Accuracy: 0.9736842105263158 @brute No. This code does not use StandardScaler anywhere. You just define it inside the pipeline, but its not used (fitted anywhere). When you do this pipeline.named_steps['rfecv'].fit(X_train, y_train) you are directly using the RFECV on the original data, not scaled data. @brute. Code updated. This uses the pipeline properly to scale and fir with RFE. @VivekKumar. Please define leaking data. You're wrong. I really don't care what rfecv does with the training data x_train. The important thing here is that we first split the dataset into a training and a testing set using the train_test_split method. We fit the rfecv method of the train set, and predict on the test set. No data from the test set is leaked into the train set. Do not confuse the OP. Thats the problem. RFECV will again split the X_train into train and test (using cv folds), there the data is scaled before split so train data of rfecv and then the model knows about the that test data because its scaled using the test data (Here I am talking about the internal train and test). Then you find that these many features are important for this, which will be biased.
common-pile/stackexchange_filtered
How to pass test configuration parameters to 'Call to Test' in HP ALM When you create test steps with parameters in test instance you can set up several test configurations (to run the same test with different set of parameters). Test instance with params (and sets of params) could be used in another test instance as "Call to Test" (If it's marked as test template). But it looks like there is only one fixed set of params for 'Called Test' The task is to pass params from calling test's "Test Configuration" to the called test. Is it possible? P.S.: till now the best solution I have is to copy test steps and not to call it, but it will not be possible to edit these substeps just in one place any more (as they are not substeps but steps as it is). You will have to change them in every test instance they are used in. The solution is simple: you need to leave Called Test parameters empty so they would be marked with ? symbol in call step. Have a look at this: Call <Expert Parameter - controlTrafficNetworkType> with the following parameters: network type = ? So when you create the new test configuration (param/value pairs) there will be desired parameter from Called Test EDIT N.B.: Default values are not implemented by default. After test instance creation you still need to copy Default values in every test configuration data where it's supposed (You can select all the params holding Ctrl pressed and copy all the values at a time). Copy Default Values button
common-pile/stackexchange_filtered
How to identify L2 devices in a Wide Area Network? This is sample of a traceroute to google.com: TraceRoute from Network-Tools.com to <IP_ADDRESS> [google.com] Hop (ms) (ms) (ms) IP Address Host name 1 0 0 0 <IP_ADDRESS> - 2 Timed out Timed out Timed out - 3 1 1 1 <IP_ADDRESS> google-level3-3x10g.dallas.level3.net 4 1 1 1 <IP_ADDRESS> - 5 1 1 1 <IP_ADDRESS> - 6 1 1 1 <IP_ADDRESS> dfw25s12-in-f14.1e100.net Trace complete It obvious there should be some layer two and layer one (physical layer tapping devices) network devices in between that we cannot trace or identify, but they have an important impact on the result. These layer 2 & 1 network devices have many roles, including security. There are many Agencies or Organizations that capture data on the physical layer or Data link layer like the PRISM surveillance program. I am looking for theory or practical way to find a way to identify layer 2 devices in order to prove or identify data capturing. You can see some hop counts in the traceroute results, but there are certainly many devices in the middle; if you could capture traffic you could see that when a packet passes a device the source MAC address would change This is incorrect. L2 devices do not change source/dest hardware address. More to the point of your question, if you're inside the target network you could try sniffing for lldp/cdp/stp traffic to gather information about the connected L2 devices. Once the packets goes through a router any information below layer 3 is lost. The "timed out" and missing hops in your traceroute are not invisible l2 devices, they're hops (routers) that do not send ICMP type 11 packets to inform the TTL was exceeded. @WhiteWinterWolf When a frame leaves from host A to host B, both within the same broadcast domain (think LAN), the frame that arrives at B will have the same Ethernet headers that it had when it left A, no matter how many (L2) switches it traverses. Answer are very helpful but my question remains,when a frame pass a layer 2 device there should be an effect on it that i try to understand. @user1832494 the answer is there isn't, except for the timing one mentioned by Steffen. For l2 devices you can use lldp (link layer discovery protocol). Information from layer 2 are usually not propagated to the higher layers because they are not needed there. Exceptions are protocols like ARP but this is only visible inside the local network. This means it is not possible to directly detect layer 2 (link layer) devices unless you are connected to the same link or inside the same local network (ARP). You might try to infer the possible effects of such devices based on irregularities in the network or timing but most will probably be invisible from remote. Any device has an effect to the packet ,like changing TTL or increasing ping time and etc,because they have some sort of processing on packet ,what are layer two effect on packet ? @user1832494: TTL or hop count are at layer 3. Layer 2 devices do not change it. As for the timing: I've mentioned it. Apart from that layer 2 devices usually don't change anything at the (layer 3) packet at all, but there are exceptions like layer 2 encryption devices or "invisible" deep packet inspection. we have two different approach,first security device that using: Tap ,Span or same technology and the second one is layer two device like switches or radios ,is it effect of packet for those devices are the same or maybe it makes a big different ? @user1832494: a tap is copying the packet for further analysis and should not or almost not impact the timing (depending on the type of tap) and should cause no loss. Switches instead forward the packet and thus impact the timing more and might cause packet loss.
common-pile/stackexchange_filtered
Adding the :hover pseudoclass Is there any way to programmatically have D3 add a ":hover" to a selection? If not, how can I do this using straight JavaScript? Did you look in the D3 docs? What have you tried? etc. etc. You have enough rep to know better. Possible duplicate of How do I simulate a mouseover in pure JavaScript that activates the CSS ":hover"? @RandyCasburn, there was nothing to try as it's not possible in JS, as the answers below show. D3 documentation would not help as this is not specific to D3. Rep has nothing to do with it. You can't programmatically add :hover from JavaScript (or D3). I'd recommend using a CSS class with the same styling rules: #foo:hover, #foo.selected { ... } And then add the .selected class from D3. (See: How do I simulate a mouseover in pure JavaScript that activates the CSS ":hover"? ) As already explained by cdrini, it is not exactly possible to accomplish this by JavaScript. Instead, you can use this code to add a class to an element on hover: element.onmouseover = function(){ this.classList.add('foo'); }; element.onmouseout = function(){ this.classList.remove('foo'); };
common-pile/stackexchange_filtered
Strong_parameters not working With Ruby 1.9.3, Rails 3.2.13, Strong_parameters 0.2.1: I have followed every indication in tutorials and railscasts, but I can not get strong_parameters working. It should be something really simple, but I can not see where is the error. config/initializers/strong_parameters.rb: ActiveRecord::Base.send(:include, ActiveModel::ForbiddenAttributesProtection) config/application.rb config.active_record.whitelist_attributes = false app/models/product.rb class Product < ActiveRecord::Base end app/controllers/products_controller.rb: class ExpedientesController < ApplicationController ... def create @product = Product.new(params[:product]) if @product.save redirect_to @product else render :new end end end This raises the Forbidden Attributes exception, as expected. But when I move to: ... def create @product = Product.new(product_params) # and same flow than before end private def product_params params.require(:product).permit(:name) end Then, if I go to the form and enter "Name: product 1" and "Color: red" no exception is raised; the new product is saved in the database with no color but with the right name. What am I doing wrong? Solved. By default, the use of not allowed attributes fails silently and the so submitted attributes are filtered out and ignored. In development and test environments the error is logged as well. To change the default behaviour, for instance in development enviroment: config/environments/development.rb: # Raises an error on unpermitted attributes assignment config.action_controller.action_on_unpermitted_parameters = :raise # default is :log To be honest, is very clearly explained in the github repository. There are tutorials like this one that rely on the default being :raise, which is confusing. Thanks for addressing this.
common-pile/stackexchange_filtered
Graph similarity measure with unknown node correspondence How to measure the similarity between two graphs G1 and G2 with equal or unequal number of nodes where, the correspondence between the nodes of the graphs are unknown. For example, node A of G1 has moved to the middle of G2. Is there any similarity measure algorithm that returns sim(G1,G1)=1 sim(G1,G2)=1 sim(G1,G3)=some number between 0 and 1 where, 1 denotes highest similarity and 0 denotes lowest similarity. Since you don't know the nodes correspondence, one simple approach is to define the signature of a graph as a sorted array containing the degrees of all nodes. Then find the longest common sub-sequence of the two signatures, where "common" doesn't necessary mean all "elements are equal", but that they are close enough. Since the signatures are sorted arrays, the problem is even simpler. And then somehow compute the distance between the two versions of the longest "common" sub-sequence. Additionally, you can factor in some score concerning the nodes that are not part of it. Hi Cobarzan, thanks for your answer. Could you please elaborate your answer little bit. What do you mean by signature of a graph. If multiple nodes of the graph have same degrees then will shorting besed on the degree be effective? How do you calculate the distance between two longest common sub-sequence? In paper (Tantardini et al., 2019), authours proposed the classification of comparing methods for comparing networks: а) known node-correspondence, b) unknown node-correspondence.
common-pile/stackexchange_filtered
Decrypting a JWE token using JOSE with A256GCM I'm curious about this and wanted to see if anyone understands it. I am encoding a payload using the jose-jwt nuget in .NET: Jose.JWT.Encode( payload, keyBytes, JweAlgorithm.A256GCMKW, JweEncryption.A256GCM, extraHeaders: extraHeaders) and this returns a token that looks correct. When I use JOSE to decrypt the same payload: Jose.JWT.Decode(payload, keyBytes, JweAlgorithm.A256GCMKW, JweEncryption.A256GCM); It throws an error: BCrypt.BCryptDecrypt(): authentication tag mismatch Is this normal? Is the JWE encryption supposed to be unable to be decrypted or can someone explain why this error is happening? Thanks Are you encoding with the public key and decoding with the private key? Yes. The decrypt method is giving an exception due to the data not being encrypted in the same method that is being used to decrypt. Is it possible to have sample jwe generated by jose-jwt and associated keys? AesGcmKeyWrapManagement management algorithm expected key of size 256 bits. I think you are using a Symmetric key. Check the source code https://github.com/dvsekhvalnov/jose-jwt/blob/master/jose-jwt/JWT.cs
common-pile/stackexchange_filtered
What would be an "earnest description" on the difference between language and grammar? I came to this website searching 'difference between language and grammar' and found this question “What is the difference between grammar and usage?” I thought on what was said there and came to realize the word 'usage' is given its own place as a term. Which seems to be an expression of cognitive fallacy in the development of the language or at least the organization of the rule. Before someone begins their freak out response please give me a chance to finish some more context for the answer I am looking for. Originally I defined language as the stylized set of rules and assets (all things dealing in individual words) that defines all usability of its spoken and written forms. I looked at a definition of grammar "the whole system and structure of a language or of languages in general, usually taken as consisting of syntax and morphology (including inflections) and sometimes also phonology and semantics." and then another and another till even lexicon and dictation was able to be included under grammar. Maybe the issue is within the orderability of the many rules. An inability maybe to assign of sequential priority to each rule except maybe categorically. Getting sentence structure right then dealing with plural rules next, as an example. The question may need to be answered if it is in fact appropriate for rules to exist that hold a definitive placing in usability but not covered under grammar. Once again more simply put, is there some sort of definitive reason that separates grammar from usage. I am not qualified to say, but feel that would be what makes Language distinctly different from grammar as it would be comprised of then of more than one super subject. As a final message to whoever replies I feel strongly someone is capable to define these terms without resorting to examples for pattern matching as substitute for an earnest description. Try trimming your last two paragraphs, or even deleting the last one, in order to fit the first paragraph. There's probably a character limit for newcomers . The question (Could you remind us?) needs an introduction. A grammar is the set of rules by which a language is spoken, often differing between generations, communities, and even individual speakers. The language itself comprises myriad parts, including grammar, syntax, lexicon, diction, phonology, and so on and so forth. I have no idea what the actual question here is … Mari-Lou A thank you I attempted refining it. What was wrote was in hopes to prevent responses like the anonym above. I asked for an earnest answer meaning showing sincere and intense conviction. Not for dramatics, but for quality as it is an unusual question it seems. I am still looking into phonology compared to morphology and still it is seeming there is nothing within language that is not covered under the word grammar. Could it be said that | Language is the conventional identifier of a spoken and or written system where as grammar is the descriptive rules in which a language follows and multiple languages may share or relate. | ?? or is that not complete enough? A dictionary provides some help here: Language The method of human communication, either spoken or written, consisting of the use of words in a structured and conventional way. [ODO] Grammar The whole system and structure of a language or of languages in general, usually taken as consisting of syntax and morphology (including inflections) and sometimes also phonology and semantics. [ODO] Language is the means of communication, and grammar is the rules which make a language intelligible. In this regard, your own analysis seems reasonable: Language is the conventional identifier of a spoken and or written system where as grammar is the descriptive rules in which a language follows and multiple languages may share or relate.
common-pile/stackexchange_filtered
jQuery datatable if data length greater than certain length I once used PHP to print my datatables. When I got to a particular column that had a string greater than 17 characters, I would use the following to print ellipses after the 17th character: if(strlen($row[tli]) > 17){echo "<td><a href='#'>".substr(row['number'],0,17)."..."</a></td>";} I need to do the same thing using ajax instead. $('#example1').DataTable({ "ajax": { "url": "api/displayQnams.php", "type": "POST", "dataSrc": '' }, "columns": [ { "data": "number", "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) { if(oData.number.length > 17) // here is where the initial check starts {$(nTd).html("<a href='#'>'"+oData.number+"...'</a>")} // here is where it should print the ellipses after the 17th character else {$(nTd).html("<a href='#'>'"+oData.number+"'</a>"} } } ] }); oData.number.length gives me the following error in the console: Cannot read property 'length' of undefined What am I missing to make this work? The problem was some of the oData was null, and you cannot compare null value using length. So I created a variable and if oData.number was null, set the variable to ''. Here is how I got it to work: "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) { if(oData.tli == null || oData.tli == ""){var tlinumber = '';} else{var tlinumber = oData.tli;} if(tlinumber.length > 17) { $(nTd).html("<a href='#'>'"+tlinumber.substring(0, 17)+"...'</a>") } else { $(nTd).html("<a href='#'>'"+tlinumber+"'</a>" } }
common-pile/stackexchange_filtered
App Signed by custom Certificates giving error code: 0x800B010A I made a CA (imported into CurrentUser/Root) and used it to make signing certificate (imported into CurrentUser/TrustedPeople). It says "This certificate is OK." and it signs my certificate fine but it get "This app package’s publisher certificate could not be verified. The root certificate and all immediate certificates of the signature in the app package must be verified 800B010A" I know one fix is to import the signing certificate into LocalMachine/TrustedPeople but I was wondering if there is something in how I made my certificates that I can change. winpty openssl genrsa -out ca.key 4096 winpty openssl req -new -x509 -days 365 -key ca.key -out ca.crt -config extfile.cnf winpty openssl pkcs12 -export -out CACertificate.pfx -inkey ca.key -in ca.crt winpty openssl genrsa -out client.key.pem 4096 winpty openssl req -new -key client.key.pem -out client.csr winpty openssl x509 -req -in client.csr -CA ca.crt -CAkey ca.key -out client.cert.pem -CAcreateserial -days 365 -sha256 -extfile client_extfile.cnf winpty openssl pkcs12 -export -out clientCertificate.pfx -inkey client.key.pem -in client.cert.pem makeappx pack /d <source_directory> /p <output_package.appx> signtool sign /fd SHA256 /a /f <certificate_file.pfx> /p <password> <path_to_appx_file> CA cnf file [ req ] distinguished_name = req_distinguished_name x509_extensions = v3_ca prompt = no default_bits = 4096 default_keyfile = ca.key default_md = sha256 [ req_distinguished_name ] CN=kk O=kk L=kk C=kk [ v3_ca ] subjectKeyIdentifier = hash authorityKeyIdentifier = keyid:always,issuer basicConstraints = critical, CA:true, pathlen:0 keyUsage = critical, digitalSignature, cRLSign, keyCertSign extendedKeyUsage = codeSigning Client cnf file [ req ] distinguished_name = req_distinguished_name x509_extensions = v3_req prompt = no default_md = sha256 [ req_distinguished_name ] CN=kk O=kk L=kk C=kk [ v3_req ] basicConstraints = critical, CA:FALSE keyUsage = critical, digitalSignature extendedKeyUsage = codeSigning subjectKeyIdentifier = hash authorityKeyIdentifier = keyid,issuer
common-pile/stackexchange_filtered
AttributeError when rewriting code so it works in Python 3.4 I am trying to alter the code below so that it works in Python 3.4. However, I get the Error AttributeError: 'int' object has no attribute 'replace' in the line line.replace(",", "\t"). I am trying to understand how to rewrite this part of the code. import os import gzip from io import BytesIO import pandas as pd try: import urllib.request as urllib2 except ImportError: import urllib2 baseURL = "http://ec.europa.eu/eurostat/estat-navtree-portlet-prod/BulkDownloadListing?file=" filename = "data/irt_euryld_d.tsv.gz" outFilePath = filename.split('/')[1][:-3] response = urllib2.urlopen(baseURL + filename) compressedFile = BytesIO() compressedFile.write(response.read()) compressedFile.seek(0) decompressedFile = gzip.GzipFile(fileobj=compressedFile, mode='rb') with open(outFilePath, 'w') as outfile: outfile.write(decompressedFile.read().decode("utf-8", errors="ignore")) #Now have to deal with tsv file import csv csvout = 'C:/Sidney/ECB.tsv' outfile = open(csvout, "w") with open(outFilePath, "rb") as f: for line in f.read(): line.replace(",", "\t") outfile.write(line) outfile.close() Thank You You're writing ASCII (by default) with the 'w' mode, but the file you're getting that content from is being read as bytes with the 'rb' mode. Open that file with 'r'. And then, as Sebastian suggests, just iterate over the file object with for line in f:. Using f.read() will read the entire thing into a single string, so if you iterate over that, you'll be iterating over each character of the file. Strictly speaking, since all you're doing is replacing a single character, the end result will be identical, but iterating over the file object is preferred (uses less memory). Let's make better use of the with construct and go from this: outfile = open(csvout, "w") with open(outFilePath, "rb") as f: for line in f.read(): line.replace(",", "\t") outfile.write(line) outfile.close() to this: with open(outFilePath, "r") as f, open(csvout, 'w') as outfile: for line in f: outfile.write(line.replace(",", "\t")) Also, I should note that this is much easier to do with find-and-replace in your text editor of choice (I like Notepad++). Additionally try for line in f: instead of for line in f.read():. Can we please add the output file to a context manager? with open(outFilePath, "r") as f, open(csvout, "w") as outfile: @SebastianHöffner, suggestion implemented. Shouldn't alter the output, but it's a better practice. @ChristopherPearson, I cleaned up the code to make better use of with. Sweet. that looks much better! I don't think I had ever seen anybody write open(foo)... with open(bar)... close(foo) before. I had to read the question code a couple of times to make sure I was reading it right. Try rewriting it as this: with open(outFilePath, "r") as f: for line in f: #don't iterate over entire file at once, go line by line line.replace(",", "\t") outfile.write(line) Originally you were opening it as a 'read-binary' rb file, which returns an integer (bytes), not a string as you were expecting. In Python, int objects do not have the .replace() method, however the string object does. This is the cause for your AttributeError. Ensuring that you open it as a regular 'read' r file, will then return a string which has the .replace() method available to call. Related post on return type of .read() here and more information available from the docs here.
common-pile/stackexchange_filtered
Infinite dimensional smooth projective geometry Are there two infinite dimensional (Banach or Hilbert) manifolds $(P,L)$ which satisfy the axioms of a smooth projective geometry desribed in this page: Smooth Projectove Geometry If X and Y are two non-isomorphic Banach spaces would their projectivizations P(X) and P(Y) be examples of what you ask for? I'm not sure, just a thought.
common-pile/stackexchange_filtered
Can't click json file with python selenium webdriver in firefox I try to gather the json files of the french lobby register for a research project, I can't click the field with my selenium webdriver. that's the location of the button I tried to click both the text or the button itself, but I got an error back, weirdly after a few days I don#t get an error, but the field's still not clickable. The code I used & my prior tries are here: I'm a student assistant researcher with little to none experience in webscraping, so everything I know is a collection of stack overflow, reddit & google searches. If you have any ideas, please help :) Have a nice day! Prior tries that failed: By.CLASS_NAME; By.PARTIAL_LINK_TEXT, By.XPATH didn't work, I tried all with the div class, a class & span location. Refer the code below with in-line explanation: from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium import webdriver from selenium.webdriver.common.by import By import time driver = webdriver.Firefox() driver.get("https://www.hatvp.fr/le-repertoire/liste-des-entites-enregistrees/") driver.maximize_window() # Below line will create wait object with 10s wait = WebDriverWait(driver, 10) # Below line will click on "PG CONSULTANT" element wait.until(EC.element_to_be_clickable((By.XPATH, "//span[contains(text(),'PG CONSULTANT')]"))).click() # Below line will capture the number of tabs open on the browser tabs = driver.window_handles # Below line will switch to the next tab driver.switch_to.window(tabs[1]) # Below line will click on the "Télécharger le fichier JSON" element wait.until(EC.element_to_be_clickable((By.XPATH, "//span[text()='Télécharger le fichier JSON']"))).click() time.sleep(10)
common-pile/stackexchange_filtered
jquery(elem).parents('form') returns unexpected nodes IE 6 & 8 <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script> <form><input type="submit"/></form> <form><input type="submit"/></form> <form><input type="submit"/></form> <script type="text/javascript"> $('input:submit').click(function(){ alert($(this).parents('form').length);return false; }); </script> The 2nd & 3rd button will alert "2" when clicked. The 1st <form> will always be contained in the parents() returned value, WHY? It doesn't appear in Chrome & Firefox, is it a bug of IE or jQuery, or my code? I was about to write about using console.log(), then I realised IE6 wouldn't have a JavaScript console. Ouch. :P And this bug doesn't appear when you replaced the form tag into others such as table & div. non-repro on W7 IE8 http://jsfiddle.net/gLx7V/show/ My IE8 returns 1 for all buttons. jsfiddle.net/gLx7V/show is right, thanks, I still could not understand it, but I find that the key point is that there is no body tag in my files. Instead of using HTML to format your code, select the code and click the {} symbol in the toolbar to create a code block. Then you won't have to type < and > over and over -- text inside a code block is rendered as typed. On the other hand, outside the code block, in your description, you do need to type "<" to make the < symbol appear (that's why your "" was invisible. You don't need > for >, though. @Adi Or you can just put it in code - if you're writing HTML code in your post, e.g. <form>, I'd definitely wrap it in code. Otherwise I'd just say form or form if I'm just discussing it by name.
common-pile/stackexchange_filtered
Set Color of UIActivityIndicatorView of a UIRefreshControl? Is there a way to set the color of the activity indicator (probably UIActivityIndicatorView) of a UIRefreshControl? I was able to set the color of the 'rubber' and the indicator: [_refreshControl setTintColor:[UIColor colorWithRed:0.0f/255.0f green:55.0f/255.0f blue:152.0f/255.0f alpha:1.0]]; But I want to have the 'rubber' blue and the activity indicator white, is this possible? This is not officially supported, but if you want to risk future iOS changes breaking your code you can try this: Building off ayoy's answer, I built a subclass of UIRefreshControl, which sets the color of the ActivityIndicator in beginRefresing. This should be a better place to put this, since you may call this in code instead of a user causing the animation to begin. @implementation WhiteRefreshControl : UIRefreshControl - (void)beginRefreshing { [super beginRefreshing]; NSArray *subviews = [[[self subviews] lastObject] subviews]; //Range check on subviews if (subviews.count > 1) { id spinner = [subviews objectAtIndex:1]; //Class check on activity indicator if ([spinner isKindOfClass:[UIActivityIndicatorView class]]) { UIActivityIndicatorView *spinnerActivity = (UIActivityIndicatorView*)spinner; spinnerActivity.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhite; } } } Thanks, that's exactly what I need. Very good and reusable :) Also thanks to ayoy for the initial idea :) Shouldn't you be calling [super beginRefreshing]; at the end, or at some point? This relies on the hierarchy of the UIRefreshControl remaining unchanged - which is not guaranteed by Apple. Well, you technically can do it, but it's not supported. You better follow Dave's suggestion, or read on if you insist. If you investigate subviews of UIRefreshControl it turns out that it contains one subview, of class _UIRefreshControlDefaultContentView. If you then check subviews of that content view in refreshing state, it contains the following: UILabel UIActivityIndicatorView UIImageView UIImageView So technically in your callback to UIControlEventValueChanged event you can do something like this: UIActivityIndicatorView *spinner = [[[[self.refreshControl subviews] lastObject] subviews] objectAtIndex:1]; spinner.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhite; And that would work. It also doesn't violate App Review Guidelines as it doesn't use private API (browsing subviews of a view and playing with them using public API is legal). But keep in mind that the internal implementation of UIRefreshControl can change anytime and your code may not work or even crash in later versions of iOS. Hmm, interesting, I copied you code, it is not working... It seems that there is no UIActivityIndicator inside, but: for (id v in [[[_refreshControl subviews] lastObject] subviews]) { NSLog(@"%@", [v class]); } Gives me: UILabel, UIImageView, UIImageView As I stated in the answer, you have to call that in a callback to UIControlEventValueChanged. Then it gets the UIActivityIndicatorView. I'm using this same method, but just thought it would be worth mentioning you should use some checks (range and class) in case apple decides to change how UIRefreshControl is organized in the future. No, that's not possible. You'll need to file an enhancement request to ask Apple to implement this. Thanks Dave, I have opened an enhancement request with Apple! ID: 13870593
common-pile/stackexchange_filtered
Rails - Querying Noticed Notification with the params id I have searched through the related questions for example this one and the solutions marked there doesn't work for me. So here is my problem: I want to get a list of notifications that are for a specific recipient, and the notifications have to be made on comments belonging to a specific plant. Currently I am using ruby to filter but the database hit is not ideal. Here is the state of my code. Models: class Plant < ApplicationRecord has_many :comments end class User < ApplicationRecord has_many :notifications, as: :recipient, dependent: :destroy end class Notification < ApplicationRecord belongs_to :recipient, polymorphic: true end class Comment < ApplicationRecord has_noticed_notifications end class CommentNotification < Noticed::Base def comment params[:comment] end end This is the query I am currently using: @plant.comments.flat_map { |comment| comment.notifications_as_comment }.filter { |notification| notification.recipient == current_user }.map(&:mark_as_read!) Any help is deeply appreciated... Do you have Comment model? Yes, I do. I forgot to add that. I will do that now. Noticed has a built in helper method for finding notifications based on the params. If you add has_noticed_notifications to the model which you want to search for in the params, Comment in your case. You can then call @comment.notifications_as_comment and it will return all notifications where the @comment is params[:comment] This is in the Noticed readme here. I definitely came here and found this question before I found the details in the readme! I resolved this by making a comment method and then using that in my filter, it also killed all the excess dB hits I was getting. def comment_id self[:params][:comment].id end Then I used this query to arrive at the result, looks cleaner too. Note comment_ids = @plant.comments.ids Notification.unread.where(recipient_id: current_user.id) .filter { |notification| comment_ids.include?(notification.comment_id) } .map(&:mark_as_read!)
common-pile/stackexchange_filtered
Lotus Domino mail routing and separation Mail Separation – Goal is to allow mail separation between different OUs while minimizing the number of servers required. a) Users of the same OU can email back and forth. b) Member of different OUs cannot receive emails from other OUs c) When User sends mail from each sub OU, they should only be able to see/use addresses corresponding to that sub OU d) May need a large number of OUs. EXAMPLE: John Doe/OUb/CORP/O =<EMAIL_ADDRESS> Mailfile = data\WEB\b\mail\jdoeB.nsf John Doe/OUc/CORP/O =<EMAIL_ADDRESS> Mailfile = data\WEB\c\mail\jdoeC.nsf Bill Smith/OUb/CORP/O =<EMAIL_ADDRESS> Mailfile = data\WEB\b\mail\bsmithB.nsf Bill Smith/OUc/CORP/O =<EMAIL_ADDRESS> Mailfile = data\WEB\c\mail\bsmithC.nsf Bill Smith/OUc/CORP/O can email John Doe/OUc/CORP/O but not John Doe/OUb/CORP/O Thanks You can achieve this with Extended Acl. Read this article on how to start. You can also read the admin help on this topic
common-pile/stackexchange_filtered
Using the distributivity law for propositional logic I know how to use the standard rule $$p\vee (q\wedge r)\equiv (p\vee q)\wedge (p\vee r)$$ but what if I have a two by two statement like: $$(p\vee q)\wedge (r\vee s)$$ ... I'm guessing that it follows a similar rule to the FOIL method in algebra? I took a shot in the dark and came up with this, but I want to make sure my logic is correct. $$(p\wedge r)\vee (p\wedge s)\vee (q\wedge r)\vee (q\wedge s)$$ What you wrote is correct.I just don't understand why you're not sure about what you wrote. Notice that, por instance, $p\vee q$ is a statement itself, so you can apply the rule just as you did. You’re right: the underlying law is the same as in ordinary algebra, so the calculation works out in the same fashion. In detail: Think of $p\lor q$ as a single entity; call it $t$ temporarily. Then you have $$t\land(r\lor s)\equiv(t\land r)\lor(t\land s)\;.$$ Now expand $t$ in each of the disjuncts: $$t\land r\equiv(p\lor q)\land r\equiv(p\land r)\lor(q\land r)$$ and $$t\land s\equiv(p\lor q)\land s\equiv(p\land s)\lor(q\land s)\;,$$ so the original expression is equivalent to $$\Big((p\land r)\lor(q\land r)\Big)\lor\Big((p\land s)\lor(q\land s)\Big)\;.$$ Finally, the big parentheses are clearly unnecessary, so you have $$(p\land r)\lor(q\land r)\lor(p\land s)\lor(q\land s)\;.$$ Let $t=p\lor q$. Then: $$(p\lor q) \land (r\lor s) = t\land (r\lor s) = (t\land r)\lor(t\land s)$$ Substitute back $p\lor q$ and you get: $$=((p\lor q)\land r)\lor ((p\lor q)\land s)$$ Now distribute the sub-expressions: $$((p\lor q)\land r) = (p\land r)\lor (q\land r)$$ $$((p\lor q)\land s) = (p\land s)\lor (q\land s)$$ Substituting back in and you get: $$\begin{align}(p\lor q) \land (r\lor s) &= ((p\land r)\lor (q\land r))\lor ((p\land s)\lor (q\land s))\\ &= (p\land r)\lor (q\land r)\lor (p\land s)\lor (q\land s) \end{align}$$
common-pile/stackexchange_filtered
difference between an adjective phrase and an adverbial phrase In a web-site, I happen upon a sentence I can’t understand grammatically. Famished from the journey, John decided to hunker down with his horse. They mark that a front part is an adjective phrase. I think this phrase can be changed into the following Because John was famished from the journey, John decided to hunker down. So I think the front part (Famished from the journey) is an adverbial phrase. Is it wrong? You're confusing form and function. "Famished" is an adjective and "famished from the journey" is its phrasal equivalent (i.e. an adjective phrase). Its function in the sentence is adjunct (your 'adverbial'). An adjective phrase is a group of words headed by an adjective that describes a noun or a pronoun. G-Monster this would be an adjective phrase "starved from the journey" A phrase is a group of words that stand together as a single grammatical unit, typically as part of a clause or a sentence. A phrase does not contain a subject and verb and, consequently, cannot convey a complete thought The subject of a sentence is the person or thing doing the action or being described. Because John is famished from the journey, John decided to hunker down. is a sentence. But John was famished from the journey is not a phrase as it contains a subject. Also your sentence is not a correct one as we repeat John and we do not need to. John, famished from the journey, decided to hunker down.* A sentence is a set of words that is complete in itself, typically containing a subject and predicate, conveying a statement, question, exclamation, or command, and consisting of a main clause and sometimes one or more subordinate clauses. G-Monster Note famished from the journey would still be an adjective phrase, contained in the sentence however we place it within that sentence. Dogs covered in mud are not allowed upstairs. covered in mud is the Adjective Phrase It highlights the need to distinguish word/phrase category and function. "Famished from the journey" is clearly an adjective phrase but, importantly, its function in the sentence is that of 'adverbial' (aka adjunct). 'Adverbial' is a function that may be realised by an AdvP ("He spoke quickly"), a PP ("He spoke with enthusiasm"), an NP ("He’s speaking this evening"). And in the OP's example, it's realised by an AdjP. @BillJ I am not so sure of the poster's level of English but I think we need to easy him into the correct construction. Do you think the OP is confused about what a phrase is? @gotube Yes. Quote, I think this phrase can be changed into the following... Because John was famished from the journey, John decided to hunker down. @gotbube by the way, what abbreviation is the OP? let me know Your sentence is not a close enough paraphrase of the first. In the original sentence, there is no meaning of "because". It's certainly implied that he stopped travelling because he was hungry, but it's not explicit. John is merely described as "famished", and the reader is led to infer that's his reason for stopping. So a better paraphrase would be: John was famished from the journey, and he decided to hunker down. Here, it's still only implied that John stopped because he was hungry, and "famished from the journey" is clearly an adjective phrase.
common-pile/stackexchange_filtered
React dropdown with options from Firebase realtime db (Formik + materialUI) I'm having trouble with the dropdown that maps through the data I fetch from the Firebase realtime db and assigns selected value to the Formik form in order to save it to another object in the database. I have restaurants object with pushId key containing name, city, and id (pushId key), and I have dishes with pushId key containing name, price, id (pushId key), restaurantId (id of the restaurant). *Here I need another key:value pair that will be for example restaurantId: "-MCvTh91-qHLcy09ZpYm" I did a fetch of restaurants using useEffect hook: const [restaurants, setRestaurants] = useState([]) useEffect(() => { let restQuery = Firebase.database().ref('restaurants').orderByKey() restQuery.once('value').then(function(snapshot) { snapshot.forEach(function(childSnapshot) { setRestaurants(prevState => [...prevState, childSnapshot.val()]) }) }) },[]) But I simply can't map the restaurants array to the dropdown form options and if I select a restaurant save its id to the Formik value <Formik initialValues={{ name: '', price: '', restaurantId: '', }} onSubmit = {(data, {resetForm}) => { console.log('submit: ', data) resetForm() }}> {({values, handleChange, handleSubmit}) => ( <Form onSubmit={handleSubmit}> <Field name="name" type="input" as={TextField} /><br/> <Field name="price" type="input" as={TextField} /><br/> <div>Restaurants:</div> <Field type="select" as={Select}> {restaurants.map((rest) => <MenuItem name="restaurantId" value={rest.id}> {rest.name} </MenuItem> )} </Field> <div> <Button type="submit">Submit</Button> </div> </Form> )} </Formik> This gives mi selection of the restaurants in the dropdown like: However, when I click on the option the error console throws these warnings and nothing happens Warning: Formik called `handleChange`, but you forgot to pass an `id` or `name` attribute to your input: undefined Formik cannot determine which value to update. For more info see https://github.com/jaredpalmer/formik#handlechange-e-reactchangeeventany--void Material-UI: You have provided an out-of-range value `[object Object]` for the select component. Consider providing a value that matches one of the available options or ''. The available values are `-MCvTh91-qHLcyO9ZpYm`, `-MCxfsFz6pSaokkbBwpA`, `-MCxg6CB_U4HaCE659Tw`. I'm stuck on these and anything I try doesn't work. Not a Formik expert, but the name attribute should go into the <select> equivalent, not the <option> one, afaik. @ChrisG Yup, that solved it. Thanks, is there any way for me to mark your comment as solution. Thanks again! You can write your own answer and mark it as correct if you want. As answered by @Chris G in the comments the issue was in placement of the name attribute, it should be in the select element not the option element: {({values, handleChange, handleSubmit}) => ( <Form onSubmit={handleSubmit}> <Field name="name" type="input" as={TextField} /><br/> <Field name="price" type="input" as={TextField} /><br/> <div>Restaurants:</div> <Field type="select" name="restaurantId" as={Select}> {restaurants.map((rest) => <MenuItem key={rest.id} value={rest.id}> {rest.name} </MenuItem> )} </Field> <div> <Button type="submit">Submit</Button> </div> </Form> )}
common-pile/stackexchange_filtered
Why else statement is executing although if statement is true? import java.util.Scanner; class candidate { public String name; public int count; public candidate(String name) { super(); this.name = name; } } public class DayScholar { public static void main(String[] args) { Scanner in = new Scanner(System.in); candidate[] candidates = new candidate[3]; candidates[0] = new candidate("vikas"); candidates[1] = new candidate("ganesh"); candidates[2] = new candidate("teja"); System.out.print("No. of voters : "); int voters = in.nextInt(); in.nextLine(); for (int i = 0; i < voters; i++) { System.out.print("vote : "); String name = in.nextLine().toLowerCase(); for (int j = 0; j < 3; j++) { Here is the code, although if the statement is true else is also executing. How to check the condition if (name.equals(candidates[j].name)) { candidates[j].count++; } else { **//problem here** System.out.println("N"); break; } } } int highest = 0; String winner = ""; for (int i = 0; i < 3; i++) { if (candidates[i].count > highest) { highest = candidates[i].count; winner = candidates[i].name; } else if (candidates[i].count == highest) { winner += ("\n" + candidates[i].name); } } System.out.println(winner); } } Print name and candidates[j].name. Probably you will get your answer. nextLine() result includes the line separator. How do you know that the condition is true? Please take some time to read [ask] and this question checklist, then please [edit] your question to improve it (like telling us input, expected output and actual output, and what efforts you made at debugging the problem, oh and actually ask a question (keeping the title a short summary of your problem)). When looping over the candidates array with name equal to the name of any one candidate still the condition name.equals(candidates[j].name) is false for the other two candidates Thank you. It is printing the next element in the array. How can I solve this problem? Assuming the user enters a valid name, the following loop will increment the count field on the candidate with the matching name, and print N for the other 2 candidates. for (int j = 0; j < 3; j++) { if (name.equals(candidates[j].name)) { candidates[j].count++; } else { System.out.println("N"); break; } } To fix, you need the loop to just set the index of the matching candidate, then do the increment or printing after the loop: int matchingIndex = -1; // -1 = not found for (int j = 0; j < 3; j++) { if (name.equals(candidates[j].name)) { matchingIndex = j; break; } } if (matchingIndex == -1) { System.out.println("N"); } else { candidates[matchingIndex].count++; }
common-pile/stackexchange_filtered
C#/Visual Studio trying to change the content of random array and getting 'Object reference not set to an instance of an object.' error I am trying to make a tic tac toe game where the user inputs the dimensions and then a board is created with buttons. When a button is clicked, it is disabled and the text inside changes to "X" or "O" accordingly. The user plays against a very basic "AI" which picks the buttons at random.I'm trying to check for empty (enabled) buttons on the board but I get the error: System.NullReferenceException: 'Object reference not set to an instance of an object.' heres the code: public partial class Form1 : Form{ int num; Button[,] buttonspinak; private void button2_Click(object sender, EventArgs e) { int start = 180, end = 30; num = Convert.ToInt32(textBox1.Text); buttonspinak = new Button[num, num]; for (int i = 0; i < num; i++) { end += 80; start = 180; for (int j = 0; j < num; j++) { Button b = new Button(); b.Size = new Size(60, 60); b.Location = new Point(start, end); this.Controls.Add(b); start += 80; b.BackColor = Color.White; buttonspinak[i, j] = b; b.Click += new EventHandler(Computer2); Computer(sender, e); } } } int countercomputer; Random randcompu = new Random(); private void Computer(object sender, EventArgs e) { int randomi = 0; int randomj = 0; Button b = (Button)sender; b.Enabled = false; randomi = randcompu.Next(0, num); randomj = randcompu.Next(0, num); **while (buttonspinak[randomi, randomj].Text == "O" || buttonspinak[randomi, randomj].Text == "X")** // this is the line where i get the error { randomi = randcompu.Next(0, num); randomj = randcompu.Next(0, num); //buttonspinak[randomi, randomj].Text = "C"; } buttonspinak[randomi, randomj].Text = "O"; b_Elegxos(); } private void Computer2(object sender, EventArgs e) { countercomputer++; Button b = (Button)sender; b.Enabled = false; if (countercomputer % 2 != 0) { b.Text = "X"; b.ForeColor = Color.DarkRed; } b_Elegxos(); } } Does this answer your question? What is a NullReferenceException, and how do I fix it? You seem to call Computer() in each iteration of your nested for loop in the button2_Click handler. This means that, after only initializing buttonspinak[0,0] with a new Button, Computer() gets called, which picks a random position in buttonspinak and tries to get that element's Text. But, most likely, that position in the array isn't initialized yet, so you're trying to call .Text on a null reference, resulting in your exception. You should in stead call Computer() after the for loops in button2_Click, so you can be sure all positions in buttonspinak are initialized.
common-pile/stackexchange_filtered
Observer never called I have two functions override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) NSNotificationCenter.defaultCenter().addObserverForName("personalDataDidLoad", object: self, queue: NSOperationQueue.mainQueue()) {_ in print("Received notification") self.showPersonalData() } loadPersonalData() } func loadPersonalData() { //load data print("personal data loaded") NSNotificationCenter.defaultCenter().postNotificationName("personalDataDidLoad", object: nil) but for some reason this outputs personal data loaded instead of the expected personal data loaded Received notification I'm probably missing something obvious, but I don't see it right now.... I also tried addObserver with selector: "showPersonalData:" but this throws an unrecognized selector exception.. The problem is with the 2nd parameter in postNotificationName and addObserverForName: object. When you add an observer, and pass a non-nil object value, this means that the observer block will run when a notification comes from that object, and from that object only. However, when you fire the notification, you do object: nil. So your notification is ignored. On the other hand, passing a nil value for object means, "I want to receive this notification regardless of who sends it". So you need to make sure the object value is the same in both places: either self or nil. Is there a reason you need to use addObserverForName(_:object:queue:usingBlock:)? Try this instead: override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) NSNotificationCenter.defaultCenter().addObserver(self, "personalDataDidLoadNotification:", name: "personalDataDidLoad" object: nil) loadPersonalData() } func loadPersonalData() { //load data print("personal data loaded") NSNotificationCenter.defaultCenter().postNotificationName("personalDataDidLoad", object: nil) } func personalDataDidLoadNotification(notification: NSNotification) { print("notification recieved") } I tried, but it throws an unrecognised selector error. Which in itself is weird of course, but I've got it working now with this solution. Another answer to the title question (but not this example) but will hopefully help others in the situation I have been in for the last 3 hours: Make sure your notificationcenter observer is added inside a class that has a persisted instance. I created the observer inside a class that was called as e.g. MyClass().setupNotification inside a local method of another class. This meant the observer was immediately deleted and didnt persist against any instance. Schoolboy error - but hope this helps others searching for this.
common-pile/stackexchange_filtered
sql to find certain ids and fillins I'm needing to pull 3 rows from a table for a featured section on my site. I first retrieve a list of 3 items that are sold the most from an orders table. Then I need to check to see if there are any left. If so, pull their details from the inventory table. The problem is, I always need 3. If there are not 3 items from the orders table that are still in stock, i need enough to make 3, selected from random. How can I set WHERE id IN (1, 2) and then still pull 1 random record? You can use a UNION to join the records WHERE id IN (1, 2) and then the second query is your random record. SELECT * FROM table WHERE id IN (1, 2) UNION SELECT Top 1 * FROM table If you provide more details about your query, then I can provide a more detailed answer. Edit: Based on your comment you should be able to do something this like: SELECT * FROM list_cards WHERE card_id IN (1, 2) AND qty > 0 UNION SELECT * FROM list_cards WHERE qty > 0 If you want to be sure you always get 3 results: SELECT TOP 3 C.* FROM ( SELECT C.*, '1' as Priority FROM list_cards C WHERE C.card_id IN (1, 2) AND qty > 0 UNION SELECT C.*, '2' as Priority FROM list_cards C WHERE qty > 0 ) C ORDER BY C.Priority well, i'm using cakephp and right now it's not showing my exactly what my query is. But I imagine it would look like SELECT * FROM list_cards WHERE card_id IN (1, 2) AND qty > 0 what happens if card_id 2 has a qty of 0? then i'll only get 2 results? @LordZardeck edited answer to make sure you always get 3 records. Added a field called priority so you can order by that field making sure you always the records from your first query. A hack like this where you select dummy data perhaps? SELECT TOP 3 * FROM ( SELECT * from table WHERE id IN (1,2) UNION SELECT 0; UNION SELECT 0; UNION SELECT 0; ) ORDER BY [whatever field] How about using UNION and another SELECT, with LIMIT 1?
common-pile/stackexchange_filtered
JSON Path to extract first element from the search result I'm new to JSON Path. Note: I have already checked over some questions on SO, it's not helping me with my issue. I have an example JSON given below : { "phoneNumbers": [ { "type": "iPhone", "number": "0123-4567-8888" }, { "type": "iPhone", "number": "0123-4567-8910" }, { "type": "Samsung", "number": "0123-4567-8912" } ] } Now, I have created JSON Path query which will bring all the json objects having the type as 'iPhone' : <EMAIL_ADDRESS>== 'iPhone')] Output : [ { "type": "iPhone", "number": "0123-4567-8888" }, { "type": "iPhone", "number": "0123-4567-8910" } ] After this, I want to extract element from the first index. That's where I got stuck. I tried this query : <EMAIL_ADDRESS>== 'iPhone')][0] But this query is not returning any results. What is the wrong with this query ? @Tomalak This query<EMAIL_ADDRESS>== 'iPhone')][0] is not working. That I'm saying. What query should I use for my use case ? I'm running my query here -> https://jsonpath.com/ for testing. Also I don't suppose you're planning to use https://jsonpath.com in production, so state what environment you're in. @Tomalak I have edited my question. I have not used any environment yet. I just want to know what I need to use so that I can get the element from result array. I have provided everything that's required. Hope this helps Filter expression return array can not use [index] get item inside I'm not quite familiar with json path but on which platform do you run it? Edit: You need to define a key to the array because phoneNumbers is undefined { "phoneNumbers": [ { "type": "iPhone", "number": "0123-4567-8888", }, { "type": "iPhone", "number": "0123-4567-8910", }, ], }; Then the default query jsonpath.com $.phoneNumbers[:1].type outputs: [ "iPhone" ] I have not used any used any environment yet. I'm using some online json path evaluator to test my scenario. @AnishB. "some online json path evaluator" Is it forbidden to share that location of the online evaluator? No. No. I'm using this https://jsonpath.com/ to test. :)
common-pile/stackexchange_filtered
Multi-nested ui-views Here's my config: $stateProvider. state('frontPage', { url: '/', templateUrl: 'index.html', controller: 'MainCtrl', onEnter: function() { console.log('frontPage'); } }). state('frontPage.interestGame', { url: 'interest', templateUrl: 'interest-game/index.html', controller: 'GameCtrl', onEnter: function() { console.log('frontPage.interestGame'); } }). state('frontPage.interestGame.game', { url: ':platform', templateUrl: 'interest-game/game.html', controller: 'GameCtrl', onEnter: function() { console.log('frontPage.interestGame.game'); } }); I am able to go to / and /interest and the templates, controllers, and onEnter functions all run as expected. However when I go to /interest/anything it fails to load my templates. It's simply an empty page with no console.log errors... I see that all my scripts were loaded as expected so I know that it's not a server issue... Perhaps I'm misunderstanding how the nested states work...? I believe each url state entry has to start with a leading /. Try changing :platform to /:platform. That didn't work... Perhaps I'll need to make a plnkr. You do indeed need that leading / before :platform, otherwise it would be interpreted as /interest:anything (no slash in between). Also, interest-game/index.html should contain a <div ui-view></div>.
common-pile/stackexchange_filtered
CSS only: Replace all characters in <p> with the same character I have a <p class="hidden"></p> with some text in it. I want to replace all characters in the paragraph with the same character, e.g. a question mark. Note that this is not a viable solution since it requires to specify aprioristically the length of the new string: .hidden { text-indent: -9999px; line-height: 0; } .hidden::after { content: "???"; } As a way of example: <p>Just some text!</p> <p class="hidden">Hello, world!</p> Should be rendered: Just some text! ????????????? The only way that I can see that done using pure CSS is by specifying a font that only contains question mark glyphs. Trivial to do in JavaScript though. The only way to use p = font-size : 0px | p:after = font-size : 12px. This text will not be indexed by the search engine https://stackoverflow.com/a/10212940/1400279 Does this answer your question? How to use CSS to replace or change text? One idea is to build your own font that contain only 1 character (the ? sign) and use it for your text. I am not familiar with this but you can easily find a lot of tools to do it. I will simply give an example using a strange font to show you the idea: @font-face { font-family: "Strange"; src: url("https://css-challenges.com/ahem/dugun.regular.otf"); } p { font-size:35px; } .hidden { font-family: "Strange"; } <p>some text here</p> <p class="hidden">some text here</p>
common-pile/stackexchange_filtered
1 Jayaraman: The path integral for this gauge system keeps giving me extra terms I didn't expect. 2 Blanchard: What kind of terms? Are they just regularization artifacts? 3 Jayaraman: No, they persist even after I clean up the calculation. When I examine the asymptotic behavior of the gauge field at the boundary, something geometric emerges. 4 Blanchard: Boundary effects can be tricky. Are you working in three or four dimensions? 5 Jayaraman: Three dimensions first. The boundary analysis forces an additional contribution to the effective action - it has the exact form of a Chern-Simons term. 6 Blanchard: That's not accidental. Chern-Simons terms are topological invariants. They don't depend on the local metric properties. 7 Jayaraman: Right, and when I extend the same reasoning to four dimensions, I get a Pontryagin term instead. The pattern suggests these aren't just mathematical curiosities. 8 Blanchard: They emerge from the geometric phase structure. Think about Berry's argument - when you have nontrivial topology in the parameter space, the holonomy contributes additional phases. 9 Jayaraman: The holonomy! That's the missing piece. The gauge field configuration space has nontrivial topology, so parallel transport around closed loops picks up these geometric phases. 10 Blanchard: Exactly. And in the path integral formalism, those geometric phases translate directly into topological terms in the effective action. 11 Jayaraman: This means the Wess-Zumino-Witten term I keep seeing in two-dimensional models follows the same logic - it's capturing the geometric phase contribution from the underlying topology. 12 Blanchard: The beautiful part is how the low-energy effective theory automatically includes these topological contributions, even when the original microscopic theory didn't have them explicitly. 13 Jayaraman: So the emergence isn't just mathematical convenience - it's inevitable once you properly account for the topological structure of the gauge field configuration space.
sci-datasets/scilogues
Vertical IconTabBar in SAPUI5 I am programming a SAPUI5 application and I would like achieve a vertical menu seemed IconTabBar. IconTabBar only allows me horizontal configuration. Can I simulate that behavior with another components? I was trying to create a "different" IconTabBar that only has one IconTabFilter as an aggregation and add it in a Vertical layout but it isn't work. Short answer, No. There is no out-of-box solution for your requirement. The IconTabBar is only available in the horizontal orientation and there isn't a provision (atleast not yet) to change it to vertical. PS: If there is something that you have tried in particular, post code snippets to help others analyze better.
common-pile/stackexchange_filtered
Icons in system tray panel have changed size in 18.04 I'm not sure what I did, but the size of the icons and clock in the system tray panel have changed and they are huge. Adjusting screen edge and height does not help.
common-pile/stackexchange_filtered
waiting for a/the good sale price Have you bought that fashion coat yet? - Not yet. I’m waiting for a good sale price. Have you bought that fashion coat yet? - Not yet. I’m waiting for the good sale price. Which article is appropriate here if we are waiting for an occasion when that coat will be sold at a lower price than usual? I suppose we need to use "a good sale price" because we don't know what price will be on the sales. But we can use "the good sale price" when we are waiting for a certain price on the coat, for example, 100$ or lower. Right? Or do we need to use "the" anyway because we speak about a certain coat? The definite article can only apply to one specific thing. In your example, there is no specific price, so the definite article is not appropriate. There could be any number of prices that the first person may consider "good", and evidently, they do not know what price it will be lowered to. It doesn't matter that it is a specific coat - the coat and the price have their own articles. You are speaking about buying the coat at a discounted price. An alternative scenario where you might use the definite article is if you were expecting the price to be dropped at a specific time and were committed to buying it at the lowered price, no matter what. For example "I'm waiting for the January sale price".
common-pile/stackexchange_filtered
Error: operand size mismatch for `vpsubw` The vpsubw AVX2 instruction is being used normally (the number of operands and the width of operands are not problematic), but the following error still occurs: Error: operand size mismatch for vpsubw If all the instructions about vpsubw in the code are commented out, the error will still be reported, which is very strange. vpsubw %ymm13,(%rsp),%ymm13 # f0[0]*g0[0] vpsubw %ymm9,%ymm1,%ymm9 # f0[0]*g0[1] vpsubw %ymm3,%ymm14,%ymm3 # f0[1]*g0[0] vpsubw %ymm10,%ymm2,%ymm10 # f0[1]*g0[1] vpsubw %ymm4,%ymm15,%ymm4 # f1[0]*g1[0] vpsubw %ymm11,%ymm5,%ymm11 # f1[0]*g1[1] vpsubw %ymm7,%ymm0,%ymm7 # f1[1]*g1[0] vpsubw %ymm12,%ymm6,%ymm12 # f1[1]*g1[1] I've tried multiple methods, but none of them seem to work. Any ideas? I've tried commenting out all the vpsubw instructions, but it still doesn't work. Only the first operand can be memory. GAS's error message isn't very helpful for vpsubw %ymm13,(%rsp),%ymm13, but that's the problem. (last operand in Intel syntax; https://www.felixcloutier.com/x86/psubb:psubw:psubd). Consider using intrinsics to let a C compiler make working asm for you. I tried commenting out all the vpsubw commands, but it still doesn't work. Well that makes no sense. You still get an operand-size mismatch from some other instruction that isn't vpsubw? In that case the rest of your code is also broken. Or you used the wrong comment character; ; is a statement separator so it would have no effect. @Peter Cordes Thanks!vpsubw %ymm13,(%rsp),%ymm13 Here is exactly the problem!The problem has been solved! Basically a duplicate of operand size mismatch for `imul ' - GAS prints the wrong error message when you use memory instead of a register for an operand that has to be a register.
common-pile/stackexchange_filtered
Translate simple Jquery to VanillaJS I have this: $('#night > li').appendTo('#day'); The code moves all <li> elements of <ul id="night"> to the end of <ul id="day">. Please, how can I translate this into VanillaJS? I mean, how do I rewrite the code so I do not need Jquery? Have this so far: document.getElementById('night').li.appendTo.document.getElementById('day'); http://stackoverflow.com/questions/20435653/what-is-vanillajs You don't need jQuery. jQuery is basically a way of making javascript a bit easier but with a fairly chunky library to do so (another http request to slow down a website). Google "JavaScript tutorials" and get stuck in. jQuery doesn't do anything that you cannot do with JavaScript. $('#someid') = getElementById('someid') @dwhite.me : "jQuery doesn't do anything that you cannot do with JavaScript"... except write shorter, more readable code :) @TrueBlueAussie - Fairly irrelevant. Code needs to be interpreted by the browser first, enhance user experience second (including minimising load time as much as possible) and THEN a very distant third be legible. Could look like so var target = document.getElementById( 'day' ); [].forEach.call(document.querySelectorAll( '#night > li' ), function( li ) { day.appendChild( li ); }); typo: car should be var In pure JavaScript you could do it like this: var night = document.getElementById("night"); var day = document.getElementById("day"); var lis = document.querySelectorAll("#night > li"); for (var i = 0, len = lis.length; i < len; i++) { day.appendChild(lis[i]); } See fiddle for working example. You can try something like this: var dayUl = document.getElementById("day"); var nightUl = document.getElementById("night"); var nightLis = nightUl.childNodes; for (var i = 0, len = nightLis.length; i < len; i++) { dayUl.appendChild(nightLis[i]); } Also, you can go with @Marcus Ekwall's solution, but keep in mind that the solution isn't fully compatible with IE8 or below, and the first query for the night node is redundant (because below he searches for #night > li)
common-pile/stackexchange_filtered
How to stop people from closing as off-topic when asking how to do something Recently most questions that have been most useful to me (mostly regarding javascript) have been closed as off-topic for "Questions asking us to recommend or find a book, tool, software library, tutorial or other off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam." What is the best way to scale back the use of "closing" these questions? Many of these are not questions such as "which is better: mac, windows or linux". They are legitimate questions asking for advice about how to integrate multiple components/libraries to perform a task, and most of the recent ones that I have seen have legitimately helpful answers describing various combinations of libraries, etc. that can be combined to perform a specific function. A typical example might be "what is the best way to stringify an object in NodeJS and then compress it, and reverse the process in the client side browser after sending it over a websocket?". Obviously, the content of the question should describe that the specific issue is compressing/decompressing the JSON (since compression libraries typically want a stream but JSON.stringify and JSON.parse aren't streaming functions), and the goal is to do it efficiently as a stream. Because this can involve up to five libraries, there are literally thousands of permutations, and typically, a complete solution comes from partial answers by various people. One person may have a solution to the server stringification/compression (which is complicated by the need to stream the JSON string into a compression function), while another answer may have a different solution for how to do this in the browser. Obviously, some people may reference existing answered questions (ie. about the websocket part). But ultimately, a complete answer can be formed. In other words, some of the questions most likely to be closed as "off-topic" for this reason are also some of the questions that would benefit the community most from the collaborative stack overflow approach. Or, putting it another way, the current stack overflow standard seems to be that if there is only one way to do something then it is okay to ask about it, but if there are multiple ways, it will be closed as off-topic because people may provide opinionated answers. But it is when there are lots of multiple ways to do something that I want people's actual experience most of all to quickly get to the most tried and true approach. To summarize; how to get people to be more judicious and scale back the annoying practice of closing legitimate questions as off-topic for "Questions asking us to recommend or find a book, tool, software library, tutorial or other off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam."? This is not about asking generic questions. My contrived example specifically asks how to pipeline, on a server, stringifying an object, then compressing it, then sending it over a websocket, and then doing the reverse on the client side. The key issues are how to do this in a streaming pipeline and ensure that the server compression is compatible with the client decompression (since not all tools are available for both the server and client different libraries may be required, but they must be compatible). Had this been a real question instead of an example, the body of the question would have specifically noted that the object may be very large so it would be preferable to not have to use two full size buffers for the uncompressed and compressed data (ie. use streams). Note that this question is not about actually answering the technical question. It is about not getting questions "closed out" when other people are actually commenting and responding to them (ie. at least some people are finding them useful and valid). @NeilButterworth a very valid point, but these are the types of issues that are raised in the answers. So for my contrived example, somebody may propose a solution that is memory intensive, but fast, while somebody else may propose a solution that has low memory requirements but is slower. Since my contrived example involves both a server and client, there are now four permutations of possible solutions. This is why the discussion is needed. We aren't a discussion site or a forum though, we do questions and their answers and that's all. Meta is the nearest we get to discussions. Adding one point here: the close-reason Questions asking us to recommend or find a book, tool, software library, tutorial or other off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam did not originally exist. It was not handed down on a stone tablet from the mountain. It was implemented and enforced after observing such questions, their responses, and the effects on the site, and observing the overall effect was detrimental. They don't work on SE. That's not to say they're bad questions, it is to say th intersection w SE is unworkable One might argue that there are indeed many legitimate questions related to programming. That alone does not make them suitable for this site. "What is the best way to scale back the use of "closing" these questions?" -- your question is being asked backwards. The closings look to be appropriate, and your question should in fact be, "how can I learn to best use this site so that my questions are considered on-topic". The site will not change its rules just for you (or me), and so you (and I) need to learn to adapt our expectations and our site usage to match the site requirements. Arguing about question legitimacy is orthogonal to the issue; we don't care how legitimate the question is. All we care about is how useful it will be to someone in the future. Recommendation questions can be useful, but they are generally more trouble than they're worth. All you see are the ones that are left, which are the ones worth keeping. What you don't see is all the others that are deleted. SO cannot do system design. If an OP's requirments are posted, they are nearly always unclear. If they were well-defined, they would be a requirement spec that is too broad. No thanks. If an OP wants a system design, I am happy to met with them and discuss terms. Possible duplicate of Is there a less restrictive Stack Exchange site specially suited for not too specific questions? @gnat I don't think it is a duplicate. So far it seems people have two issues: 1) the phrase "what is the best way to ..." instead of "how can I ...". It seems that it would be more useful for experienced SO users to just suggest rewording the question. 2) My contrived example assumed that each step was interrelated to the others. Robert Longson pointed out that compression is baked in to websockets and referred me to an existing question that had already been answered. So my contrived example was actually more specific than the acceptable question. His answer was more useful than closing-out. Please remember that my original purpose in raising this discussion was that I noticed how many questions are being "closed out" which I find useful, and judging by the amount of responses to them other people do also (I am guessing they are not the people monitoring the meta discussions though). It just seems like there could be a better way to get these questions back on track rather than cutting them off cold. Again, question legitimacy is irrelevant. If they want us to recommend some software or a tool, it's off-topic. There might be an XY problem in there, but it's generally going to be on the asker to update their question to fix that aspect, as we probably won't have enough information to do so. Closure does not prevent commenting, or editing. All it does is prevent answers, which, for off-topic questions is what we want to happen. @fbueckert Yes, I understand that that is the world as it is today; but this is the meta area, where we can talk about the world as it could be :-) What you described means that alot of answers are ending up as comments instead of answers. I am just suggesting to consider if there are alternatives to the quick "close-out" such as proposing to the OP of a question to rephrase "what is the best way to ..." to "how can I ..." instead of closing something out. They can make those changes once it's closed. Their question, in the current state, is not one we want answers to. That's why we close it. Once it has been fixed, the question can be reopened. All closing does is prevent answers, to questions that are problematic in some form or another. Solve the problem if you want to be able to get answers for it. @Casey if closure was immutable, I would agree with you. Right now closure carries a very useful message explaining what needs to change on the question for it to be in a position to be reopened.... It seems like the issue isn't that they're being closed but that they're getting closed for the wrong reason. Your example is too broad and primarily opinion based, not a recommendation request. Your example question would appear to be too broad i.e. It asks multiple distinct questions at once. what is the best way to stringify an object in NodeJS and then compress it, and reverse the process in the client side browser after sending it over a websocket? Break down the problem into the component parts and explain what your problem is with each part e.g What definition of "best" do you have for part 1? Least execution time, least memory used, something else? Each of these could and probably should be a separate question. Also what have you done thus far to solve these problems and where have you got stuck, it's much easier to help you if you say here's what I've already written but things go wrong here where I expect this to happen and yet some other thing happens instead. The problem with breaking it down is that items 1 and 2 are inter-related, and item 3 has to be compatible with items 1 and 2. Agreed that item 4 is a throwaway, and only included in the question to provide context for the conditions under which 1-3 are being performed. So 2 is what compression can I use in Node that is compatible with browsers ability to uncompress? And 1 is How can I stringify something in Node such that it can be consumed in a browser. Compression is orthogonal to the underlying data content. No, AFAIK browsers don't decompress websocket data. This requires an external javascript library. Which is why whatever library/format is used on the server has to be compatible with what is used in the browser. But maybe I am wrong and if questions like this weren't closed somebody would be able to provide a concise clarification. Compression is not orthogonal to the question - it is the question (there are hundreds of examples how to do this without compression). And please remember, this is a contrived question to make a point (for this meta question). Sure they do: https://stackoverflow.com/questions/11646680/could-websocket-support-gzip-compression#comment15442271_11647130 and https://bugzilla.mozilla.org/show_bug.cgi?id=792831 which is why if you ask about that specific issue you can get an answer. So why isn't your comment above a legitimate answer to a legitimate question? Is it really just the specific use of the word "best"? If so, can we please just incorporate a pipeline into stack overflow to convert the phrase "what is the best way to ..." to "how can I ..."? I don't understand what you mean. https://stackoverflow.com/questions/11646680/could-websocket-support-gzip-compression is a legitimate question with answers, it's not closed as off-topic. It does however only ask one thing and does not try to conflate multiple issues into one question. Your main problem is your example is too broad, if we split it up to fix that we get an issue with one of the parts being unclear because it's ill defined. Note that the individual parts are probably already on the site as existing Q&A as I've just demonstrated. I mean that I would have no issues with you answering MY contrived question with a reference to https://stackoverflow.com/questions/11646680/could-websocket-support-gzip-compression and a note that it had already been asked and answered. That would be helpful, closing it as off-topic is not. @Casey Except your question isn't a good question; you've conflated several different issues into a single one, and assumed the solution has to take all of them into account. That's usually too broad. If that's not helpful, the onus is on you to narrow it down so that it can actually be answered. We're not trying to be helpful to just you; but also everybody else that comes across this question because they have the same problem. @fbueckert no, it is a pipeline. Stringifying an object is a batch operation, compression is a stream operation, sending on a websocket is a batch operation. The question is about whether they can all be integrated into a single streaming pipeline. The sending over a websocket part was just to give context to the other parts. The client/server aspect alluded to the idea that the different sides may have to do it differently, but they both need to be compatible. @RobertLongson Note that per https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API "Starting in Gecko 8.0 (Firefox 8.0 / Thunderbird 8.0 / SeaMonkey 2.5), the deflate-stream extension to the WebSocket protocol has been disabled, since it's been deprecated from the specification drafts. This resolves incompatibilities with some sites." You may be looking at the wrong symptom here. The problem is seldom in the title; it's often to do with what's actually being asked. Your example of "which is better: mac, windows or linux" has problems in that it's not clear what's being asked; the goal, if any, is ill-defined at best, and thus cannot be objectively answered. Your counterexample suffers from the same flaw. "What is the best way to stringify an object in NodeJS and then compress it, and reverse the process in the client side browser after sending it over a websocket?" Two immediate questions: Who cares what the "best" way is if it works effectively for your use case? (e.g. why are you asking about "best"?) What are you really trying to accomplish? The problem as stated with that question is that it's not really clear what one is trying to accomplish. If readers see a clear goal in mind, then that improves the chances of it being on-topic here. let's not get hung-up on the use of the word "best". Bearing in mind that it is a contrived question to use an an example for the meta question (and not a fully formed question in its own right), I am not sure what is the most concise way to say "which method, which is obviously not needlessly wasteful of resources, can be used to ..." (the key word being "needlessly"). But even as a contrived question, I think it is fairly straightforward. JSON objects are just text, with lots of duplication, so there is significant bandwidth savings if they can be compressed before transmission. @Casey: You would be surprised, then, to discover that there are a very large number of questions which get caught in moderation hell behind the phrase "best". It's so subjective that it's actually a really bad idea to even mention it. That said, to your main point, this is the kind of information I as a prospective answerer would be interested in knowing - your intent. You wish to reduce bandwidth usage when sending JSON payloads. Now we're getting somewhere with the question. @Casey: From the above, this begs the question of how much data is being transmitted, what your data constraints are, and what your solutions have been up to this point in regards to compression. It may even be the case that compression is the wrong solution for your use case. You don't know that immediately since you've defined your solution as your question when you probably shouldn't have. Ironically, my contrived example really is something I have been looking into, and the reason for my original post is because of the number of questions I saw recently which were "closed out" for the reasons I stated. I have been using SO for about six years now, and never noticed this phenomenon before. But I only recently started using javascript, and it seems this phenomenon may be related to the fast moving pace of web development and people trying to keep up with the changes. Would be nice if SO could adapt and accommodate the concept of "current best practices" (or something). Again @Casey, I get the impression that you're trying to blame the system instead of you wanting to actually repair the question you have. Your question sounds legit. It's just the case that as posed, it's too broad and sounds more like solutionizing as opposed to an actual question. It is not about my contrived question. It is about the frequency with which I am seeing so many other questions being cut-off. In order to open the discussion I contrived an example question which (in my opinion) is typical of many questions which add value but are being cut-off relegating lots of useful information to be buried in comments instead of answers. I'm not sure I follow anymore @Casey. Devoid of context or purpose, questions which follow the same pattern as your contrived example are not going to survive for very long here. I hope that above in comments I at least highlighted what an OP should be prepared to do if confronted with this scenario to make it less likely that their question will be closed. I should stress this: we're not your enemy. We're not trying to be jerks here. What we are doing is enforcing a high standard of our questions and content here. The choice then lies with the OP to either rise to that standard, or post on another part of the Internet. The ultimate goal of Stack Overflow has always been, at least as far as I can remember, to build a complete collection of questions and answers. The issue with "best way to do X"-questions lies within "best". What is best? Is it the fastest, the safest? Who defines best? YOU do! The person asking the question. Consider a question such as "Best way to transfer data from PC1 to PC2". The fastest is to send it directly, without any checks. That's fast, but it sure as hell isn't safe. The safer approach would be to check the data transmitted, which slows down the process. All subjective. The issue that subjective Q&As introduce is that you can have a million questions asking basically the same, with ever so slight modifications, which imo is better suited for a discussion, i.e. in chat, or using a different platform. First make sure your question meets the on-topic criteria stated here What topics can I ask about here? Also make sure your question doesn't fall into this category: What types of questions should I avoid asking? Last but not least make sure you're asking a good question, more information can be found here: How do I ask a good question? As it sounds the kind of question you're asking about fall into the category primarily opinion based which is off-topic. As stated in comments you'll need to define best, most efficient better to make your questions more meaningful. I am suggesting that I am getting value out of these questions; and gauging by the responses of other people before the questions are being closed, other people are getting value also. I am suggesting to reconsider the criteria in the links you included above. I wanted to upvote this to guard against a post deletion but the advice here is so blasé I cannot bring myself to do it. @Makoto Did you mean to call me arrogant? If so I should probably flag your comment as being unkind ;) If you consider yourself to be your advice, you may interpret my comment as you so desire. @Casey: We don't close questions based on whether someone can manage to scrape together some kind of value from them. We close questions on the basis of what will generate easily indexable useful information that is generally useful to a range of people.
common-pile/stackexchange_filtered
Time spent to sort $10^7$ records with insertion sort I am stuck with my revision for the upcoming test. The question asks" An implementation of insertion sort spent 1 second to sort a list of ${10^6}$ records. How many seconds it will spend to sort ${10^7}$ records? By using $\frac{T(x)}{T(1)}$ = $\frac{10^7}{10^6}$ I thought the answer was $10$ seconds but the actual answer says it's $100$ seconds. Can someone please help me out? :( Hint: Time complexity of Insertion sort is $O(n^2)$ Roughly speaking if $10^6$ records took $1$ second then $10\times 10^6$ records will take $10^2\times1=100$ seconds Hint: what is the Time Complexity of insertion sort?
common-pile/stackexchange_filtered
Borel sets in Cramer's book I have two following quiestions. On the page 13 (Mathematical methods of statistic) the set R of all rational points x = p/q belonging to the half-open interval (0,1] is considered. It's claimed that every point of [0,1] is a limiting point of R. And the limiting point z is called a limiting point if every neighbourhood of z contains at least one point of set. Is any proof of that? For me it is not obvious, that there no exists any irrational point, whose tiny neighbourhood does not contain any number p/q. Right after that, in Borel sets section: S is the class of all point sets I such that I is the sum of a finite or enumerable sequence of intervals. ... The set R considered in the preceding paragraph belongs to S.. The difference (0,1) - R, on the other hand, does not contain any non-degenerate interval, and if we try to represent it as a sum of degenerate intervals, a non-enumerable set of such intervals will be required. "Does not contain any non-degenerate interval" means that it contains only degenerate intervals, doesnt it? But why? If we divide interval (0,1) by enumerable number of points, does we divide it in enumerable number of intervals? For example, 1/2 divides (0,1) into two intervals. I really appreciate if somebody could explain. You're asking two very different questions. Perhaps separating them into two different threads is better. (I'm also fairly sure that at least one of them already received an answer on this site before.) Question 1: remark: some people define $\mathbb R$ to be the completion of $\mathbb Q$, so the answer to your question is immediate. Here is a more explicit reason: Let $\alpha \notin \mathbb Q$ be a real number. Let $\epsilon>0$ and choose a natural number $s$ so that $\frac{1}{s}<\epsilon$, which is possible by the archimedean property (there is a natural number larger than $\frac{1}{\epsilon}$.) Let $r:=\lfloor s \alpha\rfloor$, and take $q=\frac{r}{s}$. Then $$|\alpha-\frac{r}{s}|=|(\alpha s-r)/s|<1/s<\epsilon.$$ Question 2: Borel sets are technically elements of the $\sigma$-algebra generated by open sets. In particular, closed under countable intersection and countable union. Recall that $\mathbb Q$ is countable. Then $$\mathbb Q =\bigcup_{n \in \mathbb N} \bigcap_{k \in \mathbb N} \left(q_n-\frac{1}{k},q_n+\frac{1}{k}\right).$$ In this case, $\mathbb Q \cap [0,1]$ is certainly a Borel set. By taking complements and intersecting, it is not tough to see that $A:=(0,1)-\mathbb Q \cap [0,1]$ is Borel as well. Now, can $A$ be written as the countable union of non-degenerate intervals? No. Suppose that $A$ contains a non-degenerate interval $(a,b)$. We can assume that it is open, since $(a,b) \subset[a,b], (a,b], [a,b)$. Pick some $\alpha \in (a,b)$, since $(a,b)$ is open, there is some $\epsilon$-ball around $\alpha$ contained in $(a,b)$. Then by the first point, we can find a rational number $q$ in this $\epsilon$-ball, a contradiction, since $q \notin A$ by construction. Since every interval in $A$ is degenerate, it just contains points. So, $A$ must be the union of uncountably many "intervals," since they are actually just points (and $|A|$ is uncountable.) Is any proof of that? For me it is not obvious, that there no exists any irrational point, whose tiny neighbourhood does not contain any number p/q. If $x \in (0,1]$, let: $$u_n=\frac{\lfloor 2^nx \rfloor}{2^n}$$ Then $u_n \in (0,1]$ and $u_n \to x$ (if $x=0$, consider $u_n=2^{-n}$ instead). In other words, for all neighbourhood of a real point, there is a rational point inside. "Does not contain any non-degenerate interval" means that it contains only degenerate intervals, doesnt it? But why? If we divide interval (0,1) by enumerable number of points, does we divide it in enumerable number of intervals? For example, 1/2 divides (0,1) into two intervals. We are dealing with $(0,1) \setminus R$, not $(0,1)$. $(0,1)\setminus R$ cannot be written as a countable union of intervals (it has a lot of "holes"). "holes" themselves are countable, but "spaces" between them are uncountable? @DmitriyKozlov: Yes, that's it. $\mathbb{Q}$ is countable but $\mathbb{R}$ is uncountable so $\mathbb{R} \setminus \mathbb{Q}$ is uncountable. However, what matters here is that, though there is only a countable number of holes, they are dense, so you cannot find a non-degenerate interval without a rational point (i.e. a hole) inside. Thanks to your and previous answer it's clear now! When I am able to upvote, I will do that.
common-pile/stackexchange_filtered
BigQuery table schema types not being translated correctly in apache beam There is a bug in the python Apache Beam SDK for BigQuery currently which translates BQ TIMESTAMP incorrectly to BQ DATETIME. This seems to have been fixed, but I have a feeling it may be in a pre-release not the latest stable release (2.49.0). This appears in an error that describes an input/output schema mismatch when converted. This error only applies when using the Storage Write API. The legacy streaming API works fine. The SDK converts LOGICAL_TYPE<beam:logical_type:micros_instant:v1> to DATETIME, not TIMESTAMP. I was wondering if anyone has found a workaround for now until the (relatively) new bug is fixed? May be not a possible workaround, however, please do take a look at Storage Read API - https://beam.apache.org/documentation/io/built-in/google-bigquery/#storage-api For anyone with the same issue, add this line before writing to BigQuery # imports from apache_beam.typehints.schemas import LogicalType, MillisInstant # logical type mapping LogicalType.register_logical_type(MillisInstant) The Apache Beam devs are aware of the issue and are working to find a more permanent solution.
common-pile/stackexchange_filtered
How do you set the add guake to the list of alternative terminals on Kubuntu 22.04? I've recently installed Kubuntu 22.04 and am trying to set guake as the default terminal emulator. I can't seem to find any instructions on how to do it with KDE. You can set guake as an alternative terminal in Kubuntu 22.04 by wrapping it with a custom command: Open settings to default applications Click on "Other" Enter /bin/bash -c 'guake --show --new-tab "$PWD"' and press "Ok" Click apply Close all application windows or reboot Try opening terminal in some app Guake will open to the current directory
common-pile/stackexchange_filtered
json_serialize(...) is returning null even when the input is not null I have a query like this: select json_serialize(data) from mytable Where data is a column that contains JSON but I get a null returned from json_serialize. Is this a bug? By default, json_serialize returns VARCHAR2(4000). See: https://docs.oracle.com/en/database/oracle/oracle-database/19/adjsn/oracle-sql-function-json_serialize.html When the JSON text that would be returned exceeds 4000 bytes, it is considered an error condition. However, the default error behavior for JSON_SERIALIZE is NULL ON ERROR. Try adding RETURNING CLOB: select json_serialize(data returning clob) from mytable
common-pile/stackexchange_filtered
Forwarding Old URL with trailing slash I was using the Divi builder with WordPress for quite some time to build my site. I outgrew it and switched to Webflow so that custom code would be easier to achieve. I have gotten the site live, but there is a major problem... Divi Builder created URL's that looked like this https://hike2hike.com/eldorado-peak-climb-washington/ Now that I have all the site files on my hosts server, the URL's I am getting look like this https://hike2hike.com/eldorado-peak-climb-washington.html <-- Trailing slash is missing and .HTML added and are missing the trailing slash. I have edited the .htaccess file with the following code: # Remove trailing slash from non-filepath urls RewriteCond %{REQUEST_URI} /(.+)/$ RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^ https://www.hike2hike.com/%1 [R=301,L] # Include trailing slash on the directory RewriteCond %{REQUEST_URI} !(.+)/$ RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^(.+)$ https://www.hike2hike.com/$1/ [R=301,L] # Force HTTPS and WWW RewriteCond %{HTTP_HOST} !^www\.(.*)$ [OR,NC] RewriteCond %{https} off RewriteRule ^(.*)$ https://www.hike2hike.com/$1 [R=301,L] But, I am still getting a server error when I try to use the old links to get into the site. Any thoughts on how I get the old URLs to transfer to the new site URL's so I don't lose all the SEO I have built up over 5 years? Good try, IMHO I believe you almost had it right, you need to place your https forcing rule to the top of your htaccess else it will be complete redirect of URLs; corrected your regex in your last rule of checking if uri is ending with / or not too, could you please try following once. Fair warning I couldn't test it as of now. After placing this .htaccess file, please make sure you clear your browser cache before testing your URLs. # Force HTTPS and WWW RewriteCond %{HTTP_HOST} !^www\.(.*)$ [OR,NC] RewriteCond %{https} off RewriteRule ^(.*)$ https://www.hike2hike.com/$1 [R=301,L] # Remove trailing slash from non-filepath urls RewriteCond %{REQUEST_URI} ^/(.+)/$ RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}\.html -f RewriteRule ^(.*)$ https://www.hike2hike.com/%1 [R=301,L] # Include trailing slash on the directory RewriteCond %{REQUEST_URI} !/$ RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^(.+)$ https://www.hike2hike.com/$1/ [R=301,L]
common-pile/stackexchange_filtered
Is it possible to hide a tab from a group of users in Team Foundation Server 2010? I have a tab (Internal Development Review) on one of my work item forms that I would not like to show to all users: Is it possible to hide this from a specific user group (or conversely, to grant it to another group)? I cannot find a way to put permissions on a tab. Well, I sort of took care of this. I added an EMPTY rule to the field and set Not: to my Senior Developer group, which does not hide the tab but disables and shows no information in the text box. This more or less does what I want it to (although I'd rather hide the tab altogether). We did it by using the Target attribute in the Layout tag. The developers use the interface that is integrated in VS2010, the testers use the web portal. We removed all unnecessary tabs from the web interface. Good idea, but we already use the web portal for a different group as well. It turns out to not be as big of a deal as it seemed when the original requirements were gathered, so disabling the text box was good enough. Thanks! Example: ... ...
common-pile/stackexchange_filtered
Negative feedback from block diagram to circuit components I can read and understand the block diagrams which show the internal amplifier and the feedback network and I can read and understand the schematics of several single-BJT amplifier circuits, but I have a very difficult time going back-and-forth between the two. I have been unable to find resources that show how to define loop gain and feedback factor when viewing the schematic, or how to predict component values by looking at the block diagram. I tried it on my own here hoping that users can help me understand what I'm missing. My objective was to begin with a common emitter circuit schematic (below right) and use it to derive the familiar equations for the block diagram (below left). In specific, I'd like my analysis to give me the closed-loop gain, feedback factor (\$K\$), and values for \$v_{in}\$, \$v_f\$, and \$i_{out}\$. (I use \$K\$ instead of the more common \$\beta\$ because the latter is already used to describe the transistor.) Is my analysis correct? NB: I edited this question to correct an earlier error where I neglected \$r_e\$ when calculating voltage gain. For the circuit above, I applied a test voltage of \$v_s=100mV\$ and the simulation showed an output current of \$342\mu A\$. If all goes well, I should be able to predict this result using the expressions I find for closed-loop gain. 1. Transconductance I understand that to properly analyze this circuit I will need to visualize it as a transconductance amplifier, so next I examined the closed-loop gain \$A_f=\frac{i_{out}}{v_s}\$. To get the closed-loop gain, first I'll need some expressions for \$i_{out}\$. I began with the output voltage, which is easily found with the resistors \$R_C\$ and \$R_E\$. \$i_{out}=\frac{v_{s}A_V}{R_C}\$ where \$A_V=\frac{R_C}{(R_E+r_e)}\$. \$i_{out}=\frac{v_s({\frac{R_C}{(R_E+r_e)}})}{R_C}=\frac{v_s}{(R_E+r_e)}\$ \$i_{out}=\frac{v_s}{(R_E+r_e)}\$ 2. Feedback Voltage Next, I wanted to understand how the feedback network \$K\$ works. I found a value for \$K\$ by working backwards from \$i_{out}\$. I know the effect of the internal amplifier \$A\$, so I know that \$i_{out}\$ will be \$g_m\$ times \$v_{in}\$. \$v_{in}g_m=i_{out}=\frac{v_s}{(R_E+r_e)}\$ \$v_{in}=\frac{v_s}{(R_E+r_e)g_m}=\frac{v_s}{R_Eg_m+r_eg_m}\$ Because \$r_e\$ and \$g_m\$ are related through inversion,\$r_eg_m=1\$. So... \$v_{in}=\frac{v_s}{R_eg_m+1}\$ Because \$v_{in}=v_s+v_f\$, I know that... \$v_s-\frac{v_s}{R_Eg_m+1}=v_f\$ Finally, I can say that \$v_f=v_s[1-\frac{1}{(R_Eg_m+1)}]\$ 3. Defining K, the feedback factor I know that \$K\$ will have a value in ohms, or \$(\frac{V}{I})\$. Its effect on the input, the voltage \$v_f\$, will be \$v_f=Ki_{out}\$. If I use my expressions for \$v_f\$ and \$i_{out}\$ I can find an expression for \$K\$. \$v_f=Ki_{out}=\frac{v_s(1-\frac{1}{R_Eg_m+1})}{\frac{v_s}{R_E+r_e}}\$ \$K=v_s[1-\frac{1}{R_Eg_m+1}]*(\frac{R_E+r_e}{v_s})\$ I can cancel out \$v_s\$, giving... \$K=[1-\frac{1}{R_Eg_m+1}]*(R_E+r_e)\$ Reworking, I get \$K=(R_E+r_e) - \frac{R_E+r_e}{(R_Eg_m+1)}\$ This yields a mess of \$R_E\$ variables: \$K = R_E+r_e-\frac{(R_E+r_e)}{(\frac{R_E}{r_e}+1)}\$ Which eventually boils down to \$K=R_E\$. 4. Finding the closed-loop gain Finally, I plugged in my \$K=R_E\$ expression into the standard closed-loop gain \$A_f=\frac{g_m}{1+Kg_m}\$ equation: \$A_f=\frac{g_m}{1+Kg_m}\$ \$A_f=\frac{g_m}{1+R_Eg_m}\$ 5. To Double-Check I went back to my original schematic and checked my work. if \$A_f=\frac{g_m}{1+R_Eg_m}\$, then my \$A_f=\frac{0.12}{1+(284*0.12)}=0.00342\$ If \$A_f=0.00342\$, my output current should be \$i_out=A_fv_s=0.00342*0.1v=0.000342A=342\mu A\$ If \$K=R_E=284\Omega\$, then \$v_f=Ki_{out}=284*0.000342=97mV\$ If \$v_f=97mV\$, then \$v_{in}=v_s-v_f=100mV-97mV=3mV\$ So, the negative feedback \$K\$ prevents the majority (97%) of the signal voltage from reaching the transistor. The closed loop gain is defined as \$A_f=\frac{g_m}{1+Kg_m}\$ and the feedback factor \$K=R_E\$ Everything checks out in simulation and it all makes conceptual sense... so, is my analysis correct? No - it is not correct. The closed-loop gain would approach infinite for RE=0. Alreeady the start of your analysis (Av=Rc/RE) ist not correct. @LvW, I edited the question to use $R_E+r_e$ instead, thanks for pointing that out. The resistor RE provides (output)-current-controlled voltage feedback. Therefore, for analyzing the feedback mechanism, it is correct to consider the BJT as a transconductance device with voltage-in and current-out. From this consideration we already can conclude that the feedback factor will be a resistive quantity. Applying the transconductance view it is a simple matter to write down the output-to-input ratio ic/vbe with vb=vs and ve=icRE. (Note: All the variables are differential values; for simplicity I have assumed ic=ie with ib=0). From this, you can find the closed-loop "gain" ic/vs (closed-loop transconductance). Now - analyzing the denominator of this ratio, you can find the loop gain expression and the feedback "factor" (which has the unit "ohm"). Of course, the numerator is identical to the open-loop "gain" (open-loop transconductance). Ok, all this makes sense of course, but the question is whether my analysis is correct. Note that I did revise the question to account for $r_e$ I must admit that I did not check all the steps in your calculation - however, the result is correct (Af=Closed-loop transconductance). The loop gain is Kgm=REgm and the feedback "factor" is RE. Ok first things, the block diagram used in control theory need not always give you the same 'answer' (of the form A/1+AK) in an actual circuit due to the following reasons (here A is the open loop gain and K the feedback factor as shown in your diagram): (a) The control block doesnt show the impact of loading. A and K will have input and output impedances (b) In the control block, the signal flow is one way. In an actual circuit the signal flows both ways. (c) Not all circuits can be neatly represented in that control block manner. A good example is a common emitter or common source amplifier with a degenerate resistor as you have shown. If you want accurate answers in a circuit - use KCL at all nodes. Having said this - this is how you calculate open loop gain, loop gain and closed loop gain 'quickly, but maybe inaccurately': Step 1: open the feedback path i.e. disconnect the feedback from the output and ground that feedback route. i.e. the input to K is 0. Calculate the small signal gain. The answer is your open loop gain (OLG). Step 2: Ground your input. Apply a test voltage to your disconnected feedback line i.e. at the input to K. Now calculate the small signal gain. This answer is the loop gain (LG). If you see a negative sign, it is negative feedback. Step3: Now blindly write the closed loop gain = OLG/(1+LG) Note that this form assumes negative feedback, so dont carry the negative sign from the calculated LG. This process will allow you to calculate CLG quickly at the cost of some errors.
common-pile/stackexchange_filtered
+- 5V differential ADC in the market? I want to integrate an analog signal with +- 5v differential output with my rasberry pi 4b. I have 3 inputs. I am quite new to ADCs and drowning in information instead of finding a solution. Can someone point me in the right direction? Have you tried at mouser.com and other vendor sites? They have filters to help you find what you need. You might also want to have a look at this video on the EEVBlog: https://www.youtube.com/watch?v=zqlAq266aTs Do note that +/-5V diff. output isn't trivial and there will be a lot of "traps" for a beginner. Do you need to measure (digitize) voltages that go negative? how far negative? would a microphone output (10 milliVolts from a dynamic microphone) be your plan? I have a university project to monitor a cnc tool with the help of a vibration sensor. I am stuck in China with barely any documentation for the sensor available. The most I can make out is 18-28 V DC input voltage, +-5 Vp signal. That is all the info I have about the sensor I would apply +24v to the sensor, connect an oscilloscope to the output, and tap it with my finger or otherwise simulate working conditions to see how the output changes and if it ever goes negative. I am pretty sure it does go into negative. I looked it up again and it is a three axis and speed sensor. The output is x y and z coordinates. Raspberry Pis do not come with integrated Analog-to-Digital Converters (ADCs). You will have to buy an external board (HAT in the Raspberry Pi lingo) that provides that functionality when connected to your RPi 4b board. You will also have to make sure that this board accepts differential voltages in the voltage range you have. If the absolute value of any of the voltages is negative (relative to the board's ground), you may have a really hard time to find something that will work for you. Places you can starting looking for the appropriate HAT for you: Pinout.xyz Sparkfun Adafruit UPDATE Let me know if you’d like to build your own ADC circuit instead. It seems like your answer boils down to "shop for something that meets your needs". That doesn't seem very helpful to me. @ElliotAlderson - I take your point. The alternative for the OP would be to build his own ADC circuit. If that’s where he wants to go, I’d be more than happy to point him to the right direction.
common-pile/stackexchange_filtered
How to select unique values only in one field in an Access query I have looked several places on how to have a single distinct column while displaying other related data to the unique field. All of the examples I have seen only involve a single table and a handful of fields which isn't applicable to my situation (see code below). Currently I am using the max function to narrow down the number of selected records, but it is still leaving duplicates in the [Part Group Nbr] column which I need to have be unique values only. All I need is representative data from each [Part Group Nbr]. I have also done a side query using the SELECT DISTINCT function to get a unique list of just the [Part Group Nbr] field but I can't figure out any meaningful way to join it to the query. SELECT Reps.[Logistics Rep], Max([Supplier Link].[Supplier Name]) AS [Supplier Name], Max([Supplier Link].[Supplier Nbr]) AS [Supplier Nbr], Max([Part Number].[Loc #]) AS [Loc #], Max([Part Number].[Part Nbr]) AS [Part Nbr], Max([Part Number].[Part Name]) AS [Part Name], Max([Part Number].[Part Group Nbr]) AS [Part Group Nbr], Max([Part Number].[RCM Pack Nbr]) AS [RCM Pack Nbr], Max([Part Number].[Part Status]) AS [Part Status], Max([Part Number].[Project Type]) AS [Project Type], Max([Part Number].[Pack Rank]) AS [Pack Rank], Max([Part Number].[Pack Container]) AS [Pack Container], Max([Part Number].[Pack Quantity]) AS [Pack Quantity], Max(E0.[Drawing Review]) AS [Drawing Review], Max(E0.[Part/Pack Ranking & VSM]) AS [Part/Pack Ranking & VSM], Max(E0.DIS) AS DIS, Max(E0.[Pre Concept]) AS [Pre Concept], Max(E0.[E-0 Status]) AS [E-0 Status], Max(E1.[OEM Impact Study]) AS [OEM Impact Study], Max(E1.[Concept Activity]) AS [Concept Activity], Max(E1.[E-1 Status]) AS [E-1 Status], Max(E2.Prototype) AS Prototype, Max(E2.[NAPS/PIFs]) AS [NAPS/PIFs], Max(E2.[Mass Pro Bid]) AS [Mass Pro Bid], Max(E2.[Mass Pro Selection]) AS [Mass Pro Selection], Max(E2.[PO/Budget Application]) AS [PO/Budget Application], Max(E2.[Quality Confirmation]) AS [Quality Confirmation], Max(E2.[E-2 Status]) AS [E-2 Status], [Part Number].[Base 5], Max(Left([Part Number].[Part Nbr],8)) AS [base 8], Max(Left([Part Number].[Part Nbr],11)) AS [Base 10] FROM ((((Reps INNER JOIN [Supplier Link] ON Reps.[Logistics Rep] = [Supplier Link].[Logistics Rep]) INNER JOIN [Part Number] ON [Supplier Link].[Supplier Name] = [Part Number].[Supplier Name]) INNER JOIN ([Unique parts List] INNER JOIN E0 ON [Unique parts List].[Part Nbr] = E0.[Part Nbr]) ON [Part Number].[Part Nbr] = [Unique parts List].[Part Nbr]) INNER JOIN E1 ON [Unique parts List].[Part Nbr] = E1.[Part Nbr]) INNER JOIN E2 ON [Unique parts List].[Part Nbr] = E2.[Part Nbr] WHERE ((([Part Number].[Project Type])="NEW" Or ([Part Number].[Project Type])="MOT" Or ([Part Number].[Project Type])="MOF")) GROUP BY Reps.[Logistics Rep], [Part Number].[Base 5] HAVING (((Max([Part Number].[Pack Rank]))="AR" Or (Max([Part Number].[Pack Rank]))="AV" Or (Max([Part Number].[Pack Rank]))="AC" Or (Max([Part Number].[Pack Rank]))="BR" Or (Max([Part Number].[Pack Rank]))="BE" Or (Max([Part Number].[Pack Rank]))="BV")); There is an error in you joins INNER JOIN ([Unique parts List] INNER JOIN E0 ON [Unique parts List].[Part Nbr] = E0.[Part Nbr]) ON [Part Number].[Part Nbr] = [Unique parts List].[Part Nbr]) It doesn't seem to be an error - it runs fine as is and it's actually the code generated by Access when I make the query (just did it again to be sure). When I try to "fix" it, it starts throwing errors.
common-pile/stackexchange_filtered
Confusing julia behavior. @everywhere macro changes the scope of local variables to global I just encountered a very confusing julia behavior. I always thought that variables defined inside a function remain local to that function. But in the following example, the scope changes. I define a simple function as below using Distributed addprocs(2) function f() @everywhere x = myid() @everywhere println("x = ", x) end Executing the following code f() gives the result x = 1 From worker 2: x = 2 From worker 3: x = 3 But since x is defined inside the function, I would expect the variable x to be not defined outside the function. However, upon executing the following code x I get the result 1 Even more confusing is the execution of the following code @fetchfrom 3 x which again gives 1 This is super confusing behavior. First, how does x become available outside the function? Second, why are all the processors/cores returning the same value of x? Thank you for your help. @everywhere always evaluates into Main on the process on which it's executed. @fetchfrom doesn't work as you expect I think - check this discussion which gives the functions you want. fetch(@spawnat(3, getfield(Main, :x))) returns 3 as expected.
common-pile/stackexchange_filtered
Add values to loop in corresponding order Hey so I want to add the information that is retrieved from my parser in this case the InfoLoop() to a variable with all the attributes. movie_list = jp_movies, maxx # these values in movie_list include tokens ei(107290) that the parser takes and # it then grabs all the key info I want about that movie with Imdbpy plugin print("Processing...") # print the title for the shows found with token for movie_list in movie_list: returnlist = Media.InfoLoop(movie_list) print ("Info found for: "+ returnlist.show_title()) This works and returns the info I want: Info found for: Jurassic Park Info found for: Mad Max: Fury Road Since the returnlist includes the information I want I then want to pass it back to another class instance that is asking for this information in order. # Share with Movie() print("Pushing values to instance...") for movie_list in movie_list: Media.Movie((returnlist.show_title()), max_test, (returnlist.show_cover()), max_max_youtube, (returnlist.show_year()), (returnlist.show_rating())) Now the code above outputs the correct values as well. I want it to loop these actions for every movie. Is there a way to have it store the info from Media.Movie into the variables inside movie_list (jp_movie, maxx) ie the movie it gets the list for. Updated and currently working with: jp_movies, maxx = str(107290), str(1392190) movie_list = [jp_movies, maxx] for movie in movie_list: print("Processing...") returnlist = Media.InfoLoop(movie_list) print ("Info found for: "+ returnlist.show_title()) print("Pushing values to instance...") current_movie = Media.Movie((returnlist.show_title()), max_test, (returnlist.show_cover()), mad_max_youtube, (returnlist.show_year()), (returnlist.show_rating())) movie_list.append(current_movie) it throws a 'str' object has no attribute 'append' Pretty new to python so please be nice :3! for movie_list in movie_list is, at best, needlessly confusing. Sorry yah it seemed to work so i kept it lol. I basically want it to loop for the number of values in movie_list is there a better way to do that? @ScottHunter So I understand you want to keep the info for all the movies, correct? For that, you will need to store each movie's data in a different place; The recommended way is to use a list. right now you are rewriting the same object, which is why it only saves the last movie. Also, you used the name "movie_list" twice: once for the list and another for the object in the for loop. You should try the following: print("Pushing values to instance...") my_movie_list = [] for movie in movie_list: returnlist = Media.InfoLoop(movie) current_movie = Media.Movie((returnlist.show_title()), max_test, (returnlist.show_cover()), max_max_youtube, (returnlist.show_year()), (returnlist.show_rating())) my_movie_list.append(current_movie) Let me know if this works Hey! Doesn't throw any errors but I have some questions. 1. what does it get stored as in the my_movie_list? 2. What is .append doing in this situation? Ill try my best oh I am guessing I should add those variables (jp_movie and maxx) inside my_movie_list correct? What type are jp_movies and maxx? what each of them represents? They are the original tokens that are passed to the parser to look up the movie info. They are declared like: jp_movies, maxx = str(107290), str(1392190)
common-pile/stackexchange_filtered
How to find and replace json with shell variables using jq? I have read properties with jq from a json object and have stored them to variables. I want to now read these variables and essentially find and replace a word inside the string with a global shell variable. I've set my json ID's from my JSON file # Set Json ID's TARGET_ID=$(jq '.DefaultCacheBehavior.TargetOriginId' distconfig.json) DOMAIN_NAME=$(jq '.Origins.Items[0].DomainName' distconfig.json) ORIGIN_ID=$(jq '.Origins.Items[0].Id' distconfig.json) echo "$TARGET_ID" echo "$DOMAIN_NAME" echo "$ORIGIN_ID" This returns "S3-Website-stag4.example.io.s3-website.us-east-2.amazonaws.com" "stag4.example.io.s3-website.us-east-2.amazonaws.com" "S3-Website-stag4.example.io.s3-website.us-east-2.amazonaws.com" I have my location id variable and would like to write it to find and replace all stag4 references in those 3 ID's. Then I would like to write those 3 ID's to the initial json object, or create a temp version of it. Example, if: $DOMAIN_NAME is"stag4.example.io.s3-website.us-east-2.amazonaws.com" I would like to essentially have it set to: $LOCATION_NAME="stag6" DOMAIN_LOCATION="example.io" "$DOMAIN_NAME=S3-Website-\$LOCATION_NAME\.example.io.s3-website.us-east-2.amazonaws.com" "$TARGET_ID=\$LOCATION_NAME\.example.io.s3-website.us-east-2.amazonaws.com" "$ORIGIN_ID=S3-Website-\$LOCATION_NAME\.example.io.s3-website.us-east-2.amazonaws.com" Then write those 3 to the temp or new json file so I can run my cloudformation command: aws cloudfront create-distribution --distribution-config file://disttemp.json I have now built out the proper variables from the initial json file like so: $LOCATION_NAME="stag6" DOMAIN_LOCATION="example.io" echo "Build New IDs" TARGET_ID_BUILT="S3-Website-$LOCATION_NAME.$DOMAIN_LOCATION.s3-website.us-east-2.amazonaws.com" DOMAIN_NAME_BUILT="$LOCATION_NAME.$DOMAIN_LOCATION.s3-website.us-east-2.amazonaws.com" ORIGIN_ID_BUILT="S3-Website-$LOCATION_NAME.$DOMAIN_LOCATION.s3-website.us-east-2.amazonaws.com" echo "$TARGET_ID_BUILT" echo "$DOMAIN_NAME_BUILT" echo "$ORIGIN_ID_BUILT" How do I write these variables to the json file with jq? EDIT: Sample of distconfig.json requested – domain/creds swapped to example { "CallerReference": "my-test-distribution-2", "Comment": "", "CacheBehaviors": { "Quantity": 0 }, "IsIPV6Enabled": true, "Logging": { "Bucket": "", "Prefix": "", "Enabled": false, "IncludeCookies": false }, "WebACLId": "", "Origins": { "Items": [ { "OriginPath": "", "CustomOriginConfig": { "OriginSslProtocols": { "Items": [ "TLSv1", "TLSv1.1", "TLSv1.2" ], "Quantity": 3 }, "OriginProtocolPolicy": "http-only", "OriginReadTimeout": 30, "HTTPPort": 80, "HTTPSPort": 443, "OriginKeepaliveTimeout": 5 }, "CustomHeaders": { "Quantity": 0 }, "Id": "S3-Website-stag4.example.io.s3-website.us-east-2.amazonaws.com", "DomainName": "stag4.example.io.s3-website.us-east-2.amazonaws.com" } ], "Quantity": 1 }, } "DefaultRootObject": "", "PriceClass": "PriceClass_All", "Enabled": true, "DefaultCacheBehavior": { "TrustedSigners": { "Enabled": false, "Quantity": 0 }, "LambdaFunctionAssociations": { "Quantity": 0 }, "TargetOriginId": "S3-Website-stag4.example.io.s3-website.us-east-2.amazonaws.com", "ViewerProtocolPolicy": "redirect-to-https", "ForwardedValues": { "Headers": { "Quantity": 0 }, "Cookies": { "Forward": "none" }, "QueryStringCacheKeys": { "Quantity": 0 }, "QueryString": false }, "MaxTTL": 31536000, "SmoothStreaming": false, "DefaultTTL": 86400, "AllowedMethods": { "Items": [ "HEAD", "GET" ], "CachedMethods": { "Items": [ "HEAD", "GET" ], "Quantity": 2 }, "Quantity": 2 }, "MinTTL": 0, "Compress": true }, "ViewerCertificate": { "SSLSupportMethod": "sni-only", "ACMCertificateArn": "xxxx", "MinimumProtocolVersion": "TLSv1.1_2016", "Certificate": "xxxx", "CertificateSource": "acm" }, "CustomErrorResponses": { "Quantity": 0 }, "HttpVersion": "http2", "Restrictions": { "GeoRestriction": { "RestrictionType": "none", "Quantity": 0 } }, "Aliases": { "Quantity": 0 } } This link might help https://stackoverflow.com/questions/42716734/modify-a-key-value-in-a-json-using-jq Yeah i'm trying to use a temp file like suggested im just not sure how to do the 'find and replace' action of setting my new variables in the new file in place of where I got the old variables in the initial file @oguzismail added a snippet, thanks @user3648969 see How to create a Minimal, Complete, and Verifiable example. the sample you provided is an incomplete JSON value, and it doesn't have a key named DefaultCacheBehavior whereas your code indicates that TARGET_ID is retrieved from there. @oguzismail Sorrry, I put an ellipsis at the bottom of the object to indicate it continued, I just didn't feel like cluttering up the post with the full object. As long as I know the function to find and replace one of the variables I can apply it to the different paths @oguzismail I've added the rest of the json object for you You should use sed to do the substitution and then inject the value back into the JSON. echo $TARGET_ID | sed 's/stag4/stag5/g' Outputs S3-Website-stag5.example.io.s3-website.us-east-2.amazonaws.com Next we'll put the value back into the original JSON, this will technically output a new JSON and does not edit the file, however, you can easily solve for this on the output by temporarily saving to a tmp file. We will use the --arg flag to reference our bash variable and set the new value for our field cat distconfig.json | jq --arg  TARGET_ID $TARGET_ID '.DefaultCacheBehavior.TargetOriginId = $TARGET_ID' > tmp.json && mv tmp.json distconfig.json
common-pile/stackexchange_filtered
How a String can be modified if String is not final In String class, I see all instance variables are private. I see methods to operate on String. If final keyword is not there in String class, all other code remains as is, and we sub-class the String class, since variables are private they are not accessible outside the class, how can we modify the string object. Please let me know a specific method from the sub-class, which we can modify string object. Thanks! This is a duplicate of something, but the long story short is that when you do String bat = "cat"; followed by bat = "brown" + cat, the JVM actually creates a new string object behind the scenes in the second case. Why do you think there is such a method? What sub-class? String is, itself, final. That means you can't sub-class String. @ElliottFrisch OP said If final keyword is not there in String class. It allows you to override methods like toString(), length(), substring(), etc, which could appear as mutations, and to provide mutator methods. From the documentation: Strings are constant; their values cannot be changed after they are created. Also, String is a final class, so you can't extend it. If you want a collection of characters you can modify, use StringBuilder: https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html
common-pile/stackexchange_filtered
Prove the following $e^{iAx} = \cos (x)I + i \sin (x) A$ the question says as following, Let x be a real number and A a matrix such that $A^2 = I$. Show that the $e^{iAx} = \cos (x)I + i \sin (x) A$. my problem is that I don't know how to deal with this equation using matrix form, I know how to deal with such a question $e^{ix} = \cos (x) + i \sin (x)$ but how to represent the matrix form in a graph in order to get the values of the exponential function $e^{iAx}$. I will be very happy if someone explains this equation or any reference will be also good. Thank you Both sides satisfy the same differential equation and have the same initial conditions, so they agree. More explicitly, let $f(x)=e^{iAx}$ and let $g(x)=I\cos x + i A \sin x$. These are matrix-valued functions of $x$. Compute the following: $$f'=iAe^{iAx},\quad f''=-e^{iAx},\quad g'=-I\sin x+i A\cos x,\quad g''=-I\cos x -iA\sin x.$$ Therefore $f''=-f$ and $g''=-g$. Moreover $f(0)=g(0)=I$ and $f'(0)=g'(0)=iA$. Thus $f\equiv g$.
common-pile/stackexchange_filtered
Multi-coloured circular div using background colours? I'm trying to create a multi-coloured circle in CSS to simulate a wheel of fortune, I've tried using linear gradients but it just applies strips of colour running vertically through the circular div rather than being coloured areas as if you were cutting up a pizza if that makes sense? This is the code I've tried: background: -moz-linear-gradient(left, red, red 20%, blue 20%, blue); Which results in: But I want it to look more like this?: Is this possible in CSS or am I going to have to use a background image (I'd rather avoid this because it isn't as easy to scale as the page resizes etc..)? It could be possible, but it would be quite the long HTML/CSS. You will have to create many objects, then cut them using ::before and ::after statements. Wouldn't it be easier just to use a background image, and have 2 or 3 media queries to use different background for the different screen sizes? Use html canvas to make a piechart that would be close enough to what you want to achieve I guess. ..or use SVG much simpler. https://stackoverflow.com/questions/27943053/how-to-create-a-circle-with-links-on-border-side Woah.. I've been working all day on other code and just come back to see all the replies. I will check shortly and report back what works! Please check my answer. It is more appropriate to your question and I gave two versions. @EM-Creations @EM-Creations i elaborated more my answer to give more examples ;) I also implemented the wheel of fortune :) @N.Ivanov the reason I want to avoid images is because it doesn't scale as well as pure CSS even using media queries. TemaniAfif @EM-Creations said he was going to go with my updated version because it seemed to be the most concise and easy to modify, works perfectly with the element he already had. And my updates coming soon! :) @ElvinMammadov the OP choosed your answer because it was easy for him to handle so i think it's useless to update it with a copy of what i did as in this case the OP could simply pick up what i did ;) You can make this with using borders: .chart { position: absolute; width: 0; height: 0; border-radius: 60px; -moz-border-radius: 60px; -webkit-border-radius: 60px; } #chart1 { border-right: 60px solid red; border-top: 60px solid transparent; border-left: 60px solid transparent; border-bottom: 60px solid transparent; } #chart2 { border-right: 60px solid transparent; border-top: 60px solid green; border-left: 60px solid transparent; border-bottom: 60px solid transparent; } #chart3 { border-right: 60px solid transparent; border-top: 60px solid transparent; border-left: 60px solid blue; border-bottom: 60px solid transparent; } #chart4 { border-right: 60px solid transparent; border-top: 60px solid transparent; border-left: 60px solid transparent; border-bottom: 60px solid yellow; } <div id="chart1" class="chart"></div> <div id="chart2" class="chart"></div> <div id="chart3" class="chart"></div> <div id="chart4" class="chart"></div> UPDATE 1 .pizza { width: 300px; height: 300px; border-radius: 100%; background: linear-gradient(45deg, lightblue 50%, blue 0%), linear-gradient(-45deg, green 50%, darkgreen 0%), linear-gradient(-45deg, #E5E500 50%, yellow 0%), linear-gradient(45deg, tomato 50%, red 0%); background-size: 50% 50%; background-position: 0% 0%, 100% 0%, 0 100%, 100% 100%; background-repeat: no-repeat; } <div class="pizza"></div> I think I'm going to go with your updated version because it seems to be the most concise and easy to modify, works perfectly with the element I already have, thank you! Chaps, let's not all argue, everyone gave a working answer for which I am grateful and I upvoted all working answers (I tested all of them) but this one seemed the most easy to modify and was a simple copy and paste with no other changes to my code; that's why I choose it as the accepted answer. One solution is to use multiple background layer considering rotated linear-gradient. We can also rely on pseudo-element and some transparent colors. Then simply adjust the degrees, colors, opacity of colors and position of pseudo element to obtain any chart you want: .circle { margin: 20px; width: 200px; height: 200px; border-radius: 50%; background: linear-gradient(to right, rgba(255,0,0,0.5) 50%, yellow 0%), linear-gradient(-110deg, black 50%, pink 0%); position: relative; overflow: hidden; } .circle:after, .circle:before{ content: ""; position: absolute; top: 0; left: 0; bottom: 0; right: 0; } .circle:after { background: linear-gradient(-45deg, rgba(255, 180, 180, 0.5) 50%, transparent 0%); bottom: 50%; left: 50%; } .circle:before { background: linear-gradient(0deg, rgba(128, 169, 170, 0.5) 50%, transparent 0%), linear-gradient(50deg, rgba(0, 169, 170, 1) 50%, transparent 0%); } <div class="circle"></div> Here is more example considering different configuration Using only one element and multiple gradient: .circle { margin: 20px; width: 200px; height: 200px; border-radius: 50%; background: linear-gradient(0deg, rgba(0, 255, 217, 0.4) 50%, transparent 0%), linear-gradient(45deg, rgba(0, 128, 0, 0.4) 50%, transparent 0%), linear-gradient(90deg, rgba(11, 255, 0, 0.4) 50%, transparent 0%), linear-gradient(135deg, pink 50%, transparent 0%), linear-gradient(180deg, brown 50%, transparent 0%), linear-gradient(225deg, yellow 50%, transparent 0%), linear-gradient(270deg, red 50%, transparent 0%); position: relative; overflow: hidden; } <div class="circle"></div> Using multiple elements and one gradient per element : .circle { margin: 20px; width: 200px; height: 200px; border-radius: 50%; background: linear-gradient(to right, red 50%, yellow 0%); position: relative; overflow: hidden; } .circle:after { content: ""; position: absolute; top: 0; left: 0; bottom: 0; right: 0; background: linear-gradient(45deg, rgba(255, 180, 180, 0.5) 50%, transparent 0%); } .circle:before { content: ""; position: absolute; top: 0; left: 0; bottom: 0; right: 0; background: linear-gradient(125deg, rgba(128, 169, 170, 0.5) 50%, transparent 0%); } .circle-alt { width: 200px; height: 200px; border-radius: 50%; background: linear-gradient(to bottom, rgba(0, 250, 0, 0.5) 50%, rgba(0, 250, 255, 0.5) 0%); position: absolute; overflow: hidden; } <div class="circle"> <div class="circle-alt"></div> </div> Using Multiple elements and multiple gradients per elements and only solid color (without changing background-position like the answer of @vals) : .circle { margin: 20px; width: 200px; height: 200px; border-radius: 50%; background: linear-gradient(to right, red 50%, transparent 0%), linear-gradient(225deg, transparent 50%, blue 0%), linear-gradient(0deg, green 50%, transparent 0%), linear-gradient(-45deg, black 50%, transparent 0%), linear-gradient(-90deg, yellow 50%, transparent 0%); position: relative; overflow: hidden; } .circle:before { content: ""; position: absolute; top: 0; left: 0; bottom: 50%; right: 50%; background:linear-gradient(45deg,lightblue 50%, transparent 0%) } .circle:after { content: ""; position: absolute; top: 50%; left: 0; bottom: 0; right: 50%; background:linear-gradient(135deg, brown 50%, pink 0%); } <div class="circle"></div> The wheel of fortune (With rotation !): .circle { margin: 20px; width: 200px; height: 200px; border-radius: 50%; background: linear-gradient(to right, #06b51d 50%, transparent 0%), linear-gradient(60deg, #7e00ff 50%, transparent 0%), linear-gradient(30deg, #ff00bd 50%, transparent 0%), linear-gradient(0deg, #ff0000 50%, transparent 0%), linear-gradient(-30deg, #ff4700 50%, transparent 0%), linear-gradient(-60deg, #ffa500 50%, transparent 0%), linear-gradient(-90deg, #ffff00 50%, transparent 0%); position: relative; overflow: hidden; animation: rotate 6s linear infinite; } .circle:before { content: ""; position: absolute; top: 0; left: 0; bottom: 50%; right: 50%; background: linear-gradient(210deg, transparent 64%, #09ffa5 0%), linear-gradient(240deg, transparent 37%, #34ff00 0%); } .circle:after { content: ""; position: absolute; top: 50%; left: 0; bottom: 0; right: 50%; background:linear-gradient(150deg, #00acff 37%, transparent 0%), linear-gradient(120deg, #0075ff 63%, #1200ff 0%); } @keyframes rotate { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } <div class="circle"></div> Related question with a different way to achieve the same result: Sass/CSS color wheel How did you make this wheel of colors? Was it yourself or some generator? @NevinMadhukarK it was myself I need to make something like this - https://imgur.com/a/MODPouI Any advice on which of your examples might help with that? @NevinMadhukarK you can check this question: https://stackoverflow.com/a/60442793/8620333 I wrote a SASS code to easily control it. I managed to get it on that answer. Although I was thinking of more of a linear gradient answer. That uses span if I am correct. Extending on the answer of @Temani Afif, but more similar to your request: .test { width: 600px; height: 600px; border-radius: 50%; background-size: 50% 50%; background-repeat: no-repeat; background-image: linear-gradient(150deg, transparent 63%, tomato 63%), linear-gradient(120deg, transparent 36.5%, red 36.5%), linear-gradient(fuchsia, fuchsia), linear-gradient(240deg, transparent 63%, green 63%), linear-gradient(210deg, transparent 36.5%, lime 36.5%), linear-gradient(lightgreen, lightgreen), linear-gradient(330deg, transparent 63%, blue 63%), linear-gradient(300deg, transparent 36.5%, lightblue 36.5%), linear-gradient(cyan, cyan), linear-gradient(60deg, transparent 63%, papayawhip 63%), linear-gradient(30deg, transparent 36.5%, yellow 36.5%), linear-gradient(gold, gold); background-position: right top, right top, right top, right bottom, right bottom, right bottom, left bottom, left bottom, left bottom, left top, left top, left top; } <div class="test"></div> You could achieve this with css, but as you want 12 slices you will have to use a more complicated markup. If you only want to use 4 or 8, a much simpler solution using a multiple background would be possible. Use the border-radius combined with a skew-trick to draw a slice of arbitratry angle Use multiple wrapped slices, each rotated Another idea which I would prefer: Use a svg graphic for it. .container { position: absolute; left: 300px; top: 0; } .wrap { position: absolute; transform: rotate(30deg); transform-origin: 0% 100%; } .slice { height: 100px; width: 100px; overflow: hidden; transform-origin: 0% 100%; transform: skew(-60deg); position: relative; } .slice::before { height: inherit; width: inherit; position: absolute; content: ""; border-radius: 0 100% 0 0; transform-origin: 0% 100%; transform: skew(60deg); } .wrap-0 { transform: rotate(0deg); } .wrap-0 .slice::before { background: hsl(0, 100%, 50%); } .wrap-1 { transform: rotate(30deg); } .wrap-1 .slice::before { background: hsl(30, 100%, 50%); } .wrap-2 { transform: rotate(60deg); } .wrap-2 .slice::before { background: hsl(60, 100%, 50%); } .wrap-3 { transform: rotate(90deg); } .wrap-3 .slice::before { background: hsl(90, 100%, 50%); } .wrap-4 { transform: rotate(120deg); } .wrap-4 .slice::before { background: hsl(120, 100%, 50%); } .wrap-5 { transform: rotate(150deg); } .wrap-5 .slice::before { background: hsl(150, 100%, 50%); } .wrap-6 { transform: rotate(180deg); } .wrap-6 .slice::before { background: hsl(180, 100%, 50%); } .wrap-7 { transform: rotate(210deg); } .wrap-7 .slice::before { background: hsl(210, 100%, 50%); } .wrap-8 { transform: rotate(240deg); } .wrap-8 .slice::before { background: hsl(240, 100%, 50%); } .wrap-9 { transform: rotate(270deg); } .wrap-9 .slice::before { background: hsl(270, 100%, 50%); } .wrap-10 { transform: rotate(300deg); } .wrap-10 .slice::before { background: hsl(300, 100%, 50%); } .wrap-11 { transform: rotate(330deg); } .wrap-11 .slice::before { background: hsl(330, 100%, 50%); } <div class="container"> <div class="wrap wrap-0"> <div class="slice"></div> </div> <div class="wrap wrap-1"> <div class="slice"></div> </div> <div class="wrap wrap-2"> <div class="slice"></div> </div> <div class="wrap wrap-3"> <div class="slice"></div> </div> <div class="wrap wrap-4"> <div class="slice"></div> </div> <div class="wrap wrap-5"> <div class="slice"></div> </div> <div class="wrap wrap-6"> <div class="slice"></div> </div> <div class="wrap wrap-7"> <div class="slice"></div> </div> <div class="wrap wrap-8"> <div class="slice"></div> </div> <div class="wrap wrap-9"> <div class="slice"></div> </div> <div class="wrap wrap-10"> <div class="slice"></div> </div> <div class="wrap wrap-11"> <div class="slice"></div> </div> </div> CSS Tricks has a post about conic gradients that describes the "colorful umbrella" as an intermediate step, which looks perfect for your use. I've put it together into a Code Pen for convenience. HTML: <div class="wheel"> <ul class="umbrella"> <li class="color"></li> <li class="color"></li> <li class="color"></li> <li class="color"></li> <li class="color"></li> <li class="color"></li> <li class="color"></li> <li class="color"></li> <li class="color"></li> <li class="color"></li> <li class="color"></li> <li class="color"></li> </ul> </div> SCSS: @mixin circle($size) { content: ""; position: absolute; border-radius: 50%; width: $size; height: $size; left: calc(50% - #{$size/2}); top: calc(50% - #{$size/2}); } $wheel: 15em; .color { @include circle($wheel); clip: rect(0, $wheel, $wheel, #{$wheel/2}); &:after { @include circle($wheel); background: blue; clip: rect(0, #{$wheel/2}, $wheel, 0); transform: rotate(45deg); } } .color, .color:nth-child(n+7):after { clip: rect(0, $wheel, $wheel, #{$wheel/2}); } .color:after, .color:nth-child(n+7) { @include circle($wheel); clip: rect(0, #{$wheel/2}, $wheel, 0); } $colors: (#9ED110, #50B517, #179067, #476EAF, #9f49ac, #CC42A2, #FF3BA7, #FF5800, #FF8100, #FEAC00, #FFCC00, #EDE604); @for $i from 0 to length($colors) { .color:nth-child(#{1+$i}):after { background-color: nth($colors, $i+1); @if $i < 6 { transform: rotate(#{30*(1+$i)}deg); z-index: #{length($colors)-$i}; } @else { transform: rotate(#{-30+(30*(1+$i))}deg); } } } As a side note, if your only issue with background images is the scaling issue, keep in mind that SVG images scale smoothly, since they're basically vector graphics. (You'd have to draw that manually, but the image would scale.) I like the idea of conic gradients but I don't think using <li> tags to represent colour on a wheel is semantically correct. I'm also steering away from SVG to keep things simple as I'll be binding JavaScript events and manipulate the wheel from JavaScript too. The <ul> and <li> tags could just as easily be <div> or <span> tags (or something else) if the semantics bother you. (There's also an argument to be made that a color wheel is precisely a list of colors, but I don't feel the need to entrench myself on that point.) Needing to manipulate the colors from JS is a consideration you might want to add to your question up top. Aye, I understand it could be swapped out for more semantic tags but it's not as concise as the other choices, that's why I didn't accept it as the "accepted answer". I still upvoted it though as it's a valid solution, thank you! <div class="circle"> <div class="table italy"> <div class="table-cell green"></div> <div class="table-cell white"></div> <div class="table-cell red"></div> </div> </div> <div class="circle"> <div class="table france"> <div class="table-cell blue"></div> <div class="table-cell white"></div> <div class="table-cell red"></div> </div> </div> <div class="circle"> <div class="table windows"> <div class="table-cell red"></div> <div class="table-cell green"></div> <div class="table-cell yellow"></div> <div class="table-cell blue"></div> </div> </div> <div class="circle"> <div class="table rainbow"> <div class="table-cell red"></div> <div class="table-cell orange"></div> <div class="table-cell yellow"></div> <div class="table-cell green"></div> <div class="table-cell blue"></div> <div class="table-cell indigo"></div> <div class="table-cell violet"></div> </div> </div> There you have it: a reliable way to create multi-color circles. The great thing about this approach is that it doesn’t matter how many colors you have AND it works all the way back to IE. just a question : how can this HTML works without any CSS with it ?
common-pile/stackexchange_filtered
Does firebase store user's name and email when using FCM for push messages? I'm trying to understand how much data is stored on Firebase when we use FCM to send a push notification. I know we need to have a registered unique device ID on firebase to ensure that device gets a notification. I want to know in specific if a user's name and email also get stored on it. Is it also possible to register a new user without an email on firebase? I've gone over the firebase documentation provided here but I'm unclear about the user name and email getting shared with each instance invocation. Firebase Cloud Messaging has no concept of a user, it merely sends a message to the device on which the specific token was minted. It only stores the minimum information that it needs to deliver the messages, which (given that it doesn't have any concept of a user) does not incude a user name or their email address. The link you provide is to the documentation of Firebase Authentication, which is a completely separate product within the Firebase platform that does store user information. But you don't need to use Firebase Authentication in order to use its Cloud Messaging. Thanks so much for the clarification! I assumed firebase auth is necessary for a Cloud Messaging to happen successfully. So as long as I have my app running on a registered device I can send them push notifications. And the only thing that FCM stores is the device ID and nothing else concerned to the user Yup, that's correct.
common-pile/stackexchange_filtered
How to select values where another value is an array? I'm trying to select values where another POST values are an array, I do not know what is wrong with my query giving me this error. I'm trying to know what courses are just added to table. I have five inputs in the form. Notice: Trying to get property of non-object in C:\Apache\htdocs\xxx\addcourse.php on line 262 Here is my code <?php if(isset($_POST['Submit'])) { $code= isset($_POST['code']) ? $_POST['code'] : ''; $coursecode = isset($_POST['coursecode']) ? $_POST['coursecode'] : ''; $both=$code[$x] .' '. $coursecode[$x]; $sqlcourses = "SELECT * FROM courses where course_code='$both' ORDER BY course_id DESC LIMIT 5 "; $resultcourses = $mysqli->query($sqlcourses); if ($resultcourses->num_rows > 0) { while($row = $resultcourses->fetch_assoc()) { ?> </p> <p>&nbsp;</p> <p>&nbsp; </p> <table width="415" border="0"> <tr> <?php $courses=$row["course_code"]; echo $courses; ?> </div> </tr> </table> <?php } } } ?> And which line of code is 262? I just noticed that I need to edit $both to '$both' in the query. Know no errors,but not giving me any result? Your query is failing. At first glance, $both contains a space - $both=$code[$x] .' '. $coursecode[$x];, so it needs to be wrapped in quotes - ...where course_code='$both'.... your for loop doesn't make sense, $code is evaluated up top but defined inside the loop Your loop creates multiple queries, with the last one overwriting all the others. I have removed the for loop and get Notice: Undefined offset: 5 in C:\Apache\htdocs\xxx\addcourse.php on line 252 Notice: Undefined offset: 5 in C:\Apache\htdocs\xxx\addcourse.php on line 252 The line 252 is $both=$code[$x] .' '. $coursecode[$x]; Notice: Undefined offset: 5 tells you that either $code[5] or $coursecode[5] is not set, most likely $coursecode[5]. I just fixed it, though I needed the loop. Thank you all First, you build an array of the course codes that you want to retrieve; I'm leaving off the boundary checks for simplicity: $codes = []; foreach ($_POST['code'] as $k => $code) { $codes[] = $code . ' ' . $_POST['coursecode'][$k]; } Then, you prepare the statement you will use: $stmt = $mysqli->prepare("SELECT * FROM courses WHERE course_code = ? ORDER BY course_id DESC LIMIT 5"); Followed by the main loop: foreach ($codes as $code) { $stmt->bind_param('s', $code); assert($stmt->execute()); $res = $stmt->get_result(); while ($row = $res->fetch_assoc()) { // ... } } you can try this way with small modified code first you have to convert string to array to get index (x) in array $code = explode(" ", $code); $course = explode(" ", $coursecode); foreach ($code as $cd => $x) { $both = $code[$x].' '.$coursecode[$x]; $sqlcourses = "SELECT * FROM courses where course_code='$both' ORDER BY course_id DESC LIMIT 5 "; $resultcourses = $mysqli->query($sqlcourses); } second you can choose variable $code or $course as length of loop based on your case foreach ($course as $crs => $x) { your condition... }
common-pile/stackexchange_filtered
Is it possible to add a diagonal line or slashbox to a very simple template of a table? I have a very simple template of a table I would like to add a slashbox at the top left corner (entry|item), similar to this post LaTeX table cell with a diagonal line and 2 sub cells However, I have tried to add their code on top of the code below, yet I was not able to make it work. Can someone provide a simple solution that creates a slashbox / diagonal line for this table? \documentclass{article} \usepackage{xcolor} \usepackage{bbding} \usepackage{amsthm, thmtools} \usepackage{mathtools} \usepackage{steinmetz} \usepackage{amsmath,amssymb,amsfonts} \usepackage{graphics} \usepackage{cancel} \usepackage{subcaption} \usepackage{sidecap} \usepackage{setspace} \usepackage{verbatim} \everymath{\displaystyle} \setlength\parindent{0pt} \setlength{\footskip}{40pt} \begin{document} \begin{center} \centering\begin{tabular}{ |p{3cm}||p{2cm}|p{2cm}|p{2cm}|p{2cm}|} \hline & entry 1 & entry 2 & entry 3 & entry 4 \\ \hline item 1 & $\%$ & $\%$ & $\%$ & $\%$\\ \hline item 2 & $\%$ & $\%$ & $\%$ & $\%$\\ \hline item 3 & $\%$ & $\%$ & $\%$ & $\%$\\ \hline item 4 & $\%$ & $\%$ & $\%$ & $\%$\\ \hline \end{tabular}\\ \end{center} \end{document} are you sure you want to globally do \everymath{\displaystyle} ?(it makes inline math essentially unusable as inline math, although it can be useful for some special situations where you need to use inline math for technical reasons but want it to look like display @DavidCarlisle I might have added that line as a quick fix for something a long time ago. I am not sure what this line does anymore. it makes inline math essentially unusable? Oh that sounds bad Do you need text to appear in the slashbox as in your linked example? Or just the diagonal line? You can do that with the diagbox package: \documentclass{article} \usepackage{array, diagbox} \setlength\parindent{0pt} \begin{document} \begin{center}\setlength{\extrarowheight}{2pt} \begin{tabular}{ |p{3cm}||*{4}{p{2cm}|}} \hline \diagbox[innerwidth = 3cm, height = 4ex]{}{} & entry 1 & entry 2 & entry 3 & entry 4 \\ \hline item 1 & $\%$ & $\%$ & $\%$ & $\%$\\ \hline item 2 & $\%$ & $\%$ & $\%$ & $\%$\\ \hline item 3 & $\%$ & $\%$ & $\%$ & $\%$\\ \hline item 4 & $\%$ & $\%$ & $\%$ & $\%$\\ \hline \end{tabular} \end{center} \end{document} With {NiceTabualar} of nicematrix, you do need adjustment to the command \diagbox (in fact, it's a command \diagbox provided by nicematrix). \documentclass{article} \usepackage{nicematrix} \begin{document} \begin{center}\setlength{\extrarowheight}{2pt} \begin{NiceTabular}{ |p{3cm}||*{4}{p{2cm}|}}[hvlines] \diagbox{}{} & entry 1 & entry 2 & entry 3 & entry 4 \\ item 1 & $\%$ & $\%$ & $\%$ & $\%$\\ item 2 & $\%$ & $\%$ & $\%$ & $\%$\\ item 3 & $\%$ & $\%$ & $\%$ & $\%$\\ item 4 & $\%$ & $\%$ & $\%$ & $\%$\\ \end{NiceTabular} \end{center} \end{document}
common-pile/stackexchange_filtered
Google Cloud permissions I have a hosted server on Google Cloud Platform (GCP), and I am trying to overwrite some files. I was able to make a connection through WinSCP, and I'm able to find the directory of the files I need to overwrite, however, all files are read-only. How can I manage the permissions to give myself add/change permissions? I agree this seems to be related to permissions on the files. I am not able to comment and wanted to add that if you want to avoid changing the ownership of directory and files, you can always set up a group as an owner. Details can be found on this discussion Summarizing: # groupadd mygroup # useradd -G mygroup user1 # chown -R :mygroup /path/folder # chmod -R g+rw /path/folder Create new group ‘mygroup’ Adds user user1 to mygroup Recursively grants group ownership to content of /path/folder/ to mygroup Recursively grants group read & write permission to contents of /path/folder This will effectively allow you to manage users in mygroup with the appropriate permissions and access. You need to be the owner of the file in order to be able to make changes. For example, if root is the owner of the file, you won't be able to change it (since GCP doesn't allow root access through FTP). What you should do is make you (the user logged through WinSCP) owner of the file using command line and then make changes to the file. Be careful to make the old owner of the file owner again. For example, using Centos and WinSCP you should do this: Login to your server with WinSCP Login to your server through putty or any other command line client in putty: sudo chown YOUR_USER /complete/URL/file/in/your/server.XYZ make whatever changes you need to make to your file in putty: sudo chown OLD_USER /complete/URL/file/in/your/server.XYZ YOUR_USER is the user you are logged in on WinSCP. OLD_USER can be apache, root or whatever If you want to upload a new file you must take ownership of the folder. To do that do not specify the file on the chown command, for instance: sudo chown YOUR_USER /complete/URL/folder/ Once you finish, give back ownership to OLD_USER. This can be a pain but is the only way I found to edit my files in my GCP server... Hope this helps.
common-pile/stackexchange_filtered
Any resource explaining how to get a volume charge density from a surface charge density? Where (book, lecture notes) could one find a clear explanation (better if examples are provided) about how to find the volume charge density in a point given the surface charge density there? I beg your pardon if I haven't been clear. I meant: if I have a charge in a point, i need to multiply it by a 3D delta function to obtain the volume density in that point. The request was how to find the volume density in a point when the surface density is provided. Thanks Tip: Consider to reformulate question purely as a physics question without an explicit resource request. All questions are implicitly resource requests. Explicit res. recom. qs are restricted on Phys.SE.
common-pile/stackexchange_filtered
java.util.Function source code wildcard boundary usage understanding Trying to understand the source code of java.util.Function Have attempted to create my own version of this class, on comparing my version with source code, found one difference - unable to understand the reason behind usage of a generic type boundary. myVersion default <V> MyFunction<T, V> andThen(MyFunction<? super R, V> after) { return t -> after.apply(apply(t)); } javaSource default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) { Objects.requireNonNull(after); return (T t) -> after.apply(apply(t)); } this is pretty much the same as java.util.Function andThen method except that instead of ? extends V, V has been used. why is the type upper bound ? extends V used in andThen method - is there any scenario that will only work with ? extends V and not with V note: I understand the ? super R part is required because without it, we will only be able to chain another function that has the input argument type exactly as R Have the same doubt about the usage of ? super V in compose method also Related: What is PECS (Producer Extends Consumer Super)?. @Slaw this question is not regarding collections with boundary. assuming its designed based on PECS, the ? extends V is the return type implying value would be read and hence it should should be ? super V right. Can you please clarify PECS does not only apply to collections. The concept applies to generics in general. A Function consumes an object and produces a result. This is also related: Difference between <? super T> and <? extends T> in Java. @Slaw, thanks for the clarification. I was of the impression that PECS concept was applicable only to collections as most of the examples use just some collection or other its related to some general answers in PECS but difficult to understand. The user has given clear query which i think should be answered and not be marked as duplicate. The Function interface, and your MyFunction interface, should both be designed with PECS in mind (link What is PECS (Producer Extends Consumer Super)? already supplied by a comment). While MyFunction can compile and be used with a simple return type of V, it can be made more flexible. This example may be a little contrived but it illustrates the flexibility that can be added by making it ? extends V instead. MyFunction<Integer, Integer> first = x -> x + 1; MyFunction<Integer, Integer> second = x -> x * 2; MyFunction<Integer, Number> andThen = first.andThen(second); The last line won't compile unless you make the return type include ? extends V. This allows a function variable to be declared to return a wider type. The V is inferred as Number, and the ? extends V part allows it take functions that return Integer, a subtype. What happens when one needs such flexibility, e.g. when the return type may not be an Integer, but it is a Number? MyFunction<Integer, Double> third = x -> x / 3.0; andThen = first.andThen(third); This is useful when you need to compose functions that may return a different type within the same object hierarchy, e.g. Integer or Double are both Numbers. This flexibility is not possible if you limit the return type to V. The variable andThen can't be used for both results of andThen calls. Sure, you could force a variable type to be the same as the return type of andThen, but there's no reason to limit the flexibility of a user calling your code. Producer extends, for flexibility. Why would someone create a function MyFunction<Integer, Number> andThen = first.andThen(second); when he/she knows that the return type of first.andThen(second) is an Integer.
common-pile/stackexchange_filtered
Calling a powershell function using a .bat file I would like to know how to call a powershell function using a .Bat file. I have this simple function: (Script.ps1) function testfunction { Write-Log "Calling from Bat file" } and I would like to call the function testfunction within the .Bat File. powershell .\Script.ps1 ... What's the reason for still using .bat files since you now have PowerShell? The powershell file has a series of functions and it's located on shared folder. A different batch file is located locally in each server. The batch file needs to execute different functions depending on what each server needs thus the reason why the .bat file needs to call a different function depending on the server environment. I am new to powershell so I figured this would be the easiest way for each server to manage itself. I mean, use another PowerShell script instead of ancient .bat files. great idea. How can I do that? Step 1: learn basic PowerShell. Sure, .bat files are crusty and old, but they're still out there. It's heedless to assume they can always be avoided. I noticed that there is a switch -ExecutionPolicy ByPass which allows the batch file to run using Powershell. This works here, taken from the answer by vonPryz. @echo off :: Create a test script file echo function test { write-host "Called from %~f0" } > s.ps1 powershell -ExecutionPolicy ByPass -command ". "%cd%\s.ps1"; test;" del s.ps1 pause thanks for the ...%cd%.... i didn't know this yet. Start Powershell with -command switch, include the script and call the function. You need to dot source the script before its function can be called. :: Create a test script file C:\temp>echo function test { write-host "Called from .bat" } > c:\temp\s.ps1 C:\temp>powershell -command ". c:\temp\s.ps1; test;" :: Output Called from .bat Also, take a look at some samples. This can be worked around I guess but by default in Windows 8 I receive this error: ---> . : File D:\abc\s.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at http://go.microsoft.com/fwlink/?LinkID=135170. @foxidrive Set the execution policy as per the document you liked to? The problem is that you can't give the advice to any person without also telling them that they have to change the execution policy. It's great for a single machine but not for general scripting advice. @foxidrive I don't quite follow your reasoning. Granted, the OP seems to be lacking basic Powershell skills. Thus extra hint about setting execution policy could be useful. Then again, the error message is quite clear and provides good advice how to change the policy should need be. What I mean is that every solution where this technique is employed also needs a warning that it will not work unless further steps are taken. There is also the likelihood that people in a corporate setting will not be able to disable security settings to make it work. It's not an 'out of the box' technique that will run by itself and that makes it less useful for the class of people that ask questions and don't have technical knowledge. Does that clarify what I mean? I know this is very old but I was recently trying to do this same thing and it took me a long time to find out what to do. The answer is amazingly simple In BatchFile (RunMe) powershell -command ". Script.ps1; Set-SomeFunction %1 %2 %3 %4 %5" Then you can call the batch like RunMe -SomeParm val -SomeParm2 val -SomeSwitch -SomeBool $true also, to run as admin powershell -command "Start-Process -verb runas powershell" "'-noexit -command ". Script.ps1; Set-SomeFunction %1 %2 %3 %4 %5 %6 %7 %8 %9'" I've done it using powershell.exe -ExecutionPolicy Bypass -file ".\Write_date.ps1" Seems similar to what others have written but I'm not sure what vonPryz meant by needing the dot source the script before calling the script. The above worked on a Win7 with executionpolicy set to restricted. I usually do it like that: powershell {Set-ExecutionPolicy unrestricted} powershell.exe -executionpolicy ByPass ./script/powerhsell-script.ps1 %par1% %par2% powershell {Set-ExecutionPolicy Restricted} Hope you need that :)
common-pile/stackexchange_filtered
App Project - Displaying Data Please see attached. I need to represent this data within an App. My thoughts are just to keep it as a list - with pretty icons. The user will be doing nothing with this data, it is just for reference. I did consider putting this info into boxes, but the boxes may look clickable and also will take up more room, making the page even longer than what it already is! What do we think? I think we need some more background to help you sort through this one. What is this app for? Who are your users? What are their goals? I agree with Andrew Martin, is this simple help so people can understand the format of the data? Rather than have it as a lengthy list, why not make it in-line help? Sorting ****Sorting Sort your data by priority and sort those data again. Go through your users and use cases . Ask yourself a question why are you showing all the data. Show only what is required. In mobile cases use tables or sort data by making a super categories. Agreeing to the above (sort by importance, group by category, reduce based on use cases), I have these additional remarks to the actual form you pasted: Instead of one row with two cells listing "Drug" and drug name (which look like groups to me based on the indentation), turn this into a group labelled with the drug name. Instead of littering the labels with an "if applicable" caveat, either don't show not-applicable (i.e., empty) data fields, or indicate "not applicable" in the date field. Move safety ranges or explanations ("if needed < 800mg..") into a third column or a popover or some other control, so they don't interfere with the layout (making the first column too wide for all other entries) or with finding the measure of interest (distracting the user by the need to read/skim additional information). Keep it simple and display data similar to http://nutritiondata.self.com. I don't know what the data is but could you only show the most important things to users? so you don't have longer page and keep it simple? You also could split the list by category and make them collapse. It really depends on your user, but to start, I would begin by sorting the data by both order of importance (important values first) and categories. So separate the data by category to make it less visually intimidating and show important values first so users don't need to search for them.
common-pile/stackexchange_filtered
After upgrading to Xcode 6.3, on launch I now get the error: "The Bonjour service could not be resolved." After upgrading to Xcode 6.3, I now get an alert panel with the error: The Bonjour service could not be resolved. The server may be temporarily unavailable. Contact your system administrator. How can I fix this? This duplicate was put on hold due to being off-topic. http://stackoverflow.com/questions/29644543/the-bonjour-service-could-not-be-resolved Questions about general computing hardware and software are off-topic for Stack Overflow unless they directly involve tools used primarily for programming. This question directly involves Xcode which is primarily used for programming. I'm voting to close this question as off-topic because it was asked and voted off-topic on a duplicate question. http://stackoverflow.com/questions/29644543/the-bonjour-service-could-not-be-resolved Neither mine (closed) or this one is an off-topic, what's wrong with you @DCGoD ? This is a problem many Xcode 6.3 user experience... I voted to reopen this question. I agree with the OP. I'll vote to reopen the other linked question(s) too. (though I would then vote to close one of the questions as a duplicate, probably the other since this has an answer) Either delete or move out the file ~/Library/Application Support/Xcode/XCSServiceManager_KnownServices.plist. I have 0 files inside ~/Library/Application Support/Xcode/ still getting "The Bonjour service could not be resolved" error in Xcode 9. Can you please help here for further troubleshooting? this answer worked for me: https://stackoverflow.com/questions/24788591/xcode-cannot-click-next-while-creating-bots
common-pile/stackexchange_filtered
How to get a JSON object from a file and map it to a Java class using Apache Camel routes? I have created a RequestRoute which extends RouteBuilder: @Component public class RequestRoute extends RouteBuilder { @Override public void configure() throws Exception { from("file:input?noop=true").to(User.class); } And in the main class, I have added the route created above to Camel context: @SpringBootApplication public class DemoApplication { @SneakyThrows public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); CamelContext context = new DefaultCamelContext(); context.addRoutes(new RequestRoute()); } } How can I get a JSON object from a file inside the folder and transform it to a Class using Camel routes? Convert JSON object to POJO is done by unmarshal. Reference How about calling process method and inside of it use ObjectMapper to convert the JSON object to a Java class. Yes, you can do the transformation in java way. You need to do an unmarshal. from("file:input?noop=true") .unmarshal().json(JsonLibrary.Jackson, User.class)
common-pile/stackexchange_filtered
How can I read faster from Kafka I created a new Kafka server (I created 1 broker with 1 partition) and I succeeded to produce and consume from this server using java code, but Im not satisfied from the amount of events that I'm reading per second as a consumer. I have already played with the following consumer setting: AUTO_OFFSET_RESET_CONFIG = "earliest" FETCH_MAX_BYTES_CONFIG = 52428800 MAX_PARTITION_FETCH_BYTES_CONFIG = 1048576 MAX_POLL_RECORDS_CONFIG = 10000 pollDuration = 3000 But no matter what I entered as a value to each one of the setting, the result stayed the same Currently, I produced 100,000 messages to Kafka. each message size is 2 kilobytes and it took 20669 milliseconds or 20 seconds (total time) to read all batches of 100000 records, which means 5000 records per second. I expect it to be much higher, what are the most ideal values ​​that I can set or maybe I need to use other setting or maybe I need to set my Kafka server otherwise (multiple brokers or partitions)? Add more topics. Add more partitions. Ensure you are running multiple concurrent consumers with a decent ratio to the number of partitions (not necessarily 1:1 but equally don't have 100 partitions and one reader). Check for bottlenecks e.g. network, disk etc. Perhaps you need to spread your partitions across multiple disks and/or have clustered kafka setup. edit: I wouldn't be surprised if this thread gets deleted since it's a just 'make it faster' which isn't really a problem Thanks for the answer :) so in fact you are saying that the consumer setting has nothing to do with the performance issue. Further to your answer, I thought maybe to activate multiple consumer instances (using multi thread in java), and each thread will read from different partition, meaning different group id. is that something that you think should work? and why do you think it will be deleted? its a performance problem you can say for the last part - it's a bit generic and a bit of a RTFM. Anyway - yes your consumers should read from a different partition automatically (depending on how it's accessed). It gets into trickier realms though when you're talking about 'performance for example, your partitions may be top heavy (e.g. not evenly distributed). Your bottlenecks could be for multiple reasons (again, it might be slow because the writes are hammering it). It's not necessarily a one size fits all and can take months to hit upon a solutions that meets your requirements. AUTO_OFFSET_RESET_CONFIG will read from message 0 (provided it's not been removed), so might not be the behavior you want - perhaps LATEST is best (again it's as per your requirements though). Look at how you're accessing the kafka instance (through a connector?) is there any contention. If your writes are keeping up I'd say that the issue is with your consumer only though (for now). Ok, at least I have a direction now Thanks! Apart from the settings you mentioned and ignoring horizontal scaling/partitioning: if you are not using compression, do it! From the wiki: If enabled, data will be compressed by the producer, written in compressed format on the server and decompressed by the consumer. lz4 compression type proved to be a good one in my experience, sample settings for the producer: compression.type = lz4 batch.size = 131072 linger.ms = 10 That means less data has to be transmitted in the network and on the other hand more cpu usage for compression/decompression. you can find more info related to the batch and linger time in this other answer I gave related to timeouts, however it is focused on the producer part. Great advice! Thanks! from a fundamental point of view - kafka clients maintain a single socket per "broker of interest" (==any broker that leads a topic partition they care about). over this socket kafka will only do a single request/response at a time (there's a producer setting for max.in.flight.requests.per.connection but the broker only ever serves one at a time). that means that, by and large, if you want more bandwidth you need more sockets and bigger requests. this means multiple brokers and/or multiple clients, and definitely more than a single partition. as for things you can tune for your case (single client, single partition, single socket): FETCH_MAX_BYTES_CONFIG = 52428800 MAX_PARTITION_FETCH_BYTES_CONFIG = 1048576 youre setting the max size of response overall to 50MB, yet limiting the size of data from any specific partition in that same response to 1MB. in your case (1 partition) that means your max response size is effectively 1MB. bump it up. as stated in other answers, you can enable compression for your topic (on the producer side ideally, though the brokers can be configured to "transcode"), and you can also play around with other less-impactful parameters like check.crcs and receive.buffer.bytes for a complete list of consumer configs - see https://kafka.apache.org/documentation/#consumerconfigs so if I understand currently, I should set the MAX_PARTITION_FETCH_BYTES_CONFIG at least as the FETCH_MAX_BYTES_CONFIG if not much more. am I right? i dont think MAX_PARTITION_FETCH_BYTES_CONFIG > FETCH_MAX_BYTES_CONFIG gets you anything extra, but i usually recommend people set both to the same value. Ok great! Thank you for the help!
common-pile/stackexchange_filtered
An example in Yet Another Haskell Tutorial I am new to Haskell. In Yet Another Haskell Tutorial, page Type Basics, I find this example: count2 bTest list = foldr (\x cnt -> if bTest x then cnt+1 else cnt) 0 list but I think that the lambda function \x cnt -> if bTest x then cnt+1 else cnt is not a pure function, given that its behavior depends on something external to the function, namely the function bTest. Is this correct? In Haskell all functions are pure. You can not define this lambda expression at the upper level, since there bTest is unknown. It is thus a function that behaves differently based on the first parameter of count2. The phrase you're looking for is "closure" - a function that references a value outside its own scope. That's not at all the same as being impure, since like all values in Haskell, the closed-over ones must be immutable. Note that pretty much the same reasoning applies to the use of foldr in the definition of count2. Lambda abstractions are expressions which denote function values, much like arithmetic expressions denote numeric values. Both kinds of expressions might refer to variables defined elsewhere, and this does not break "purity"/referential transparency. The value of the arithmetic expression 2*x + 1 depends on the value of x, but that does not make the above code "impure". Consider the function f :: Int -> Int f x = 2*x + 1 This produces the same output value for the same input value, so it it pure. Now, consider the lambda expression \y -> 2*x + y This denotes a function value which depends on x, much like the arithmetic expression depends on x. There's no difference in this regard. Indeed, the function g :: Int -> (Int -> Int) g x = \y -> 2*x + y is pure: given the same x, it returns the same output value, which is a function. And, on top of that, the returned function is pure: given the same y, it returns the same numeric value. To stress the point let h = g 5 in h 23 == h 23 evaluates to True since both h 23 evaluate to 2*5+23. By comparison, this evaluates to False let h1 = g 5 h2 = g 1 in h1 23 == h2 23 since we compare 2*5+23 against 2*1+23. This, however, does not break purity since h1 and h2 are different function values: we are not calling the same function with the same input, and that can indeed produce different results. No this is not correct. The lambda function returns the same output for the same input any time it is called, without any other effects. To do that it does depend on the value of a parameter to the outer function, but that's just a detail. In different invocations of count2 there might be used different values for bTest. In such situations the two lambda function will be different, yes, but the bTest values serve as a hidden implicit input. Still, the same inputs entailing the same output, which is the definition of "pure".
common-pile/stackexchange_filtered
Certificate extension value contains 2 extra bytes (\u0004\u0002) octet encoding for testing purposes my unittest generates a test certificate with custom extensions using BouncyCastle for .NET core. Generate function static internal class CertificateGenerator { public static X509Certificate2 GenerateCertificate(string region) { var randomGenerator = new CryptoApiRandomGenerator(); var random = new SecureRandom(randomGenerator); var certificateGenerator = new X509V3CertificateGenerator(); var serialNumber = BigIntegers.CreateRandomInRange( BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random); certificateGenerator.SetSerialNumber(serialNumber); const string signatureAlgorithm = "SHA1WithRSA"; certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm); var subjectDN = new X509Name("CN=FOOBAR"); var issuerDN = subjectDN; certificateGenerator.SetIssuerDN(issuerDN); certificateGenerator.SetSubjectDN(subjectDN); var notBefore = DateTime.UtcNow.Date.AddHours(-24); var notAfter = notBefore.AddYears(1000); certificateGenerator.SetNotBefore(notBefore); certificateGenerator.SetNotAfter(notAfter); var fakeOid = "<IP_ADDRESS>.<IP_ADDRESS>.345434.345"; if (region != null) { certificateGenerator.AddExtension(new DerObjectIdentifier(fakeOid), false, Encoding.ASCII.GetBytes(region)); } const int strength = 4096; var keyGenerationParameters = new KeyGenerationParameters(random, strength); var keyPairGenerator = new RsaKeyPairGenerator(); keyPairGenerator.Init(keyGenerationParameters); var subjectKeyPair = keyPairGenerator.GenerateKeyPair(); certificateGenerator.SetPublicKey(subjectKeyPair.Public); var issuerKeyPair = subjectKeyPair; var certificate = certificateGenerator.Generate(issuerKeyPair.Private, random); var store = new Pkcs12Store(); string friendlyName = certificate.SubjectDN.ToString(); var certificateEntry = new X509CertificateEntry(certificate); store.SetCertificateEntry(friendlyName, certificateEntry); store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(subjectKeyPair.Private), new[] { certificateEntry }); string password = "password"; var stream = new MemoryStream(); store.Save(stream, password.ToCharArray(), random); byte[] pfx = Pkcs12Utilities.ConvertToDefiniteLength(stream.ToArray(), password.ToCharArray()); var convertedCertificate = new X509Certificate2( pfx, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable); return convertedCertificate; } } Reader public class CertificateExtensionReader { private readonly ILogger logger; public CertificateExtensionReader(ILogger logger) { this.logger = logger; } public CertificateExtensionValues ReadExtensionValues(byte[] certificate) { var x509Certificate2 = new X509Certificate2(certificate); var region = GetCustomExtensionValue(x509Certificate2.Extensions, new Oid("<IP_ADDRESS>.<IP_ADDRESS>.345434.345")); return new CertificateExtensionValues { Region = region }; } private string GetCustomExtensionValue(X509ExtensionCollection x509Extensions, Oid oId) { var extension = x509Extensions[oId.Value]; if(extension == null) throw new CertificateExtensionValidationException($"The client certificate does not contain the expected extensions '{oId.FriendlyName}' with OID {oId.Value}."); if (extension.RawData == null) throw new CertificateExtensionValidationException($"Device client certificate does not a value for the '{oId.FriendlyName}' extension with OID {oId.Value}"); var customExtensionValue = Encoding.UTF8.GetString(extension.RawData).Trim(); logger.LogInformation($"Custom Extension value for the '{oId.FriendlyName}' extension with OID {oId.Value}: '{customExtensionValue}'"); return customExtensionValue; } } public class CertificateExtensionValues { public string Region { get; set; } } Test [TestFixture] public class CertificateExtensionReaderFixture { private ILogger logger = new NullLogger<CertificateExtensionReaderFixture>(); private CertificateExtensionReader reader; [SetUp] public void Setup() { reader = new CertificateExtensionReader(logger); } [Test] public void ShouldReadExtensionValues() { var certificate = CertificateGenerator.GenerateCertificate("r1").Export(X509ContentType.Pfx); var values = reader.ReadExtensionValues(certificate); values.Region.Should().Be("r1"); } } Expected values.Region to be "r1" with a length of 2, but "\u0004\u0002r1" has a length of 4, differs near "\u0004\u0002r" (index 0). So BouncyCastle added two extra bytes \u0004\u0002 (End of transmission, begin of text) for the extension value. I saved the certificate to a file and dumped it via certutil -dump -v test.pfx What am I doing wrong? Is it the generation of the certificate? Or is is how I read the values? Are all extension values encoded this way? I was expecting only the string bytes. I could not find something in the spec. What am I doing wrong? you are creating extension wrong. certificateGenerator.AddExtension(new DerObjectIdentifier(fakeOid), false, Encoding.ASCII.GetBytes(region)); Last parameter is incorrect. It must contain any valid ASN.1 type. Since parameter value is invalid ASN.1 type, BC assumes it is just a random/arbitrary octet string and implicitly encodes raw value into ASN.1 OCTET_STRING type. If it is supposed to be a text string, then use any of applicable ASN.1 string types that fits you requirements and char set. And you have to update your reader to expect ASN.1 string type you chose for encoding and then decode string value from ASN.1 string type. thx. I now add the value using new DerUtf8String(region). Do you know how to read it correctly using .net core only? .NET Core doesn't have ASN data parser. For simple scenarios (when string length is less than 128 chars) you safely can skip first two bytes and remaining bytes will represent encoded UTF-8 string. Yeah that is what I was doing right now. But I felt a bit dirty :D Thanks again. .NET team announced some ASN parser capabilities in .NET 5, but it is a long road. If you really need it now, you can use 3rd party libraries.
common-pile/stackexchange_filtered
Printing figures with thin hulls / double outer layers In Blender etc. many 3D models are composed of objects with double hulls. For instance, an arm might not just a hollow cylinder with a single outer surface but is often "moulded" out of a torus and thus has 2 surface layers like any real world object would have. If one wants to print such a figure the space between these outer layers can be filled by the slicer software but of course the rest of the space within the arm cylinder remains hollow. This can lead to very thin und unstable walls. I don't see a way to fix this aside from redrawing such figures. But maybe one of you has found an ingenious way of fixing this. Would making the model solid work for you? Blender is notorious for creating objects that do not print well. This is because of incorrect use of Blender. Please use the search at the top of the page to find similar questions, this might help you solve the issue or give insight to update the question. If the inner and outer shell are two separate grids, just deleting the inner one will solve the problem. If they are one contiguous grid (with a hole), split it into two at the hole, delete the inner part, and seal the hole.
common-pile/stackexchange_filtered
How do I break this infinite loop Im trying to create a menu. The idea is to make the script loop back to the main menu when the number two is selected. It loops back but when i select number 1 it just keeps looping. How do i fix this. import os import sys def mainmenu(): print """ this is a test menu """ mainmenu() choice = raw_input("DMF>>") if choice == '1': def men1(): print """ this is the second menu """ men1() def back(): men1_actions['mainmenu']() men1_actions = { 'mainmenu': mainmenu, '2': back, } while True: choice2 = raw_input("DMF>>") if choice2 == '2': back() remove while True: to stop looping. Simple! it breaks the loop but exits the script. Im trying to make it go back to the main menu so i can select option 1 again. I'm not sure with what you are pertaining to exactly but you can first define the functions and then just call on one raw_input to indicate whether the input is 1 or 2. def mainmenu(): print """this is a test menu""" def men1(): print """this is the second menu""" while True: choice = raw_input("DMF>>") if choice == '1': mainmenu() elif choice == '2': men1() else: print """Please choose between 1 or 2"""
common-pile/stackexchange_filtered
What exactly is CTF and how can I as programmer prepare for a CTF with beginner-friendly people? I reached out to an old friend of mine who was a terrific programmer back in my school days and he invited me to attend one of the CTF events with his university group. This group seems very beginner friendly and open to everyone, but I still fear that I have not nearly enough knowledge in the security field to be able to participate. So I would like to prepare a bit for it, find out exactly what this is and what I can do to improve to a basic level. Internet research just gave me a very vague idea of what a CTF is. What I already have is basic and intermediate knowledge in some programming languages including C#, PHP/Javascript/etc (basic), C (very basic), Java. I don't know if this is of any use, but I thought it can't hurt. What exactly is a CTF and how can I, as a total beginner, prepare for a CTF event on my own? By the way: this very site has its own CTF team and we (kinda regularly) participate in CTFs. Join us in The DMZ and meet the lovely people that are part of the team! @TomK.: You might want to include that information in the CTF tag wiki. CTFs (Capture The Flag) are like courses within games. Some website provide easy ones to learn the ropes, with simple challenges of increasing difficulty. For example http://overthewire.org/wargames/ will teach you how to use tools (Hex dump, vi, even the terminal itself) with each challenge. The main goal is usually to find some code, either embedded in a file (stegano), hidden in a file inside a server where you will need to abuse a known vulnerability (regular CTFs), or even exploit a program's source code to find a secret password (reversing). Just like any programming challenge, take your time, learn the tools, and don't be afraid to look for help or writeups (obviously not on the CTF you're trying to achieve), but they can provide insight on tools to use, depending on the type of challenge. Some links : https://www.hackthebox.eu/ : Various categories of CTF as explained above, ranging from easy to hard, lots of writeups http://overthewire.org/wargames/ : Mostly regular CTFs with a file hidden in a server, and specific rules to find/decrypt it. Good for beginners, will teach you the basic tools Vulnhub also has a lot of CTF challenges as well as boot2root and others. Most of these come with a walkthrough which is a good way to learn if you are stuck. https://www.vulnhub.com/ To say "CTF" is a little like saying "video game". How do you prepare for a video game? Well, it depends on what the game is! Tetris is very different from Skyrim, which is different from Mario Kart. There is very little that you can do to prepare without knowing a LOT more information. In one CTF I needed to understand networking, TCP/IP, web app design, encryption, and memory forensics. There is no way to prepare for all of that without knowing that it is needed. The one thing that is common to all CTFs is that there are usually a lot of logic puzzles. The best way to prepare for a CTF is to do CTFs. Most of the fun of a CTF is not knowing what you need to know and quickly learning what you need to figure it out. This doesn't explain what a CTF actually is. It says the CTF is like a video game, but never explains what it is. @Clonkex the OP seems to know what a CTF is, technically. I'm answering the "how do I prepare" part. Given that OP's question includes "What exactly is a CTF", it seems like answering that part is also important. What is a CTF? It's a type of computer security competition, called CTF because you capture a "flag", a unique string, and submit it to the scoring infrastructure for points. CTFs are almost always time-limited, often something like 24-48 hours (typically continuous over a weekend, which gives competitors around the world a fair shot regardless of time zone). There are two main kinds of CTFs - jeopardy and attack/defense. Jeopardy-style CTFs are easier to organize and also easier to play / less punishing for new players. In a jeopardy-style CTF, the organizers write a set of challenges (vulnerable binary or web services running on the cloud, crackme-type reversing challenges, things hidden in disk images or packet captures, or encrypted messages), assign point values to each challenge, and make them available to competitors (often on a board like the one from jeopardy, with challenges organized by difficulty and category (binary exploitation, reverse engineering, web exploitation, cryptography, and forensics being the typical categories)). When the competition starts, contestants get access to the grid of challenges, you solve them and submit flags for points, and at the end whoever has the most points wins (ties usually broken by time to reach the winning point total - faster is better). In an attack/defense CTF, the organizers still construct a set of vulnerable services, but each team has to a run a copy of these services, which they have to defend. You hack other teams to steal their flags, and try to patch your own services to prevent other teams from doing the same to you. A/D CTFs entail a lot of extra logistics and infrastructure work for the organizers (VPNs, per-team target hosts, &c). They can also be very demoralizing for new players if you're getting stomped (or someone has persistence on your infrastructure) and there's nothing you can do about it. They can also be a lot of fun though, and they work some unusual skills like binary patching and exploit reflection. In terms of preparation: study, practice, and tooling. Florent Uguet's suggestions for wargames are good for practice. Some other resources you might find useful include: Trail of Bits' CTF Field Guide has some lectures, lists of tools, and walkthroughs of old CTF problems. picoCTF is a CTF aimed at highschool students with very little background. The competition is over, but the organizers have left the problems up for people to learn from. It's a good place to start, and if you have programming experience you're well ahead of the curve and should be able to chew through the early stuff pretty quickly. There's also a new picoCTF coming in October I think. pwnable.kr has a variety of good binary exploitation challenges to practice on. You can often find write-ups of challenges from past CTFs online, which is a good way to get familiar with particularly ctfy idioms or the sorts of problems likely to come up in a particular ctf. ctftime.org aggregates writeups, in addition to hosting a calendar of upcoming ctfs. In terms of tooling, one piece of advice I would offer is to get strong at a scripting language. CTF is generally under time pressure, and speed is more important than perfect correctness. Python seems to be the most common language of choice, and there's a lot of good tooling for ctf-type challenges in python (pwntools, for example). Picking up a little familiarity there might be good too. CTF is basically what it is known under in games. It's Capture The Flag, but instead of a flag to steal you must achieve multiple goals which act as flags. For example a flag in the competition could be to reverse engineer a key validation to develop a key generator. Since you know some programming languages and the basic principles of these, it would be helpfull if you intensify your logic understanding and investigation skills. Look at old CTF's and just do some. If you stumble on problems, research the topics and understand the mechanics. Like Schroeder already said. It's very hard to prepare, since you most probably don't know what will be the tasks. As a personal tip: Relax. You're there with them to learn and just have fun exploring system flaws. Try to have a great time. I notice that most answers seem to avoid your question of "How to prepare for a CTF", hence I will chime in. Firstly, you'll want to do all CTFs from the organizer, especially those with the same title. For example, in the recent TokyoWesterns CTF 2019 (CodeBlue Qualifiers) held last weekend, there was one question, "Slack Emoji Converter Kai" that referenced another CTF question in their previous CTF last year (2018), "Slack Emoji Converter". It required a similar exploitation using Ghostscript and if you did not have the experience, it would have taken an unnecessary amount of time just to read/learn about the exploit. Secondly, you'll want to perform OSINT on the organizers. You want to know who are the members and what they have published/discovered recently. Why should you do this? Just like in the previous example, CTF question writers take inspiration from exploits around them. If they aren't referencing an old exploit, they probably have a new one. The PHPNote question in that CTF required an exploit two of the members jointly published back in June. Teams who were aware of it took just a few hours to make a working exploit, while those who were unprepared took over 12 hours to solve. Read about their recently acquired CVEs and recent publications. Lastly, you'll want to read up on all top-severity exploits within the last 1-2 years (for high level CTFs) or just common/popular exploits (for beginner CTFs). Note that this only applies for normal CTFs. I still don't know of a reliable way to prepare for DEFCON Finals. Learning about exploits only apply if the CTF focuses on exploits. This is why most other answers avoid talking about how to prepare. "CTF" is completely undefined.
common-pile/stackexchange_filtered
Can't install csv module I am a mac user and today I tried installing csv today and here is command pip install csv.But unfortunately it returned the following error Could not find a version that satisfies the requirement csv (from versions: ) No matching distribution found for csv I have Python version 2.7.13 and I have installed other dependencies like scikit-learn,numpy and matplotlib, but for some reason I can't install csv. csv is part of python's standard library so you don't need to install it with pip. Just use it with: import csv
common-pile/stackexchange_filtered
Begin writing a PKCS token on java card I want to start implementing pkcs on java card. I have searched a lot but I couldn't find where to begin. I know that a standard token should support PKCS#11 functionalities and probably PKCS#15. should I read those two standards and just do my best to implement them on my card? Is there any open source implementation of PKCS on Java Card? Regards OpenSC seems useful. @Abraham I have found OpenSC but it only supports off-card part and it also does not support my card. My problem is on-card application. I found IsoApplet and I built it and installed it on my card, but opensc does returns an error saying "Failed to connect to card: Card is invalid or cannot be handled". now I do not know how to fix it and if my applet is okay! Which operation system are you using(Windows/Linux/..)? Can you receive your card's ATR using Opensc-tool (in windows) or pcsc-lite in Linux? The steps are mentioned here clearly. Did you use this website too? Maybe you need to add your card's ATR to openSC libraries. Adding output of Opensc-tool -l and pcsctest to the question and also trying with another reader may be useful. @Abraham I'm using windows and I have made the steps mentioned in the programmer's website. the output to command " opensc-tool -l " is "openpgp-tool.exe: illegal option". I don't know whether the problem is my card type or sth else!!! I have also changed the reader, the problem still remained! @Abraham I got the ATR using "opensc-tool.exe -a" what should I do next? :D I think I have found the problem! when I type "opensc-tool.exe -n" the result is "Unsupported card" ! can I ask what kind of card do you use, if I can find one @Abraham? Have a look at IsoApplet (that does exactly this) https://github.com/philipWendland/IsoApplet I found where the problem is! My card is not compatible with OpenSC, as a result there was a problem connecting to my card and make function. here you can find the list of compatible hardwares.
common-pile/stackexchange_filtered
How do I get the most out of a Science officer in Star Trek Online? I created a science officer, and I got to Lieutenant Commander, but I spent all my upgrades on weapons and ships. I think I'm doing it wrong. What should I be trying to focus on with a science officer? What role should I be playing in combat in single-player missions? Should I be getting security officers as my crew and be in a support role to them when doing ground combat missions? It's been a while since I played so this may be outdated. In most cases, you'll want to try and even out your points across most skills. Maxing out your skills should only be done when you want the extra ability that some skills give you. Generally, I play science officers as a support/debuff space character. I usually focus on shield drains, tractor beams, and "healing" powers. When on ground missions, I focus on setting up expose/exploit attacks. My ground crew is usually a mix of Tactical, Science, and Engineering officers. What you want to do is to find powers and abilities that mesh with your play style. Hope that helps.
common-pile/stackexchange_filtered
Is there a way to wrap an entire javascript so it only runs on a specific HTML ID? I have inherited a third party Javascript - it's about 7000 lines when de-minified - that I need to use to open and close a panel of content when a link is clicked. It works fine when I import the HTML and js file to a content module in my CMS (DNN) but has the unfortunate side effect of breaking the bootstrap hamburger menu when the page is viewed on a mobile device. I have neither the time nor JS skill to work out exactly how 7000 lines of script work, which bits I actually need and then adjust them so they only do what I need them to and not impact on the menu. What I am hoping is that there is some way I can wrap the entire script so that it only applies to a specific area of the HTML and not to the menu area. I can easily assign an ID to the div that contains the code where I want it to operate. So is there was way to do this - a way of testing at the start of the script that the current element matches the ID I assign, if it does then enable all functions in the entire script and if not then do nothing? Update after reading initial replies... The offending code can be seen at https://dnnplaypen.epicservices.com.au/application The JS file (unminified version) can be found at https://dnnplaypen.epicservices.com.au/portals/0/scripts/main.unmin.js - I believe it may in fact be a complete BootStrap JS implementation which possibly explains the conflict. and this is the relevant section of the HTML... <a href="#MemberTypes" class="btn btn-link" data-toggle="collapse" role="button" aria-expanded="false" aria-controls="MemberTypes">View them.</a></p> <div id="MemberTypes" class="collapse"> <p style="margin-left:20px;"><img src="/portals/0/Images/OrangeDot.png"> &nbsp;<span style="font-weight:bold">Civil Intrastructure (CIM) Entrant</span></p> <p style="margin-left:40px;">(Works in the civil industry and either supervises 1 or more people or has a civil university qualification e.g. leading hands, site supervisors, engineers, project managers, CEOs)</p> <p style="margin-left:40px;">You’ll answer some questions about your qualification & employment details to confirm your eligibility.</p> <p style="margin-left:20px;"><img src="/portals/0/Images/OrangeDot.png"> &nbsp;<span style="font-weight:bold">Student</span></p> <p style="margin-left:40px;">(Studying civil-related course at university at least 50% of the time)</p><p style="margin-left:40px;">Please have current enrolment document(s) as evidence.</p> <p style="margin-left:20px;"><img src="/portals/0/Images/OrangeDot.png"> &nbsp;<span style="font-weight:bold">Affiliate</span></p><p style="margin-left:40px;">i.e. Part of the supply chain servicing the industry</p> </div> Any assistance in identifying which part of the JS is invoked when the link is clicked would be much appreciated. A script doesn't "apply" to any part of the HTML. It just runs and makes whatever changes it wants to the DOM. There's no way to say "this part of the DOM is off limits". Unfortunately there's no simple answer for this without seeing code. If you have 7000 lines of code, it is quite certainly not something that can just be "wrapped" and all applied to one element. There will be a lot of logic throughout the code that does all sorts of things. If you can't post example code, try examining the HTML of the elemens you want to fix and then search inside the JS code for the code that selects those DOM nodes using classes, IDs, tag names, attributes. remove the bootstrap, write your own code. Possibly. First, opening and closing an element on a click shouldn't take even 7 lines of code, let alone 7000. Refusing to look into that code is dereliction. Just throwing it into an app without knowing what it does is irresponsible. Second, your best bet may be to use DevTools to trace the click event. In Chrome you open the Sources panel, and in Firefox you open the Debugger panel. On the right side, near the top, there is a pause icon. Click that, then click the part of the webpage that toggles the content. If you're lucky, the debugger will halt execution on the first statement in the toggle codepath, which you can and should step through. Third, the strategy we'll use is to wrap the entire block of code inside a function that exposes a fake version of the DOM API. This 7k block of mystery code is ultimately using some of the basic DOM methods to identify and manipulate the relevant elements. Your goal will be to create a fake version of that API that only returns the specific element you care about. You'll add an ID or other identifying attribute to the element in question, and then return that element whenever the mystery code invokes your API (which it will think is the real API). Here is a simple example: // first, get our hands on the one element you want the mystery code to see const elementThatShouldToggle = document.getElementById('target-element') // second, construct an object that provides methods with the same names as what the real document provides const fakeDOM = { // normally, document.getElementById takes an argument // your fake version will ignore that arg and just return the content el getElementById: () => elementThatShouldToggle, // you may need to mock several DOM accessor methods querySelector: () => elementThatShouldToggle, querySelectorAll: () => [elementThatShouldToggle] } // third: wrap the mystery code in a function that uses variable shadowing to obscure the real DOM, substituting your fake DOM instead (function sandbox(document) { /* paste the 7000 lines of mystery code here */ })(fakeDOM) There are drawbacks to this approach: You'll need to create fake versions of every DOM method that the mystery code uses; this will require you to run the app several times and look for exceptions. For every exception, you'll need to study the stack trace to identify any DOM methods that are implicated, and then create mocks that return safe values. If the mystery code uses the same DOM methods as the code you like, your fake API implementations will have to be a little smarter. You may need to set up branching behavior in your fake methods that return the real elements in some cases, and safe values for all other cases. Again, this will be a guess-and-test affair. Once the mystery code has its hands on a real DOM node, it can use the API on that node to access the entire rest of the document. It's probably not an evolving threat, so it's probably enough to then also mock the DOMNode API on the element that you provide to the mystery code. There may be calls inside the mystery code that does scary or bad things but without using the APIs that you're studying. If you do nothing to detect or prevent that, then the bad stuff will happen, and injecting this code into your app will inject the bad stuff, too. How will you know when you've done enough guessing and testing? Well, because you refuse to study the 7000 lines of code, there's really no way to be sure. For all we know, there's a setTimeout buried in there that does something really interesting after 45 minutes. The only way to figure that out would be to wait for 45 minutes. With this mocking strategy, it is guaranteed that you will write far more new code than if you just wrote your own toggle script. This is hard mode. It will be complicated, tedious, brittle, and even after all of that it will not provide the guarantee that you want. A better approach would be to use the debugger to study the codepath that gets invoked on click, and then extract that code or write a replacement. Toggling some content is generally a near-trivial task. If you need help doing that, there are countless tutorials online, no doubt including some Q&As here on SO.
common-pile/stackexchange_filtered
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.example.whatsappclone.User I am not able to retrieve data from Firebase it always crashes saying: com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.example.whatsappclone.User This is My Model Class public class User { String uid, name, phoneNumber, profileImage; public User() { } public User(String uid, String name, String phoneNumber, String profileImage) { this.uid = uid; this.name = name; this.phoneNumber = phoneNumber; this.profileImage = profileImage; } public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getProfileImage() { return profileImage; } public void setProfileImage(String profileImage) { this.profileImage = profileImage; } } This is My ViewHolder Class public class UsersAdapter extends RecyclerView.Adapter<UsersAdapter.UsersViewHolder> { Context context; ArrayList<User> users; public UsersAdapter(Context context, ArrayList<User>users) { this.context = context; this.users = users; } @NonNull @Override public UsersViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.conversation_layout, parent, false); return new UsersViewHolder(view); } @Override public void onBindViewHolder(@NonNull UsersViewHolder holder, int position) { User user = users.get(position); holder.binding.userName.setText(user.getName()); Glide.with(context).load(user.getProfileImage()) .into(holder.binding.profile); } @Override public int getItemCount() { return users.size(); } public class UsersViewHolder extends RecyclerView.ViewHolder { ConversationLayoutBinding binding; public UsersViewHolder(@NonNull View itemView) { super(itemView); binding = ConversationLayoutBinding.bind(itemView); } } } This is My MainActivity public class MainActivity extends AppCompatActivity { ActivityMainBinding binding; FirebaseDatabase database; ArrayList<User> users; UsersAdapter usersAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivityMainBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); database = FirebaseDatabase.getInstance(); users = new ArrayList<>(); usersAdapter = new UsersAdapter(this, users); binding.recyclerView.setAdapter(usersAdapter); database.getReference().child("users").addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { users.clear(); for (DataSnapshot snapshot1 : snapshot.getChildren()) { User user = snapshot1.getValue(User.class); users.add(user); } usersAdapter.notifyDataSetChanged(); } @Override public void onCancelled(@NonNull DatabaseError error) { } }); } } My Firebase database Structured Firebase Database Strucuture Firebase JSON { "users" : { "A5DEg64d47StvLuvRtLWiu1bHSC3" : { "name" : "Rahul Singh", "phoneNumber" : "+918350877517", "profileImage" : "https://firebasestorage.googleapis.com/v0/b/whatsapp-clone-b908d.appspot.com/o/Profiles%2FA5DEg64d47StvLuvRtLWiu1bHSC3?alt=media&token=55fcdc75-da0c-43f5-8f9c-44bfa7df500f", "uid" : "A5DEg64d47StvLuvRtLWiu1bHSC3" }, "CO6Yw59BHweNJ03UdbcsGq4kyXY2" : { "name" : "Alok Bhai", "phoneNumber" : "+919886542409", "profileImage" : "https://firebasestorage.googleapis.com/v0/b/whatsapp-clone-b908d.appspot.com/o/Profiles%2FCO6Yw59BHweNJ03UdbcsGq4kyXY2?alt=media&token=b006e40d-e8df-4b96-9165-d980cd018af3", "uid" : "CO6Yw59BHweNJ03UdbcsGq4kyXY2" }, "F8mhqJk4POeLFWxpF373K2D8DYG2" : { "name" : "radhe govind'", "phoneNumber" : "+916378757808", "profileImage" : "No Image", "uid" : "F8mhqJk4POeLFWxpF373K2D8DYG2" }, "NOt57HC59DZm1s5XaBk0mHb9H553" : { "name" : "Mohit Dada", "phoneNumber" : "+917853471027", "profileImage" : "https://firebasestorage.googleapis.com/v0/b/whatsapp-clone-b908d.appspot.com/o/Profiles%2FNOt57HC59DZm1s5XaBk0mHb9H553?alt=media&token=6aba255c-5f96-4ba1-a4a4-b998d3ae5b4a", "uid" : "NOt57HC59DZm1s5XaBk0mHb9H553" }, "XnJUq8LzauZPCLCi5v4SeCGgSPa2" : { "name" : "Alok Singh Deshwal", "phoneNumber" : "+919960726182", "profileImage" : "No Image", "uid" : "XnJUq8LzauZPCLCi5v4SeCGgSPa2" }, "ZIcwyjMGC3Yk5GrT7vIeTxphQPt2" : { "name" : "Anku Bhai", "phoneNumber" : "+919094974311", "profileImage" : "https://firebasestorage.googleapis.com/v0/b/whatsapp-clone-b908d.appspot.com/o/Profiles%2FZIcwyjMGC3Yk5GrT7vIeTxphQPt2?alt=media&token=5773be33-d610-4f8d-8bbd-d655e5228666", "uid" : "ZIcwyjMGC3Yk5GrT7vIeTxphQPt2" }, "kE3i5DsP9DTorG5DkJ4Vy7nArwZ2" : { "name" : "Prinshu", "phoneNumber" : "+91989600555", "profileImage" : "https://firebasestorage.googleapis.com/v0/b/whatsapp-clone-b908d.appspot.com/o/Profiles%2FkE3i5DsP9DTorG5DkJ4Vy7nArwZ2?alt=media&token=e4d13d95-3906-4bdf-aaac-028816e490d5", "uid" : "kE3i5DsP9DTorG5DkJ4Vy7nArwZ2" }, "name" : "Vivek Fauzdar", "phoneNumber" : "+916486627517", "profileImage" : "https://firebasestorage.googleapis.com/v0/b/whatsapp-clone-b908d.appspot.com/o/Profiles%2FA5DEg64d47StvLuvRtLWiu1bHSC3?alt=media&token=cf8613fb-ae66-4892-bd79-4affa89d86e4", "uid" : "A5DEg64d47StvLuvRtLWiu1bHSC3", "vYfKxxkvoCV0p4c4P64t3F1IrEn1" : { "name" : "Om Swami", "phoneNumber" : "+919887012345", "profileImage" : "No Image", "uid" : "vYfKxxkvoCV0p4c4P64t3F1IrEn1" } } } If the app crashes, there is a stack trace. Please look that up on logcat, and add it to your question. the app is crashing at com.example.whatsappclone.MainActivity$1.onDataChange(MainActivity.java:46) which is User user = snapshot1.getValue(User.class); Please edit your question and add your database structure as a JSON file. You can simply get it by clicking the Export JSON in the overflow menu (⠇) in your Firebase Console. Please Check Sir You are getting the following error: com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.example.whatsappclone.User Because under your "users" there aren't only User objects, there are also strings: "name" : "Vivek Fauzdar", "phoneNumber" : "+916486627517", "profileImage" : "https://firebasestorage.googleapis.com/v0/b/whatsapp-clone-b908d.appspot.com/o/Profiles%2FA5DEg64d47StvLuvRtLWiu1bHSC3?alt=media&token=cf8613fb-ae66-4892-bd79-4affa89d86e4", "uid" : "A5DEg64d47StvLuvRtLWiu1bHSC3", When you are using the following line of code: User user = snapshot1.getValue(User.class); It means that you are trying to map each child into an object of type User, which isn't possible since you are mixing User objects with strings, hence that error. The simplest solution would be to remove all those strings and make sure you have only User objects under the "users" node. The code looks good to me. See, all these children exist right under the "users" node. sir sorry I m a beginner and I did not get it completely, can u further explain please Have you tried to remove those 4 String values that exist at the bottom of your JSON file? Does it work after you delete them? no sir it is not working It's really hard to help with "it is not working". What exactly didn't work? Please export the changed JSON file and add it to your question to see that those 5 strings are gone. sir, i have to remove those strings from User.class file??? No, from the Database. Open the Firebase console and remove them. Have you removed the those four strings from the database? sir should i delete them? Sir I have deleted them from firebase. Perfect, does it work right now? it is working sir but i did not get it why it is working now and not before?? Once you have only User objects and not strings, all children will be mapped successfully. if "users" is first layer of database children it will be a reference instead of database.getReference().child("users").addValueEventListener ... use database.getReference("users").addValueEventListener ... if "users" is a child or an upper reference database.getReference("upperReference").child("users").addValueEventListener ... This is occurring because there is a requirement to transform your data into a Firebase node. I have coded the same in java ,and it is working fine This should be your firebase hierarchy Check this image , in this under the user child we have one another key which is your uID The error you're encountering will be resolved when you update the current code with the following modification: database .getReference() .child("users") .child(uid) .setValue(user) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void unused) { Intent intent= new Intent(SetUpProfileActivity.this,ActivityMainChat.class); startActivity(intent); } }); Make sure you add .child(uid) database.getReference().child("users").child(uid).setValue(user)...
common-pile/stackexchange_filtered
Define a pointer with an arbitrary span If I have a large array where the data streams are interleaved in some complex fashion, can I define a pointer p such that p + 1 is some arbitrary offset b bytes. For example lets say I have 1,000,000 ints, 4 bytes each. int* p_int = my_int_array; This gives me *(p_int+1) == my_int_array[1] (moves 4 bytes) I am looking for something like something_here(b)* big_span_p_int = my_int_array; which would make *(big_span_p_int + 1) == my_int_array[b] (moves 4*b or b bytes, whichever is possible or easier) Is this possible? easy? Thanks for the help. EDIT: b is compile time variable. Since *p_int = my_int_array[0], then *(p_int+1) == my_int_array[2] should actually be *(p_int+1) == my_int_array[1]. It's still a good question, I upvoted :) Your question is unclear because if you have an int* it already moves 4 bytes every time you add 1 to it (if int is 4 bytes wide). So what do you want that is different from what currently happens? So, why do you want it to have a built-in "span"? If you want to move an int *p pointer by b * sizeof(int) bytes, you can simply do p += b. Creating a pointer with a built-in span that jumps the same distance when incremented by 1 is just syntactic sugar. Granted, it can be useful in generic code... But what exactly are you doing that prevents you from just using p += b? @AnT I assume the answer to that is generic code, perhaps involving the complex interleaving mentioned in the first sentence. You don’t need a page on why to answer “Make a class with binary operator+, unary operator*, operator->, etc.”. This is in fact what I intend to do when I’m less busy, if nobody beats me to it. Using some of your code. There is no need to declare an additional pointer/array. Applying pointer arithmetic on p_int is enough to traverse and reach the number value you are seeking. Let's look at this example: int main() { int my_int_array[5] {1,2,3,4,5}; int* p_int = my_int_array; int b = 2; std::cout << *(p_int + b) << std::endl; // Output is 3, because *p_int == my_int_array[0], so my_int_array[2] will give you the third index of the array. } Graphically represented: Memory Address | Stored Value (values or memory addresses) ---------------------------------------------- 0 | ..... 1 | ..... 2 | ..... 3 | ..... 4 | ..... 5 | ..... 6 | ..... 7 | ..... 8 | ..... . | ..... . | ..... . | ..... n-1 | ..... Imagine the memory as being a very big array in which you can access positions by its memory address (in this case we've simplified the addresses to natural numbers. In reality they're hexadecimal values). "n" is the total amount (or size) of the memory. Since Memory counts and starts in 0, size is equivalent to n-1. Using the example above: 1. When you invoke: int my_int_array[5] {1,2,3,4,5}; The Operating System and the C++ compiler allocates the integer array memory statically for you, but we can think that our memory has been changed. E.g. Memory address 2 (decided by the compiler) now has our first value of my_int_array. Memory Address | Name - Stored Value (values or memory addresses) ----------------------------------------------------- 0 | ..... 1 | ..... 2 | my_int_array[0] = 1 3 | my_int_array[1] = 2 4 | my_int_array[2] = 3 5 | my_int_array[3] = 4 6 | my_int_array[4] = 5 7 | ..... 8 | ..... . | ..... . | ..... . | ..... n-1 | ..... 2. Now if we say: int* p_int = my_int_array; The memory changes again. E.g. Memory address 8 (decided by the compiler) now has a int pointer called *p_int. Memory Address | Name - Stored Value (values or memory addresses) ----------------------------------------------------- 0 | ..... 1 | ..... 2 | my_int_array[0] = 1 3 | my_int_array[1] = 2 4 | my_int_array[2] = 3 5 | my_int_array[3] = 4 6 | my_int_array[4] = 5 7 | ..... 8 | p_int = 2 (which means it points to memory address 2, which has the value of my_int_array[0] = 1) . | ..... . | ..... . | ..... n-1 | ..... 3. If in your program you now say: p_int += 2; // You increase the value by 2 (or 8 bytes), it now points elsewhere, 2 index values ahead in the array. Memory Address | Name - Stored Value (values or memory addresses) ----------------------------------------------------- 0 | ..... 1 | ..... 2 | my_int_array[0] = 1 3 | my_int_array[1] = 2 4 | my_int_array[2] = 3 5 | my_int_array[3] = 4 6 | my_int_array[4] = 5 7 | ..... 8 | p_int = 4 (which means it points to memory address 4, which has the value of my_int_array[2] = 3) . | ..... . | ..... . | ..... n-1 | ..... When doing memory allocation and pointer arithmetic in a simple case like this, you don't have to worry about the size in bytes of an int (4 bytes). The pointers here are already bound to a type (in this case int) when you declared them, so just by increasing their value by integer values, p_int + 1, this will make point p_int point to the next 4 bytes or int value. Just by adding the values to the pointers you will get the next integer. If b is a constant expression (a compile-time constant), then pointer declared as int (*big_span_p_int)[b] will move by b * sizeof(int) bytes every time you increment it. In C you can use a run-time value in place of b, but since your question is tagged [C++], this is not applicable. Thanks, unfortunately, I am looking for a span based on compile time variable, not constant. I updated the question to clarify.
common-pile/stackexchange_filtered
MsTeams chatbot, OnTeamsCardActionInvokeAsync method is being hit twice Learning about chatbot for MsTeams, I am facing an issue with : WebApp DialogBot.cs class, method OnTeamsCardActionInvokeAsync It is being called twice sometimes and I can reproduce the behavior when debugging. Not only this method but in general other methods as well are hit twice coming from MsTeams. These two calls to this method causes my service to respond twice and duplicated messages are displayed in MsTeams chatbot. Would you know if it is a known issue or if there are some approaches to avoid this behavior? When debugging it happens. Because the execution is paused for sometime and MSTeams assumes it's not responding so it sends another request just to make sure it gets the response. But as it's stopped because of debugging it responds to all request sent. @Prasad-MSFT thank you for your feedback. You are right , it happens always when debugging. My issue is that it also happens sometimes when executing without debugging, just the chat bot already deployed in Azure. Do you mean Teams sends a second request in case service response is delayed some seconds ? Why it is happening in execution without debugging ? Is there a way to avoid that behavior? Yes Alberto, MS Teams sends another request when service response gets delayed. Not able to get proper resolution to avoid this yet.
common-pile/stackexchange_filtered
Completion Handler to trigger collectionView Reload once Images are downloaded - Xcode [SWIFT] I'm using a code I got off here to download some images and present them in a collection view. Heres the code: func downloadImage (url: URL, completion: () -> Void){ let session = URLSession(configuration: .default) let downloadPicTask = session.dataTask(with: url) { (data, response, error) in if let e = error { print("Error downloading image \(e)") } else { if let res = response as? HTTPURLResponse { print("Downloaded image with response code \(res.statusCode)") if let imageData = data { let image = UIImage(data: imageData) self.globalImages.append(image!) print("what does this say?-->", self.globalImages.count) } else { print("Couldn't get image: Image is nil") } } else { print("Couldn't get response code for some reason") } } } completion() downloadPicTask.resume() } And I'm calling the download image in view did load where URL is the URL. (this URL works and I can download image). downloadImage(url: url) { () -> () in collectionView.ReloadData() } The completion handler I've tried calls reloadData() way too soon. I'm wanting it to be called when the image is finished downloading? so then the image can be displayed as soon as it's downloaded. What is wrong with this code? Please help! You would call the completion handler as soon as you have the image. So, in your code: if let imageData = data { let image = UIImage(data: imageData) self.globalImages.append(image!) print("what does this say?-->", self.globalImages.count) // call the completion handler here Be aware, though, that you are likely to have other issues caused by data sharing across multiple threads, and also that your idea of storing the downloaded images successively in an array (globalImages) is not likely to work correctly. it doesn't let me put the completion handler there. It has error Escaping closure captures non-escaping parameter 'completion' https://stackoverflow.com/questions/59784963/swift-escaping-closure-captures-non-escaping-parameter-oncompletion
common-pile/stackexchange_filtered
How do i stop/cancel the segue when UIAlertView triggered I got a button that leads to a tableViewController. I created UIAlertView that gets triggered when the resultArray is null, which also means there is nothing to show on tableView but when user clicks ok, nothing changes and it goes to empty tableView. How can I stop going into the other view controller? this is my code if (refilteredArray.count==0) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No result" message:@"Please enter a different combination." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; } The segue is not triggered with code, its a button triggered IBAction - (IBAction)motorButton:(id)sender { ... } you can use following method - (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender in the method body you can verify if your array is empty or not and if it is return NO. To be more specyfic you should check your segue identifier (remember to add it to your segue in IB first) You need to go for if.. else block if (refilteredArray.count==0) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No result" message:@"Please enter a different combination." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; }else{ [self performSegueWithIdentifier:@"yourSegue" sender:sender]; } For more info, check this link about segue well thats the problem, its an (IBAction)motorButton:(id)sender { its not triggered with code Just put this code in the IBAction and delete the segue at storyboard. Just do it by programmatically how do i set a connection without the direct connection from storyboard how can i accomplish that
common-pile/stackexchange_filtered
Given $P(A|B), P(A|B^c)$ and $P(B|A)$ how do I find $P(A)$ and $P(B)$ For reference sake: $P(A|B) = 1/3$, $P(A|B^c) = 2/3$ $P(B|A) = 1/2$ Now, I know $P(A∩B) = P(A|B)*P(B)$ and that $P(A|B^c) = P(A∩B^c)/P(B^c)$ But where to go next I do not know. I think I need to find either $P(A∩B)$ or $P(A∩B^c)$ which I would be able to sub into the earlier equations to find $P(A)$ and $P(B)$ with ease, but how to do that I don't know. Am I missing an equation or am I just missing something that's staring me in the face? Thank You Are you familiar with Baye's theorem ? It will give you a start point If not the Bayes' theorem then consider that from the first equation $$P(B)=\frac{P(A\cap B)} {\frac13}$$ and from the second one $$1-P(B)=\frac{P(A\cap B)} {\frac23}.$$ The quotient of the two is $$\frac{P(B)}{1-P(B)}=2.$$ From the third equation we learn that $$P(A)=\frac{P(A\cap B)}{\frac12}.$$ We can do the trick above again and we already know $P(B)$. $$P(A|B)=\frac{P(B|A)P(A)}{P(B|A)P(A)+P(B|A^c)P(A^c)}$$ and rearrange. With regards to finding $P(B)$, swap $A$ with $B$ in the formula wherever either occurs. $$P(B|A^c)=1-P(B|A)=\frac{1}{2}$$
common-pile/stackexchange_filtered
Minimum time lock in java I'm looking for a way to limit access to a method in java to no more than once every X seconds. Here's my situation : I want to run this code in parallel with multiple threads : private MyService service; public void run() { // Send request to remote service InputStream response = service.executeRequest(); // Process response ... some more code } The executeRequest() method sends an http request to a remote server (which isn't mine, I have no access to its implementation) and waits for the response from the server. It then does some processing of the data. I would like to have many threads run this in parallel. My problem is that the remote server will crash if too many requests are sent simultaneously. So I want some way of making sure that the executeRequest() method will never be called more than once every second. Do you know how I could do that in java ? Thanks What about limiting the number of concurrent executions and blocking new calls until a service instance is available? Are you using any particular technology for your remote server? The remote server isn't mine. MyService.executeRequest sends an http request to the remote server and waits for the response. I have no control over it. You could use a Semaphore to throttle the number of threads able to call executeRequest(): http://download.oracle.com/javase/1,5,0/docs/api/java/util/concurrent/Semaphore.html The executing thread could increment the semaphore prior to entering the execute and other threads could wait for it to fall to either 0 or a number which reflects how many are allowed to run in parallel. A Timertask: http://download.oracle.com/javase/1.4.2/docs/api/java/util/TimerTask.html Could be used to decrement the semaphore after 3 seconds... Throttling the entry to no more than 1 new entrant every 3 seconds: Hrm, I'm not sure that restricting the frequency of access to a method will result in prevention of overload. Perhaps there isn't enough info in the above post, but it seems that a WorkerThread + JobQueue setup would work just fine here. Food for thought: Multithreaded job queue manager EDIT: Trying to be a bit less vague... Have the server collect the requests into some data structure, perhaps a class called Job. Have Jobs then be placed into the bottom of a Queue. Have WorkerThread objects pop Job objects off the top of the Queue and process them. Make sure to only instantiate as many WorkerThread objects as you need to maintain proper server load. Only experimentation will determine this number, but as a very rough rule, start with # of processing cores - 1. (aka start 7 workers on an 8 core machine) EDIT #2 In light of new information: Setup a Queue on the client side Make a Worker that can track what Jobs have been submitted, which Jobs have gotten a response and which Jobs are still processing. This will allow for limiting the number of Jobs being submitted at any one time. Make Worker track 'lastSubmissionTime' to prevent any submission occuring < 1 second from previous Sorry, i wasn't precise enough. The remote server isn't mine. I'm sending http requests to the remote server and waiting for the response. I don't know how it's built, but sending too many requests in too short intervals will make it crash, which is why i want to limit the number of requests i'm sending to one every second Ah, in that case, build the Job and JobQueue on the client side and have a single Worker manage the Job submissions to the server. You could set it up so that the Worker submits one job per second, or you could have the Worker keep track of how many outstanding jobs there are by tracking submissions AND responses... or do both :) Limiting concurrency on the client side is not a good pattern — how are clients supposed to know about each other? In your controller class where you call worker to execute the service, use ExecutorService to start the pool of threads to ultilize the worker class. ExecutorService pool = Executors.newFixedThreadPool(10); pool.submit(new MyServiceImpl(someObject)); To add to what others have already suggested, Have a worker class to take task from the queue execute and wait for the number of minutes as you require before taking another task from the queue. I have made this 2min as an example. Example: public class MyServiceImpl implements MyService , Runnable { public static final int MAX_SIZE = 10; private final BlockingQueue<Object> queue = new ArrayBlockingQueue<Object>(MAX_SIZE); @Override public void run() { try { Object obj; while ((obj==queue.take()) != null) { executeRequest(obj); //wait for 2 min Thread.sleep(1000 * 60 * 2); } } catch (InterruptedException e) {} } public void executeRequest(Object obj) { // do routine } public MyServiceImpl (Object token) { try { queue.put(token); } catch (InterruptedException e) { throw new AssertionError(e); } } } Using dynamic proxy you can wrap your service and handle max execution in the InvocationHandler: MyService proxy = (MyService) Proxy.newProxyInstance( // MyService.class.getClassLoader(), // new Class[] {MyService.class}, // new MaxInvocationHandler()); where naive implementation of InvocationHandler could look something like this: class MaxInvocationHandler implements InvocationHandler { private static final long MAX_INTERVAL = 1000L; private static final long MAX_INVOCATIONS = 1; AtomicLong time = new AtomicLong(); AtomicLong counter = new AtomicLong(); @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { long currentTime = System.currentTimeMillis(); if (time.get() < currentTime) { time.set(currentTime + MAX_INTERVAL); counter.set(1); } else if(counter.incrementAndGet() > MAX_INVOCATIONS) { throw new RuntimeException("Max invocation exceeded"); } return method.invoke(proxy, args); } } Have you thought about using sleep to have the threads pause before jumping to hit the remote call? You could have the threads sleep for a random # of seconds between 1 and 5 which would limit the number of threads hitting the method at any one time. You could also put a lock on the method that expires after 1 second so each thread "grabs" the lock, executes the method, but its lock expires so the next thread can grab it and execute. Put the lock at the beginning of the method -- and have it do nothing except hold the thread for one second thread.sleep(1000) and then continue execution. That will limit you to one thread hitting the method at a time. EDIT: Response to OP's Comment Below class X { private final ReentrantLock lock = new ReentrantLock(); // ... public void m() { lock.lock(); // block until condition holds try { thread.sleep(1000) //added to example by floppydisk. } finally { lock.unlock() doYourConnectionHere(); } } } Modified from: ReentrantLock. Inside the try/catch, all you do is thread.sleep(1000) instead of actually doing something. It then releases the lock for the next thread and continues executing the rest of the method body--in your case the connection to the remote server. Your first suggestion doesn't really work for me, because there is nothing preventing two threads from awakening at the same time and calling the service almost simultaneously. Your second suggestion is kind of what i'm looking for but I haven't found an example of it. @jonasr: Updated the answer to provide a better code example. The problem with this is that every thread will wait 1 second before calling the method even if they don't have to. It's maybe not much but if I need to increase the delay it could be a problem Part of the problem with threading is you cannot guarantee order of execution. If you start two threads, thread1 and thread2 you cannot assume that thread1 will access the method before thread2 takes a shot at it based on how the processor's scheduler works. If you need to increase delay, use the random time wait idea. that would space out execution even more.
common-pile/stackexchange_filtered
Creating a new Java project I am able to create a default project in PDE just like mentioned here. However I want to know how to create a Java project. How can I do that? As a minimum you need to add the Java project nature to the project you create. Use something like: private void addNatureToProject(IProject proj, String natureId, IProgressMonitor monitor) throws CoreException { IProjectDescription description = proj.getDescription(); String[] prevNatures = description.getNatureIds(); String[] newNatures = new String[prevNatures.length + 1]; System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length); newNatures[prevNatures.length] = natureId; description.setNatureIds(newNatures); proj.setDescription(description, monitor); } The nature id for a Java project is 'org.eclipse.jdt.core.javanature' (also in the JavaCore.NATURE_ID constant). Note that this does not add the various builders that are normally used in a Java project. The IProjectDescription.setBuildSpec method adds those in a similar way. Create a command for the build spec with: ICommand command = description.newCommand(); command.setBuilderName(builderID); where 'builderId' is 'org.eclipse.jdt.core.javabuilder' for the main Java builder (JavaCore.BUILDER_ID constant). All this information is stored in the '.project' file in the project root folder. This is an XML file which you can look at to see the set up of existing projects. Please refer to New Project Creation Wizards On the Plug-in Project page, use com.example.helloworld as the name for your project and check the box for Create a Java project (this should be the default). Leave the other settings on the page with their default settings and then click Next to accept the default plug-in project structure. The link you provided is about using the eclipse's project wizard. I could not find any related information to the plugin development environment of Eclipse. I miss something? Window->Open Perspective->Java then File->New->Java Project (you may have to go via "Project..." to get to the "Java Project" option) Thanks for the interest but you missed the real requirement as @Saagar Elias Jacky did I guess.
common-pile/stackexchange_filtered
Reading text-file until EOF using fgets in C what is the correct way to read a text file until EOF using fgets in C? Now I have this (simplified): char line[100 + 1]; while (fgets(line, sizeof(line), tsin) != NULL) { // tsin is FILE* input ... //doing stuff with line } Specifically I'm wondering if there should be something else as the while-condition? Does the parsing from the text-file to "line" have to be carried out in the while-condition? The parsing should be done in the while loop or I guess you could store each line into an array or something and then do your parsing after the while loop. Close the file when you're done with it too That's 100% OK, you could even just do while (fgets(line, sizeof(line), tsin)) {...} and let the return of fgets serve as the test in and of itself. (a valid pointer will test true and NULL will test false) I think you are doing right, the answer about leaving out != NULL does not add value. According to the reference On success, the function returns str. If the end-of-file is encountered while attempting to read a character, the eof indicator is set (feof). If this happens before any characters could be read, the pointer returned is a null pointer (and the contents of str remain unchanged). If a read error occurs, the error indicator (ferror) is set and a null pointer is also returned (but the contents pointed by str may have changed). So checking the returned value whether it is NULL is enough. Also the parsing goes into the while-body. What you have done is 100% OK, but you can also simply rely on the return of fgets as the test itself, e.g. char line[100 + 1] = ""; /* initialize all to 0 ('\0') */ while (fgets(line, sizeof(line), tsin)) { /* tsin is FILE* input */ /* ... doing stuff with line */ } Why? fgets will return a pointer to line on success, or NULL on failure (for whatever reason). A valid pointer will test true and, of course, NULL will test false. (note: you must insure that line is a character array declared in scope to use sizeof line as the length. If line is simply a pointer to an array, then you are only reading sizeof (char *) characters) I see little value to initialize all line[] other than style/debug. Do you see other value? Nope, other than always trying to impress upon new C programmers that the cost of initializing all variables is quite small compared to the time spent debugging when you don't. In this case, that's the only point. your code implies that NULL is 0, but that is not the case on all platforms. @AndersK., That's true according to the C standard, but Posix is stricter. @AndersK. do you have an example of a platform where while (fgets(...)) would fail? I'm curious, I haven't run across one. @DavidC.Rankin see e.g. http://stackoverflow.com/questions/2597142/when-was-the-null-macro-not-0 but true, maybe it is irrelevant nowadays (I'm old) Considering I've got 2 in high school and 1 in middle-school and I've been around since the mid 60's, you can't be that much older... i had the same problem and i solved it in this way while (fgets(line, sizeof(line), tsin) != 0) { //get an int value ... //doing stuff with line }
common-pile/stackexchange_filtered
What's the fastest and most memory efficient BZip2 decompression tool to use in Java Currently using the Apache Commons Compress package which uses about 60% of the overall heap and takes around 6 minutes to decompress about 500 files each 4-5Mb when decompressing BZip2 files. My main problem is I can't find anything to compare this performance to, I have found AT4J but implementing this as per the documentation leads to an ArrayIndexOutOfBoundsException while trying to read one of the files into the buffer. For the few files it did manage to process the performance was pretty similar, and the fact that AT4J includes the compressor classes from Commons Compress to give 'an extra option' implies this is expected. Does anyone know of any other Java libraries for decompressing BZip2 files and if so whether they are any comparison to Apache? Thanks in advance. This benchmark of different compression techniques suggest they got 6 MB/s decompressing BZip2 https://tukaani.org/lzma/benchmarks.html This suggests that your 2.2 GB of data should take about 6 minutes even with a native library. If you want to speed this up, I suggest using multiple threads or using gzip which is much faster. Thanks @PeterLawrey that was the sort of thing I needed :)
common-pile/stackexchange_filtered
preventDefault doesn't work I have a problem with preventDefault function. It doesn't work. Here is my JS file: (function() { var app = { initialize : function () { this.setUpListeners(); }, setUpListeners: function () { $('form').on('submit', app.submitForm); }, submitForm: function(e){ e.preventDefault(); } } app.initialize(); }()); My HTML code has 2 confirm button. Second step is hidden and should be display, when first step will be done. But I can't at least add preventDefault for first step. Here is my HTML: <form id="login"> <!-- #first_step --> <div id="first_step"> <h1>Registration Form</h1> <fieldset id="inputs"> <div class="form-group"> <label for="username">Username</label> <input type="text" name="username" id="username" class="form-control" placeholder="Create a username" required=""> </div> <div class="form-group"> <label for="password">Password</label> <input type="password" name="password" id="password" class="form-control" placeholder="Create a password" required=""> </div> <div class="form-group"> <label for="cpassword">Password</label> <input type="password" name="password" id="cpassword" class="form-control" placeholder="Confirm your password"> </div> </fieldset> <fieldset id="actions"> <div class="form-group"> <input type="submit" class="submit" name="submit_first" id="submit_first" value="Next"> </div> </fieldset> </div> <!-- #second_step --> <div id="second_step"> <h1>Registration Form</h1> <fieldset id="inputs"> <label>Name</label> <input type="text" name="name" id="firstname" class="form-control" placeholder="Enter your name" autofocus="" required=""> <label>Surname</label> <input type="text" name="surname" id="lastname" class="form-control" placeholder="Enter your last name" required=""> <label>Email</label> <input type="email" name="email" id="email" class="form-control" placeholder="Enter your email" required=""> </fieldset> <fieldset id="actions"> <input class="submit" type="submit" name="submit_second" id="submit_second" value="Next"> </fieldset> </div> </form> I'm sorry. I'm just a beginner in js and will be very thankful if someone help me 99% sure you forgot $ before your (function()...) @Amit it is anonymous function @Amit Why should there be a $? It's a self invoking anonymous function, the syntax is fine. @OP: Are you getting any JS errors? Did you forget to load jquery? You are using it here: $('form').on('submit', app.submitForm); @Quasdunk, Alexander - Because it looks like the classic jQuery syntax for running the code when the page is ready, where otherwise if the form element doesn't exist yet everything will fail No, jquery loaded properly. http://graf.co.nf/register.php - here is a link in Internet This JS work fine - http://graf.co.nf/js/jquery.main.js but I want to realize this page using functions like here http://graf.co.nf/js/test.js As I said, you forgot the $ It doesn't work also with $ Here is an example, where this function work without $ -- http://graf.co.nf/View/test.html @SergeyPodgornyy It works there because the script is at the end, so the elements have been loaded. If you run the script at the beginning, none of the elements it tries to select exist yet. That seems to be the difference between your two links. The working one loads common.js at the end, the failing one loads it at the beginning. $(function() { var app = { initialize : function () { this.setUpListeners(); }, setUpListeners: function () { $('form').on('submit', app.submitForm); }, submitForm: function(e){ e.preventDefault(); } } app.initialize(); });
common-pile/stackexchange_filtered
Random Quote in java Problem Statement: Create a class diagram and Java code for the following system and scenario, taking into account the possibility of future extensions. "The system is a command line utility that prints a short 'quote of the day' on the user's terminal when run. To begin with the quote is selected randomly from a set of hard-coded strings within the program itself, but that might change later on -- the quotes might be based on the user's history, the time of day, the date, etc.. Scenario: User types "java QuoteOfTheDay" on the command line. System prints out a quote of the day, with an attribution. This is my code for the following: Class Containing the main method package quoteOfTheDay; import java.util.Random; public class QuoteOfTheDay { public static void main(String[] args) { System.out.println(); Random rand = new Random(); System.out.println(Quote.QUOTES[rand.nextInt(Quote.QUOTES.length)]); } } Quote Class containng the quotes. package quoteOfTheDay; public class Quote { public static final String QUOTES[] = { "Be yourself; everyone else is already taken.― Oscar Wilde", "A room without books is like a body without a soul. ― Marcus Tullius Cicero", "Be the change that you wish to see in the world. ― Mahatma Gandhi", "If you tell the truth, you don't have to remember anything. ― Mark Twain", "If you want to know what a man's like, take a good look at how he treats his inferiors, not his equals.― J.K. Rowling", "To live is the rarest thing in the world. Most people exist, that is all.― Oscar Wilde", "Without music, life would be a mistake. ― Friedrich Nietzsche", "Always forgive your enemies, nothing annoys them so much. ― Oscar Wilde", "Life isn't about getting and having, it's about giving and being. –Kevin Kruse", "Whatever the mind of man can conceive and believe, it can achieve. –Napoleon Hill", "Strive not to be a success, but rather to be of value. –Albert Einstein", }; } Is this the right approach? Am I missing some things from the problem requirements? I am open for any kind of suggestions. I think you should start by creating a class diagram like the question says. Right now, it would not contain all that many classes, right? And keeping in mind future extensions: What if for example I wanted to add the birth and death of a person to the attribution (so I get an idea of what time period that quote is from)? I would have to add it everywhere that person is mentioned. If you followed my advice to your first question, this would be easier (I would just have to add it once). +1 For your awesome quotes, I am reading Napoleon Hill's book "think and grow rich" atm :D The using of a public field should be avoided and instead you should use a method to get the value. If you take into account that the class will be extended (like written in the problem statement), I would suggest that you add a getRandomQuote() method to the Quote class. Also you should make your String array QUOTES private. I don't know what the conventions for the array braces [] are , but I would write it private static final String[] QUOTES A Random should be created once and then used as often one needs.So I would suggest to create it at the constructor. private Random random; public Quotes(){ random = new Random(); } public String getRandomQuote(){ // return your random quote here } You should always name your variables and methods in a meaningful easily readable way. So I have renamed rand to random. I think the important info is in taking into account the possibility of future extensions So I think a bit of object-oriented design is expected. First we define an interface for obtaining data: public interface Source<T> { public T getNext(); } Then we need an interface for the data sink: public interface Sink<T> { void put(T elem); } In this scenario the data sink will be a simple command line printer. public class CommandLinePrinter implements Sink<String> { @Override public void put(String elem) { System.out.println(elem); } } And the data source is a random quote provide: public class RandomQuoteProvider implements Source<String> { private final Random randomNumberGenerator; private final List<String> quotes; public RandomQuoteProvider(List<String> quotes) { this.quotes = quotes; this.randomNumberGenerator = new Random(); } @Override public String getNext() { return this.quotes.get(this.randomNumberGenerator.nextInt(this.quotes.size())); } } As controller we can keep the QuoteOfTheDay class: public class QuoteOfTheDay { private final Source<String> dataSource; private final Sink<String> dataSink; public QuoteOfTheDay() { List<String> data = new ArrayList<String>(11); data.add("Be yourself; everyone else is already taken.― Oscar Wilde"); data.add("A room without books is like a body without a soul. ― Marcus Tullius Cicero"); data.add("Be the change that you wish to see in the world. ― Mahatma Gandhi"); data.add("If you tell the truth, you don't have to remember anything. ― Mark Twain"); data.add("If you want to know what a man's like, take a good look at how he treats his inferiors, not his equals.― J.K. Rowling"); data.add("To live is the rarest thing in the world. Most people exist, that is all.― Oscar Wilde"); data.add("Without music, life would be a mistake. ― Friedrich Nietzsche"); data.add("Always forgive your enemies, nothing annoys them so much. ― Oscar Wilde"); data.add("Life isn't about getting and having, it's about giving and being. –Kevin Kruse"); data.add("Whatever the mind of man can conceive and believe, it can achieve. –Napoleon Hill"); data.add("Strive not to be a success, but rather to be of value. –Albert Einstein"); this.dataSource = new RandomQuoteProvider(data); this.dataSink = new CommandLinePrinter(); } public void print() { this.dataSink.put(this.dataSource.getNext()); } public static void main(String[] args) { QuoteOfTheDay quoteOfTheDay = new QuoteOfTheDay(); quoteOfTheDay.print(); } } In the exercise it is already mentioned that in future implementations the quotes might be based on the user's history, the time of day, the date, etc. Now you can easily exchange the RandomQuoteProvider with something more sophisticated. You could also decide to not print the quote to the command line but display it in a popup window.
common-pile/stackexchange_filtered
Fresh install Arch Linux freeze I've installed Arch Linux using linux kernel (non lts version), with amd-ucode (pacman -S amd-ucode). The screen is totally frozen. I can't CTRL + ALT + F1, 2, 3 .. , RCTRL + F1, 2. What can I do? Have you tried logging in? I assume that fails too? What happens if you just type your username and hit enter? maybe my keyboard stops working and it is not in fact frozen.. i don't know I can't enter any text. It is frozen. @terdon Since you talked about amd-ucode, did you load it with initrd? i don't think so, how can i do that?
common-pile/stackexchange_filtered
Query Optimisation: SUMIF and CASE WHEN I am writing a query to pull the number of rewarded ads. To do so, I have to sum "rewarded_ad" events from event_name. Then, I am cleaning up null values in a second statement. So currently, my query includes a subquery. However, is there a way to do this without utilising a subquery? I am looking to optimise this process. My subquery includes: SUM(IF(LOWER(event_name)= 'rewarded_ad', 1,0)) AS rewarded_ad The outside query includes: CASE WHEN rewarded_ad IS NULL THEN 0 ELSE rewarded_ad END AS rv_count Any help is appreciated. Thank you in advance. You can replace: SUM(IF(LOWER(event_name)= 'rewarded_ad', 1,0)) AS rewarded_ad with: COUNTIF(LOWER(event_name) = 'rewarded_ad') AS rewarded_ad This should never return NULL because COUNT() never returns NULL. So, this should answer your question with no subquery. But a NULL values can appear if the subquery returns no rows. To handle that, use COALESCE(): COALESCE(COUNTIF(LOWER(event_name) = 'rewarded_ad'), 0) AS rewarded_ad Maybe IFNULL? IFNULL(SUM(IF(LOWER(event_name)= 'rewarded_ad', 1,0)), 0) AS rv_count
common-pile/stackexchange_filtered
Override home and back button is case a boolean is true I was wondering if I can override the action of the back and home button is some cases. Normally these buttons should just react like they always do, but in a case some setting is true I want to override the buttons and let them call my own methods. I´m using these two methods to override these buttons: @Override public void onBackPressed() { // call my backbutton pressed method when boolean==true } @Override public void onAttachedToWindow() { this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD); super.onAttachedToWindow(); // call my homebutton pressed method when boolean==true } I was wondering if I can override the action of the back and home button is some cases. Yes you can do override Home button. I have developed an application which disable hard button, you can have a look. I have taken a toggle button which locks all hard button to work except Power button public class DisableHardButton extends Activity { /** Called when the activity is first created. */ TextView mTextView; ToggleButton mToggleButton; boolean isLock=false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mTextView=(TextView) findViewById(R.id.tvInfo); mToggleButton=(ToggleButton) findViewById(R.id.btnLock); mToggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub isLock=isChecked; onAttachedToWindow(); } }); } @Override public boolean dispatchKeyEvent(KeyEvent event) { if ( (event.getKeyCode() == KeyEvent.KEYCODE_HOME) && isLock) { mTextView.setText("KEYCODE_HOME"); return true; } else return super.dispatchKeyEvent(event); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // TODO Auto-generated method stub if( (keyCode==KeyEvent.KEYCODE_BACK) && isLock) { mTextView.setText("KEYCODE_BACK"); return true; } else return super.onKeyDown(keyCode, event); } @Override public void onAttachedToWindow() { System.out.println("Onactivity attached :"+isLock); if(isLock) { this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD); super.onAttachedToWindow(); } else { this.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION); super.onAttachedToWindow(); } } } main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:id="@+id/tvInfo" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <ToggleButton android:id="@+id/btnLock" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textOff="UnLocked" android:textOn="Locked" /> </LinearLayout> Wow, this is great, exactly what I´m looking for! Didn't knew this, thought you couldn't change it, +1 :) If I first let an optionmenu popup and press the home button it still goes to the homescreen, any idea how to catch that call? pleasure :), @LarsDiego dint get you? IIRC this way of overriding the home button thankfully no longer works as of Android 4.0 Yes, fortunately, this approach does not work on Android 4.0.3. @CommonsWare is there is any way to make this happen in ICS and Jelly bean ?most of the SO posts say no, and onAttachedWindow with the setType throws an exception @DharaShah: "is there is any way to make this happen in ICS and Jelly bean ?" -- have your app be a HOME screen. @CommonsWare sir i have, but it still doesnt work, i tried using onAttachedWindow bt then returns an illegalstateException, and i even tried onWindowFocus but that throws an exception in the log, with the message that custom window properties have been maintained. I knw its not valid to have the home button behave the way users may find it overwhelming but thats a requirement :( @CommonsWare i added android:launchMode="singleInstance" android:stateNotNeeded="true" to the activity that should be displayed and thus when clicking on home, i get a selection box to select from. This is the only way to make it work ya sir ? @CommonsWare i just realized that making the activity a home screen activity, displays the app name in the set of launchers but when clicking on a textview to exit, the same app opens when actually the original launcher should open :(. but i just want to know only-is user pressed home button or not? but in your solution when user press home button activity not go to invisible state it in remain same state. while after pressing home button application no longer visible. and this code also not working on 4.1.x and 4.2.x For the versions greater than 4.0 this will help to disable HARD Home button. https://github.com/shaobin0604/Android-HomeKey-Locker " Window type can not be changed after the window is added." I got this error. How does that code work for everyone expect me? You call super.onBackPressed() to call the normal method. Exemple : @Override public void onBackPressed() { if (activated) { //doyourthing } else { super.onBackPressed() } } No you can not. What you can do is to ovveride the method and manage the boolean inside it: for instance: public void onBackPressed() { // call my backbutton pressed method when boolean==true if (myCondition) { // take care of my needs } else // call super to let the back behavior be "normal" } Regarding overriding the behaviour of Home Button you are out of luck. However if your app is a specific one and have limited targeted audience, like inter-organization app, hospital kiosk, restaurant ordering, you can try making your app as Home (the launcher app). You can find a good example here: How to Write Custom Launcher App in Android And to override the back key events, lot of examples are there. For example: Catch keypress with android Override back button to act like home button Android - How To Override the "Back" button so it doesn't Finish() my Activity? make your boolean variable member variable boolean temp; @Override public void onBackPressed() { // call my backbutton pressed method when boolean==true if(temp) //your methode else finish(); } I use this: public void onBackPressed() { switch (screen) { case 1: screen = 99; setContentView(R.layout.menu); break; case 99: finish(); break; } return; } When I am in a other screen (other then menu screen), I set the variable screen to 1. When I press the back button, it goes back to the menu screen (instead of killing the app). and give the screen variable the number 99, then when you hit the back button again, it kills the app. However, you can't change the home button.
common-pile/stackexchange_filtered
setting $ENV{variable} when calling python I'm new to Python and would like reproduce a convenience I used when working in Perl. When calling a Perl script I usually set some $ENV variables (like VERBOSE, DEVELOP and DEBUG). Inside the called script I recover their values using my $verbose=$ENV{VERBOSE}; my $develop=$ENV{DEVELOP}; my $debug=$ENV{DEBUG}; This allow print stmts conditional on these variables. Can I do the same thing in Python? I know thanks to previous responses (Thank you!) to use os.environ[var] within the script to access the values. But I have not been able to figure out how to assign a value to a variable when I call the script from the command line as I could when callinbg a Perl script Can values be set for such variables on the commandline invoking a python script? TIA They are accessible via the os.environ dictionary. os.environ['VERBOSE']
common-pile/stackexchange_filtered
ES6 pass function as parameter example I don't know JS/ES6 well enough to describe my question in code. So most of this question is conceptually and in pseudo code. Say I have a Contractor class like this: class Contractor { constructor(jobFn) { // save jobFn; } dailyRoutine() { // let result = DriveToWork() const result = 6 DoTheJob(result) DriveBackHome() } } The problem is, what the DoTheJob() does might be different things in different places. So in place A, it could be he = new Contractor(write_front_end(with, this, and that)) And in place B, it could be he = new Contractor(fix_backend_node(with, express)) I.e., the behavior need to be passed in during the constructor, and the action might need to take different kind and different amount of parameters. Would such thing be possible with ES6? Please show ES6 code that can pass function with different kind and different amount of parameters through the constructor to DoTheJob(). Further, the challenge is that the jobFn need to be a Curried function, meaning there is one or more parameter missing to do the DoTheJob job. Say if the jobFn is passed with Curried add(3), then DoTheJob will do UncurriedAdd of add(3, 6); if then jobFn is passed with Curried multiple(5), then DoTheJob will do Uncurried of multiple(5, 6); Just assign the passed function to this.DoTheJob, and then call this.DoTheJob inside dailyRoutine: class Contractor { constructor(jobFn) { this.DoTheJob = jobFn; } dailyRoutine() { // DriveToWork() this.DoTheJob(); // DriveBackHome() } } const c1 = new Contractor(() => console.log('doing job A')); c1.dailyRoutine(); const c2 = new Contractor(() => console.log('doing job B')); c2.dailyRoutine(); // c1 again: c1.dailyRoutine(); // feel free to reference any in-scope variables in the passed function, // no need to pass the variables as additional parameters const data = 'data'; const c3 = new Contractor(() => console.log('data is', data)); c3.dailyRoutine(); If dailyRoutine needs to be invoked with data that needs to be sent to the passed doTheJob function, just define the needed arguments in the function you pass, there's no need for actual currying here: class Contractor { constructor(jobFn) { this.DoTheJob = jobFn; } dailyRoutine(doJobArg) { this.DoTheJob(doJobArg); } } // feel free to reference any in-scope variables in the passed function, // no need to pass the variables as additional parameters const data = 'data'; const c3 = new Contractor((arg) => console.log('data is', data, 'and arg is', arg)); c3.dailyRoutine('argDoTheJobIsCalledWith'); thanks a lot. While trying to apply to my real case, I realized that the jobFn need to be a Curried function, meaning there is one or more parameter missing to do the DoTheJob job. I'll update my question. See edit, pretty sure actual currying isn't necessary, you can just define another parameter (or few) as needed, and call the function with the additional info that needs to be passed in Wonderful, wonderful! Splendid, and simple -- I was about to say I've thought of a clumsy way of doing it, but before I start, you've already given the updated answer. THANKS A LOT!!! In my case, I may advise you that it's better to give the predicate to dailyRoutine, because this way you'll be able to reuse the same instance and give different predicates. Anyway, there's a pure OOP solution for this, using method polymorphism, the JavaScript way (aka duck typing): class Contractor { driveBackHome() {} dailyRoutine() { const result = 6 this.doTheJob(result) this.driveBackHome() } } class SpecializedContractorA extends Contractor { doTheJob(result) { console.log('aaaaaaaaaaaaaaaaaaaaa', result) } } class SpecializedContractorB extends Contractor { doTheJob(result) { console.log('bbbbbbbbbbbbbbbb', result) } } const a = new SpecializedContractorA() a.dailyRoutine() const b = new SpecializedContractorB() b.dailyRoutine() Thanks for the answer. For the simplicity and for focusing on my question, I omitted the gory details of my real case, when the class I'm using is at the 4th level of sub class D: A <- B <- C <- D, whereas the dailyRoutine is defined at the 2nd level (B). Since I believe multiple-inherit is not supported by JS/ES6, I think passing function with different kind and different amount of parameters would be the best approach. @xpt I still see that you don't need multi-inheritance. Why? Duck typing works flawlessly here: dailyRoutine is in B, and you define doTheJob in the 8th level... no problem: if(this.doTheJob) this.doTheJob (result). Do you get the idea? In a dynamically-typed language you're free to do something if it's there. Hmm... I guess different people architect things differently. For me, reusing the same D in different scenarios by passing different functions (with different parameters) seems to be more preferable to me. I view it more cleaner personally, as I might need to use it in ten different scenarios but don't what to create ten different sub classes just for that. But thanks for helping -- I'm sure there will be people who will agree with you... @xpt From my stand point, your approach is odd: it's not OOP nor FP. It's a shortcut. But if you're confortable with it, you're who's implementing the project :D You're welcome.
common-pile/stackexchange_filtered
How to correctly rotate and move a 3D perspective camera in LibGDX I have been trying on and off now for a few weeks to correctly handle object and camera rotation in LibGDX. I have the below move and yrotate methods in a custom class for my objects, 'this' being a ModelInstance: public void move(float i) { // TODO Auto-generated method stub this.instance.transform.translate(0, 0, i); this.instance.calculateTransforms(); } public void yrotate(float i) { // TODO Auto-generated method stub this.instance.transform.rotate(Vector3.Y, -i); this.instance.calculateTransforms(); } This all seems to work fine as I can rotate objects and move them in the rotated direction correctly (though I must admit I'm a bit stumped as to why the Y Vector has to be negative). I am now trying to replicate this for the camera. I can see that the camera also has a lot of methods available to it but they do not exactly match those used for objects. At the moment I am doing the following for the camera: void move(float i) { // cam.translate(0, 0, i); cam.position.add(0, 0, i); cam.update(); } void yrotate(float i) { cam.rotate(Vector3.Y, -i); // cam.direction.rotate(Vector3.Y, -i); cam.update(); } The above seems to rotate and move the camera. However, when moving the camera the position x, y and z is not taken into consideration the rotation that has been applied. I am thinking that for the objects it's the 'calculateTransforms' bit that does the magic here in making sure the object moves in the direction it's facing, but I'm struggling to find anything like this for the camera. Any help would be greatly appreciated! You want to move the camera a certain distance in whatever direction it's looking? That is it in a nutshell, yes. If you want to move the camera into the direction it is looking into, then you can do that something like this: private final Vector3 tmpV = new Vector3(); void move(float amount) { cam.position.add(tmpV.set(cam.direction).scl(amount)); cam.update(); } If you for some reason don't like to add a temporary vector then you can scale the vector inline: void move(float a) { cam.position.add(cam.direction.x * a, cam.direction.y * a, cam.direction.z * a); cam.update(); } Btw, you shouldn't call calculateTransforms if you didn't modify the nodes. See also the documentation: This method can be used to recalculate all transforms if any of the Node's local properties (translation, rotation, scale) was modified. Yay; thanks for the response Xoppa. I have added this to my camera class and it works well. Though can you explain why a vector needs to be added to store/calculate this please? Is there no way that this can be achieved with the existing methods without the need for an additional vector? Thank you so much for the alternative! I can see with the extra methods there that this is perhaps slightly more overhead from those extra calculations.. Is that right? Or is there some other reason why doing this would not be your initial suggestion? How to force the camera to look in direction of player after player rotates?
common-pile/stackexchange_filtered
Which part of the CheckedTextView was clicked? A checkedTextView shows a text box and a checkbox. Is it possible for code to determine if only the checkbox part was clicked? If so, the code could respond differently the user clicking the checkbox or the text view. I think you can't know which part has been clicked, judging by the CheckedTextView source code as the CheckedTextView is one view. However you can create your own by betting ideas in the source...
common-pile/stackexchange_filtered
Postgres JOIN on timestamp fails Trying to do a simple FULL OUTER JOIN on a timestamp and it is outputing the full cartesian product instead of matching identical dates. What is wrong here? SQL Fiddle with example data CREATE TABLE A ( id INT, time TIMESTAMP ); CREATE TABLE B ( id INT, time TIMESTAMP ); Query: SELECT A.Id AS a_id, A.Time AS a_time, B.Id AS b_id, B.Time AS b_time FROM A FULL OUTER JOIN B ON A.Time = B.Time -- This works: -- SELECT A.id, A.time, B.id, B.time -- FROM A -- FULL OUTER JOIN B ON A.id = B.id What result you expect? The same thing as the commented out query. A full outer join produces a cartesian product by definition. Maybe you mean inner join? You are using the wrong parameters on TO_DATE() on your INSERTS easy to test if you do SELECT * FROM A; SELECT * FROM B; Instead of TO_DATE('01-01-2002', '%d-%m-%Y') Should be: TO_DATE('01-01-2002', '%DD-%MM-%Y') SQL DEMO In your sql fiddle all your inserted dates are the same because your date pattern is wrong. Try using TO_DATE('01-01-2002', 'DD-MM-YYYY') instead of TO_DATE('01-01-2002', '%d-%m-%y')
common-pile/stackexchange_filtered
Java Regex text between complex characters I'm trying to pull the text out of a string with the help of regex, but I haven't used it much before and I can't figure out the format for the Pattern.compile. I want to cut out the weight (9 ounces) from the following string: <li><b>Shipping Weight:</b> 9 ounces (<a href="http://www.amazon.com/gp/help/seller/shipping.html?ie=UTF8&amp;asin=0982817509&amp;seller=ATVPDKIKX0DER">View shipping rates and policies</a>)</li> print("Actual Weight:" + link.outerHtml()); Pattern p = Pattern.compile("Weight:\\</\\b\\>(.*?)\\ ("); Matcher m = p.matcher(link.outerHtml()); m.find(); System.out.println(m.group(1)); What should be my Pattern.compile format. I'm trying to cut between "Weight:" and " (". Any help would be amazing! I've been searching for awhile now, but I couldn't find a good place to explain the formatting. do you want to replace or match Thanks for all the help! Looks like I was over complicating things, I just went with: Pattern p = Pattern.compile("Weight: (.*?) \("); and that seemed to do the trick you don't even need group. look behind works in this case: Pattern p = Pattern.compile("(?<=Weight:</b> )[^(]*"); You don't seem to be escaping the last (, so that'd be a problem (I think, I don't use Java - considering parenthesises are used in regex to express groups). I've also added \s's, which mean you don't have to trim the result. Pattern.compile("Weight:</b>\s+(.*?)\s+\("); Thanks! I wasn't able to use the \s, but you were right that I wasn't escaping the last parenthesis. As an alternative: Pattern.compile("\d*\sounces"); this is a risky one... who knows what text for that <a> link would be? I don't think it is anymore - I edited it. This should work perfectly. Nice and easy to read. Just add "Weight" in front of your Group Match when using it in the rest of your code. No need to regex for a CONSTANT
common-pile/stackexchange_filtered
Python argparse and sys.argv I am making a script which automatically download and rename albums from bandcamp purchases to my server. For now i am passing sys.argv to the script like python script.py Artistname Albumname Year DownloadLink Genre then in the script i set variables like artist = sys.argv[1] album = sys.argv[2] year = sys.argv[3] link = sys.argv[4] genre = sys.argv[5] do commands with these vars Now i wanted to use argparse instead maybe with a little help commands too. I have read the python docs about it but i cant seems to make it work.. Any help? What part can't you make work? Where is your code for it? not really answering your question, sorry, but i like docopt a lot... For a simple input like this argparse doesn't make things any easier, You could just replicate this with 5 positionals. But if you need to add more controls, it can be a big help. What have you tried so far? You haven't specified an actual problem. That being said, I prefer defining my required args in a function. import argparse def cli_args(self): parser = argparse.ArgumentParser( description='This is an example') parser.add_argument('--arg1', dest='agr1', required=True, help='the first arg. This is required') parser.add_argument('--arg2', dest='agr2',default=0, help='another arg. this will default to 0') # return dictionary of args return vars(parser.parse_args()) Try click.pocoo.org and don't mind with argparse. For self-documenting example of usage (launch like >python script.py --count 3 --name Nikolay): import click @click.command() @click.option('--count', default=1, help='Number of greetings.') @click.option('--name', prompt='Your name', help='The person to greet.') def hello(count, name): """Simple program that greets NAME for a total of COUNT times.""" for x in range(count): click.echo('Hello %s!' % name) if __name__ == '__main__': hello() Try @click.argument instead of option if you want exactly what you wrote in the topic. why downvote? seems like a perfectly legitimate answer! +1. I have tried this def main(): parser = argparse.ArgumentParser(description='xxxx', prog='xxxx') parser.add_argument('artist', help='Artist name, separted by "_". Ex: The_Beatles') parser.add_argument('album', help='Album title, separated by "_". Ex: The_Joshua_Tree') parser.add_argument('yar', help='Release year') parser.add_argument('url', help='Bandcamp download url inside bracelets.') parser.add_argument('genre', help='Album genre, separted by a point. Ex: hip.hop') args = parser.parse_args() main() Then in the script i have release = ("%s - %s - (%s) - [FLAC]"%(artist,album,year)).replace('_',' ') If i run the script with script.py Artist Album Year URL Genre It Give me an error that global name release is not defined. Where is the error? If i run script.py -h I have the correct help with all the positional arguments and help..
common-pile/stackexchange_filtered
How do I deal with non-English *links*? My question revolves around answers posted in English referencing sources in another language. After looking at How do I deal with non-English content? and How to deal with non-English posts I can find no reference to links in this case. For example Lucas has posted a good answer in English however has linked to a Portuguese source. (Granted this was likely by accident and for this site in particular it is trivial to switch languages). However my question is: Is it worth an edit to update the source to directly point to the English source if one exists? Good find pep, sorry i didn't find it in my original search. In cases like the one you quote I'd be tempted to add the link to the English content rather than simply replace it. If the original page linked to wasn't English and has been translated, then leaving the original link allows people to translate it themselves and verify that the English translation is accurate.
common-pile/stackexchange_filtered