text
stringlengths
64
89.7k
meta
dict
Q: Cross platform network aware clipboard Do you know of any network-aware cut'n paste (clipboard) tool between Windows (XP min) and Linux (Ubuntu) - Need to free scarce brainpower resource consumed by retyping dodging strategies. A: This is an odd case used by a friend, but just in case it fits your scenario. He has different computers in physical proximity connected by network and wanted to share the keyboard and mouse. He decided to try Synergy http://synergy-foss.org/ It was serendipity that it also allows for copy and paste between computers. Again a very specific case where the boxes, and screens are near each other and the goal was to cut it to one keyboard. If it's just remote access, I just copied something in an UltraVNC viewer on Windows, and pasted it locally, and did the same from Ubuntu using remote desktop viewer.
{ "pile_set_name": "StackExchange" }
Q: ArgumentOutOfRangeException: Argument is out of range I have the following List: public Question init() { questions = new List<GameManager.Question>(); questions.Add(new GameManager.Question("Ya no hay técnicas que te puedan salvar.", "Sí que las hay, sólo que nunca las has aprendido.")); questions.Add(new GameManager.Question("Espero que tengas un barco para una rápida huida.", "¿Por qué? ¿Acaso querías pedir uno prestado?")); questions.Add(new GameManager.Question("Ahora entiendo lo que significan basura y estupidez.", "Me alegra que asistieras a tu reunión familiar diaria.")); return questions; } I initialize the following buttons on start: for (int i = 0; i < questionList.Count; i++) { GameObject child = Instantiate(questionButton, buttonLayout.transform); child.GetComponent<Text>().text = questionList[i].answer; child.GetComponent<Button>().onClick.AddListener(() => QuestionCheck(i)); } And I have the following code: public void QuestionCheck(int index) { if (currentQuestion.answer == questionList[index].answer) { playerAsk = 1; playerScore += 1; scorePlayer.GetComponent<Text>().text = "Jugador: " + playerScore; roundStatus.text = "Has ganado la ronda!"; roundStatus.color = Color.green; correct.Play(); } } I think it crashes on the following line: if (currentQuestion.answer == questionList[index].answer) Also if I try the following line it also crashes: questionList.RemoveAt(index); I obtain the following error: ArgumentOutOfRangeException: Argument is out of range. Parameter name: index Why this is happening? EDIT: I've seen that the index from QuestionCheck is always 15, why this is happening? A: This is scoping issue. Once the event happens, i is already at questionList.Count which is out of the array range. And all of your QuestionCheck will be called with questionList.Count (15 in your case) What you want to do is save i to a temporary value, and used that instead: for (int i = 0; i < questionList.Count; i++) { var currentIndex = i; GameObject child = Instantiate(questionButton, buttonLayout.transform); child.GetComponent<Text>().text = questionList[i].answer; child.GetComponent<Button>().onClick.AddListener(() => QuestionCheck(currentIndex )); }
{ "pile_set_name": "StackExchange" }
Q: Slice an array values less than 85 in php I have an array array(0=>12,1=>34,2=>334,3=>87,4=>75); and what i want is values which is less than 85 in this array. Thanks in Advance. A: You can use PHP's builtin array function array_filter to handle filtering values based on a custom filtering function. <?php function less_than_85($value) { return $value < 85; } $arr = array_filter($arr, "less_than_85"); ?> See a live example using your sample input here.
{ "pile_set_name": "StackExchange" }
Q: An application of the first (group) isomorphism theorem Suppose that $G$ is a group and $N$ is a normal subgroup of $G$. How do we find out what $G/N$ is isomorphic to? For example, $C_m$ is a normal subgroup of $D_{2n}$ generated by a rotation of angle $2\pi/m$. We can partiotion the group $D_{2n}$ using the normal subgrouop $C_m$. We want to find a surjective homomorphism $\phi: G\to G'$ such that $\ker(\phi) = C_m$? What surjective homomorphism $\phi: G\to G'$ should we have so that $D_{2n}/C_m$ is isomorphic to $G'$? A: I assume $m|n$, so $n=md$ and $C_m\cong\langle r^d\rangle$. In this case, $|D_{2n}/C_m|=2d$. Working with cosets you can check that the quotient is generated by $[r]=rC_m$ and $[j]=jC_m$ satisfying the relations $[r]^d=[1]=C_m$, $[j]^2=[1]=C_m$ and $[j][r]=[r^{-1}][j]$. The correct guess is that $$D_{2n}/C_m\cong D_{2d}=\langle R,J\mid R^d=J^2=1,JR=R^{-1}J\rangle.$$ Now, define a homomorphism $\phi:D_{2n}\to D_{2d}$ by $\phi(r)=R$ and $\phi(j)=J$ (and extend multiplicatively). Check that this map is well defined (this involves the fact that $d|n$) and surjective. By the first isomorphism theorem $$D_{2n}/\ker\phi\cong D_{2d}.$$ Finally, check that $\ker\phi=\langle r^d\rangle$.
{ "pile_set_name": "StackExchange" }
Q: Find the list of inactive users in Bitbucket? How can I find the list of those users who never logged in to their Bitbucket account? Is there any query or macro, or will I have to do it manually ? A: You can do this with SQL query to database: SELECT cu.lower_user_name ,cu.display_name ,cu.lower_display_name ,cu.lower_email_address ,cu.is_active ,dateadd(second,cast(cast(cua.attribute_value AS nvarchar(255)) AS bigint)/1000,'19700101 00:00:00:000') AS LAST_LOGIN FROM [BitBucketDB].[dbo].[cwd_user] As cu LEFT JOIN [BitBucketDB].[dbo].cwd_membership AS cm ON cu.directory_id=cm.directory_id AND cu.lower_user_name=cm.lower_child_name AND cm.membership_type='GROUP_USER' LEFT JOIN [BitBucketDB].[dbo].cwd_user_attribute As cua ON cu.ID = cua.user_id and cua.attribute_name='lastAuthenticationTimestamp' WHERE cm.lower_parent_name='stash-users'
{ "pile_set_name": "StackExchange" }
Q: Properly overloading [bracket] operator for hashtable get and set I am trying to implement a hashtable class. The problem I am facing atm is how to properly overload the square bracket operators so that getting the value at a key from the hashtable is distinguishable from setting a key to a value. So far here is what the class looks like: template <typename K, typename V> class HashTable { typedef pair<K, V> KeyVal; avl_tree <KeyVal> **TABLE; unsigned TABLESIZE; public: HashTable( const unsigned & ); V& operator [] ( const K& ); //Setter const V& operator [](const K&) const; //Getter typedef unsigned (*hashtype)(const K&); static hashtype Hash; ~HashTable(); }; And this is the implementation of each overload of the brackets: template <typename K, typename V> V& HashTable<K, V>::operator [] ( const K& ret ) { unsigned index = HashTable<K, V>::Hash(ret) % TABLESIZE; avl_tree <KeyVal> *ptr = AVL_TREE::find(TABLE[index], KeyVal(ret, 0)); if ( ptr == None ) ptr = (TABLE[index] = AVL_TREE::insert(TABLE[index], KeyVal(ret, 0))); return ptr->data.second; } template <typename K, typename V> const V& HashTable<K, V>::operator [](const K& ret) const { avl_tree <KeyVal> *ptr = AVL_TREE::find(TABLE[HashTable<K, V>::Hash(ret) % TABLESIZE], KeyVal(ret, 0)); if (ptr == None) throw "Exception: [KeyError] Key not found exception."; return ptr->data.second; } Now if I do: cout << table["hash"] << "\n"; //table declared as type HashTable<std::string, int> I get an output of 0, but I want it to use the getter implementation of the overloaded square brackets; i.e. this should throw an exception. How do I do this? A: The usual way to handle this situation is to have operator[] return a proxy. Then, for the proxy overload operator T approximately as you've done your const overload above. Overload operator= about like your non-const version. template <typename K, typename V> class HashTable { typedef pair<K, V> KeyVal; avl_tree <KeyVal> **TABLE; unsigned TABLESIZE; template <class K, class V> class proxy { HashTable<K, V> &h; K key; public: proxy(HashTable<K, V> &h, K key) : h(h), key(key) {} operator V() const { auto pos = h.find(key); if (pos) return *pos; else throw not_present(); } proxy &operator=(V const &value) { h.set(key, value); return *this; } }; public: HashTable( const unsigned & ); proxy operator [] ( const K& k) { return proxy(*this, k); } typedef unsigned (*hashtype)(const K&); static hashtype Hash; ~HashTable(); }; You basically have two cases when you use this: some_hash_table[some_key] = some_value; value_type v = some_hash_table[some_key]; In both cases, some_hash_table[some_key] returns an instance of proxy. In the first case, you're assigning to the proxy object, so that invokes the proxy's operator=, passing it some_value, so some_value gets added to the table with key as its key. In the second case, you're trying to assign an object of type proxy to a variable of type value_type. Obviously that can't be assigned directly -- but proxy::operator V returns an object of the value type for the underlying Hashtable -- so the compiler invokes that to produce a value that can be assigned to v. That, in turn, checks for the presence of the proper key in the table, and throws an exception if its not present.
{ "pile_set_name": "StackExchange" }
Q: How do users learn about various gestures that are used on touch screens? How does the user learn about various gesture in the interfaces? Does the ipad or android device have inbuilt gestural instructions when someone buys a new device? Does it demonstrate the gestures involved when somebody buys or downloads an app? Does the app provides an intro of various gestures it takes care of? I am asking this because it appears that the user goes into a stream of trial and error to understand an app or use the app, by trying various ways to move across the screens - sometimes succeed, fail or get frustrated. Any research, evidence or observations? A: The basic gestures, such as flicking, pinching, and tapping, are mentioned in user guides that are included in the box. For example, see PDF manuals for Apple iPad, HP TouchPad, and Barnes & Noble NOOK (search for "pinch" to find the section on gestures). If an application uses gestures in an unusual manner, developers provide an intro about the application-specific gestures. Phoster (on the right) isn't a great example since the gestures are standard but that's the way a user would be introduced to such a new interaction. A: Gesture-based interfaces, such as those on smartphones and tablets, gained a lot of criticism for the disadvantages of gestures as an interaction system. One of the main points against gesture interfaces is the problem of discovery - since these gestural interactions are supposed to be "natural" and "intuitive", there is usually no affordance (hint for possible action) on screen for possible actions. For example, on the desktop, you could hover over links and buttons, and something would happen (the cursor could change into a finger). This means that users should learn and memorize gestures, or stumble upon them accidentally (the trial and error you referred to). Don Norman writes about this problem and other in his article Gestural Interfaces: A Step Backwards In Usability. Now, to your questions: Yes - The iPhone user guide (pdf) does teach the user the basic gestures (assuming that people even reads these things through). So does the iPad (pdf) and other smartphones and tablets. But knowing the basic gestures doesn't mean that users would know when to use them, which leads to the next question. Usually not - Each app developer decides how to use those interactions. They can also introduce the new gestures if they deem necessary. The buying and downloading process is usually not the place to teach the user about these gestures (although app developers could post instructions and screenshots of how their apps work on the app's store page). Sometimes - You are asking about invitations - the process of inviting the user to start using the app. Some apps take the user through a tutorial ("tour") upon opening the app for the first time. Others show contextual tooltips when they're appropriate. . If you're interested in this, you could read more about it in this UX Booth post and browse through examples in this Flickr photostreem.
{ "pile_set_name": "StackExchange" }
Q: Enter MS-Word equations into text area I am creating a web application where teachers can enter maths, physics and chemistry questions and notes. The problem that I am currently facing is how to enable copying equations from Microsoft Word and being able to paste into a textarea. Non-equation parts of text successfully copy over. Alternatively, is there is a way a teacher can upload a Word file and my application converts it to an image? For directly typing into the textarea, I am using wiris editor. I am using PHP, MySQL and JavaScript. A: The short answer is no. The best solution for you would be for teachers to export equations as images. It appears that Word 2010 + Save math equation as image has a solution for this (cumbersome as it is). From this image, your page would have to accept image files for upload. You can prepare this by having your form include an enctype as follows: <form action="save.php" enctype="multipart/form-data" method="post"> <input type="file" name="image" /> </form>
{ "pile_set_name": "StackExchange" }
Q: Expand by ID for future periods only Is there a way to fill in for implicit missingness for future dates based on id? For example, imagine a experiment that starts in Jan-2016. I have 3 participants that join in at different periods. Subject 1 joins me in Jan and continues to stay until Aug. Subj 2 joins me in March, and stays in the experiment until August. Subject 3 also joins me in March, but drops out sometime in in May, so no observations are recorded for periods May-Aug. The question is, how do I fill in the dates when subject 3 dropped out of the experiment? Here is some mock data for how things look like: Subject Date 1 1 Jan-16 2 1 Feb-16 3 1 Mar-16 4 1 Apr-16 5 1 May-16 6 1 Jun-16 7 1 Jul-16 8 1 Aug-16 9 2 Mar-16 10 2 Apr-16 11 2 May-16 12 2 Jun-16 13 2 Jul-16 14 2 Aug-16 15 3 Mar-16 16 3 Apr-16 structure(list(Subject = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L), Date = structure(c(5L, 4L, 8L, 2L, 9L, 7L, 6L, 3L, 8L, 2L, 9L, 7L, 6L, 3L, 8L, 2L), .Label = c("", "Apr-16", "Aug-16", "Feb-16", "Jan-16", "Jul-16", "Jun-16", "Mar-16", "May-16"), class = "factor")), class = "data.frame", row.names = c(NA, -16L), .Names = c("Subject", "Date")) And here is how the data should look like: Subject Date 1 1 Jan-16 2 1 Feb-16 3 1 Mar-16 4 1 Apr-16 5 1 May-16 6 1 Jun-16 7 1 Jul-16 8 1 Aug-16 9 2 Mar-16 10 2 Apr-16 11 2 May-16 12 2 Jun-16 13 2 Jul-16 14 2 Aug-16 15 3 Mar-16 16 3 Apr-16 17 3 May-16 18 3 Jun-16 19 3 Jul-16 20 3 Aug-16 structure(list(Subject = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L), Date = structure(c(4L, 3L, 7L, 1L, 8L, 6L, 5L, 2L, 7L, 1L, 8L, 6L, 5L, 2L, 7L, 1L, 8L, 6L, 5L, 2L), .Label = c("Apr-16", "Aug-16", "Feb-16", "Jan-16", "Jul-16", "Jun-16", "Mar-16", "May-16"), class = "factor")), class = "data.frame", row.names = c(NA, -20L), .Names = c("Subject", "Date")) I tried using expand from tidyr and TimeFill from DataCombine package, but the issue with those approaches is that I would get dates for periods before a participant joined an experiment. In this particular instance, I only want the periods to be filled for cases when a participant drops out of an experiment. A: The complete function from tidyr is designed for turning implicit missing values into explicit missing values. We will have to do some filtering to not include past completion. The easiest way seems to be to do a join on a table with starting values: library(dplyr) library(tidyr) df <- df %>% filter(Date != '') %>% droplevels() %>% group_by(Subject) df2 <- summarise(df, start = first(Date)) df %>% complete(Subject, Date) %>% left_join(df2) %>% mutate(Date2 = as.Date(paste0('01-', Date), format = '%d-%b-%y'), start = as.Date(paste0('01-', start), format = '%d-%b-%y')) %>% filter(Date2 >= start) %>% arrange(Subject, Date2) %>% select(-start, -Date2) Result: Source: local data frame [20 x 2] Groups: Subject [3] Subject Date <int> <fctr> 1 1 Jan-16 2 1 Feb-16 3 1 Mar-16 4 1 Apr-16 5 1 May-16 6 1 Jun-16 7 1 Jul-16 8 1 Aug-16 9 2 Mar-16 10 2 Apr-16 11 2 May-16 12 2 Jun-16 13 2 Jul-16 14 2 Aug-16 15 3 Mar-16 16 3 Apr-16 17 3 May-16 18 3 Jun-16 19 3 Jul-16 20 3 Aug-16 I use date conversion to do a reliable comparison with the starting date, but you might be able to use the row_numbers somehow. A problem is that complete will rearrange the data. p.s. Note that your example dput has an empty factor level (""), so I filter that out first.
{ "pile_set_name": "StackExchange" }
Q: DISTINCT results in ORA-01791: not a SELECTed expression select DISTINCT a.FNAME||' '||a.LNAME from AUTHOR a, books B, BOOKAUTHOR ba, customers C, orders where C.firstname='BECCA' and C.lastname='NELSON' and a.AUTHORID=ba.AUTHORID and b.ISBN=bA.ISBN order by a.LNAME gives ORA-01791: not a SELECTed expression but works without DISTINCT. How to make it work? A: Just add LNAME as a column on its own in the select clause: SELECT full_name FROM ( select DISTINCT a.FNAME||' '||a.LNAME AS full_name, a.LNAME from AUTHOR a, books B, BOOKAUTHOR ba, customers C, orders where C.firstname='BECCA' and C.lastname='NELSON' and a.AUTHORID=ba.AUTHORID and b.ISBN=bA.ISBN ) order by a.LNAME If you only want the first column in the output, you can put the whole thing in a subquery.
{ "pile_set_name": "StackExchange" }
Q: Model returning error - ValueError: logits and labels must have the same shape ((None, 18) vs (None, 1)) I'm playing around with a keras based multi label classifer. I created a function that loads training and test data and then I process/split X/Y within the function itself. I'm getting a error when running my model but not quite sure the meaning: Here's my code: def KerasClassifer(df_train, df_test): X_train = df_train[columnType].copy() y_train = df_train[variableToPredict].copy() labels = y_train.unique() print(X_train.shape[1]) #using keras to do classification from tensorflow import keras from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Dropout, Activation from tensorflow.keras.optimizers import SGD model = Sequential() model.add(Dense(5000, activation='relu', input_dim=X_train.shape[1])) model.add(Dropout(0.1)) model.add(Dense(600, activation='relu')) model.add(Dropout(0.1)) model.add(Dense(len(labels), activation='sigmoid')) sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True) model.compile(loss='binary_crossentropy', optimizer=sgd) model.fit(X_train, y_train, epochs=5, batch_size=2000) preds = model.predict(X_test) preds[preds>=0.5] = 1 preds[preds<0.5] = 0 score = model.evaluate(X_test, y_test, batch_size=2000) score Here are attributes of my data(if it helps): x train shape (392436, 109) y train shape (392436,) len of y labels 18 How can I fix the code to avoid this error? A: If you have 18 categories the shape of y_train should be (392436, 18). You can use tf.one_hot for that: import tensorflow as tf y_train = tf.one_hot(y_train, depth=len(labels)) And if you're taking your values from one column, I suspect this is not "multi-label", but multi-class. Can a sample really belong to multiple categories? If not, you will need to change a few other things too. For instance, you would need softmax activation: model.add(Dense(len(labels), activation='softmax')) And also categorical crossentropy loss: model.compile(loss='categorical_crossentropy', optimizer=sgd)
{ "pile_set_name": "StackExchange" }
Q: What is the best approach to encapsulate blocking I/O in future-rs? I read the tokio documentation and I wonder what is the best approach for encapsulating costly synchronous I/O in a future. With the reactor framework, we get the advantage of a green threading model: a few OS threads handle a lot of concurrent tasks through an executor. The future model of tokio is demand driven, which means the future itself will poll its internal state to provide informations about its completion; allowing backpressure and cancellation capabilities. As far as I understand, the polling phase of the future must be non-blocking to work well. The I/O I want to encapsulate can be seen as a long atomic and costly operation. Ideally, an independent task would perform the I/O and the associated future would poll the I/O thread for the completion status. The two only options I see are: Include the blocking I/O in the poll function of the future. spawn an OS thread to perform the I/O and use the future mechanism to poll its state, as shown in the documentation As I understand it, neither solution is optimal and don't get the full advantage of the green-threading model (first is not advised in documentation and second don't pass through the executor provided by reactor framework). Is there another solution? A: Ideally, an independent task would perform the I/O and the associated future would poll the I/O thread for the completion status. Yes, this is the recommended approach for asynchronous execution. Note that this is not restricted to I/O, but is valid for any long-running synchronous task! Futures crate The ThreadPool type was created for this1. In this case, you spawn work to run in the pool. The pool itself performs the work to check to see if the work is completed yet and returns a type that fulfills the Future trait. use futures::{ executor::{self, ThreadPool}, future, task::{SpawnError, SpawnExt}, }; // 0.3.1, features = ["thread-pool"] use std::{thread, time::Duration}; async fn delay_for(pool: &ThreadPool, seconds: u64) -> Result<u64, SpawnError> { pool.spawn_with_handle(async { thread::sleep(Duration::from_secs(3)); 3 })? .await; Ok(seconds) } fn main() -> Result<(), SpawnError> { let pool = ThreadPool::new().expect("Unable to create threadpool"); let a = delay_for(&pool, 3); let b = delay_for(&pool, 1); let c = executor::block_on(async { let (a, b) = future::join(a, b).await; Ok(a? + b?) }); println!("{}", c?); Ok(()) } You can see that the total time is only 3 seconds: % time ./target/debug/example 4 real 3.010 user 0.002 sys 0.003 1 — There's some discussion that the current implementation may not be the best for blocking operations, but it suffices for now. Tokio Here, we use task::spawn_blocking use futures::future; // 0.3.1 use std::{thread, time::Duration}; use tokio::task; // 0.2.9, features = ["full"] async fn delay_for(seconds: u64) -> Result<u64, task::JoinError> { task::spawn_blocking(move || { thread::sleep(Duration::from_secs(seconds)); seconds }) .await?; Ok(seconds) } #[tokio::main] async fn main() -> Result<(), task::JoinError> { let a = delay_for(3); let b = delay_for(1); let (a, b) = future::join(a, b).await; let c = a? + b?; println!("{}", c); Ok(()) } Additional points Note that this is not an efficient way of sleeping, it's just a placeholder for some blocking operation. If you actually need to sleep, use something like futures-timer or tokio::time. See Why does Future::select choose the future with a longer sleep period first? for more details neither solution is optimal and don't get the full advantage of the green-threading model That's correct - because you don't have something that is asynchronous! You are trying to combine two different methodologies and there has to be an ugly bit somewhere to translate between them. second don't pass through the executor provided by reactor framework I'm not sure what you mean here. There's an executor implicitly created by block_on or tokio::main. The thread pool has some internal logic that checks to see if a thread is done, but that should only be triggered when the user's executor polls it.
{ "pile_set_name": "StackExchange" }
Q: can't find the solution for robot path finding I'm new to the pddl. I need to find solution where a robot can put different objects in different destination cells. I'm using the software from http://www.fast-downward.org/. However, The problem is that my actions can't find the solution as required. The restriction is that no 2 objects can be in the same room even if the robot is carrying an object. attached: the domain file: (define (domain gripper-strips) (:predicates (ROOM ?x) ;iff x is a room (OBJECT ?x) ;iff x is an onject (HAND ?x) ;iff x is the robot's hand (FREE ?x) ;iff x is the robot's hand and it is free of object (ROBOT-AT ?x) ;iff x is a room and robot is located in x (OBJECT-AT ?x ?y) ;iff x is an object + y is a room and x is located at y (PATH ?x ?y) ;iff x and y are both room and there is no wall in-between (CARRY ?x) ;iff x is an object and robot is carrying it ) (:action MoveWithoutObject :parameters (?room1 ?room2 ?hand) :precondition (and (ROOM ?room1) (ROOM ?room1) (HAND ?hand) (not(=?room1 ?room2)) (FREE ?hand) (ROBOT-AT ?room1) (PATH ?room1 ?room2)) :effect (and (ROBOT-AT ?room2) (not (ROBOT-AT ?room1))) ) (:action MoveWithObject :parameters (?room1 ?room2 ?obj ?hand) :precondition (and (ROOM ?room1) (ROOM ?room2) (OBJECT ?obj) (HAND ?hand) (not(=?room1 ?room2)) (not (OBJECT-AT ?obj ?room1)) (not (OBJECT-AT ?obj ?room2)) (ROBOT-AT ?room1) (not(FREE ?hand)) (PATH ?room1 ?room2)) :effect (and (ROBOT-AT ?room2) (not (ROBOT-AT ?room1))) ) (:action Pickup :parameters (?obj ?room ?hand) :precondition (and (OBJECT ?obj) (ROOM ?room) (HAND ?hand) (OBJECT-AT ?obj ?room) (ROBOT-AT ?room) (FREE ?hand) (not(CARRY ?obj))) :effect (and (CARRY ?obj) (not (OBJECT-AT ?obj ?room)) (not (FREE ?hand))) ) (:action Release :parameters (?obj ?room ?hand) :precondition (and (OBJECT ?obj) (ROOM ?room) (HAND ?hand) (not(OBJECT-AT ?obj ?room)) (ROBOT-AT ?room) (not(FREE ?hand)) (CARRY ?obj)) :effect (and (OBJECT-AT ?obj ?room) (not(CARRY ?obj)) (FREE ?hand)))) and the problem file: (define (problem strips-gripper-x-8) (:domain gripper-strips) (:objects room1 room2 room3 room4 room5 room6 room7 room8 room9 object1 object2 object3 hand) (:init (ROOM room1)(ROOM room2)(ROOM room3)(ROOM room4)(ROOM room5)(ROOM room6)(ROOM room7)(ROOM room8)(ROOM room9) (OBJECT object1)(OBJECT objec21)(OBJECT object3) (HAND hand) (FREE hand) (ROBOT-AT room1) (OBJECT-AT object1 room6)(OBJECT-AT object2 room4)(OBJECT-AT object3 room7) (PATH room1 room4)(PATH room4 room1) (PATH room4 room5)(PATH room5 room4) (PATH room5 room6)(PATH room6 room5) (PATH room5 room8)(PATH room8 room5) (PATH room6 room9)(PATH room9 room6) (PATH room6 room3)(PATH room3 room6) (PATH room3 room2)(PATH room2 room3) (PATH room8 room7)(PATH room7 room8)) (:goal (and (OBJECT-AT object1 room7)(OBJECT-AT object2 room2)(OBJECT-AT object3 room9)))) A: Your approach is seemingly correct, but you have a couple of typos in your files that hinder the possibility of finding a solution. problem.pddl: change (OBJECT object1)(OBJECT objec21)(OBJECT object3) with (OBJECT object1) (OBJECT object2) (OBJECT object3) domain.pddl: change change (ROOM ?room1) (ROOM ?room1) in action MoveWithoutObject with (ROOM ?room1) (ROOM ?room2) EDIT: This escaped my first check since I didn't know the language in the first place and I assumed there was an universal quantification over the variables. You also need to fix MoveWithObject like this: (:action MoveWithObject :parameters (?room1 ?room2 ?obj1 ?obj2 ?obj3 ?hand) :precondition (and (ROOM ?room1) (ROOM ?room2) (HAND ?hand) (not(=?room1 ?room2)) (OBJECT ?obj1) (OBJECT ?obj2) (OBJECT ?obj3) (not (OBJECT-AT ?obj1 ?room1)) (not (OBJECT-AT ?obj1 ?room2)) (not (OBJECT-AT ?obj2 ?room1)) (not (OBJECT-AT ?obj2 ?room2)) (not (OBJECT-AT ?obj3 ?room1)) (not (OBJECT-AT ?obj3 ?room2)) (not (= ?obj1 ?obj2)) (not (= ?obj1 ?obj3)) (not (= ?obj2 ?obj3)) (ROBOT-AT ?room1) (not (FREE ?hand)) (PATH ?room1 ?room2)) :effect (and (ROBOT-AT ?room2) (not (ROBOT-AT ?room1))) ) Now the solver finds the following solution: Solution found! Actual search time: 2.23336s [t=4.41504s] movewithoutobject room1 room4 hand (1) movewithoutobject room4 room5 hand (1) movewithoutobject room5 room6 hand (1) pickup object1 room6 hand (1) movewithobject room6 room3 object1 object2 object3 hand (1) release object1 room3 hand (1) movewithoutobject room3 room6 hand (1) movewithoutobject room6 room5 hand (1) movewithoutobject room5 room8 hand (1) movewithoutobject room8 room7 hand (1) pickup object3 room7 hand (1) movewithobject room7 room8 object1 object2 object3 hand (1) movewithobject room8 room5 object1 object2 object3 hand (1) movewithobject room5 room6 object1 object2 object3 hand (1) movewithobject room6 room9 object1 object2 object3 hand (1) release object3 room9 hand (1) movewithoutobject room9 room6 hand (1) movewithoutobject room6 room3 hand (1) pickup object1 room3 hand (1) movewithobject room3 room6 object1 object2 object3 hand (1) movewithobject room6 room5 object1 object2 object3 hand (1) movewithobject room5 room8 object1 object2 object3 hand (1) movewithobject room8 room7 object1 object2 object3 hand (1) release object1 room7 hand (1) movewithoutobject room7 room8 hand (1) movewithoutobject room8 room5 hand (1) movewithoutobject room5 room4 hand (1) pickup object2 room4 hand (1) movewithobject room4 room5 object1 object2 object3 hand (1) movewithobject room5 room6 object1 object2 object3 hand (1) movewithobject room6 room3 object1 object2 object3 hand (1) movewithobject room3 room2 object1 object2 object3 hand (1) release object2 room2 hand (1) Plan length: 33 step(s). Plan cost: 33 I used the following strategy for finding this solution, other strategies might find longer paths: $ fast-downward.py --alias seq-opt-bjolp problem.pddl
{ "pile_set_name": "StackExchange" }
Q: Is there a way to add a local database to a netbeans java project package? I have a java project I need to write that reads data in from a comma delimited text file. But, for extra credit we can use a database instead of a text file . I dont want to pay for a host or deal with servers. So, is there a way to create a database that is in my java package so I can use sql? I'm using netbeans (if it matters). I need everything to be in my java package so when I turn it in to my teacher he doesn't need to download extensions or do anything special. A: What you are asking for is referred to as an embedded database, as opposed to a database server. Besides JavaDB/Apache Derby mentioned in the correct answer by Lesya, another choice would be H2. Both are built in pure Java and can be bundled with your app. While both H2 and Derby are good options, you might find H2 is easier to learn, configure, and bundle.
{ "pile_set_name": "StackExchange" }
Q: MySQL JOIN vs PHP foreach loop I'm having a problem optimizing a MySQL Query, but so far it takes too long to pull a simple result limited to 500 records. My query is this: SELECT ou.*, gr.accepted, gr.value FROM offer_usermeta ou LEFT JOIN gateway_requests AS gr ON ou.customer_id = gr.customer_id WHERE ou.customer_id != "" AND ou.created >= '2012-10-08 00:00:00' AND ou.created <= '2012-10-08 23:59:59' ORDER BY ou.created DESC LIMIT 500 This query is taking an entire minute to iterate over maybe 40,000 records. I need it to pull in gateway responses based on the customer ID if there are any and the data looks correct with this query, but I need tips on optimizing. I was considering just pulling the data in separately and foreach'ing it together as necessary, but I know that's probably going to be far slower... Any tips? (I'm using codeigniter if anyone knows a fancy trick in there as well) A: Add an index on the created column if you haven't so far. The DB will have to fetch all records to do the order by and match the where condition no matter if you have a limit of only 500 records. After that try SELECT ou.*, gr.accepted, gr.value FROM offer_usermeta ou LEFT JOIN gateway_requests AS gr ON ou.customer_id = gr.customer_id WHERE ou.created between '2012-10-08 00:00:00' and '2012-10-08 23:59:59' ORDER BY ou.created DESC LIMIT 500
{ "pile_set_name": "StackExchange" }
Q: Different formulation of Riemann tensor I want to write the Riemann tensor in two dimensions as $$R_{abcd}=\frac{R}{2}(g_{ac}g_{bd}-g_{ad}g_{bc})$$ Now I know that the Ricci scalar is defined as $$R={R^{a}}_{a}=g^{ab}R_{ba}=g^{ab}R_{ab}$$ and the Ricci tensor is $$R_{ab}={R^m}_{amb}=g^{mn}R_{namb}.$$ So I found $$R=g^{ab}g^{mn}R_{namb}.$$ How does this return the identity I am looking for? A: The purely covariant components of the Riemann-tensor satisfy the following symmetries: $$ R_{abcd}=R_{cdab} \\ R_{abcd}=-R_{bacd}. $$ It is of course skew-symmetric under the exchange of $c-d$ as well, but that follows from the first property. So basically, $R_{(ab)(cd)}$ (the brackets are NOT symmetrization here!!!) is symmetric in $(ab)\leftrightarrow(cd)$ and skew-symmetric under the exchange of any two indices in the brackets. In two dimensions, there is only one independent component of skew-symmetric second order tensors, as if $A_{ab}$ is skew, then if you know $A_{12}$, you know $A_{21}$ and you also know that $A_{11}=A_{22}=0$. Which means that in two dimensions, a skew-symmetric index-pair $(ab)$ has only one effective value. Obviously, then a symmetric (but, basically, any) array built out of such pairs also have only one value. Hence, the fact that $R$ has only one independent component in two dimensions follow from $R$'s symmetries alone, and not from the definition of $R$. Which also means that the space of tensors which satisfy the symmetries of $R_{abcd}$ is one dimensional at every point. It is easy to check that the tensor $$ X_{abcd}=g_{ac}g_{bd}-g_{ad}g_{bc} $$ satisfies the symmetries of the curvature tensor, and $X$ is manifestly not zero anywhere. So $X$ provides a basis for the one-dimensional space of tensors-that-have-the-symmetries-of-R at every point, therefore there exists a function $K$ such that $$ R_{abcd}=KX_{abcd}. $$ The function $K$ can be determined by contracting $R$: $$ R=R_{abcd}g^{ac}g^{bd}=KX_{abcd}g^{ac}g^{bd}=K(g_{ac}g_{bd}-g_{ad}g_{bc})g^{ac}g^{bd}=K(4-2)=2K, $$ from which $$ R_{abcd}=\frac{K}{2}(g_{ac}g_{bd}-g_{ad}g_{bc}) $$ follows.
{ "pile_set_name": "StackExchange" }
Q: How to select the parent node only on parsed xml by using jquery I have the XML like this <Response> <Title> <RequestID>1</RequestID> </Title> <RequestID>120</RequestID> </Response> I need to get the RequestID value 120 only. var xml = "<Response><Title><RequestID>1</RequestID></Title><RequestID>120</RequestID></Response>"; var xmlData = $.parseXML(xml); var RID = $xmlData.find('RequestID'); //It is returning the data like [1, 120]; How can i get the value from the parent node of the RequestID only not nested child node? A: You can use the child selector. The child selector only selects the first-level descendants. var xml = "<Response><Title><RequestID>1</RequestID></Title><RequestID>120</RequestID></Response>"; var xmlData = $.parseXML(xml); var RID = $(xmlData).find('Response > RequestID').text(); console.log(RID); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
{ "pile_set_name": "StackExchange" }
Q: Why won't figure.area = ... not work? Swift 3.0 struct Shape{ struct Rectangle { var length = 0 var width = 0 var area: Float = 0 } struct Square { var length = 0 var width = 0 var area: Float = 0 } func area(length: Float, width: Float) -> Float { return length * width } } var figure = Shape.Rectangle() figure.width = 2; figure.length = 3 figure.area = Shape.area(figure.length,figure.width) Why won't figure.area = ... not work? It allows me to write that in xCode but it doesn't run properly in the PlayGround. Can you declare a function inside of a struct? If yes, how do I declare this (figure.area = Shape.area(figure.length,figure.width)) properly? A: You haven initialised an instance of Shape when you call area, so the compiler will be confused. You can either initialise a Shape instance and then call area Shape().area(etc...) Or make the area function a static function, then you can call it like you have been (a much better option anyways) E.g. struct Shape{ .... static func area(length: Float, width: Float) -> Float { return length * width } } Also, with swift 3, all arguments must be explicitly written unless there is an underscore before them in the function declaration. So you function call should look like this figure.area = Shape.area(length: figure.length, width: figure.width)
{ "pile_set_name": "StackExchange" }
Q: Where are they calling from? When making phone calls internationally, phone numbers are prefixed with a code indicating what country the number is located in. These codes are prefix codes, meaning that no code is a prefix of another. Now, earlier today you missed a call, and you're kind of curious where that call might have come from. So you want to look up the calling code. But, being a prefix code, you're not quite sure where it ends, so you decide to write a program to separate the calling code from the rest of the number. Input As input, you will recieve a string consisting of the digits 0-9. The first few digits will be one of the country calling codes listed below (this means the first digit will never be 0). After the country calling code, the rest of the input will contain zero or more digits in any order - it is not guaranteed to be a valid phone number. Your program must be able to handle inputs containing at least 15 digits Output Your program should output the unique country calling code that is a prefix of the number. The valid outputs are as follows: 1 20 211 212 213 216 218 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 260 261 262 263 264 265 266 267 268 269 27 290 291 297 298 299 30 31 32 33 34 350 351 352 353 354 355 356 357 358 359 36 370 371 372 373 374 375 376 377 378 379 380 381 382 383 385 386 387 389 39 40 41 420 421 423 43 44 45 46 47 48 49 500 501 502 503 504 505 506 507 508 509 51 52 53 54 55 56 57 58 590 591 592 593 594 595 596 597 598 5993 5994 5997 5999 60 61 62 63 64 65 66 670 672 673 674 675 676 677 678 679 680 681 682 683 685 686 687 688 689 690 691 692 7 800 808 81 82 84 850 852 853 855 856 86 870 875 876 877 878 879 880 881 882 883 886 888 90 91 92 93 94 95 960 961 962 963 964 965 966 967 968 970 971 972 973 974 975 976 977 979 98 991 992 993 994 995 996 998 This list is based on the codes listed on Wikipedia's list of country calling codes page as of revision 915410826, with a few modifications All codes listed as unassigned or discontinued and some codes listed as reserved for future use were omitted If a code listed on Wikipedia is a prefix of another, the latter was omitted If a single country or territory would have more than one code, and if those codes would have a common prefix, those codes are omitted in favour of their common prefix. This may result in independent countries being lumped together, or disputed territories being lumped in with a particular claimant. This is not intended as a political statement, and decisions about the inclusion or omission of territories and states were made based on the codes, not any beliefs I hold regarding the ownership or sovereignty of the entities using them. If given an input that does not begin with any of these codes, your program's behaviour is undefined. And finally: This is code-golf, fewer bytes of code is better Your submission may be either a function or a full program Any of the default I/O methods are fine The standard loopholes are forbidden Test cases input -> output 5292649259 -> 52 3264296721 -> 32 1550 -> 1 33121394 -> 33 7 -> 7 2542112543 -> 254 2005992972 -> 20 350 -> 350 360 -> 36 8505234469 -> 850 9795586334 -> 979 148985513598795 -> 1 222222 -> 222 5999995 -> 5999 A: JavaScript (ES6),  75 73  71 bytes Saved 1 byte thanks to @Shaggy Saved 2 bytes thanks to @Neil s=>/1|7|(2[^07]|3[578]|42|599?|50|6[789]|8[0578]|9[679]|.)./.exec(s)[0] Try it online! A: 05AB1E, 28 25 24 bytes η•A󾫸tEΓ∞ζ∊u½d•.¥¤ØªKн Try it online! η # prefixes of the input •A󾫸tEΓ∞ζ∊u½d• # compressed integer 211112166111113621489811655218129 .¥ # undelta: [0, 2, 3, 4, 5, 6, 8, 9, 15, 21, 22, 23, 24, 25, 26, 29, 35, 37, 38, 42, 50, 59, 67, 68, 69, 75, 80, 85, 87, 88, 96, 97, 99, 108] ¤ # last element of that list: 108 Ø # nth prime: 599 ª # append it to the list K # remove all those values from the list of prefixes н # get the first prefix left A: Retina 0.8.2, 60 bytes !`^(2[1-69]?|3[578]?|42?|599?|50?|6[789]?|8[578]?|9[679]?)?. Try it online!
{ "pile_set_name": "StackExchange" }
Q: When shall I create UML diagrams when developing software? I am currently working on a new software and I am not sure how to go on. I already started coding before having a good plan. My opinion was to start with below sequence Create User Stories Create BMSC & Hsmc Code the required features Test Refactor & solve bugs Now I want to know where do I put the UML Diagram, before coding or after coding? A: To be honest, there can not be a ultimate answer here. There are various process models and you have to find one that suits your needs and your project. Test driven development for example puts tests in front of writing the actual code. My point is, if you feel like UML gives you confidence - go do it. But if you feel like a minimal working example gives you more insights - write some code first and come back to uml later.
{ "pile_set_name": "StackExchange" }
Q: Custom binary crossentropy loss in keras that ignores columns with no non-zero values I'm trying to segment data where the label can be quite sparse. Therefore I want to only calculate gradients in columns that have at least one nonzero value. I've tried some methods where I apply an extra input which is the mask of these nonzero columns, but given that all the necessary information already is contained in y_true, a method which only looks at y_true to find the mask would definitely be preferable. If I would implement it with numpy, it would probably look something like this: def loss(y_true, y_pred): indices = np.where(np.sum(y_true, axis=1) > 0) return binary_crossentropy(y_true[indices], y_pred[indices]) y_true and y_pred are in this example vectorized 2D images. How could this be "translated" to a differentiable Keras loss function? A: Use tf-compatible operations, via tf and keras.backend: import tensorflow as tf import keras.backend as K from keras.losses import binary_crossentropy def custom_loss(y_true, y_pred): indices = K.squeeze(tf.where(K.sum(y_true, axis=1) > 0)) y_true_sparse = K.cast(K.gather(y_true, indices), dtype='float32') y_pred_sparse = K.cast(K.gather(y_pred, indices), dtype='float32') return binary_crossentropy(y_true_sparse, y_pred_sparse) # returns a tensor I'm unsure about the exact dimensionality specs of your problem, but loss must evaluate to a single value - which above doesn't, since you're passing multi-dimensional predictions and labels. To reduce dims, wrap the return above with e.g. K.mean. Example: y_true = np.random.randint(0,2,(10,2)) y_pred = np.abs(np.random.randn(10,2)) y_pred /= np.max(y_pred) # scale between 0 and 1 print(K.get_value(custom_loss(y_true, y_pred))) # get_value evaluates returned tensor print(K.get_value(K.mean(custom_loss(y_true, y_pred)) >> [1.1489482 1.2705883 0.76229745 5.101402 3.1309896] # sparse; 5 / 10 results >> 2.28284 # single value, as required (Lastly, note that this sparsity will bias the loss by excluding all-zero columns from the total label/pred count; if undesired, you can average via K.sum and K.shape or K.size)
{ "pile_set_name": "StackExchange" }
Q: What does this entry in Windows Event log mean? Please help me about this log in Windows Event log. What does this mean? 障害が発生しているアプリケーション名: xxx.exe、バージョン: 1.0.0.0、タイム スタンプ: 0x4db446eb 障害が発生しているモジュール名: mscorwks.dll、バージョン: 2.0.50727.4927、タイム スタンプ: 0x4a275a68 例外コード: 0xc0000005 障害オフセット: 0x002063db 障害が発生しているプロセス ID: 0x%9 障害が発生しているアプリケーションの開始時刻: 0x%10 障害が発生しているアプリケーション パス: %11 障害が発生しているモジュール パス: %12 レポート ID: %13 (Sorry about Japanese) A: Google Translate says: Failing application name: xxx.exe, Version: 1.0.0.0, time stamp: 0x4db446eb Failing module name: mscorwks.dll, version: 2.0.50727.4927, time stamp: 0x4a275a68 Exception Code: 0xc0000005 Fault offset: 0x002063db Process ID that has failed: 0x% 9 Start time of an application that has failed: 0x% 10 Faulty application path:% 11 Module path that has failed:% 12 Report ID:% 13 0xc0000005 is an access violation exception, something in the code is trying to access memory that doesn't belong to it (or doesn't exist). Since mscorwks.dll is part of .Net, (I think) and will have been thoroughly tested, both by Microsoft and their "field testers" (i.e., users), it's more likely to be a problem in your xxx.exe application. You might want to try running it under a debugger so you can more easily figure out exactly what the problem is. Debugging is usually more revealing than post-mortem analysis, especially for a generic problem like this that could have a thousand different causes.
{ "pile_set_name": "StackExchange" }
Q: Can human hand move at a speed rate like this baseball pitch or is it just the speed of ball? The fastest baseball pitch ever recorded was in 1974 at a speed of $100.9\frac{\mathrm{mile}}{\mathrm{hour}}$ (see correction below). Does this mean that the pitcher's hand was also traveling at that speed or just the ball? Is it physically possible to move hand/leg at that speed? I'm asking this because basically pitcher's hand was moving 17.7 inches per 10 millisecond which is really a super(unbelievable) speed for human. Update: The figure originally given in this question was dated; a current record of $105.1\frac{\mathrm{mile}}{\mathrm{hour}}~\left(169.14\frac{\mathrm{km}}{\mathrm{hour}}\right)$ was set by Aroldis Chapman in 2010 (source). A: I know little about baseball, but if you are willing to extend your question to include God's own sport of cricket, the fastest speed recorded by a bowler was 100.3 mph. This speed was recorded at the moment when the ball leaves the bowlers hand (the ball slows down once it's released) so the bowler's hand was indeed travelling at 100.3 mph. As Alexander points out, you can attain these high speeds using leverage. A typical fast bowler's arm is around a meter long from the shoulder joint to the cricket ball, and the rules demand the arm be kept straight during bowling. Dividing the speed by the circumference of the circle traced by the arm give the rotation speed as one rotation in 140ms, which isn't superhumanly fast. It's certainly faster than I can manage, but then I'm not paid millions of pounds per year to play cricket! A: "It's all in the wrist" as they say.. yes, of course the hand connected to the ball was moving at this speed (or higher) at the time of throw. This is the same in many other sports like volleyball or tennis. Untrained athletes keep one or more joints stiff during the movement which means they lose the maximum speed and also risk injury due to the added inertia of the arm that has to be accelerated by the shoulder muscles. A good throw or volleyball spike works by folding the arm into a smaller shape in the beginning of the throw, which reduces the angular inertia allowing the shoulder to accelerate the upper arm. After a while, the upper arm muscles start to accelerate the lower arm + wrist combo, with the wrist a bit twisted, reducing that inertia. And finally the wrist is accelerated by the lower arm muscles. All these accelerations add up to a huge speed at the wrist-end. Check out the hit at 0:29 in this beautiful slow-motion video
{ "pile_set_name": "StackExchange" }
Q: ASP.NET doesn't display an image from database in IE8 i'm trying to display an image from the database in an ASP.NET web page. I'm using a generic handler, and it works fine on firefox, chrome and IE9, but not in IE8. That's my generic handler code: public void ProcessRequest(HttpContext context) { byte[] FileContent = null; if (context.Request.QueryString["imagen"] != null) { FileContent = GetImageFromDatabase(context.Request.QueryString["imagen"]); context.Response.ContentType = "image/png"; context.Response.BinaryWrite(FileContent); } } And i have an image in my asp page markup: <asp:Image ID="imgInicio" runat="server" Width="100%" AlternateText="Inicio" /> Finally i call this on the load event; imgInicio.ImageUrl = String.Format(@"~/ShowImage.ashx?imagen={0}", idImage); I have tried it all. Any help would be appreciated. A: Problem solved I found the solution. I don´t know why in Internet Explorer 8 you have to specify the format of the image. I had to write code to format it using System.Drawing namespace. I added a helper class with the following methods: public static Image ImageFromBytes(byte[] buffer) { try { using (MemoryStream ms = new MemoryStream(buffer)) { return Image.FromStream(ms); } } catch { return null; } } public static byte[] FormatImage(byte[] buffer, ImageFormat format) { using (MemoryStream ms = new MemoryStream()) { using (Image img = ImageFromBytes(buffer)) { img.Save(ms, format); } return ms.ToArray(); } } And then i call the mehod inside the handler: context.Response.BinaryWrite(ImageHelper.FormatImage(FileContent, System.Drawing.Imaging.ImageFormat.Png)); I think that, when we convert the bytes to a System.Drawing.Image and then use the Save method to retrieve the bytes again, the framework does something, maybe add or remove some bytes, that other browsers ignore, but they are important to Internet Explorer 8. That's what i think, but it's not certain. The thing is that it works for me
{ "pile_set_name": "StackExchange" }
Q: Java - Socket has 'connection timed out error' or 'no route to host' error with certain internet I'm making a client/server pair with sockets to send and receive data back and forth. When I'm at home on my internet using two separate machines for client/server, it works fine as expected. Data is transmitted and so forth. However, today when I was working at a local coffee shop (Second Cup, in case that's relevant), this did not work. I kept getting the following errors: either connection timed out, or no route to host. Here is the relevant code: Server: public class TestServer { public static void main(String[] args) throws Exception { TestServer myServer = new TestServer(); myServer.run(); } private void run() throws Exception { ServerSocket mySS = new ServerSocket(9999); while(true) { Socket SS_accept = mySS.accept(); BufferedReader myBR = new BufferedReader(new InputStreamReader(SS_accept.getInputStream())); String temp = myBR.readLine(); System.out.println(temp); if (temp!=null) { PrintStream serverPS = new PrintStream(SS_accept.getOutputStream()); serverPS.println("Response received"); } } } } Client: (the relevant part) //sends a command to the server, and returns the server's response private String tellServer(String text) throws Exception { mySocket = new Socket("192.168.0.XXX", 9999); //the IPv4 address //use the socket's outputStream to tell stuff to the server PrintStream myPS = new PrintStream(mySocket.getOutputStream()); myPS.println(text); //the following code will get data back from the server BufferedReader clientBR = new BufferedReader(new InputStreamReader(mySocket.getInputStream())); String temp = clientBR.readLine(); if (temp!=null) { return temp; } else { return ""; } } It's pretty much as simple as can be. Again, as mentioned, at home on my internet it works fine - just do ipconfig, grab the IPv4 address, and put it in for the client. In coffee shops with free wifi, it doesn't work. I even fiddled with many different ports just in case. Thanks for any help, I'm new to sockets and finding this confusing. A: 192.168.x.y is a local address. source You need your home machines ip address as the INTERNET sees it. When you're home next, go to http://www.whatismyip.com/ and see what it thinks you are. Note that you might need to go onto your router and route traffic from your router to your machine for port 9999, since that's what you'll probably be hitting.
{ "pile_set_name": "StackExchange" }
Q: How many times does the for-loop run? How many times does the for-loop run? done <- false n <- 0 while (n < a-1) and (done = false) done <- true for m <- a downto n if list[m] < list[m - 1] then tmp <- list[m] list[m] <- list[m-1] list[m - 1] <- tmp done <- false n <- n + 1 return list In the worst case, is the answer (n ^ 2 + n) / 2 correct?. Does the while-loop run n+1 times? A: If downto includes the value of n, then: It will run for ((a+1)+a+(a-1)+(a-2)+...+1) times in the worst case. This equals ((a+1)*(a+2))/2. If downto does not include the value of n, then: It will run for (a+(a-1)+(a-2)+...+1) times in the worst case. This equals (a*(a+1))/2. In both cases, the while loop will run a times.
{ "pile_set_name": "StackExchange" }
Q: If I step up 9V to 12V with a boost converter, what happens when the input goes to 12V? I want to use either a 9 V or 12 V power supply. If the input is 9 V, I want to step it up to 12 V with a boost converter. But if the input is 12 V will the output still be 12 V or will it be boosted to 15 V or so. The boost converter is the XL6009. A: The output voltage is set by the feedback pin voltage, which in turn is set by a resistive divider. The regulator aims to ensure that the feedback pin stays at its comparative reference voltage (1.25V in this case) by adjusting the output voltage. Given that the reference is set by fixed resistors, then it is in principal entirely independent of the input voltage. That means if you set the regulator to 12V out, you will get 12V out regardless of whether the input voltage is 5V, 9V, 10V, etc. However in practice things aren't so simple. The DC/DC converter will have input vs output voltage requirements that must be met. Those conditions will depend on the topology of your circuit (hence @Jodes question I presume). If you wire up the XL6009 as a boost converter, the input voltage must be less than the output voltage for correct regulation. Conversely if you wire it up as a buck converter, the input voltage must be higher than the output voltage. In order to work with both a 12V and a 9V input, you will need to use the buck-boost topology. This should allow the regulator to both step up the voltage if the input is lower than the required output voltage, or step it down if the input is higher (or equal).
{ "pile_set_name": "StackExchange" }
Q: Using whereRaw() and orWhereRaw() with Join in laravel 5.2 I am writing a code like this:- $results = User::select('users.id','users.user_type','users.status','homechef_details.user_id','homechef_details.address1','homechef_details.name','homechef_details.updated_rating') ->join('homechef_details', function($query) use ($rating,$keyword) { $query->on('users.id', '=', 'homechef_details.user_id'); $query->where('users.status','=',1); if(isset($rating) && !empty($rating)) { if(count($rating)==1) $query->whereRaw('FLOOR(homechef_details.updated_rating) = '.$rating[0]); else if(count($rating)>1) { $query->where(function($q) use($rating) { $q->whereRaw('FLOOR(homechef_details.updated_rating) = '.$rating[0]); for($r = 1; $r < count($rating); $r++) { $q->orWhereRaw('FLOOR(homechef_details.updated_rating) = '.$rating[$r]); } }); } } })->get(); I need to check the floor value of the column value in the where clause. I am getting this error:- Call to undefined method Illuminate\Database\Query\JoinClause::whereRaw() How can I fix this error? A: It seems that the JoinClause class doesn't have a method for raw queries, i suggest you try soemthing like $results = User::select('users.id','users.user_type','users.status','homechef_details.user_id','homechef_details.address1','homechef_details.name','homechef_details.updated_rating') ->join('homechef_details','users.id', '=', 'homechef_details.user_id')->where('users.status','=',1); if(isset($rating) && !empty($rating)) { if(count($rating)==1) $results = $results->whereRaw('FLOOR(homechef_details.updated_rating) = '.$rating[0]); else if(count($rating)>1) { $results = $results->where(function($q) use($rating) { $q->whereRaw('FLOOR(homechef_details.updated_rating) = '.$rating[0]); for($r = 1; $r < count($rating); $r++) { $q->orWhereRaw('FLOOR(homechef_details.updated_rating) = '.$rating[$r]); } }); } } $results = $results->get();
{ "pile_set_name": "StackExchange" }
Q: How to twist an object with Sverchok? If I want to twist an object in Blender I can easily do it, for example with proportional editing: How can I achieve the same result with Sverchok? I've been trying with "List item" but could not get results. I would like to twist an object imported from the scene with Object In rather than a mesh created directly with Sverchok. Thanks A: This is one way to do it. currently: first split the verts of the object then multiply each vert's vector by a unique matrix (which is some function of z-height here i'm multiplying the vertex's Z component by 51.94) then recombine using mesh_join. We don't have a proportional editing method inside sverchok, you'd need to combine math nodes to emulate that feature. Not impossible, this layout should suggest further development. You can import this json Gist ID directly 8e11420e351e79be0760f86c2f51de06 in the Sv Import/Export panel. (make sure you update Sverchok to 0.5.6.2 or later) A: why not use simple deformation node? it is new node, that can twist, bend
{ "pile_set_name": "StackExchange" }
Q: UI update in didEnterRegion? I'm making an app that features the use of geofencing using a CLLocationManager. I've implemented these two methods and they are both getting called appropriately: - (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region { [self updateUI]; // update the UI } - (void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region { [self updateUI]; // update the UI } I'm doing a set of UI updates in a method called updateUI like so: - (void)updateUI { // Update labels, constraints, alphas and similar } updateUI is called within didEnterRegion and didExitRegion, but that raises a few questions: How does that work when the app is in the background? Should I detect if the app is open or in the background, then do the UI update in viewWillAppear instead? If updating the UI is a bad thing to do in these didEnterRegion and didExitRegion, what exactly are the consequences of doing it? Thanks! Erik A: If your app was not in the foreground when the notification arrived, it won't be foregrounded. Thus there is very little point doing anything to the interface at this point, because, in effect, there is no interface. Just process the notification in some way - i.e. note down what happened - and stop. Your job at this point is to get out of there as fast as possible and let the app go back to sleep. The next time your app comes to the front (becomes active), you'll get a notification of that, and now you can make the interface match the data.
{ "pile_set_name": "StackExchange" }
Q: Count how many of each character appears in C I'm trying to do exercise 1-14 from the C programming language book by Brian Kernighan. I'm using a list a list where the index number corresponds to the ASCII value, so list[65] should print out the number of times 'A' has appeared in my input. Unfortunately my program just seems not to increment. Any help would be appreciated! #include <stdio.h> #define MAXLEN 1000 int main() { int c, i; int chartype[MAXLEN]; for(i = 0; i < MAXLEN; ++i) chartype[i] = 0; while((c = getchar()) != EOF){ ++chartype[c - '0']; } for(i = 0; i < MAXLEN; ++i){ if(chartype[i]>0) printf("%c, %d\n", i, chartype[i]); } return 0; } output: 53, ? 56, ? A: The problem here is that c - '0' in the second loop. When you type 'A', you're incrementing the integer in index position c - '0', which is c - 48. So for 'A', it's incrementing integer number 17 (65-48), which is some special character. By just typing ++chartype[c], you increment the position of the character in the array and fix the problem. Also getchar() will take the input when you press the Enter key on input console or on encountering end of line in the input file. It will increment the value at index 10 every time Enter key is pressed or end of line is encountered. So simply add a condition in the last loop to avoid printing that. Or you can refer to some other sources to check how getchar() can avoid enter key or end of line. I have also used the suggestions given by Phil Kiener. #include <stdio.h> int main() { int c, i; int chartype[256] = { 0 }; // maximum value for an unsigned char while((c = getchar()) != EOF) { ++chartype[c]; // no need to subtract '0' } for(i = 0; i < 255; ++i) { if(chartype[i] > 0 && i!='\n') { //avoiding printing value present at index 10 printf("%c, %d\n", i, chartype[i]); } } return 0; }
{ "pile_set_name": "StackExchange" }
Q: Printing the length of shortest way in maze I'm trying to make Java program finding the shortest way in maze and printing the length of the way. . is a way and 'x' is obstacle. If I inputs ....xxx. x.x....x xxx..... x......x ...xxxxx ........ xxx..... xx...... the output is infinite: 0, 0 0, 1 1, 1 0, 1 1, 1 0, 1 1, 1 0, 1 1, 1 0, 1 1, 1 0, 1 1, 1 0, 1 ... and java.lang.StackOverflowError occurs. The right output must be 0, 0 0, 1 1, 1 0, 1 0, 2 0, 3 1, 3 2, 3 3, 3 3, 4 3, 5 3, 6 3, 5 3, 4 3, 3 3. 2 4, 2 5, 2 5, 3 6, 3 7, 3 7, 4 7, 5 7, 6 7, 7 16 How can I modify my code and get a right answer? Or what algorithm should I use to make a new code? I'm so confused.. I tried many times but I can not get the right answer T_T Plz help me import java.util.Scanner; public class ShortestMazeWay { static int count=0; static int[] result = new int[10000]; // save the move direction static int[][] find = new int[8][8]; static int[][] maze = new int[8][8]; // 0 = can go, 1 = can not go public static void main(String[] args) { Scanner sc = new Scanner(System.in); for(int i=0; i<8; i++) { String str = sc.nextLine(); for(int j=0; j<8; j++) { if(str.charAt(j)=='.') maze[i][j]=0; else maze[i][j]=1; } } find(0, 0); // start from (0, 0) } static void find(int i, int j) { find[i][j] = 1; // 0 = can go, 1 = can not go System.out.println(i+", "+j); // to check the way if(i==7 && j==7) // the end point is (7, 7) System.out.println(count); else { count++; if(i+1<8 && maze[i+1][j]!=1 && find[i+1][j]==0) // ↓ { result[count] = 1; find[i][j] = 0; find(i+1, j); } else if(j+1<8 && maze[i][j+1]!=1 && find[i][j+1]==0) // → { result[count] = 2; find[i][j] = 0; find(i, j+1); } else if(i-1>=0 && maze[i-1][j]!=1 && find[i-1][j]==0) // ↑ { if(result[count-1]==2) // if moved ↓ in previous step, count--; // go back to previous position else result[count] = 3; find[i][j] = 0; find(i-1, j); } else if(j-1>=0 && maze[i][j-1]!=1 && find[i][j-1]==0) // ← { if(result[count-1]==1) // if moved → in previous step, count--; // go back to previous position else result[count] = 4; find[i][j] = 0; find(i, j-1); } } } } A: When walking on the .'s, you need to make sure you don't step on a . that you already stepped on. One way to do that, is to leave a breadcrumb, e.g. change the . to a *, and remember to change it back to a '.' when you backtrack. Example: Direction order is up,right,down,left: *...xxx. 1 **..xxx. 2 ***.xxx. 3 ****xxx. 4 ****xxx. 5 ****xxx. 6 x.x....x x.x....x x.x....x x.x....x x.x*...x x.x**..x xxx..... xxx..... xxx..... xxx..... xxx..... xxx..... x......x x......x x......x x......x x......x x......x ...xxxxx ...xxxxx ...xxxxx ...xxxxx ...xxxxx ...xxxxx ........ ........ ........ ........ ........ ........ xxx..... xxx..... xxx..... xxx..... xxx..... xxx..... xx...... xx...... xx...... xx...... xx...... xx...... ****xxx. 7 ****xxx. 8 ****xxx. 9 ****xxx. 10 ****xxx. 11 ****xxx. 12 x.x***.x x.x****x x.x****x x.x****x x.x****x x.x****x xxx..... xxx..... xxx...*. xxx...** xxx...*. xxx...*. x......x x......x x......x x......x x.....*x x....**x ...xxxxx ...xxxxx ...xxxxx ...xxxxx ...xxxxx ...xxxxx ........ ........ ........ ........ ........ ........ xxx..... xxx..... xxx..... xxx..... xxx..... xxx..... xx...... xx...... xx...... xx...... xx...... xx...... ****xxx. 13 ****xxx. 14 ****xxx. 15 ****xxx. 16 ****xxx. 17 ****xxx. 18 x.x****x x.x****x x.x****x x.x****x x.x****x x.x****x xxx..**. xxx.***. xxx.***. xxx.***. xxx****. xxx.***. x....**x x....**x x...***x x..****x x..****x x.*****x ...xxxxx ...xxxxx ...xxxxx ...xxxxx ...xxxxx ...xxxxx ........ ........ ........ ........ ........ ........ xxx..... xxx..... xxx..... xxx..... xxx..... xxx..... xx...... xx...... xx...... xx...... xx...... xx...... Notice how it backtracked between step 10 and 11, and again between step 17 and 18. Remember: The first time you get to the end is not necessarily the shortest route. You must try all combinations for all steps, and remember the shortest path found, not just the first path found. With the direction order used above, here are some examples of complete routes: First Shortest Shortest Last Longest ****xxx. ****xxx. ****xxx. ****xxx. ****xxx. x.x****x x.x*...x x.x*...x x.x*...x x.x****x xxx.***. xxx*.... xxx*.... xxx*.... xxx.***. x.*****x x.**...x x.**...x x***...x x.*****x ..*xxxxx ..*xxxxx ..*xxxxx **.xxxxx ***xxxxx ..****** ..****** ..***... ****.... ******** xxx....* xxx....* xxx.***. xxx*.... xxx***** xx.....* xx.....* xx....** xx.***** xx.***** So, because you have to remember the full route taken every time you get to the end, a stack implementation is better than the recursive implementation currently used. UPDATE: OPTIMIZATION Had a new thought about a way to solve the problem without backtracking, which means it should be faster. Replace the breadcrumbs with a step number, i.e. the (fewest) number of steps to get to that position. Initialize maze with -1 for blocked (x) and Integer.MAX_VALUE for open (.), then do this: walk(maze, 0, 0, 1); private static void walk(int[][] maze, int y, int x, int step) { if (y >= 0 && y < 8 && x >= 0 && x < 8 && maze[y][x] > step) { maze[y][x] = step; walk(maze, y - 1, x, step + 1); walk(maze, y + 1, x, step + 1); walk(maze, y, x + 1, step + 1); walk(maze, y, x - 1, step + 1); } } The result is a maze like this: 1 2 3 4 XX XX XX .. <-- Unreachable XX 3 XX 5 6 7 8 XX XX XX XX 6 7 8 9 10 XX 9 8 7 8 9 10 XX 11 10 9 XX XX XX XX XX 12 11 10 11 12 13 14 15 XX XX XX 12 13 14 15 16 XX XX 14 13 14 15 16 17 Now you can find the shortest path by tracing from the end (17), going to a lower number, until you're back at the start (1).
{ "pile_set_name": "StackExchange" }
Q: Activate chrome app from web page? I am building a packaged chrome app (It is needed as I want to access chrome.socket). I have a website from which I would like to call my app (if installed or ask the user to install it) by clicking a link. Is this possible ? Not able to find any easy way for this workflow. A: The url_handlers might be the best way to achieve this. You can also use the externally_connectable manifest property to declare that your website can connect to your app, then call chrome.runtime.sendMessage or chrome.runtime.connect from your webpage and handle it in an chrome.runtime.onMessage handler in the app. Which one is better suited depends on your needs. The url_handlers is an easier way, but it will permanently assign the URL on your link to your app, so you won't be able to use it for anything else if the app is installed. The externally_connectable is a harder way, but it enables a much more elaborate bidirectional communication between your website and the app. You can even use a combination of the two approaches, if you need: launch the app using the url_handlers feature, then establish a communication channel back to the website once the app is up and running.
{ "pile_set_name": "StackExchange" }
Q: uwsgi nginx web.py interal server error: application not found Within my nginx sites-available/default this is the relevant portion for my app: location /app/ { include uwsgi_params; uwsgi_pass unix:///tmp/uwsgi.socket; } My app.xml file within the uwsgi/sites-available/ folder: <uwsgi> <socket>/tmp/uwsgi.socket</socket> <plugins>python</plugins> <chdir>/web/NetWeaveCustom</chdir> <module>index</module> </uwsgi> Finally my /web/NetWeaveCustom/index.py module is as follows: import web urls = ( '/(.*)','index' ) app = web.application(urls, globals()).wsgifunc() class index: def GET(self,name): return name Here is my uwsgi error log: [pid: 15963|app: -1|req: -1/15] 192.168.1.98 () {42 vars in 686 bytes} [Sun Dec 30 18:51:37 2012] GET /app/ => generated 48 bytes in 0 msecs (HTTP/1.1 500) 2 headers in 63 bytes (0 switches on core 0) [pid: 15963|app: -1|req: -1/16] 192.168.1.98 () {42 vars in 686 bytes} [Sun Dec 30 18:51:54 2012] GET /app/ => generated 48 bytes in 0 msecs (HTTP/1.1 500) 2 headers in 63 bytes (0 switches on core 0) [pid: 15964|app: -1|req: -1/17] 192.168.1.98 () {42 vars in 686 bytes} [Sun Dec 30 18:51:55 2012] GET /app/ => generated 48 bytes in 0 msecs (HTTP/1.1 500) 2 headers in 63 bytes (0 switches on core 0) [pid: 15963|app: -1|req: -1/18] 192.168.1.98 () {42 vars in 686 bytes} [Sun Dec 30 18:51:55 2012] GET /app/ => generated 48 bytes in 0 msecs (HTTP/1.1 500) 2 headers in 63 bytes (0 switches on core 0) When I got to my server/app/ folder I get the following error: uWSGI Error: Python application not found. There are no errors reported in the nginx error log. The strange thing is that this was working quite well until I decided to restart the uwsgi service. As soon as I did this error happened. Any suggestions as to what is going wrong here? A: uWSGI searches for the 'application' callable, while you are defining an 'app' one. Use <module>index:app</module> or add <callable>app</callable>
{ "pile_set_name": "StackExchange" }
Q: Confused on Java ThreadPool It is my first time to use Java Thread Pool for my new project, after I came across this link http://www.javacodegeeks.com/2013/01/java-thread-pool-example-using-executors-and-threadpoolexecutor.html, I am more confused on this, here is the code from the page, package com.journaldev.threadpool; public class WorkerThread implements Runnable { private String command; public WorkerThread(String s){ this.command=s; } @Override public void run() { System.out.println(Thread.currentThread().getName()+' Start. Command = '+command); processCommand(); System.out.println(Thread.currentThread().getName()+' End.'); } private void processCommand() { try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } } @Override public String toString(){ return this.command; } } package com.journaldev.threadpool; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class SimpleThreadPool { public static void main(String[] args) { ExecutorService executor = Executors.newFixedThreadPool(5); for (int i = 0; i < 10; i++) { Runnable worker = new WorkerThread('' + i); executor.execute(worker); } executor.shutdown(); while (!executor.isTerminated()) { } System.out.println('Finished all threads'); } } in the code, a fixed size pool is created and 10 worker threads are created, am I right? The thread pool is supposed to decrease the burden of a system, on the contrary, in the above code, I think it increases the burden by creating the pool in addition to the worker threads. why bother to use the thread pool? Can anyone explain? Thanks I also read this post on StackOverflow http://stackoverflow.com/questions/19765904/how-threadpool-re-use-threads-and-how-it-works it did not help me either. A: This is confusing because the Runnables are named WorkerThread, but they don't extend java.lang.Thread, they're just objects that implement Runnable. Implementing Runnable lets you specify a task that needs to be executed without having to instantiate an actual Thread object. The only threads created in your example are the main thread and the ones created by the Executor. Note that, even if you change this code to make WorkerThread extend Thread, as long as the code doesn't call start on them it wouldn't result in more threads actually running. Constructing a thread object involves some things like checking with the Security Manager and initializing threadlocals, but it doesn't actually do anything at the OS-level to allocate a thread. As far as the Executor is concerned they're just Runnables, it would execute them using the threadpool's threads.
{ "pile_set_name": "StackExchange" }
Q: Changing object file output path in makefile I have a makefile which does the following: FILES=file1.c file2.c file3.c subdir1/afile1.c subdir2/bfile1.c OBJS=$(FILES:.c=.o) all: $(OBJS) This will write the object files to the same directory as the source files but I don't want that. I want them to be written to separate subdirectories named "objs", "objs/subdir1" and "objs/subdir2" so I've tried the following: OBJS=$(FILES:.c=objs/.o) But this doesn't work. I've also tried to create a new rule like so: %.o: %.c: $(CC) -o objs/$@ $(CFLAGS) $*.c But this results in the following error: Mixed implicit and static pattern rules. Stop. So what is the easiest way to have the object files stored inside an "objs" subdirectory that mirrors the structure of the source file directory? i.e. file1.o, file2.o... should go into "objs", afile1.oshould go into "objs/subdir1" and bfile1.o should go into "objs/subdir2"? A: As alluded to in my comments, if you want targets to be created in a subdirectory you have to tell make that's what you want by modifying your target in your rule... just modifying the compiler command isn't enough because make doesn't know anything about what the recipes are doing. Write your rule as: OBJS = $(FILES:%.c=objs/%.o) objs/%.o : %.c $(CC) -o $@ $(CFLAGS) $<
{ "pile_set_name": "StackExchange" }
Q: Mongoose findOneAndUpdate updating as ObjectId I have the following schema: let PlayerSchema = new mongoose.Schema( { name: String, country: String, roundResults: [ { round: Number, result: String, points: Number } ] } ); When I use findOneAndUpdate to update a document: Player.findOneAndUpdate({ id: req.params.id }, {$push: {"roundResults": result }}, {safe: true, upsert: true, new : true}, (err, player) => { if( ! err && player ) { res.json( player ); } else { res.json( err ); } } ); I get the following unexpected result: [ { "_id": "57c9eb55c2a07a401462e3ec", "name": "Joe Bloggs", "country": "England", "__v": 0, "roundResults": [ { "_id": "57c9eba11c597d5e1460e4f0" } ] } ] I don't have a roundResults schema but, I get an _id as shown above, I would expect to see,: "roundResults": [ "round": 1, "result": "1", "points": 3 ] Can anyone explain why this is, or how I get this to nest the data I am displaying directly above? A: Even if you pass literal object for sub documents, it is a Schema. And id would be generated for that. If it is an array define its type Array. Attention that if you define any schema for a property it is considered as a subdoc and entity so it has id
{ "pile_set_name": "StackExchange" }
Q: How can I pass a multi-line variable to a docker container? According to this comment, multi-line variables are supported with docker compose: environment: KEY: |- line1 line2 However, when I execute echo $KEY in the container, it has replaced the newline with spaces: line1 line2 Am I missing something? My docker version is 1.12.1. A: The YAML syntax is correct. The shell command wasn't: echo "$KEY" prints the string with newlines.
{ "pile_set_name": "StackExchange" }
Q: Why doesn't work method of adding a contact to the array? I add a new contact in the method: addToBook(). First I check the fields, if they are not empty, then I create the instance of the class LocalStorage and pass the field values and make JSON from it. I want to see the new product in the array and LocalStorage but I get the error: Uncaught TypeError: Can not read property 'push' of undefined" Help me fix it. class Contacts { constructor() { // Storage Array this.contacts = []; } addToBook() { let isNull = forms.name.value != '' && forms.phone.value != '' && forms.email.value != ''; if (isNull) { // format the input into a valid JSON structure let obj = new LocalStorage(forms.name.value, forms.phone.value, forms.email.value); this.contacts.push(obj); localStorage["addbook"] = JSON.stringify(this.contacts); console.log(this.contacts); } console.log(this.contacts); } } let contacts = new Contacts(); class Forms { constructor() { // Blocks this.addNewContact = document.getElementById("addNewContact"); this.registerForm = document.querySelector('.addNewContact-form'); // Forms this.fields = document.forms.register.elements; this.name = this.fields[0].value; this.phone = this.fields[1].value; this.email = this.fields[2].value; // Buttons this.cancelBtn = document.getElementById("Cancel"); this.addBtn = document.getElementById("Add"); this.BookDiv = document.querySelector('.addbook'); // display the form div this.addNewContact.addEventListener("click", (e) => { this.registerForm.style.display = "block"; if (this.registerForm.style.display = "block") { this.BookDiv.style.display = "none"; } }); this.cancelBtn.addEventListener("click", (e) => { this.registerForm.style.display = "none"; if (this.registerForm.style.display = "none") { this.BookDiv.style.display = "block"; } }); this.addBtn.addEventListener("click", contacts.addToBook); } } let forms = new Forms(); class LocalStorage { constructor(name, phone, email) { this.name = name; this.phone = phone; this.email = email; } } <div class="AddNewContact"> <button id="addNewContact" type="button">Add new contact</button> <i class="fas fa-search "></i> <input type="text" placeholder="SEARCH BY NAME"> <button id="ImportData" type="button">Import data to book</button> </div> <div class="addNewContact-form"> <form name="register"> <label for="name">Name</label><input type="text" id="name" class="formFields"> <label for="phone">Phone</label><input type="text" id="phone" class="formFields"> <label for="email">E-Mail</label><input type="text" id="email" class="formFields"> <br><br> <button id="Add" type="button">Add Now</button><button id="Cancel" type="button">Cancel</button> </form> </div> A: When you pass a reference to a function like this: this.addBtn.addEventListener("click", contacts.addToBook); you loose the binding to this. Which you depend on when you call this.contacts.push(obj); in addToBook() You can hard bind the reference you want this to be with: this.addBtn.addEventListener("click", contacts.addToBook.bind(contacts); You could also pass in a function that explicitly calls addToBook with the correct context: this.addBtn.addEventListener("click", () => contacts.addToBook());
{ "pile_set_name": "StackExchange" }
Q: Pixel correlations from two raster datasets in R I am having trouble calculating the pixel by pixel correlation coefficient between two datasets. My current code takes in two folders full of rasters and creates two independent raster stacks. These rasters all have the same cellsize and extent. I then try and take the correlation coefficient (spearman in my case) between the column values of those rasters. library(raster) r <- raster() raster1 <- list.files(path = "data/List1", pattern = "*.tif$", full.names = T) raster2 <- list.files(path = "data/List2", pattern = "*.tif$", full.names = T) l1 <- stack(raster1) l2 <- stack(raster2) list1Values <- values(l1) list2Values <- values(l2) corValues <- vector(mode = 'numeric') for (i in 1:dim(list1Values)[1]){ corValues[i] <- cor(x = list1Values[i,], y = list2Values[i,], method = 'spearman') } corRaster <- setValues(r, values = corValues) However at the correlation for loop it gives six error messages saying In cor(x = list1Values[i, ], y = list2Values[i, ], method = "spearman") : the standard deviation is zero Ignoring that and continuing on, the last line errors out saying Error in setValues(r, values = corValues) : length(values) is not equal to ncell(x), or to 1 My initial guess was that since the datasets have a lot of NA values (In this case it is a lot of open ocean that there is no data for), that could cause problems, so I added the use = "complete.obs" parameter to the cor function. This errors saying Error in cor(x = list1Values[i, ], y = list2Values[i, ], method = "spearman", : no complete element pairs My guess is that this last error is telling me the matrices it created don't line up, and no non-NA cells match. I have no clue how this is possible because I have been working with these rasters for years and they certainly line up. Other than that, I don't know why this isn't working. This question is not a duplicate of Correlation/relationship between map layers in R? in any way. First I am not using point data, but instead raster. I am also interested in a simple pearson and/or spearman correlation coefficient NOT cross correlation nor spatial correlation. I'm also not using two layers, but two sets of hundreds of layers (making the statistical analysis of the correlation valid). Lastly, this code is doing fundamentally different things than that post and I am asking for specific help with the errors arising. A: If I'm reading what you're trying to do correctly, a more robust approach would be to use raster::calc() on your stacked layers, as follows. This allows on-disk calculations as well as the option to speed things up with parallel processing. # combine your two raster stacks. Now layers 1:(n/2) will be # correlated with layers ((n/2)+1):n. Make sure both stacks have the same # number of layers, i.e. nlayers(l_all) is even! l_all <- stack(l1, l2) # write a little function to do the correlation. The input is the vector # of values at cell n, which has length() == nlayers(l_all) corvec <- function(vec = NULL) { cor( # 'top' half of stack x = vec[1:(length(vec)/2)], # 'bottom' half of stack y = vec[((length(vec)/2) + 1):length(vec)], use = 'complete.obs', method = 'spearman' ) } corlyrs <- calc( l_all, fun = function(x) { # handle areas where all cell vals are NA, e.g. ocean if (all(is.na(x))) { NA_real_ } else { corvec(vec = x) } } ) The above will return a rasterLayer of correlation values. It took about 30s to correlate 2 sets of 6 300x300 cell rasters on my laptop. To speed things up with clusterR, # keep a cpu or two spare cpus <- max(1, (parallel::detectCores() - 1)) beginCluster(n = cpus) corlyrs <- clusterR(x = l_all, fun = calc, args = list(fun = function(cell) { if (all(is.na(cell))) { NA_real_ } else { corvec(cell) } }), export = 'corvec' ) endCluster() The last option may not be worth it unless your rasters are quite large. Saved me about 10 seconds on the actual calc, according to microbenchmark, but it also took about that long to establish the cluster. Benefits are much clearer with big rasters.
{ "pile_set_name": "StackExchange" }
Q: Is it possible to get user input in Windows Service C# I'm developing a Windows Service in C#. One of my requirements is to get some user input: to present some options and let them select one; based on their choice, the service should perform an associated operation. Is it possible to get user input in a Windows Service, with C#? A: No, a Windows Service is not designed for that. You would need to use a desktop or web application. If there is a good reason to use a service, you would need to create an application and have it send or communicate the input to the service.
{ "pile_set_name": "StackExchange" }
Q: First time smartphone buyer: Looking for a good phone for occasional use and testing Android Apps I've never had a smartphone before, but since I started Android development I thought it would be beneficial to have a physical device -- the emulator has some limitations. I do plan to make this phone my daily driver, but I am not really a heavy phone user. What I am looking for: Is developer friendly A nice camera A mid-sized display - I don't want anything so big that it's tough to carry Front-facing stereo speakers would be nice but it's not a requirement - I know many HTC phones have these but I have heard that the more recent models tend to get hot Screen does not get very hot - a phone that runs warm bothers me Relatively low SAR rating - It can't hurt to have a lower rating phone Can easily turn off the data plan and use wifi Fits in my $300-$400 budget I don't have a ton of knowledge about phone models and I would really appreciate some recommendations. A: For development it is a good idea to get a high-end phone. The nexus 5x is a high-end phone for a great price. It has a front facing speaker, 5.2 inch display with a 1920x1080 resolution. The CPU is a Snapdragon 808 and has 2GB of RAM. The phone is running android 6.0 and will continue to get updates for the next 2 years. A good reason to get a nexus for development is because of a "skinless (stock android UI)" android meaning less power is used to just have the phone turned on. Originally the nexus line was created for developers. The phone is also in your price range at 349 USD on Amazon.
{ "pile_set_name": "StackExchange" }
Q: route - link_to url_path Use the google-maps-for-rails and it works great! Can I use (routes) url_path in the marker infowindow. I use this code now def gmaps4rails_infowindow "<a href='http://domainname/en/guide/umbrie/steden/#{slug}'>#{name} - #{city_h1} </a> <br><br>#{city_description} <br> <br> <img src='/assets/#{slug}.jpg'> " end But I want to show another model in the same map, so different url's. I tried my url_path in the method, but with no succes. How can I do this? Based on your reply I tried this controller: @json = City.all.to_gmaps4rails do |city, marker| marker.infowindow render_to_string(:partial => "/cities/show", :locals => { :object => city }) marker.title "#{city.city_h1}" marker.sidebar "#{city.name} - #{city.city_h1} " marker.json({ :id => city.id, :name => city.name}) end partial: %h1 = city.name i get this error message: City Load (2.2ms) SELECT `cities`.* FROM `cities` Rendered cities/_show.html.haml (28143.9ms) Completed 500 Internal Server Error in 28230ms ActionView::Template::Error (undefined local variable or method `city' for #<#<Class:0x007fcab6bf0f08>:0x007fcab6be1080>): 1: %h1 2: = city.name A: Frankly you'd better use partials and declare infowindows in controller as described here. But well, if you really want to use url_helpers in model, add this in your model: delegate :url_helpers, to: 'Rails.application.routes' and use it this way in any method: url_helpers.root_path url_helpers.whatever_path
{ "pile_set_name": "StackExchange" }
Q: Behavior when initializing character array with larger array I was trying out some array related stuff in C. I did following: char a2[4] = {'g','e','e','k','s'}; printf("a2:%s,%u\n",a2,sizeof(a2)); printf("a2[4]:%d,%c\n",a2[4],a2[4]); In this code, it prints: a2:geek,4 a2[4]:0, In this code, it prints: a2:geek�,4 a2[4]:-1,� Both code run on same online compiler. Then why different output. Is it because the standard defines this case as undefined behavior. If yes, can you point me to exact section of the standard? A: The presence of excess initializers violates a constraint in C 2018 6.7.9 2: No initializer shall attempt to provide a value for an object not contained within the entity being initialized. 'k' and 's' would provide initial values for a2[4] and a2[5]. Since a2[4] or a2[5] do not exist, they are not contained within a2, and the constraint is violated. That said, compilers will typically provide a warning then ignore the excess initializers and continue. This is the least of the problems in the code you show and has no effect on the output you see. After the definition of a2, you print it using %s. %s requires a pointer to the first character in a sequence of characters terminated by a null. However, there is no null character in a2. The resulting behavior is not defined by the C standard. Often, what happens is a program will continue to print characters from memory beyond the array. This is of course not guaranteed and is especially unreliable in the modern high-optimization environment. Assuming the printf does continue to print characters beyond the array, it appears that, on one system, there happens to be a null character beyond the array, so the printf stops after four characters. When you later print a2[4] (also behavior not defined by the C standard) as an integer (%d) and a character (%c), we see there is indeed a null character there. On the other system, there is a −1 value in the memory at a2[4], which displays as “�”. After it, there are presumably some number (possibly zero) of non-printing characters and a null character. Additionally, you print sizeof(a2) using the printf specifier %u. This is incorrect and may have undefined behavior. A proper specifier for the result of sizeof is %zu.
{ "pile_set_name": "StackExchange" }
Q: SMSG: Did any school districts actual teach the curriculum as planned and what were the results for the teachers and students? I was introduced to the SMSG math curriculum at Topeka High School between 1965 and 1966. my recollection (somewhat defective for medical reasons) was that the Topeka (KS) school system rolled the curriculum out across all grade levels the same year. Our teacher went to a summer class to prepare for the new material. He was also an athletics coach and taught math as his academic job. The students had not come up through the curriculum and the teacher had no clue. Some of the brightest students in the class were confused, the rest were lost. The next summer, I tried to get my hands on the other textbooks to attempt to catch up. No joy! The curriculum was abandoned. I have read some stories on the Internet that suggest that some students who experienced more of the curriculum and its introduction and exploration of math concepts went on to enjoy and flourish in the study of math and astrophysics. My question is the one in the title: Did any school districts actual teach the curriculum as planned and what were the results for the teachers and students? A: Your question is twofold: (1) Did any school districts actual teach the curriculum as planned and (2) what were the results for the teachers and students? At the moment, I have an answer for (1): Yes. For (2), the results for teachers and students exist in various forms, but I have not combed through them carefully. And so your second question is certainly tractable, though I do not know the answer. To find out about your query, I passed it on to Henry Pollak since (quoting from the aforelinked): Pollak was heavily involved with the School Mathematics Study Group (SMSG), an attempt to improve primary and secondary American mathematics education. Invited by Edward Begle and Albert Tucker, he participated in the initial four-week writing session of the SMSG, creating new curriculum (1958-60). He later was a member of the SMSG advisory board (1961-64, 1967-72) and its chairman (1963-64). The take-away seems to be that, yes, the curriculum was taught in some places, and assessments of its creation and implementation were carried out by ETS, the Minnesota National Laboratory, the NSF, and SMSG itself. (Note: You may be interested in consulting Phillips' The New Math: A Political History; google books begins its preview with Chapter 5.) You can find an example of an SMSG report (funded by the NSF) from 1959 here; please note that there are many such documents (cf. the archive at U of Texas Austin here) and some are quite long. (More precisely: I have not read through them in granular detail, so I am confident that a more informative response than mine can be posted to answer your question.) I paste below Pollak's response, since it draws from his first-hand experience, and I am sure its availability on MESE is more valuable than confining it to my inbox! The work on SMSG started in the summer of 1958. I was a member of the team writing the first course on algebra and did not become a member of the overall advisory board for the project until about 1962. But I have both written materials and recollections relevant to your questions, both of them incomplete and full of gaps. In summary, there was an enormous amount of teaching (1) to provide formative evaluation for revisions, (2) to carry out major evaluations, by both Educational Testing Service and the Minnesota National Laboratory, and (3) to allow schools and teachers to use the materials. I have recollection that experimental teaching began immediately, and proof of careful testing for both the National Science Foundation and SMSG itself first carried out no later than 1959. The preparation by school districts for adopting the materials was highly variable, and [the emailed question] itself provides an example. Let me note parenthetically that UICSM, the University of Illinois Committee(?) on School Mathematics, which began around 1956, so at least two years earlier, initially required a full year of training at Urbana of any teacher wishing to teach its materials. I have summaries of both the ETS and the Minnesota evaluations published in 1961, but I do not own the full reports themselves. I have further evaluation summaries from 1963. I have summaries of state-by-state programs for in-service teachers from 1964 from 23 states. Kansas is not one of them. People still active who may have more information and copies of evaluations from the 1960's are Jeremy Kilpatrick and Jim Wilson, both at the University of Georgia (but possibly retired). Henry (I am not sure how one would obtain the full reports alluded to above; it is possible that they already exist in a digitized form, or are somewhere in the Briscoe Center archives. Hopefully another MESE user can fill in more details.) A: Just a short addition. Ed Begle published a valuable study through MAA/NCTM entitled "Critical Variables in Mthematics Education", which was an attempt (in part) to sort out some of the lessons of the SMSG.
{ "pile_set_name": "StackExchange" }
Q: Java: Subclassing ResourceBundle Say I have some instance of ResourceBundle: ResourceBundle bundle = getBundle(); ... some more code that does stuff with bundle ... I want to know if bundle has a particular key. Unfortunately, all of the methods I would use (containsKey(), keySet(), etc.) also check the parent bundle for the key. The method I would want to use is handleKeySet(), which is protected, therefore not visible.To get around this issue, the only solution I can think of is to create a subclass of ResourceBundle and implement getKeys() such that it returns only the keys of the current bundle and excludes the keys of the parent.The part where I start to doubt this solution is probably due to my confused understanding of inheritance. My question is.. does this seem to be the right way to go? And if so, any hints or a push in the right direction would be appreciated. A: In theory, when you create a subclass you do not alter the behavior inheritated, what you do is "improve" it by making it more specific to your needs. For example, you could extend GregorianCalendar into MyGregCal in order to use it to calculate the zodiacal sign corresponding to a given date. But you should avoid altering it in order to, say, calculate the julian calendar. Why? Because every method that accepts a GregorianCalendar will accept a MyGregCal, and will expect that it provides the functionality of GregorianCalendar. If it does not, then bad things (worse, unexpected bad things) can happen everywhere. So, if you can not get the functionality that you need without breaking the contract of the parent class, you should look somewhere else. Write the class from scratch, or from a simpler parent class (Properties?)
{ "pile_set_name": "StackExchange" }
Q: Instant Payment Notification order description blank in Express Checkout i am trying to integrate Paypal Express. The order almost works,the price und the name of the items are shown on in the cart of paypal, so i think the SetExpresscheckout works. My problem is that the DoExpressCheckoutPayment works wrong, because in the mail the order description is blank although i give the information: $padata = '&TOKEN='.urlencode($token). '&PAYERID='.urlencode($playerid). '&PAYMENTACTION='.urlencode("SALE"). '&AMT='.urlencode($ItemTotalPrice). '&PAYMENTREQUEST_0_CURRENCYCODE='.urlencode($PayPalCurrencyCode). '&L_PAYMENTREQUEST_0_NAME0='.urlencode("Name"). '&L_PAYMENTREQUEST_0_DESC0='.urlencode("Description"). '&CURRENCYCODE='.urlencode($PayPalCurrencyCode); $paypal= new MyPayPal(); $httpParsedResponseAr = $paypal->PPHttpPost('DoExpressCheckoutPayment', $padata, $PayPalApiUsername, $PayPalApiPassword, $PayPalApiSignature, $PayPalMode); Here is the same problem: Instant Payment Notification order description blank in Express Checkout (NVP) but the solution does not help. i hope you can help me. sorry for my bad english. A: PayPal doesn't recognize your line item details (L_PAYMENTREQUEST_0_NAME0 or L_PAYMENTREQUEST_0_DESC0) because you didn't include the line item quantity or price, and you didn't include the item subtotal. Ideally, you should be passing full details on the items that you sold, but if you just want to pass a summary, you need to add the following parameters to your DoExpressCheckoutPayment call: L_PAYMENTREQUEST_0_AMT0 (set this to the order total) L_PAYMENTREQUEST_0_QTY0 (set this to 1) PAYMENTREQUEST_0_ITEMAMT (set this to the order total)
{ "pile_set_name": "StackExchange" }
Q: Regarding the Dirac Hamiltonian's use of summation notation: Einstein summation notation, as I understand it: By writing $A_i B^i$ one implicitly means a sum over elements of the rank 1 tensors A and B. The key is the contraction of an "up" and a "down" index. In a formalism where a metric raises/lowers we should see this as an inner product, where the metric encodes the information of how an inner product is taken in such a space. This notation is convenient tool that I employ on a daily basis. However, the Hamiltonian for the Dirac Equation of QFT fame can be written: $$ H = \alpha_i p_i + \beta m $$ Two down indices? Summed together? Now, in this case we're considering a flat Minkowski space-time with $i$ summing over just the spacial indices. As such, we can raise and lower the indices for "free" with a Euclidean metric. Is this not an abuse of notation? This is not Einstein's summation convention but instead a bastardised summation notation in which we just do not write summation symbols? Surely it would be more explicit to write: $$ H = \alpha_i p^i + \beta m $$ Am I right here? Am I having some kind of mathematical mental breakdown? Both? A: As long as you understand what you mean, you can use whatever notation you want. For example, when you write $p_i \alpha_i$ you might mean $$ p_i\alpha_i\equiv p_1\alpha_1+p_2\alpha_2+p_3\alpha_3 $$ or $$ p_i\alpha_i\equiv -p_1\alpha_1-p_2\alpha_2-p_3\alpha_3 $$ or any other convention you may want to follow. But as soon as you want to share your results with others, you must clearly explain what you mean by some expression. For example, the combination $$ a_0 b_0-a_1b_1-a_2b_2-a_3b_3 $$ is very useful. Some people will write $a_\mu b^\mu$ for this particular combination, while some others will write $a_\mu b_\mu$ instead. If you are calculating something for yourself, write whatever feels better to you. When writing something for someone else, you must always define your symbols (unless it is really obvious what something means). For my taste, a pair of indices are summed if and only if one is an upper index and the other one is a lower index. But many people will assume that a pair of repeated indices are always summed, regardless their position.
{ "pile_set_name": "StackExchange" }
Q: Comparing bits efficiently ( overlap set of x ) I want to compare a stream of bits of arbitrary length to a mask in c# and return a ratio of how many bits were the same. The mask to check against is anywhere between 2 bits long to 8k (with 90% of the masks being 5 bits long), the input can be anywhere between 2 bits up to ~ 500k, with an average input string of 12k (but yeah, most of the time it will be comparing 5 bits with the first 5 bits of that 12k) Now my naive implementation would be something like this: bool[] mask = new[] { true, true, false, true }; float dendrite(bool[] input) { int correct = 0; for ( int i = 0; i<mask.length; i++ ) { if ( input[i] == mask[i] ) correct++; } return (float)correct/(float)mask.length; } but I expect this is better handled (more efficient) with some kind of binary operator magic? Anyone got any pointers? EDIT: the datatype is not fixed at this point in my design, so if ints or bytearrays work better, I'd also be a happy camper, trying to optimize for efficiency here, the faster the computation, the better. eg if you can make it work like this: int[] mask = new[] { 1, 1, 0, 1 }; float dendrite(int[] input) { int correct = 0; for ( int i = 0; i<mask.length; i++ ) { if ( input[i] == mask[i] ) correct++; } return (float)correct/(float)mask.length; } or this: int mask = 13; //1101 float dendrite(int input) { return // your magic here; } // would return 0.75 for an input // of 101 given ( 1100101 in binary, // matches 3 bits of the 4 bit mask == .75 ANSWER: I ran each proposed answer against each other and Fredou's and Marten's solution ran neck to neck but Fredou submitted the fastest leanest implementation in the end. Of course since the average result varies quite wildly between implementations I might have to revisit this post later on. :) but that's probably just me messing up in my test script. ( i hope, too late now, going to bed =) sparse1.Cyclone 1317ms 3467107ticks 10000iterations result: 0,7851563 sparse1.Marten 288ms 759362ticks 10000iterations result: 0,05066964 sparse1.Fredou 216ms 568747ticks 10000iterations result: 0,8925781 sparse1.Marten 296ms 778862ticks 10000iterations result: 0,05066964 sparse1.Fredou 216ms 568601ticks 10000iterations result: 0,8925781 sparse1.Marten 300ms 789901ticks 10000iterations result: 0,05066964 sparse1.Cyclone 1314ms 3457988ticks 10000iterations result: 0,7851563 sparse1.Fredou 207ms 546606ticks 10000iterations result: 0,8925781 sparse1.Marten 298ms 786352ticks 10000iterations result: 0,05066964 sparse1.Cyclone 1301ms 3422611ticks 10000iterations result: 0,7851563 sparse1.Marten 292ms 769850ticks 10000iterations result: 0,05066964 sparse1.Cyclone 1305ms 3433320ticks 10000iterations result: 0,7851563 sparse1.Fredou 209ms 551178ticks 10000iterations result: 0,8925781 ( testscript copied here, if i destroyed yours modifying it lemme know. https://dotnetfiddle.net/h9nFSa ) A: how about this one - dotnetfiddle example using System; namespace ConsoleApplication1 { public class Program { public static void Main(string[] args) { int a = Convert.ToInt32("0001101", 2); int b = Convert.ToInt32("1100101", 2); Console.WriteLine(dendrite(a, 4, b)); } private static float dendrite(int mask, int len, int input) { return 1 - getBitCount(mask ^ (input & (int.MaxValue >> 32 - len))) / (float)len; } private static int getBitCount(int bits) { bits = bits - ((bits >> 1) & 0x55555555); bits = (bits & 0x33333333) + ((bits >> 2) & 0x33333333); return ((bits + (bits >> 4) & 0xf0f0f0f) * 0x1010101) >> 24; } } } 64 bits one here - dotnetfiddler using System; namespace ConsoleApplication1 { public class Program { public static void Main(string[] args) { // 1 ulong a = Convert.ToUInt64("0000000000000000000000000000000000000000000000000000000000001101", 2); ulong b = Convert.ToUInt64("1110010101100101011001010110110101100101011001010110010101100101", 2); Console.WriteLine(dendrite(a, 4, b)); } private static float dendrite(ulong mask, int len, ulong input) { return 1 - getBitCount(mask ^ (input & (ulong.MaxValue >> (64 - len)))) / (float)len; } private static ulong getBitCount(ulong bits) { bits = bits - ((bits >> 1) & 0x5555555555555555UL); bits = (bits & 0x3333333333333333UL) + ((bits >> 2) & 0x3333333333333333UL); return unchecked(((bits + (bits >> 4)) & 0xF0F0F0F0F0F0F0FUL) * 0x101010101010101UL) >> 56; } } }
{ "pile_set_name": "StackExchange" }
Q: Which will be oxidised between water and Copper? I have always read that the one having higher discharge potential undergoes the reaction( oxidation or reduction). But In this example why is there also oxidation of water? A: The question is not fully complete (not your mistake but someone who wrote this exercise). I am not surprised that you are confused. The question is indeed silent about the electrodes. You should have asked the question: What is the cathode made of? What is the anode made of before starting the question. The second trick in your question in your question is, which I liked, is that it is an example of exhaustive electrolyte. You passed a huge current which consumed all free metal ions and the solvent can also be reduced or oxidized. So let us look at your problem: At the cathode you have two explicit choices: (i) Reduction of Cu ions which are floating in the solution, (ii) Reduction of the solvent, which is water in your case to hydrogen! There is nothing else which can be reduced here as per your question. At the anode you still have two implicit (hidden) choices: (i) Oxidation of water and (ii) Oxidation of the anode material. Your solved questions bluntly assumes that the electrode is inert, say it is made of carbon or Pt or gold, whatever but inert. So are left with only one choice. Oxidation of water. However, let us say they actually told you that the anode is made of Copper: Oxidation potential of Cu Cu(s) ---------> Cu$^{2+}$(aq) + 2e$^{-1}$ -0.34 V Oxidation potential of water 2 H$_2$O(l)---------> O$_2$(g) + 4 H$^+$(aq) + 4e$^{-1}$ -1.23 V Which one do you think will get oxidized? The Cu electrode instead of water! This is the process and principle behind copper plating. When your examiners are quiet about electrode materials, assume the solvent is going to oxidize, i.e., water.
{ "pile_set_name": "StackExchange" }
Q: Javascript with new or not I have the following function var myInstance = (function() { var privateVar = 'Test'; function privateMethod () { // ... } return { // public interface publicMethod1: function () { // all private members are accesible here alert(privateVar); }, publicMethod2: function () { } }; })(); what's the difference if I add a new to the function. From firebug, it seems two objects are the same. And as I understand, both should enforce the singleton pattern. var myInstance = new (function() { var privateVar = 'Test'; function privateMethod () { // ... } return { // public interface publicMethod1: function () { // all private members are accesible here alert(privateVar); }, publicMethod2: function () { } }; })(); A: While the end result seems identical, how it got there and what it executed in is different. The first version executes the anonymous function with this being in the context of the window object. The second version executes the anonymous function, but this is in the context of a new empty object. In the end, they both return another object(your Singleton). It's just a slight difference in execution context. To test this out, but an alert(this); right before the declaration of the privateVar variable. @Tom Squires: That's not necessarily true and is poor practice not to declare your variables. A script with the "use strict"; directive does cause the JS engine to complain (assuming that the engine supports "use strict";
{ "pile_set_name": "StackExchange" }
Q: Função FWRITE não está gravando em formato binário em linguagem C Não estou conseguindo gravar dados em binário em um arquivo utilizando a linguagem C. Mesmo usando 'wb' a saída do arquivo são caracteres. Como posso proceder? Eis aqui parte do meu código: void cadastrar(void) { if((fp=fopen("Jogos.dat", "wb"))==NULL) { printf("\nO arquivo nao pode ser aberto!\n"); getch(); exit(1); } fseek(fp,0L, SEEK_END); do { printf("\n Digite o Nome do Jogo ('FIM' para sair): "); gets(reg[quantidade_cadastro].nome_jogo); if ((strcmp(reg[quantidade_cadastro].nome_jogo,"fim")!=0)&&(strcmp(reg[quantidade_cadastro].nome_jogo,"FIM")!=0)) { printf("\n Ano de Lancamento: "); scanf("%d",&reg[quantidade_cadastro].ano_lancamento); fflush(stdin); printf("\n Genero: "); gets(reg[quantidade_cadastro].genero); printf("\n Plataforma: "); gets(reg[quantidade_cadastro].plataforma); reg[0].status='1'; if(fwrite(&reg, sizeof(struct registro), 1, fp) != 1) { printf("\nErro de Gravacao :/"); getch(); } else { quantidade_cadastro++; printf("\n Jogo Gravado no Arquivo!\n\n"); } } }while((strcmp(reg[quantidade_cadastro].nome_jogo,"fim")!=0)&&(strcmp(reg[quantidade_cadastro].nome_jogo,"FIM")!=0)); fclose(fp);} A: O seu arquivo tem caracteres pelo seguinte motivo. Como sua struct é composta por 4 campos char e um campo int, o normal é que os dados possam ser lidos. O método fwrite escreve diretamente os valores de sua struct dentro de arquivo, sem fazer conversão de valores como o printf. Os valores usados são os da tabela ascii. Supondo que você tenha a seguinte string "ABCD", os valores seriam escritos como: 65,66,67,68. E quando o editor de texto fosse ler esses valores ele exibiria ABCD. Caso um int seja escrito no arquivo, o tamanho do int em 64bits vale 4, e o valor a ser escrito será 65. O valor escrito no arquivo será 65,0,0,0 ou A para o editor de texto. Caso o valore escrito seja 16961, deverá escrever AB. Se usar o comando string (presente no bin/ do gcc) será possível ver os nomes dos métodos, as strings e das bibliotecas usadas pelo seu sistema, isso por causa da interpretação da tabela ascii quando se lê o arquivo. Caso queira um arquivo com valores ilegíveis (sem caracteres A-Za-z-0-9), você deve armazenas valores que fujam o máximo possível dos caracteres literários e numéricos.
{ "pile_set_name": "StackExchange" }
Q: How to prevent Unity overwriting existing mappings with AutoRegistration Unity 3 offers new capabilities for AutoRegistration (Registration by Convention) such as: container.RegisterTypes( AllClasses.FromLoadedAssemblies(), //uses reflection WithMappings.FromMatchingInterface, //Matches Interfaces to implementations by name WithName.Default); This code will register all types that implement their similarly named interfaces, against those interfaces. For example, class MyService : IMyService will be registered automatically as though you had written the following: container.RegisterType<IMyService, MyService >(); My Question: What if I want this most of the time, but I want to choose a different implementation for one of my interfaces, even though a similarly named implementation exists? See: Patterns and practices on CodePlex An important article to read explaining why you would want to do this is Jeremy Miller's Convention Over Configuration article A: Unity has always used a "last in wins" rule for configuration. So do your autoconfig on the container first, then do the overrides afterwards. The last set configuration (regardless of how it happens) will be the one in the container. A: What stops you from overriding the automated mapping with a custom set loaded from configuration (which - if empty - means that no default mapping is overridden): // have your auto registration container.RegisterTypes( AllClasses.FromLoadedAssemblies(), //uses reflection WithMappings.FromMatchingInterface, //Matches Interfaces to implementations by name WithName.Default); // and override it when necessary container.LoadConfiguration(); where the configuration is <?xml version="1.0" encoding="utf-8" ?> <unity xmlns="http://schemas.microsoft.com/practices/2010/unity"> <container> <register type="IMyService" mapTo="OverriddenServiceImpl" /> </container> </unity> or <?xml version="1.0" encoding="utf-8" ?> <unity xmlns="http://schemas.microsoft.com/practices/2010/unity"> <container> ...nothing, do not override defaults ... </container> </unity> Moving the optional configuration to an XML file has the advantage - you can reconfigure the system without the need to recompile it.
{ "pile_set_name": "StackExchange" }
Q: How to fix "Class signed does not exist" error in Laravel 5.7? I just updated my Laravel project from 5.6 to 5.7. The primary reason I upgraded was I needed to add Email Verification to my project. After I completed all upgrade steps and implemented the Email Verification as per the Laravel documentation I am getting an error. So the steps leading up to the error is this: I used 1 route to test with, in my ..\routes\web.php file I have this line of code: Route::get('dashboard', ['uses' => 'DashboardController@getDashboard'])->middleware('verified'); When I try to go to that route it does redirect me to the view for ..\views\auth\verify.blade.php as it should. There I click the link to send the verification email. I get the email then I click the button in the email to verify my email. It launches a browser and starts to navigate me somewhere and thats when it gets an error: Class signed does not exist After much research I discovered the error was in the new VerificationController.php file that the instructions said to create and the line of code causing the problem is: $this->middleware('signed')->only('verify'); If I comment this line out and click the button in my email again then it works without any errors and my users email_verified_at column is updated with a datetime stamp. Below is the entire VerificationController.pas in case it sheds any light on the problem: <?php namespace App\Http\Controllers\Auth; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Foundation\Auth\VerifiesEmails; class VerificationController extends Controller { /* |-------------------------------------------------------------------------- | Email Verification Controller |-------------------------------------------------------------------------- | | This controller is responsible for handling email verification for any | user that recently registered with the application. Emails may also | be re-sent if the user didn't receive the original email message. | */ use VerifiesEmails; /** * Where to redirect users after verification. * * @var string */ protected $redirectTo = '/dashboard'; /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); $this->middleware('signed')->only('verify'); $this->middleware('throttle:6,1')->only('verify', 'resend'); } } A: Take a look at the Laravel Documentation on Signed URLs My guess is you are missing this entry in the $routeMiddleware array // In app\Http\Kernel.php /** * The application's route middleware. * * These middleware may be assigned to groups or used individually. * * @var array */ protected $routeMiddleware = [ ... 'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class, ];
{ "pile_set_name": "StackExchange" }
Q: haskell evaluation $ sign I am going through 'learn you some haskell' and I have written following application: import System.IO main = do filename <- getLine handle <- openFile filename ReadMode content <- hGetContents handle putStr . unlines . (map isLong) . lines $ content hClose handle isLong :: String -> String isLong x = if length x > 10 then x ++ " long enough" else x ++ " could be better!" And it works but when I remove "$" between lines and content a compilation fails. Could you help me understand why this is wrong? I was thinking that I compose statements with dots and I get a function (String -> IO ()) and I apply it to the "content" but why is "$" needed here?. Thanks! A: The operator (.) has type (b -> c) -> (a -> b) -> a -> c.... Its first two inputs must be functions. lines content, however, is of type [String], not a function, hence f . lines content will fail. The compiler treats it as f . (lines content) By adding the ($), you change the precedence, and it becomes f . lines $ content = (f . lines) $ content which works, because f and lines are both functions.
{ "pile_set_name": "StackExchange" }
Q: Gaussian integration of $Z(h) = \int e^{x.\Gamma x+hx} dx$ I am working on the function defined as: $$Z(h) = \int e^{-\frac{1}{2}x\Gamma x+hx}, dx$$ where $\Gamma$ is a $n\times n$ symmetric matrix, $h$ and $x$ are $n$-component vectors : $x =( x_1, x_2,\dots, x_n)$. We define the scalar product $$\langle g(x)\rangle =\int g(x) P(x)dx$$ where $$P(x)=\frac{1}{Z(0)}e^{-\frac{1}{2}x\Gamma x}.$$ Any ideas on how to show that $$\langle x_i,x_j \rangle = \left. \frac{\partial^2 \ln(Z(h))}{\partial h_i \partial h_j} \right|_{h=0} ?$$ A: You mean $\Gamma$ is positive definite, then $\Gamma = M^\top M$ so that $$Z(h) = \int_{\Bbb{R}^n} e^{-\frac12 \| M x-M^{-\top} h\|^2+\frac12\|M^{-\top}h\|^2}d^n x= \int_{\Bbb{R}^n} e^{- \frac12\| M M^{-1} y-M^{-\top} h\|+\frac12\|M^{-\top}h\|^2}d^n (M^{-1} y) \\ = \int_{\Bbb{R}^n} e^{-\frac12 \| y-M^{-\top} h\|^2+\frac12\|M^{-\top}h\|^2}|\det(M)|^{-1} d^n y= \int_{\Bbb{R}^n} e^{- \frac12\| y\|^2+\frac12\|M^{-\top}h\|^2}|\det(M)|^{-1} d^n y\\ = |\det(M)|^{-1} \sqrt{\pi/2}^ne^{\frac12\|M^{-\top}h\|^2}= |\det(\Gamma)|^{-1/2} \sqrt{\pi/2}^ne^{\frac12 h^\top \Gamma^{-1} h}$$
{ "pile_set_name": "StackExchange" }
Q: Inheritance and the prototype chain I have been reading through Mozilla Developer Network lately on JavaScript inheritance model. I am highly confused on one point. Here's the code from MDN: function Graph() { this.vertices = []; this.edges = []; } Graph.prototype = { addVertex: function(v) { this.vertices.push(v); } }; var g = new Graph(); console.log(g.hasOwnProperty('vertices'));// true console.log(g.hasOwnProperty('addVertex'));// false console.log(g.__proto__.hasOwnProperty('addVertex'));// true What I don't understand is that why does g.hasOwnProperty('addVertex') yields false since addVertex is a property of g although it's defined in Graph's prototype but still it is part of Graph. Also I had one more question: that if some object inherits from g (or so to say Graph) will it inherit only addVertex (those defined in Prototype of function) or it will inherit all three properties of graph namely vertices, edges and addVertex. A: Because hasOwnProperty specifically says it return false on inherited properties MDN: The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as own (not inherited) property. As for your second question - it depends on exactly how you have an object inherit from Graph. In the ES5 way, I would do this: var InheritedFromGraph = function() { Graph.call(this); } InheritedFromGraph.prototype = Graph.prototype; and then, yes, InheritedGraph will get the properties verticies and edge that Graph defined in it's constructor.
{ "pile_set_name": "StackExchange" }
Q: How to use beforeSave in CakePHP 3? $event, $entity and $options must be always filled? I'm inside "PostsTable.php" I'm trying to get form data to treat image files. In CakePHP 2, I used to do: public function beforeSave($options = array()) { if(!empty($this->data['Post']['picture']['name'])... Someone could explain this in Cake 3: beforeSave Cake\ORM\Table::beforeSave(Event $event, Entity $entity, ArrayObject $options) ? ADDED I try this snippet of code to see if I'm able to save this field on database just as a test but it seems beforeSave is being ignored: public function beforeSave($options) { if(!empty($entity->pic1['name'])) { $entity->pic1 = 'jus a test'; } Thanks A: Start with the function definition. Cake\ORM\Table::beforeSave(Event $event, EntityInterface $entity, ArrayObject $options) Since CakePHP is calling the function automatically, this is how it is being called, so build your function identically to the function definition: // In PostsTable.php public function beforeSave($event, $entity, $options) { } If you aren't sure what data is being sent, use CakePHP's debug() function: debug($event); debug($entity); debug($options); Once you find your data in $entity use it to do what you want to do to your data: if (!empty($entity->picture['name'])) { ...
{ "pile_set_name": "StackExchange" }
Q: Why is my street map in pokemon GO accurate even when GO is not out for my country? So I live in India and as everyone knows, the game is not out for my country yet. So i downloaded a pokemon GO apk from a 3rd party website and the game is up and working on my phone. BUT the street map in the game is perfectly correct. Every house, every street and every park in the game map matches my real surroundings. How can that happen when the game is not out for my country yet? Please help A: The game simply uses the data from Google Maps combined with gameplay data from Ingress. There's no need for them to set up anything specific for India. (Doing this by hand would be a massive task even just for one country). Also keep in mind that often features or data are already in some game even before they're actually accessible.
{ "pile_set_name": "StackExchange" }
Q: Unable to echo user queries in results I am learning PHP and in the process of making a search engine. The following code will not echo the users input, in the search field, on the results page. The search page: <!DOCTYPE html> <html> <head> <title>Search Engine</title> <style type="text/css"> body { background:#F0FFFF; margin:-80px; } form { margin:25%; } </style> </head> <body> <form action="result.php" method="post"> <input type="text" name="user_query" size="80" placeholder="Enter Search Here" /> <input type="submit" name="search" value="Search Now" /> </body> </html> The results page: <!DOCTYPE html> <html> <head> <title>Results</title> <style type="text/css"> .results { margin:5%; } </style> </head> <body bgcolor="#F0FFFF"> <form action="result.php" method="get"> <span><b>Enter Query Here:</b></span> <input type="text" name="user_keyword" size="80" /> <input type="submit" name="result" value="Search Now" /> </form> <?php if(isset($_GET['search'])) { $get_value = $_GET['user_query']; echo "<div class='results'> $get_value; </div>"; } ?> </body> </html> Can someone tell me why the user's input is not being echoed when the search is run? A: If you using method=post In form tag you must receive you data as $_POST Also method=get use $_GET Edit this lines in result page to this <?php if(isset($_POST['search'])){ $get_value = $_POST['user_query']; echo "<div class='results'>{$get_value}</div>"; } ?>
{ "pile_set_name": "StackExchange" }
Q: Quantum mechanics position/momentum state operator proof Is there any way to prove $$ e^{-i\beta p}|q\rangle = |q+\beta\rangle $$ just by using these identities $$ [q,\mathcal{F}(p)]=i\hbar \mathcal{F}'(p) \;\;\;\;[q,p]=i\hbar $$ in quantum mechanics? A: Yes, you just have to check that $e^{-i\beta P/\hbar}|q\rangle$ is an eigenket of $Q$ (uppercase represents operators) with eigenvalue $q+\beta$. We evaluate $$ Q \big ( e^{-i\beta P/\hbar}|q\rangle \big ) $$ by using the first identity (which is actually a consequence of the canonical commutation relation): $$ Q e^{-i\beta P/\hbar} = e^{-i\beta P/\hbar}Q + i\hbar \left ( \frac{ -i \beta}{\hbar} e^{-i\beta P/\hbar} \right ), $$ which upon substitution gives $$ Q \big ( e^{-i\beta P/\hbar}|q\rangle \big ) = (q + \beta ) \big ( e^{-i\beta P/\hbar}|q\rangle \big ). $$ This means that $e^{-i\beta P/\hbar}|q\rangle$ is proportional to an eigenket of $Q$ with eigenvalue $q+\beta$, namely $c|q+\beta\rangle$. Fortunately, since the displacement operator $e^{-i\beta P/\hbar}$ is unitary, $c$ must satisfy $|c|^2 = 1$ to preserve normalization of the position eigenkets. This means $c$ is just an arbitrary phase factor which can promptly be chosen to be unity and then we have our final result: $$ e^{-i\beta P/\hbar}|q\rangle = |q + \beta\rangle $$
{ "pile_set_name": "StackExchange" }
Q: How to load existing VMWare Fusion from Mac OS X onto Windows PC? I'm using a Mac VMWare Fusions, I have 6 appliances. I want to reuse 1 of them, and load them into my Windows PC. Which software should I use ? VirtualBox VMWare Work Station (recommended, since it is VMWare product ?) How do I do it ? Do I need convert them first ? What options do I select to retore them ? A: Use VMware Workstation and you do not need to convert the file. Copy the VMware Fusion machine folder (all the files) to the Windows machine with VMware Workstation and it should open. Please see the VMware Knowledgebase article below and note carefully the version requirements Yes you can go both ways, it's not a problem at all. As long as you stick with the same time era product versions (eg. Fusion 8.x and Workstation12.x) then the trouble is minimal. https://communities.vmware.com/thread/551630
{ "pile_set_name": "StackExchange" }
Q: Good reference of color-modifying functions? I can't find a good reference about color-modifying functions (such as contrast, brightness, gamma, ...). (Is there a more exact term for what I mean?) Would appreciate a tutorial with example pictures and implementation algorithms. Thank you! EDIT: Platform and language is not so important. I'm interested in pure mathematic algorithms, so please don't point me to graphic APIs ;) A: Somewhat dry, but usually thorough is the Color FAQ: http://www.poynton.com/ColorFAQ.html
{ "pile_set_name": "StackExchange" }
Q: Ignore changes to a tracked file I want to change a tracked file for development only, but keep the tracked version unchanged. Most "solutions" for this suggest git update-index --assume-unchanged but it's totally useless, because the file will still be changed by checkout or reset. Is there a better solution that survives checkout and reset commands? A: Quick Fix This is what I think you're trying to do, change a file, but ignore it when committing. git update-index --skip-worktree my-file Here is a good answer regarding the difference between assume-unchanged and skip-worktree. Git will still warn if you try to merge changes into my-file. Then you will have to "unskip" the file, merge it and "re-skip" it. git update-index --no-skip-worktree my-file # merge here git update-index --skip-worktree my-file There can also be problems if you modify the file, then switch to a branch where that file has been changed. You may have to do some fancy "skip/unskip" operations to get around that. Long Term Fix In the long term, you probably want to separate your "local" changes into a second file. For example, if the file you want to change is a config file, create a "default" config file that you check into the repository. Then, allow a second "overrides" config file that is optional and put that file in your .gitignore. Then, in your application, read the default config file and then check if the overrides file exists. If it does, merge that data with the data from the default file. This example is for a config file, but you can use that technique for other kinds of overrides if needed.
{ "pile_set_name": "StackExchange" }
Q: Etale cohomology with coefficients in $\mathbb{Q}$ Let $X$ be a smooth variety of a field $k$. Then is $$H_{et}^i(X, \mathbb{Q}) = 0$$ for all $i > 0$? The result is true for $i=1$. This follows from the same argument given for $\mathbb{Z}$-coefficients given here: Etale cohomology with coefficients in the integers. Note that one needs to at the very least assume that $X$ is normal; otherwise $H_{et}^1(X, \mathbb{Q})$ can be non-trivial. The result is true if $X = \mathrm{Spec}(k)$. This follows from standard properties of Galois cohomology. Note that the analogous result is not true with $\mathbb{Z}$-coefficients; $H^2(k, \mathbb{Z})$ is often non-trivial. If it helps, I mostly care about the case $i=2$. A: The following is surely expressing whatever is in the core non-formal aspect of Joe Berner's answer (which is above my pay grade); it is offered as an alternative version of the same ideas. Let $X$ be a normal noetherian scheme. We'll show the higher etale cohomology with coefficients in any flat $\mathbf{Z}$-module $M$ is torsion, and hence vanishes when $M$ is a $\mathbf{Q}$-vector space. Via the exact sequence $$0 \rightarrow M \rightarrow \mathbf{Q} \otimes_{\mathbf{Z}} M \rightarrow T \rightarrow 0$$ with $T$ visibly torsion, we just have to show the higher etale cohomology of the middle term vanishes; i.e., we are back to the original question of vanishing of higher etale cohomology with coefficients in a $\mathbf{Q}$-vector space $V$. We can assume $X$ is connected, so it is irreducible (as $X$ is noetherian and normal); let $\eta$ be its unique generic point. For any quasi-compact etale $E \rightarrow X$, the scheme $E$ is normal and noetherian, so its connected components are all irreducible and as such have their unique generic point over $\eta$ (due to flatness of $E$ over $X$). Thus, $E \mapsto E_{\eta}$ does not lose any information about connected components, so for the natural map $j:\eta \rightarrow X$ we see that the natural map of etale sheaves $V_X \rightarrow j_{\ast}(V_{\eta})$ induces an isomorphism upon evaluating on any such $E$, whence it is an isomorphism of sheaves. Thus, our task is the same as proving the vanishing of the higher etale cohomology on $X$ of $j_{\ast}(V_{\eta})$. Consider the Leray spectral sequence $$E_2^{n,m} = {\rm{H}}^n(X, {\rm{R}}^mj_{\ast}(V_{\eta})) \Rightarrow {\rm{H}}^{n+m}(\eta,V_{\eta}).$$ The sheaf ${\rm{R}}^m j_{\ast}(V_{\eta}$ is the etale sheafification of the presheaf on $X_{\rm{et}}$ given by $U \mapsto {\rm{H}}^m(U_{\eta},V)$ (with quasi-compact etale $U$ over $X$). The latter vanishes for $m>0$ since it is Galois cohomology (for the finitely many points of $U_{\eta}$) and $V$ is a $\mathbf{Q}$-vector space. Hence, $E_2^{n,m}=0$ for $m>0$, so $${\rm{H}}^n(X, j_{\ast}(V_{\eta})) \simeq {\rm{H}}^n(\eta,V_{\eta})$$ for all $n \ge 0$. But the right side vanishes for $n>0$ for the same Galois-cohomological reasons, so we are done. A: Yes. It is a theorem that for a quasi-compact quasi-separated locally noetherian and normal scheme $X$ that its protruncated etale homotopy type is already profinite. You can look at DAG XIII for details, but this is stated in slightly more/less generality in Artin and Mazur's book. That means that its truncated etale homotopy type is represented by some cofiltered diagram of $\pi$-finite spaces $\operatorname{Ver}_X : D \rightarrow \mathcal{S}$ (roughly, the Verdier functor in Artin-Mazur). The point here is that for any constant sheaf of abelian groups $A$ we have that the sheaf cohomology $H^i(X,\underline{A})$ is isomorphic to $\lim_{d \in D} H^i(\operatorname{Ver}_X(d),A)$. This reduces our question to showing that $H^i(Z,\mathbb{Q})$ is zero for all $i>0$ and all '$\pi$-finite spaces' $Z$, which means that $Z$ has finitely many connected components, and finitely many non-zero homotopy groups (for arbitrary basepoints $z \in Z$) which are all finite groups. We can do this pretty explicitly. Cohomology commutes with disjoint union, so assume that $Z$ is connected, its universal cover $\tilde{Z}$ is of course simply connected, and the rational Hurewicz theorem implies it has trivial rational homology in positive degrees. The universal coefficient theorem then implies it has trivial rational cohomology in positive degrees. We know that the rational cohomology of $Z$ and $\tilde{Z}$ differ by a spectral sequence $E_2^{p,q} = H^p(\pi_1(Z,z),H^q(\tilde{Z},\mathbb{Q})) \Rightarrow H^{p+q}(Z,\mathbb{Q})$. This is just a row spectral sequence, and so the question reduces to the statement that finite groups have torsion cohomology in positive degrees, which seems to be well known (although I don't have a source).
{ "pile_set_name": "StackExchange" }
Q: Using implication and equality I've searched around a quite bit for an answer to this question but I haven't found the answer. If someone can find a link to a question that has an answer that also answers this question that would be great. If not, here is my question. I am an engineering student and for years I have thought that I was using the implication arrow ($\Rightarrow$) and the equality sign ($=$) in a correct way but recently a friend told me that I was using them incorrectly. As I understand , the equality sign means that the expressions on both sides of the sign are equal and that you can use many of them in a sequence, for example: $$ x^3+2x^2+x=x(x^2+2x+1)=x(x+1)^2 $$ As for the implication arrow, as far as I understand this is considered correct usage: $$ x^3+2x^2+2x=x\ \Rightarrow \ x^3+2x^2+x=0 \ \Rightarrow \ x(x^2+2x+1)=0 \\ \Rightarrow x(x+1)^2=0\ \Rightarrow \ x=0 \ \lor \ x=-1 $$ I assume that what I have done above is correct so here comes the part where we disagree. My friend says that I can not use a sequence of equality signs after an implication arrow, that is only one equality can follow an implication. He would say that the following usage is incorrect: $$ x^3+2x^2+2x=x\ \Rightarrow \ x^3+2x^2+x=x(x^2+2x+1)=x(x+1)^2=0 \\ \Rightarrow \ x=0 \lor \ x=-1 $$ or (this is closer to the case of our original dispute) $$ x=5 \quad \text{ and } \quad y=10 \\ \Rightarrow x^2+y^2=25+100=125 $$ I don't remember if my friend gave me a clear reason why this was wrong, but he said that his high school/junior college math teacher told him that it was. Can anyone settle this dispute for us? Is this perhaps just a matter of preference? A: That looks right. If you want to be explicit: $$ x(x+1)^2 = 0 \implies (x = 0 \vee x = -1)$$ $$ (x = 5 \wedge y = 10) \implies x^2 + y^2 = 125 $$ This is logically accurate, and more than sufficient for casual explanations in precalculus.
{ "pile_set_name": "StackExchange" }
Q: Generic conditional type resolves to never when the generic type is set to never I need to have a generic type that excludes a generic property from a specified type when the generic parameter (of this property) is never. To achieve this I used Omit and conditional types. When the generic parameter is, for example, set to number it behaves as expected but when the generic type is set to never, the type resolves to never instead of excluding the specified property (Playground): type BaseType<T> = { prop1: string; genProp1: T; }; type Excluded<T> = T extends never ? Omit<BaseType<T>, "genProp1"> : BaseType<T>; const obj1: Excluded<number> = { genProp1: 5, prop1: "something, something" }; //obj2 is never const obj2: Excluded<never> = { prop1: "dark side" //error: Type 'string' is not assignable to type 'never' }; Why does it do that and how can I make it return the correct type ({ prop1: string })? EDIT: comparing to null instead of never solves the issue. I would still like to know what's happening when I use never. A: Conditional types distribute over naked type parameters. This means that the conditional type gets applied to each member of the union. never is seen as the empty union. So the conditional type never gets applied (since there are no members in the union to apply it to) resulting in the never type. The simple solution is to disable the distributive behavior of conditional types using a tuple: type BaseType<T> = { prop1: string; genProp1: T; }; type Excluded<T> = [T] extends [never] ? Omit<BaseType<T>, "genProp1"> : BaseType<T>; const obj1: Excluded<number> = { genProp1: 5, prop1: "bla" }; const obj2: Excluded<never> = { prop1: "dwdadw" }; Playground Link
{ "pile_set_name": "StackExchange" }
Q: How to add random number id inside div class bellow is my html code. this content-box will depend on content. i could be 5, 10, 20 what ever. because it will be dynamic content. now i want to add one more class each div randomly and class name will be color-1, color-2, color-3, color-4, color-5,.............. color-10. so number range will be 1-10. so how could i add those class in content-box random numberly. any idea please. HTML: <div class="content-box"> <img src="images/love-01.jpg" /> </div> <div class="content-box"> <img src="images/love-05.jpg" /> </div> <div class="content-box"> <img src="images/love-02.jpg" /> </div> <div class="content-box"> <img src="images/love-03.jpg" /> </div> <div class="content-box"> <img src="images/love-04.jpg" /> </div> http://jsfiddle.net/dKgaz/ A: $('div.content-box').addClass(function(){ var color = Math.floor(Math.random() * 10) + 1; return 'color-' + (color < 10 ? '0' + color : color) }); JS Fiddle demo. Updated the demo, to be a little more obvious: demo. A: I've updated your JSFiddle. Basically you want the following javascript: $('.content-box').each(function() { var number = 1 + Math.floor(Math.random() * 10); $(this).addClass("color-" + number.toString()); }); Your JSFiddle demo updated The $('.content-box').each bit selects each element with the content-box class and then loops through the collection applying whatever is in the brackets. In this case Math.random() gives you a number between 0 and 1, which we multiply by 10 and add 1 to get a random number between 1 and 10. The Math.floor bit ensures that there are no decimal places. Finally we take that number and add the class "color-[random number]" to the current element. Obviously there may be more than one box with the same number so you'll have to create an array to store previous ones if you don't want repetition.
{ "pile_set_name": "StackExchange" }
Q: Counting Rules application for an hypothesis testing example I´m studying the book "Common errors in statistics and how to avoid them" by Phillip I. Good and James W. Hardin. I´m in the second part: Foundations, and i found an example that is used to show where to use a one sided or two sided test, but I don´t understand how the author use counting rules in the example: One-Sided or Two-Sided Suppose on examining the cancer registry in a hospital, we uncover the following data that we put in the form of a 2 × 2 contingency table. The 9 denotes the number of males who survived, the 1 denotes the number of males who died, and so forth. The four marginal totals or marginals are 10, 14, 13, and 11. The total number of men in the study is 10, and 14 denotes the total number of women, and so forth. The marginals in this table are fixed because, indisputably, there are 11 dead bodies among the 24 persons in the study and 14 women. Suppose that before completing the table we lost the subject IDs, so that we could no longer identify which subject belonged in which category. Imagine you are given two sets of 24 labels. The first set has 14 labels with the word “woman” and 10 labels with the word “man.” The second set of labels has 11 labels with the word “dead” and 12 labels with the word “alive.” Under the null hypothesis, you are allowed to distribute the labels to subjects independently of one another. One label from each of the two sets per subject, please. There are a total of $\binom{24}{10}$ ways you could assign the labels.$\binom{14}{10}\binom{10}{1}$ of the assignments result in tables that are as extreme as our original table, (that is, in which 90% of the men survive) and in tables that are more extreme (100% of the men survive). This is a very small fraction of the total, so we conclude that a difference in survival rates of the two sexes as extreme as the difference we observed in our original table is very unlikely to have occurred by chance alone. I have bolded the part I don´t get. I do understand how combinatorics works. I think what I need help with is with how to express the decisión algorithm needed. can someone help me with this? A: The test introduced here is Fisher's Exact test. In my Comment, I recommended you try the Wikipedia explanation of this test (just click on Example in the Comment). However, this test uses the 'hypergeometric distribution', which may be in your text or class notes. (But if not, then you can google it.) Here is an explanation of the probabilities used in the test. Suppose an urn contains 24 balls, 10 blue (men) and 14 pink (women). You are going to select 11 balls (died) at random without replacement. The probability of getting exactly $X = 1$ red ball out of 11 is as follows: $$ P(X = 1) = \frac{{10 \choose 1}{14 \choose 10}}{24 \choose 11} = 0.00401.$$ This can be computed in R software in two different ways as follows: dhyper(1, 10, 14, 11) [1] 0.004010185 choose(10, 1)*choose(14,10)/choose(24,11) [1] 0.004010185 The computation uses the PDF (or PMF) of the hypergeometric distribution dhyper as programmed into R. The second uses the relevant 'binomial coefficients'. If we want $P(X \le 1) = P(X = 0) + P(X = 1) = 0.00415,$ we can use the hypergeometric CDF phyper: phyper(1, 10, 14, 11) [1] 0.00415601 P-value of Fisher's Exact test: The null hypothesis of the test is that the proportion of deaths is the same among men and women. Because the probability of getting result as extreme (only one of the men died) or more extreme (none or one died), we say that the P-value of of the test is $0.00415 < 5\%$ so we reject the null hypothesis at the 5% level (even at the 1% level.
{ "pile_set_name": "StackExchange" }
Q: Whats the best way to handle errors in code? So I'm a little concerned about my error handling... Currently my execution path looks something like this: Users.aspx -> App_Code/User.cs -> Data Layer/User.cs So now when I try to update a user record, I put my Try/Catch block in the event handler and ensure that only the App_Code class interacts with the data layer. Exceptions that happen on the data layer, to my understanding, should bubble up to the event handler below. In the data layer, I started off with this: public void Update() { var product = (from p in db.products where p.productid == id select p).FirstOrDefault(); if (product != null) { // update the thing } } More info on reddit. After chatting with a friend, he recommended something like this: public void Update() { int count = db.users.Count(u => u.userid == id); if (count == 0) // no user found { throw new ValidationException(String.Format("User not found for id {0}.", id)); } if (count > 1) // multiple users { throw new ValidationException(String.Format("Multiple users found for id {0}.", id)); } var user = db.users.FirstOrDefault(u => u.userid == id); // update the user record } Then I went onto IRC where they suggested I create my own Exceptions. I can see the pros here, but it seems a bit unnecessary when my friend's option will work just fine. Basically I'm just really confused as to how I should handle this... Obviously my initial option is insufficient, but it seems like creating my own exceptions might be complicating things too much. So what should I do here? A: In this particular situation, a better option may be to use LINQ's Single method, as so: public void Update() { var user = db.users.Single(u => u.userid == id); // update the user record } Single already does exactly what you want: it throws an Exception if there are 0 or more than 1 results matching the predicate. At this point you can decide whether you're happy for the exception thrown by Single to bubble up, or whether you want to wrap it in one with a more useful message, or a specific type. The general pattern for this would be: public void Update() { try { var user = db.users.Single(u => u.userid == id); } catch(SomeExceptionType ex) { throw new SomeOtherExceptionType("Useful message here", ex); } // update the user record } (Notice passing ex to the SomeOtherExceptionType constructor here. This allows the information about the original exception to be preserved, as is usually good general practice) As I said in the comment, the choice of how exactly you do this is probably not overly important. My advice would be to start with the simplest option- in this case allowing Single to throw its own exception- and refactor as needed. If you find yourself with the need to display or log a more specific exception message, either wrap the exception in this method, or higher up the call chain as appropriate. The principle to where you do this should be avoiding leaking between your abstraction levels. Consider the following: public void HighLevelMethod() { try { DataAccessClass.Update(); } catch(Exception ex) { throw new SomeKindOfException("What should I say here?", ex); } } The message here should be at an appropriate abstraction level for HighLevelMethod. Something along the lines of "The update failed" (though ideally something a bit more useful!). The exact reason for the update to fail is hidden within Update, so for the message to be "The update failed because no user was found" would be causing a leak of implementation details between the abstraction layers. If you wanted to specify that level of detail, that message would need to go in an exception thrown by Update itself. Likewise, only refactor to throwing your own Exception sub-class if that provides some useful information that you find yourself needing higher up the call chain. Will the code calling Update() have a different way of handling a UserNotFoundException than it would a ValidationException? If not, then don't bother with your own Exception type. If you're writing a library to be used by some other, external, code, you have to be a little more pro-active in working out when providing special messages or custom Exception types will be useful, rather than just waiting until there's a need. But the same general principles will apply. A: The point of writing custom exceptions is that you intend to do something useful with them. Is showing them to the user "useful"? Probably not. They look scary. Is logging them to a file for later examination "useful"? Possibly, especially if the application is about to keel over and die because you're doing this in a "global" exception handler (which is about all they're good for). Is catching a particular Type of exception and handling it (i.e. writing code to deal with the problem as it happens and to correct that problem, preferably without the user knowing anything about it) "useful"? Oh yes! Why use custom Exception Types? Because that's how most languages expect to identify exceptions. Look at "catch" clauses - they look for specific Types of Exception. Sorry to say it but I would vehemently disagree with your friend's recommendation - throwing the same [class of] ValidationException [objects] all over the place but relying on the Text property to explain what's going on. That's only useful in one scenario - where you show Exceptions directly to the user and that's a pretty poor practice, in my book anyway.
{ "pile_set_name": "StackExchange" }
Q: Make Git show the correct tag on branches with git describe git describe is documented to find the most recent tag that is reachable from a commit. Source: git describe --help I am a little lost understanding how exactly a tag is reachable from a commit. When run in a branch I'm not seeing the behavior I expect and I don't understand why. https://github.com/nodemcu/nodemcu-firmware uses a release scheme where all changes go into the dev branch, which is then snapped back to master regularly. Releases and annotated tags are created from master. git describe run on master produces the expected result. When run on dev I get a tag created over two years ago. ~/Data/NodeMCU/nodemcu-firmware (dev) > git describe 2.0.0-master_20170202-439-ga08e74d9 Why is this? A similar situation is with a (more or less) frozen branch of an old version we keep around for certain users. ~/Data/NodeMCU/nodemcu-firmware (1.5.4.1-final) > git describe 0.9.6-dev_20150627-953-gb9436bdf That branch was created after this annotated tag https://github.com/nodemcu/nodemcu-firmware/releases/tag/1.5.4.1-master_20161201 and only a handful of commits landed on the branch since. A: The documentation is a lie. You cannot find a tag from a commit. You can find a commit from a tag, and that's what git describe really does, in a remarkably twisty manner, as we'll see in a moment. The lie is meant to be a useful, descriptive lie. How successful it is at that is, I think, open to question. Let's take a look at how git describe really works (without getting too deep into details). First, though, we might need some background. Background (if you know all this, skip to the next section) What you need to know before we start: There are two "kinds" of tags: annotated tags, and lightweight tags. An annotated tag is one made by git tag -a or git tag -m, and actually has two parts: it's a lightweight tag plus an actual Git object, which we'll get into in a moment. By default, git describe looks only at annotated tags. Using --tags makes it look at all tags. Tags are a specific form of a more general entity, the reference or ref for short. Branch names like master are also references, and git describe is allowed to use any reference, via --all. You can also find a commit from a commit, using the commit graph. Underpinning all of the above, Git has both references and objects. These are stored in two separate databases.1 One stores names, all of the form refs/..., which map to a hash value (SHA-1 currently, though SHA-256 is being planned). The other is a simple key-value store indexed by hash values. So: refs objects +--------------------------------+ +----------------------+ | refs/heads/master a123456... | | 08aef31... <object> | | refs/tags/v1.2 b789abc... | | a123456... <object> | +--------------------------------+ | b789abc... <object> | | <lots more of these> | +----------------------+ The object database is usually much, much bigger than the reference database. There are actually four kinds of objects in it: commit objects, tree objects, blob objects, and tag objects. Every object has an object ID or OID, which is really just a hash (again, currently SHA-1, eventually SHA-256; the idea behind calling it an OID is to insulate from the eventual changeover). Blob objects hold data that Git itself does not interpret.2 All others hold data that Git does at least something with. Commit and tag objects are the ones that are particularly interesting here, because tag objects contain an OID that is the target of the tag, and commit objects contain an OID for each parent of the commit. Commit refs (refs/heads/master and the like) are constrained to contain only OIDs of commit objects. Commit objects' parent OIDs are likewise constrained: each one must be the OID of another commit object. The parent(s) of any commit are some older commit(s) that existed when that particular commit got created. If we were to look through all the objects in the repository (as, e.g., git gc and git fsck do), we could build a graph of all the commit objects, with one-way arrows linking from each commit to all of its parents. If we zoom in on one particular two-parent commit, we might see: ... <commit> <-- +--------+ | commit | <-- <commit> ... ... <commit> <-- +--------+ Zooming back out, we see an overall directed acyclic graph or DAG of all commits. Meanwhile the OIDs stored in the branch names—and in any other reference that holds a commit hash—act as entry points into this graph, places where we can start and then keep following the parent links. An annotated tag is a tag reference—a lightweight tag, more or less—that points to a tag object. If the underlying tag object then points to a commit, that too acts as an entry point to the commit DAG. Tag objects are allowed to point directly to trees or blobs, or to other tag objects, though. The process of peeling a tag refers to following an annotated tag that points to another tag object. We just keep following until we reach some non-tag object: that's the final target of this layered tag. If that final target is a commit, that's yet another entry point into the DAG. So, in the end, we typically have a branch name like master that points to the last commit in a mostly-linear string of commits: ... <-o <-o <-o <-o <--master The fact that the internal arrows all point backwards is usually not terribly interesting, although it affects git describe, so I've included it here. At various times during the repository's lifetime, we pick a commit and add a tag to it, either lightweight or annotated. If it's an annotated tag there's an actual tag object: tag:v1.1 tag:v1.2 | | v v T T | | v v ... <-o <-o <-o <-o <--master where the os are commit objects and the Ts are tag objects. 1The reference database is pretty cheesy: it's really just a flat file, .git/packed-refs, plus a bunch of individual files and sub-directories, .git/refs/**/*. Still, internally in Git, there is a plug-in interface for adding new databases, and given all the issues with the flat-file and individual files, I expect that in time, there will be a real database as an option. 2Mostly, that's your own file data. With symbolic links for instance the target of the symlink is stored as a blob object, so the data then get interpreted by your host OS later. How git describe works The git describe command wants to find some name—usually, some annotated tag object—such that the commit you're asking to describe is a descendant of the tagged commit. That is, the tag could point directly to commit X, or to a commit that is the immediate parent of X (one step back), or to a commit that is some number of steps back from X, hopefully not too many. In Git, it is very difficult find descendants of some particular commit. But it is easy to find ancestors of some particular commit. So instead of starting at each tag and working forwards, Git has to start at commit X and work backwards. Is X itself described by some tag? If not, try each of X's parents: are they the direct target of some tag? If not, try each of X's grandparents: are they the direct target of some tag? So git describe it finds the targets of all, or at least some number of, interesting references (annotated tags, or all tags, or all references). When it does this "interesting refs" on our example, it finds two commits, which we'll mark with *: tag:v1.1 tag:v1.2 | | v v T T | | v v ... <-* <-o <-* <-o <--master Now it starts at the commit we want described: the tip of master. From that commit, it can work backwards one hop to reach the commit that's starred from v1.2. Or, it can work backwards three hops to find the commit that's starred from v1.1. Since v1.2 is "closer", that's the annotated tag name that git describe will use. Meanwhile, it did have to walk one hop back from master. So the output will be: v1.2-1-g<hash> where is the abbreviated OID of the commit to which master points. This diagram—both the graph itself, and the two annotated tags—is extremely simple. Most real graphs are terribly knotted, due to branching and merging. Even if we just draw another fairly simple one, we can get things like this: tag-A tag-B v v o--o--...--o o--o <-- branch1 / \ / ...-o--o o--...--o--o <-- branch2 \ / o--o--...--o ^ tag-C In this case, tag-A is going to be "closer" to the tip of branch2, and should be what git describe picks. The actual algorithm inside git describe is pretty complicated and it's not clear to me which tag it picks in some of the trickier cases: Git doesn't have an easy way to load the whole graph and do a breadth-first search and the code is very ad hoc. However, it is clear that tag-B is not suitable, as it points to a commit that cannot be reached by starting at branch2 and working backwards. Now we can look more closely at your last example. I cloned the repository and did this: $ git log --decorate --graph --oneline origin/1.5.4.1-final 1.5.4.1-master_20161201 * b9436bdf (origin/1.5.4.1-final) Replace unmainted Flasher with NodeMCU PyFlasher * 46028b25 Fix relative path to firmware sources * 6a485568 Re-organize documentation * f03a8e45 Do not verify the Espressif BBS cert * 1885a30b Add note about frozen branch * 017b4637 Adds uart.getconfig(0) to get the current uart parameters (#1658) * 12a7b1c2 BME280: fixing humidity trimming parameter readout bug (#1652) * c8176168 Add note about how to merge master-drop PRs * 063cb6e7 Add lua.cross to CI tests. (#1649) * 384cfbec Fix missing dbg_printf (#1648) * 79013ae7 Improve SNTP module: Add list of servers and auto-sync [SNTP module only] (#1596) * ea7ad213 move init_data from .text to .rodata.dram section (#1643) * 11ded3fc Update collaborator section * 9f9fee90 add new rfswitch module to handle 433MHZ devices (#1565) * 83eec618 Fix iram/irom section contents (#1566) * 00b356be HTTP module can now chain requests (#1629) * a48e88d4 EUS bug fixes (#1605) | * 81ec3665 (tag: 1.5.4.1-master_20161201) Merge pull request #1653 from nodemcu/dev-for-drop | |\ | |/ |/| * | 85c3a249 Fix Somfy docs * | 016f289f Merge pull request #1626 from tae-jun/patch-2 |\ \ | * | 58321a92 Fix typo at rtctime.md |/ / * | 1032e9dd Extract and hoist net receive callbacks Note that commit b9436bdf, the tip of origin/1.5.4.1-final, does not have commit 81ec3665 as an ancestor. Tag 1.5.4.1-master_20161201 points to object 4e415462 which is an annotated tag object that in turn points to commit 81ec3665: $ git rev-parse 1.5.4.1-master_20161201 4e415462bc7dbc2dc0595a8c55d469740d5149d6 $ git cat-file -p 1.5.4.1-master_20161201 object 81ec3665cb5fe68eb8596612485cc206b65659c9 ... The tag you were hoping to find, 1.5.4.1-master_20161201, is not eligible to describe commit b9436bdf. There are no commits in this particular graph that are descendants of commit 81ec3665. Using git log --all --decorate --oneline --graph, I find that there are some such commits in the full graph, e.g., b96e3147: * | | e7f06395 Update to current version of SPIFFS (#1949) | | * c8ac5cfb (tag: 2.1.0-master_20170521) Merge pull request #1980 from node mcu/dev | | |\ | |_|/ |/| | * | | 787379f0 Merge branch 'master' into dev |\ \ \ | | |/ | |/| | * | 22e1adc4 Small fix in docs (#1897) | * | b96e3147 (tag: 2.0.0-master_20170202) Merge pull request #1774 from node mcu/dev | |\ \ | * \ \ 81ec3665 (tag: 1.5.4.1-master_20161201) Merge pull request #1653 from nodemcu/dev-for-drop | |\ \ \ | * | | | ecf9c644 Revert "Next 1.5.4.1 master drop (#1627)" but b96e3147 itself has its own (annotated) tag, so that's what git describe should and does list: $ git describe b96e3147 2.0.0-master_20170202 Ultimately the issue here is that there is not a simple "ancestor / descendant" relationship between any given pair of commits. Some commits do have such relationships. Others are merely siblings: they have some common ancestor. Still others may have no common ancestor, if you have a graph with multiple root commits. In any case, git describe normally needs to work against the direction of the internal arrows: it must find a tagged commit such that the to-be-described commit is a descendant of that tag. It literally can't do that, so it transforms the problem into one that it can do: find some tagged commit, out of the set of all tagged commits, such that the tagged commit is an ancestor of the desired commit—then, count the number of hops it takes to move backwards from the desired commit to this tagged commit.
{ "pile_set_name": "StackExchange" }
Q: Voting on "closer"? For example, this question was closed: closed as not constructive by Walter♦ 10 hours ago It would be cool if there was an option of down voting the closer/close. Also, why was one person able to close this? Shouldn't it require five votes? A: That one person is a moderator (the diamond after their name indicates this) - whose votes are binding. If 5 3K+ users disagree they can vote to reopen the question thus overturning the decision. So if you have 3K+ reputation on the site you can add your vote to reopen. If you don't have 3K+ reputation you can either: Add a comment and hope that 5 3K+ users see it and agree with you. Flag the question and explain why you think the question should be reopened. The other moderators will see this and if they agree with you can reopen the question (again with a single vote). Finally you can raise a question on the site's own meta where you can bring it to the wider community. A: One person can close questions only if he is the Moderator. The person Walter you have given in your question is a moderator and hence he has the rights to close the question. The question linked by you also has reasons on why it is closed. You can read that link which says six guidelines for constructive subjective questions. If you still feel this question should be re-opened, you can add a comment as ChrisF has suggested in his answer.
{ "pile_set_name": "StackExchange" }
Q: I can't change the width of specific cell / column in table in my html code I want to keep different column with different width. I have tried to change it with multiple ways including changing width for specific td/th. But width attribute is not working in my code. Table div containsoverflow property as well. But I am unable to locate why I can't change the width using inline styling or using nth-child property. Please help me solving this issue. <!DOCTYPE html> <html> <head> <style> .table-div { overflow-x:auto; overflow-y:auto; margin-bottom: 100px; margin-top: 100px; max-height: 300px;" border: 2px blue; } .lesswidth { width: 500px; } .fixedwidth { width: 150px; } table { /*table-layout: fixed;*/ /* width: 100%;*/ /* max-height: 100px;*/ /*border-collapse: collapse;*/ border-spacing: 0; border: 1px solid red; display: block; /*margin-bottom: 100px;*/ } th{ /*display: block;*/ border: 1px solid red; position: sticky; top:0; text-align: left; padding: 10px; color:black; width: 200px; background-color: #f2f2f2; } td{ /*display: block;*/ border: 1px solid red; /*text-align: left;*/ padding: 10px; color:black; background-color: #f2f2f2; width: 200px; /*margin: 100px 0px 75px 100px;*/ /*margin-right: 100px;*/ } /*td:nth-child(2) { width: 100px !important; } tr:nth-child(even){ background-color: red !important;*/ } /*tr:nth-child(even){background-color: #f2f2f2}*/ </style> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="resCSS.css"> </head> <body> <div class="container"> <div class="table-div"> <table> <!-- class="tablecolor" --> <tr> <th class="fixedwidth">NUMBER</th> <th>TYPE OF VACCINE</th> <th>RELATED USECASE</th> <th>DEVELOPER/RESEARCHER</th> <th>CURRENT STAGE</th> <th>FUNDING SOURCES</th> <th>CLINICAL TRIALS</th> <th>ANTICIPATED NEXT STEPS</th> <th>PUBLISHED RESULTS</th> <th>SOURCES</th> </tr> <tr > <td width="500">1</td> <td >DNA plasmid; INO-4800</td> <td >Same platform as vaccine candidates for Lassa, Nipah, HIV, Filovirus, HPV, cancer indications, Zika, and Hepatitis B</td> <td >Inovio Pharmaceuticals/Beijing Advaccine Biotechnology</td> <td >Pre-clinical</td> <td >Coalition for Epidemic Preparedness and Gates Foundation</td> <td >N/A</td> <td >Started Phase 1 April 2020; initial data expected late summer 2020</td> <td >N/A</td> <td >World Health Organization, MarketWatch, BioAegis Therapeutics, INOVIO</td> <tr> </table> </div> </div><!-- container --> </body> </html> A: The right way to do this is: <td style="min-width: 500px;">1</td>
{ "pile_set_name": "StackExchange" }
Q: Java String-array differences I'm currently bored and was doing some Java practice tests since it's been quite some time I've programmed in Java. After a certain question I'm now wondering the differences between the following: String[] test1 = { "A", "B", "C" }; String[] test2 = new String[]{ "A", "B", "C" }; String test3[] = { "A", "B", "C" }; String test4[] = new String[]{ "A", "B", "C" }; When I type this in a Java IDE I'm not getting any errors. I haven't tried to compile any of them yet (although I've mainly used test2 myself in the past, so I know that one works). So, does each of these compile? And if yes, what are the differences (if any)? (Is test1 better for performance than test2 because you don't make a new String[]-instantiation, or is this done anyway behind the scenes?) (If test1 is the same as test3: Why does test3 and test4 exist in Java if it's the same as test1 and test2? Are there any cases where using [] behind the field-name is preferred above behind the type?) (Are there more (almost similar) variants apart from these four?) (And other questions like these.) Just want to know out of curiosity. We learn something new every day I guess. A: They are all equivalent. So, does each of these compile? Yes, as you yourself can also verify. And if yes, what are the differences (if any)? (Is test1 better for performance than test2 because you don't make a new String[]-instantiation, or is this done anyway behind the scenes?) There are no differences in compiled byte code. (If test1 is the same as test3: Why does test3 and test4 exist if it's the same as test1 and test2?) It is just an alternative way to write it as the array indices can be put after the type name as well as after the identifier name. Only difference is if you declare multiple variable in one line, if indices are placed after the type name, all listed identifiers will be an array of that type, while if the indices are put after the identifier name, only that identifier will be an array. Example: String[] array1, array2; // Both are arrays String array3[], notArray4; // Only array3 is array I recommend putting indices after the type (String[] array1) so it will be unambigous. (Are there more (almost similar) variants apart from these four?) Not that I know of.
{ "pile_set_name": "StackExchange" }
Q: 'in-year' operator in FetchXml condition I was looking for an 'in-year' operator in FetchXML conditions, but only found the 'in-fiscal-year' operator. Is there a workaround for this functionality? A: The only Condition Operators defined by the Schema for years that are not fiscal operations are: last-year this-year next-year last-x-years next-x-years If you want a specific year (in 2008 for example) your best bet is to use the between operator: <condition attribute = 'createdon' operator='between'> <value>2008-01-01 00:00:00</value> <value>2008-12-31 23:59:59</value> </condition>
{ "pile_set_name": "StackExchange" }
Q: Having issue with 'Null pointer access' in Java if(key == '1'){//insert at ->right.right BinaryNode tempPointer = root; while(tempPointer != null){ tempPointer = tempPointer.right; } BinaryNode newNode = new BinaryNode(x); newNode.right = null; newNode.left = null; size++; lastNode = newNode; newNode.parent = tempPointer; tempPointer.right = newNode; } It keeps saying termPointer can only be null at this location. I can't figure out why though. This also fails: newNode.parent = tempPointer.parent; //'tempPointer can only be null here' tempPointer = newNode; A: Your while loop will only end when tempPointer is null. You don't set tempPointer to any other value after the loop, so it will stay null until the end of the function.
{ "pile_set_name": "StackExchange" }
Q: In Extjs, How do I see if a checkbox is checked, and then if it is checked, add that checkboxes id to an array? I am learning Extjs along with PHP and MySQL for one of my web development course in college right now, and I am very close to finishing my final project for the class and I am stuck on something as simple as a checkbox. I am more into c# programming, so my c# mindset is clashing with the necessities of ExtJS. The program asks hospital patients a vast amount of questions about their day-to-day feelings, and I have a list of Checkboxes for common symptoms and I need to be able to check to see, once they submit the form, which symptoms were checked and add that symptoms id to the symptoms array. Is this even close? if(headacheCheckbox.getValue()==true){ symptoms[headacheCheckbox.getId()]; } on the Server Side I have $id=$dbh->lastInsertId(); $symptom=$_REQUEST['symptoms']; while($tmp=$symptom->fetch()){ $stmt=$dbh->prepare("insert into symptom_input (inputid, symptomid) values (?,?)"); $stmt->bindParam(1, $id); $stmt->bindParam(2, $tmp); $stmt->execute(); } and I have my ajax request in my ExtJS taking in the symptom array as a parameter like so.. params: {action: 'create_input', symptoms: symptoms[], }, Absolutely any help/criticism is welcome. Thank You! A: This line $symptom=$_REQUEST['symptoms']; and this line while($tmp=$symptom->fetch()){ do not compute. fecth is method ffor prepared statement object http://il2.php.net/manual/en/mysqli-stmt.fetch.php (when you fetchign a result set, similar to mysql_fecth_row for unprepared statements) while you have an array parsed to this variable $symptom=$_REQUEST['symptoms']; So your fetch will throw an error in while assuming that your array looks like this $_REQUEST['symptoms'][112]; $_REQUEST['symptoms'][234]; what you need is something like this $id=$dbh->lastInsertId(); $symptom=$_REQUEST['symptoms']; foreach($symptoms as $symptomid){ $stmt=$dbh->prepare("insert into symptom_input (inputid, symptomid) values (?,?)"); $stmt->bindParam(1, $id); $stmt->bindParam(2, $symptomid); $stmt->execute(); } Also when passing a parameters assuming that code bellow is creating an array in your JavaScript if(headacheCheckbox.getValue()==true){ symptoms[headacheCheckbox.getId()]; } you need to params: {action: 'create_input', symptoms: symptoms //without square brackets and no comma IE7 will throw an error },
{ "pile_set_name": "StackExchange" }
Q: Exception trying to loop through ArrayList in processing I'm using Processing 2.0b7. I have a Spool class that is supposed to have an ArrayList of Note objects in it. In Spool's draw method, I want to call each Note in the ArrayList's draw method. However, when I try do that with this syntax, I get the error " Exception in thread "Animation Thread" java.lang.NullPointerException at spoolloops$Spool.draw(spoolloops.java:119) at spoolloops.draw(spoolloops.java:39) at processing.core.PApplet.handleDraw(PApplet.java:2142) at processing.core.PGraphicsJava2D.requestDraw(PGraphicsJava2D.java:193) at processing.core.PApplet.run(PApplet.java:2020) at java.lang.Thread.run(Thread.java:662) PLEASE NOTE This is the Processing environment, which runs some sort of Java, but is different in important respects. I know the syntax is very different, because you don't have to declare scope or return types for methods in classes. But since I'm not a Java export, I don't know the exact hows and whyfors of the differences. If you want to give an answer, please make sure that it will work in processing and not just Java. I'm pretty sure that this code will throw all kinds of errors in a pure Java environment, but that's not what it's running in, so it doesn't matter. The platform is Processing. class Spool { int diameter = 50; int i, angle; Note note, test; ArrayList<Note> notes; void Spool() { notes = new ArrayList<Note>(); notes.add( note = new Note(100.0,100.0,100.0,100.0,100.0) ); notes.add( note = new Note(120.0,120.0,120.0,120.0,120.0) ); } void draw() { for (int i = 0; i < notes.size(); i++) { test = (Note)notes.get(i); test.draw(); } angle = angle + 1; if ( angle > 360 ) { angle = 0; } } } class Note { float diameter, x,y, start, stop; Note(float Diameter, float X, float Y, float Start, float Stop) { diameter = Diameter; x = X; y = Y; start = Start; stop = Stop; } void turn(float degrees) { } void draw() { strokeWeight(25); arc( x,y,diameter, diameter, radians(start), radians(stop)); } } The notes.size() in the for loop is what seems to cause the problem, but when I change it to i < 1, the error occurs at test = (Note)notes.get(i);. I suppose the ArrayList is not properly getting filled with Note Objects? A: Class and Object Initializers do not return a type. Remove the "void" from void Spool() leave it as Spool() Otherwise it is not called during creation. Also it's not totally necessary to have the notes.add( note = new Note(100.0,100.0,100.0,100.0,100.0) ); It is my understanding that it can simply be: notes.add(new Note(100.0,100.0,100.0,100.0,100.0) );
{ "pile_set_name": "StackExchange" }
Q: FireFox transform and transition not working So, this is my CSS: img.buttonImg { -webkit-transition: all 0.5s ease-in-out; -moz-transition: all 0.5s ease-in-out; -o-transition: all 0.5s ease-in-out; -ms-transition: all 0.5s ease-in-out; transition: all 0.5s ease-in-out; } img.buttonImg:hover { -webkit-transform: rotate(360deg); -moz-transform: rotate(360deg); -o-transform: rotate(360deg); -ms-transform: rotate(360deg); transform: rotate(360deg); } Yet no animation seems to happen, the image isn't rotating at all on FireFox, but on other browsers it does. A: Here is your problem - demonstrated by this example. The transition doesn't work when hovering over the img element because of the fact that it is within a button element. I assume this is a rendering issue, as this only seems to be the case for FF. It works fine in Chrome and other modern browsers. As for a solution, removing the img element from the button will obviously solve the problem. Alternatively, you could add the rotation transition effect when hovering over the button as opposed to the child img element. Updated example - it works in FF. button.t:hover img { transform: rotate(360deg); /* other vendors.. */ } Both solutions work; however, I don't even know if it is valid to have an img element within a button element. This is probably the reason for the rendering bug; if it even is a bug.
{ "pile_set_name": "StackExchange" }
Q: Can not read data from firebase as List in android I read many articles but still my problem is continuing, while fetching data from firebase as list. could you please help me on this. Error: com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type SubCategoryLoad Object Firebase database image --> Loading data from firebase: mSubCategoryDatabaseRef = FirebaseDatabase.getInstance().getReference("user_post_add_database_ref").child("yeswanth599").child(mCategoryNameReceive); mSubCategoryDatabaseRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) { GenericTypeIndicator<Map<String,SubCategoryLoad>> genericTypeIndicator=new GenericTypeIndicator<Map<String,SubCategoryLoad>>(){}; (-->Error Showing in this Line) Map<String,SubCategoryLoad> map=(Map<String, SubCategoryLoad>)postSnapshot.getValue(genericTypeIndicator); assert map != null; mSubCategoryLoad=new ArrayList<>(map.values()); } mSubCategoryAdapter = new SubCategoryDisplayAdapter(getContext(), mSubCategoryLoad); mSubCategoryRecyclerView.setAdapter(mSubCategoryAdapter); mSubCategoryProgressCircle.setVisibility(View.INVISIBLE); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { Toast.makeText(getContext(), databaseError.getMessage(), Toast.LENGTH_SHORT).show(); mSubCategoryProgressCircle.setVisibility(View.INVISIBLE); } }); --> SubCategoryLoad.Class public class SubCategoryLoad { private String mUserPostAddress; private String mUserPostBusinessEndTime; private String mUserPostBusinessSelectedCity; private String mUserPostBusinessSelectedCountry; private String mUserPostBusinessStartTime; private String mUserPostCategory; private String mUserPostEmail; private List<UserPostAdsImages> mUserPostImages; private String mUserPostName; private String mUserPostPhonenumber; private List<UserPostAdsLanguages> mUserPostSupportingLanguage; private String mUserPostWebsite; public SubCategoryLoad() { //empty constructor needed } public SubCategoryLoad(String userPostAddress, String userPostBusinessEndTime, String userPostBusinessSelectedCity, String userPostBusinessSelectedCountry, String userPostBusinessStartTime, String userPostCategory, String userPostEmail, List<UserPostAdsImages> userPostImages, String userPostName, String userPostPhonenumber, List<UserPostAdsLanguages> userPostSupportingLanguage, String userPostWebsite ) { mUserPostAddress = userPostAddress; mUserPostBusinessEndTime = userPostBusinessEndTime; mUserPostBusinessSelectedCity = userPostBusinessSelectedCity; mUserPostBusinessSelectedCountry = userPostBusinessSelectedCountry; mUserPostBusinessStartTime = userPostBusinessStartTime; mUserPostCategory = userPostCategory; mUserPostEmail = userPostEmail; mUserPostImages = userPostImages; mUserPostName = userPostName; mUserPostPhonenumber = userPostPhonenumber; mUserPostSupportingLanguage = userPostSupportingLanguage; mUserPostWebsite = userPostWebsite; } public void setUserPostAddress(String userPostAddress) { this.mUserPostAddress = userPostAddress; } public void setUserPostBusinessEndTime(String userPostBusinessEndTime) { this.mUserPostBusinessEndTime = userPostBusinessEndTime; } public void setUserPostBusinessSelectedCity(String userPostBusinessSelectedCity) { this.mUserPostBusinessSelectedCity = userPostBusinessSelectedCity; } public void setUserPostBusinessSelectedCountry(String userPostBusinessSelectedCountry) { this.mUserPostBusinessSelectedCountry = userPostBusinessSelectedCountry; } public void setUserPostBusinessStartTime(String userPostBusinessStartTime) { this.mUserPostBusinessStartTime = userPostBusinessStartTime; } public void setUserPostCategory(String userPostCategory) { this.mUserPostCategory = userPostCategory; } public void setUserPostEmail(String userPostEmail) { this.mUserPostEmail = userPostEmail; } public void setUserPostImages(List<UserPostAdsImages> userPostImages) { this.mUserPostImages = userPostImages; } public void setUserPostName(String userPostName) { this.mUserPostName = userPostName; } public void setUserPostPhonenumber(String userPostPhonenumber) { this.mUserPostPhonenumber = userPostPhonenumber; } public void setUserPostSupportingLanguage(List<UserPostAdsLanguages> userPostSupportingLanguage) { this.mUserPostSupportingLanguage = userPostSupportingLanguage; } public void setUserPostWebsite(String userPostWebsite) { this.mUserPostWebsite = userPostWebsite; } public String getUserPostAddress() { return mUserPostAddress; } public String getUserPostBusinessEndTime() { return mUserPostBusinessEndTime; } public String getUserPostBusinessSelectedCity() { return mUserPostBusinessSelectedCity; } public String getUserPostBusinessSelectedCountry() { return mUserPostBusinessSelectedCountry; } public String getUserPostBusinessStartTime() { return mUserPostBusinessStartTime; } public String getUserPostCategory() { return mUserPostCategory; } public String getUserPostEmail() { return mUserPostEmail; } public List<UserPostAdsImages> getUserPostImages() { return mUserPostImages; } public String getUserPostName() { return mUserPostName; } public String getUserPostPhonenumber() { return mUserPostPhonenumber; } public List<UserPostAdsLanguages> getUserPostSupportingLanguage() { return mUserPostSupportingLanguage; } public String getUserPostWebsite() { return mUserPostWebsite; } } --> SubCategoryDisplayAdapter.class SubCategoryLoad subCategoryLoadCurrent = mSubCategoryLoad.get(position); holder.mSubCategoryAdsTitle.setText(subCategoryLoadCurrent.getUserPostName()); holder.mSubCategoryAdsSupportingLanguagesList.setText("English,Japanese"); //Log.i(TAG, "message:"+subCategoryLoadCurrent.getUserPostImages().get(0).getUserPostImageList()); Glide.with(mContext) .load(subCategoryLoadCurrent.getUserPostImages().get(0).getUserPostImageList()) .into(holder.mSubCategoryAdsImage); Thanks & Regards, Yeswanth. A: I used to have the same issue with my parsing and the problem was instead of a list of custom objects i was supposed to be using a Map like this private Map<String,Boolean> That field in Firebase contains a key and a state (True or False). Also you can check the code on the docs to see how they parse these objects. https://firebase.google.com/docs/database/android/read-and-write?authuser=0#read_data_once
{ "pile_set_name": "StackExchange" }
Q: Tomcat Intellij Idea: Remote deploy RackSpace Cloud Server Ubuntu-12.04, Intellij Idea-11.1.2, Windows-8, Tomcat-7.0.26, JDK-6. On Intellij Idea when i try to run jsf project on my remote Tomcat 7 server it says: Error running servername: Unable to connect to the ip-address:1099 It seems problem is about JNDI port which is 1099 but I couldn't activate it I guess. Tomcat config is sth. like that: What I've tried? Setting CATALINA_OPTS or JAVA_OPTS on the server side with: CATALINA_OPTS=-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=1099 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false and JAVA_OPTS=-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=1099 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false But this one did not work, any ideas? A: My answer to my question: The correct way to deploy remotely is editing JAVA_OPTS environment variable on the remote server. Just enter the command below: export JAVA_OPTS="-Dcom.sun.management.jmxremote= -Dcom.sun.management.jmxremote.port=1099 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false" If that's not going to work and if you don't have any obsession to deploy your website via Intellij Idea, I've got the solution for this problem. To be able to run your website under Tomcat, you can/should get artifact in form of .war file. It can be done in Intellij from project settings(ctrl+alt+shift+s) then hit the plus button and add new artifact(web:application archieve) After rebuilding the artifact, .war file can be seen in project-folder\out\artifacts. Next, you should place this file into your tomcat/webapps folder. For example if you are using Tomcat-7, the folder that I mean exists in /var/lib/tomcat7/webapps. Before copying your .war file you should rename it as ROOT.war. This provides to access your site directly by http://youripaddress:8080. After restarting Tomcat7 service you can access the site. But not finished yet, you can debug your project remotely like you are debugging your project at your local machine with Intellij Idea. Open Run/Debug Configuration in Idea, hit the plus button and there must be Remote. This is the way to debug your projects for application servers like JBoss, Glassfish as well in Idea. Enter your host and port numbers, select your project as a module. Before starting to debug, as Intellij says you should give the following parameter to your server JVM: JAVA_OPTS="$JAVA_OPTS -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005" To be able to do that in Ubuntu and for Tomcat-7, modified the catalina.sh file in usr/share/tomcat7 folder. I inserted the parameter above of the if [ -z "$LOGGING_MANAGER" ]; then line. It must be on the middle part of the file. Then you should be able to debug your project with Intellij Idea.
{ "pile_set_name": "StackExchange" }
Q: Most loose way to parse a date/time in C#? I'm parsing a broad range of RSS feeds - apprently they all use their own way to show the timestamp of the article. Now we even found one that uses a local words, like Donderdag 17 juli 2018. At the moment we have a fallback mechanism where we just fall back to DateTime.UtcNow when we can't parse the date. Still I would like to make a best attempt. What is the best way to really loosely parse a DateTime in C#? So it can handle i.e.: 13-11-2018 14.32 donderdag 13 november 2018, 14:32 13 nov 2018 14:32 13.11.2018 2018-11-13T16:32:00+2:00 etc. I know that this would not be foolproof, but still I like to make a best attempt. Is there any recommended way? Or do I have to roll my own? A: You could use DateTime.TryParseExact and include all the expected formats. DateTime result; if( DateTime.TryParseExact(input, new [] {"dd-MM-yyyy HH.mm", "dddd dd MMMM yyyy, HH:mm", "more formats here"}, CultureInfo.CreateSpecificCulture("nl-NL"), DateTimeStyles.None, out result)) { Console.WriteLine("Succeeded " + result); } The only big "gotcha" here is date formats where the date and month are in ambiguous positions. I do not see any in your example but if you were to mix cultures in one stream then it could become a problem. As an example the U.S. generally starts a formatted date with the month while the Netherlands starts it with the day of the month. If this is a problem there is no way to handle this dynamically in your use case above unless you also get the culture from the RSS stream in which case you could try to create a set of culture specific parsing rules.
{ "pile_set_name": "StackExchange" }
Q: Returning Success / Error messages - Laravel & VueJS So I am tinkering with an image uploader which will preview the image before uploading. There are restrictions in place to allow just jpg, jpeg or png image formats, however, the error messages aren't being returned and I have tried a number of methods Please see my code below: <template> <div class="row"> <div class="col-md-12"> <img :src="image" class="img-responsive" alt=""> </div> <div class="col-md-8"> <input type="file" v-on:change="onFileChange" class="form-control"> </div> <div class="col-md-4"> <button class="btn btn-success btn-block" @click="upload">Upload</button> </div> </div> </template> This is being designed using Vue and Laravel. I am literally 1 day into learning Vue so please let me know if I have missed a vital part you need to look at (such as the route/controller) <script> export default { data() { return { image: '' } }, methods: { onFileChange(e) { let files = e.target.files || e.dataTransfer.files; if (!files.length) return; this.createImage(files[0]); }, createImage(file) { let reader = new FileReader(); let vm = this; reader.onload = (e) => { vm.image = e.target.result; }; reader.readAsDataURL(file); }, upload(){ axios.post('/api/upload',{image: this.image}) .then(response => { }); } } } </script> Please see the controller below: public function upload(Request $request) { $validator = Validator::make($request->all(), [ 'image' => 'required|image64:jpeg,jpg,png' ]); if ($validator->fails()) { return response()->json(['errors'=>$validator->errors()]); } else { $imageData = $request->get('image'); $fileName = Carbon::now()->timestamp . '_' . uniqid() . '.' . explode('/', explode(':', substr($imageData, 0, strpos($imageData, ';')))[1])[1]; Image::make($request->get('image'))->save(public_path('images/').$fileName); return response()->json(['error'=>false]); } } A: Validate form and return error from laravel controller as private function validateForm($advsearch){ $validator = Validator::make($advsearch, [ 'fname' => 'required', ]); return $validator; } public function submitForm(Request $request){ $validator = $this->validateForm($request->all()); if ($validator->fails()) { return response()->json(['isvalid'=>false,'errors'=>$validator->messages()]); } ..... ..... } And display in vue by binding <div>{{errors.fname?errors.fname[0]:''}}</div> if you already bind errors in vue data data() { return { errors:[], image: '' } }, And update it after submit and if you get any error axios.post('/api/upload',{image: this.image}) .then(response => { if(response.isValid == false){ this.errors = response.errors; } }); in your update you can check errors exist or not by if(response.body.errors !== undefined){
{ "pile_set_name": "StackExchange" }
Q: for each loop based on 2 elements in xslt i have a requirement, i need to repeat loop on each record and need to take substring on each occurrence. My child elements have multiple occurrence and each of them are to be mapped respectively. Source xml. <Records> <Record> <A><C1>A record information</C1></A> <B><C1>B record information</C1></B> <C><C1></C1></C> <D><C1>D record information</C1></D> <E><C1/></E> <F><C1>F record formation</C1></F> <G><C1>P1 LABOR P1 IN G1</C1></G> <G><C1>*P2 LABOR P2 IN G1</C1></G> <G><C1>P3 LABOR P3 IN G1</C1></G> <F><C1>F 2nd record information</C1></F> <G><C1>P1 LABOR P1 IN G1</C1></G> <G><C1>*P2 LABOR P2 IN G1</C1></G> <G><C1>P3 LABOR P3 IN G1</C1></G> </Record> <Record> <A><C1>A record information</C1></A> <B><C1>B record information</C1></B> <C><C1><C1></C> <D><C1>D record information</C1></D> <E><C1/></E> <F><C1>F record information</C1></F> <G><C1>P1 LABOR P1 IN G1</C1></G> <G><C1>*P2 LABOR P2 IN G1</C1></G> <G><C1>P3 LABOR P3 IN </C1></G> <F><C1>F 2nd record information</C1></F> <G><C1>P1 LABOR P1 IN G1</C1></G> <G><C1>*P2 ABOR P2 IN G1</C1></G> <G><C1>P3 LABOR P3 IN G1</C1></G> </Record> </Records> my expected result it below. ` <Records> <Record> <A> <C1>cord infor</C1> </A> <B> <C1>cord infor</C1> </B> <C> <C1></C1> </C> <D> <C1>cord infor</C1> </D> <E> <C1/> </E> <F> <C1>record form</C1> </F> <G> <C1>LABOR P1 IN LABOR P3 IN</C1> </G> <F> <C1>record form</C1> </F> <G> <C1>LABOR P1 IN LABOR P3 IN</C1> </G> </Record> <Record> <A> <C1>cord infor</C1> </A> <B> <C1>cord infor</C1> </B> <C> <C1></C1> </C> <D> <C1>cord infor</C1> </D> <E> <C1/> </E> <F> <C1>record form</C1> </F> <G> <C1>LABOR P1 IN LABOR P3 IN</C1> </G> <F> <C1>record form</C1> </F> <G> <C1>LABOR P1 IN LABOR P3 IN</C1> </G> </Record> </Records> `enter code here for each record i need to map elements respectively with substring function. and need to group G elements with first occurrence of F by eliminating the G record which start with * the number of occurrences for each F and G are dynamic. have tried with for each with or operator but im not able to concat the G elements if i open a loop above the element name. Please help . A: i need to concat all G elements between 2 F's, while concatnating the G records, need to avoid the G record which starts with * To answer this question - and only this question: The following stylesheet starts by copying all nodes in the XML document except G, which is suppressed by a dedicated template. A third template adds a single G element concatenating the contents of all G elements following a F element, except those that start with a '*': XSLT 1.0 <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/> <xsl:strip-space elements="*"/> <xsl:key name="g" match="G" use="generate-id(preceding-sibling::F[1])" /> <!-- identity transform --> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="G"/> <xsl:template match="G[preceding-sibling::*[1][self::F]]"> <G><C1> <xsl:for-each select="key('g', generate-id(preceding-sibling::F[1]))[not(starts-with(C1, '*'))]"> <xsl:value-of select="C1"/> </xsl:for-each> </C1></G> </xsl:template> </xsl:stylesheet> When applied to the following test input: <Records> <Record> <A><C1>A record information</C1></A> <B><C1>B record information</C1></B> <C><C1></C1></C> <D><C1>D record information</C1></D> <E><C1/></E> <F><C1>F1 record information</C1></F> <G><C1>alpha</C1></G> <G><C1>*bravo</C1></G> <G><C1>charlie</C1></G> <F><C1>F2 record information</C1></F> <G><C1>red</C1></G> <G><C1>*green</C1></G> <G><C1>blue</C1></G> </Record> <Record> <A><C1>A record information</C1></A> <B><C1>B record information</C1></B> <C><C1></C1></C> <D><C1>D record information</C1></D> <E><C1/></E> <F><C1>F3 record information</C1></F> <G><C1>Adam</C1></G> <G><C1>*Betty</C1></G> <G><C1>Cecil</C1></G> <F><C1>F4 record information</C1></F> <G><C1>100</C1></G> <G><C1>*200</C1></G> <G><C1>300</C1></G> </Record> </Records> the result is: <?xml version="1.0" encoding="UTF-8"?> <Records> <Record> <A> <C1>A record information</C1> </A> <B> <C1>B record information</C1> </B> <C> <C1/> </C> <D> <C1>D record information</C1> </D> <E> <C1/> </E> <F> <C1>F1 record information</C1> </F> <G> <C1>alphacharlie</C1> </G> <F> <C1>F2 record information</C1> </F> <G> <C1>redblue</C1> </G> </Record> <Record> <A> <C1>A record information</C1> </A> <B> <C1>B record information</C1> </B> <C> <C1/> </C> <D> <C1>D record information</C1> </D> <E> <C1/> </E> <F> <C1>F3 record information</C1> </F> <G> <C1>AdamCecil</C1> </G> <F> <C1>F4 record information</C1> </F> <G> <C1>100300</C1> </G> </Record> </Records>
{ "pile_set_name": "StackExchange" }
Q: Why can the keyword "weak" only be applied to class and class-bound protocol types When I'm declaring variables as weak in Swift, I sometimes get the error message from Xcode: 'weak' may only be applied to class and class-bound protocol types I was just wondering why keyword weak can only applied to class and class-bound protocol types? What is the reason behind it? A: One common reason for this error is that you have declared you own protocol, but forgot to inherit from AnyObject: protocol PenguinDelegate: AnyObject { func userDidTapThePenguin() } class MyViewController: UIViewController { weak var delegate: PenguinDelegate? } The code above will give you the error if you forget to inherit from AnyObject. The reason being that weak only makes sense for reference types (classes). So you make the compiler less nervous by clearly stating that the PenguinDelegate is intended for classes, and not value types. A: weak is a qualifier for reference types (as opposed to value types, such as structs and built-in value types). Reference types let you have multiple references to the same object. The object gets deallocated when the last strong reference stops referencing it (weak references do not count). Value types, on the other hand, are assigned by copy. Reference counting does not apply, so weak modifier does not make sense with them. A: protocol PenguinDelegate: class { func userDidTapThePenguin() } class MyViewController: UIViewController { weak var delegate: PenguinDelegate? } If you type class after your protocol it works as well and seems more appropriate that for NSObjectProtocol.
{ "pile_set_name": "StackExchange" }
Q: Scraping html table with images using XML R package I want to scrape html tables using the XML package of R, in a similar way to discussed on this thread: Scraping html tables into R data frames using the XML package The main difference with the data I want to extract, is that I also want text relating to an image in the html table. For example the table at http://www.theplantlist.org/tpl/record/kew-422570 contains a column for "Confidence" with an image showing one to three stars. If I use: readHTMLTable("http://www.theplantlist.org/tpl/record/kew-422570") then the output column for "Confidence" is blank apart from the header. Is there any way to get some form of data in this column, for example the HTML code linking to the appropriate image? Any suggestions of how to go about this would be much appreciated! A: I was able to find the Xpath query to the image name using SelectorGadeget library(XML) library(RCurl) d = htmlParse(getURL("http://www.theplantlist.org/tpl/record/kew-422570")) path = '//*[contains(concat( " ", @class, " " ), concat( " ", "synonyms", " " ))]//img' xpathSApply(d, path, xmlAttrs)["src",] [1] "/img/H.png" "/img/L.png" "/img/H.png" "/img/H.png" "/img/H.png" [6] "/img/H.png" "/img/H.png" A: Here's an rvest solution with an even simpler CSS selector: library(rvest) pg <- html("http://www.theplantlist.org/tpl/record/kew-422570") pg %>% html_nodes("td > img") %>% html_attr("src") ## [1] "/img/H.png" "/img/L.png" "/img/H.png" "/img/H.png" "/img/H.png" ## [6] "/img/H.png" "/img/H.png"
{ "pile_set_name": "StackExchange" }
Q: how to merge the null column to get date range the table is: id range_start range_end --------------------------- 1 NULL 2018-01-01 1 2018-02-11 NULL 1 NULL NULL 1 NULL 2018-04-09 1 NULL NULL 2 2018-05-01 NULL 2 NULL 2018-08-01 the code: create table #test(id int,range_start date,range_end date) insert #test values(1,null,'2018-01-01'), (1,'2018-02-11',null), (1,null,null), (1,null,'2018-04-09'), (1,null,null), (2,'2018-05-01',null), (2,null,'2018-08-01') and I want the output can ignore the null value: id range_start range_end --------------------------- 1 NULL 2018-01-01 1 2018-02-11 2018-04-09 2 2018-05-01 2018-08-01 The first column can be reserved. Thank you very much, A: select id, min(range_start) range_start, max(range_end) range_end from ( select *, row_number()over(partition by id order by coalesce(range_start, range_end)) + case when range_end is null then 1 else 0 end rn from #test where range_start is not null or range_end is not null )a group by id, rn order by 1,2,3
{ "pile_set_name": "StackExchange" }
Q: How do I fade the corners/edges/borders of a UIImageView I was unable to find this on the forums so I decided to post this. I have a UIImageView with the following code which fades the images from one another. - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound)]; imageNames = [NSArray arrayWithObjects:@"image1.jpg", @"image2.jpg", @"image3.jpg", @"image4.jpg", @"image5.jpg", nil]; imageview.image = [UIImage imageNamed:[imageNames objectAtIndex:0]]; [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(transitionPhotos) userInfo:nil repeats:YES]; // Rounds corners of imageview CALayer *layer = [imageview layer]; [layer setMasksToBounds:YES]; [layer setCornerRadius:5]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } -(void)transitionPhotos{ if (photoCount < [imageNames count] - 1){ photoCount ++; }else{ photoCount = 0; } [UIView transitionWithView:imageview duration:2.0 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{imageview.image = [UIImage imageNamed:[imageNames objectAtIndex:photoCount]]; } completion:NULL]; } I want to implement a code that will fade the borders of my imageview. I know I can use the QuartzCore.framework, however I was unable to find a guide how to achieve the result that I want. What would be the shortest possible code to do such a method? A: Have an image containing a mask (blurred rectangle on transparent background): UIImage *mask = [UIImage imageNamed:@"mask.png"]; create a maskLayer: CALayer *maskLayer = [CALayer layer]; maskLayer.contents = (id)mask.CGImage; maskLayer.frame = imageView.bounds; and assign it as mask for your imageView: imageView.layer.mask = maskLayer; Edit: you can create the mask completely by code using the shadow properties of CALayer. Just play around with shadowRadius and shadowPath: CALayer *maskLayer = [CALayer layer]; maskLayer.frame = imageView.bounds; maskLayer.shadowRadius = 5; maskLayer.shadowPath = CGPathCreateWithRoundedRect(CGRectInset(imageView.bounds, 5, 5), 10, 10, nil); maskLayer.shadowOpacity = 1; maskLayer.shadowOffset = CGSizeZero; maskLayer.shadowColor = [UIColor whiteColor].CGColor; imageView.layer.mask = maskLayer;
{ "pile_set_name": "StackExchange" }
Q: applescript and Fetch I was going to use the Automator to run some remote to local backups but will need to do some looping so I thought that Applescript would be a better choice. As a complete newbie to Applescript, my first attempt to download all files from a given folder with specific characteristics resulted in an error: set today to current date set yesterday to (today - 1) tell application "Fetch" activate open remote folder "/public_html/books/book_3/_thumbs/Images" copy every file of folder to beginning of alias "MacintoshHD:Users:franciscaparedes:Desktop:untitled folder:" whose modification date is greater than yesterday end tell Here's my error: Fetch got an error: Can’t set beginning of alias \"Macintosh HD:Users:franciscaparedes:Desktop:untitled folder:\" whose «class pMod» > date \"Monday, December 24, 2012 6:37:17 AM\" to every file of folder." number -10006 from insertion point 1 of alias "Macintosh HD:Users:franciscaparedes:Desktop:untitled folder:" whose modification date > date "Monday, December 24, 2012 6:37:17 AM" Any thoughts would be appreciated. -Eric A: This works. I only had a quick look at this. Which means this most likely can be mad simpler. The Fetch library is IMO not the well explained. But I think that of most applescript libraries. But You should read the libraries. This will help you understand what is scriptable in the application and the syntax to use. To access the library of an app. In Applescript Editor. Go to the Windows->library menu. This will open the libraries window. If you see your app in there double click it. A new library will open with all the syntax and commands you can use. Don't get exited when you see it and start thinking oh yes baby this is good the world is mine..hahaha. Because you will soon discover it takes a bit of time to workout how to put it all together. If your app is not in the library window. Locate the app in finder and drag and drop it onto it. If it is scriptable it will be added to the library. Also read Apples Applescript Concepts set today to current date set number_of_days to 1 tell application "Fetch" activate #open a shortcut open shortcut "Shortcut Name" #set the remote window to your remote path open remote folder "/public_html/books/book_3/_thumbs/Images" #get the properties of every file in remote window. This will give use the modified date and url of each file set props to properties of remote items of transfer window 1 #iterate through the files repeat with i from 1 to number of items in props # one of the items set this_item to item i of props #get its modification date set modDate to modification date of this_item # compare the dtae by using number of days set TimeDiff to (today - modDate) -- the difference in seconds set DaysOut to (TimeDiff div days) -- the number of days out if DaysOut is greater than number_of_days then #use the files url to download it to the POSIX file path of you folder download url (url of this_item) to file "MacintoshHD:Users:franciscaparedes:Desktop:untitled folder:" end if end repeat end tell
{ "pile_set_name": "StackExchange" }
Q: How to pass data from one form to another suitescript Well it looks like I need to suite script this. I want to populate a field in my child record from the form that is creating the record. When the user clicks to add a new child record, I want to pass some info to the creation of that child record from the current parent that initialized the create child. How is this done? MORE INFO: I originally looked at Sourcing and filtering, but that was dependent on the parent record being the same. Let's say I have a note record. Meanwhile I have other entities which can have a note created and linked to it. Something like adding the set name to a note: Set -->> Books --> Note (set name = books.set.name ) -->> Authors --> Note (set name= authors.set.name) So unless I can use some eval technique, I would think I should start my dive into suite script. A: The workaround I found was to use window.opener in a client script: function rulePageInit(){ var wo = window.opener.nlapiGetFieldValue ('custrecord_configurator');
{ "pile_set_name": "StackExchange" }
Q: calculate x using regression equation I calculated the cubic regression for a set of numbers following the instructions on this site: http://epsstore.ti.com/OA_HTML/csksxvm.jsp?nSetId=71235 I am wondering how do I evaluate using the equation provided by the cubic regression without having to write down the equation on paper, and then typing in in the calculator. Ted A: On a TI-83/84 series calculator (also an Nspire with the TI-84 keyboard module in place), once you've performed the regression, go to your "y=" screen, to a blank equation, press the "vars" key, go down to "5: Statistics...", arrow right twice to "EQ", and press enter to select "RegEQ"—this will insert the full regression equation into the y-variable line you were on in the "y=" screen. Now, you can use the graph and trace to evaluate or use the table to evaluate (or directly evaluate on the home screen using $Y_1(value)$, but that's harder to use).
{ "pile_set_name": "StackExchange" }
Q: Strange behavior of C abort function on mingw-w64 I'm new to mingw-w64 and I'm running into the following problem: I recently installed MSYS on my Windows 10 computer according to the instructions provided in How to install MinGW-w64 and MSYS2? and I am currently trying to build some Win32 C programs. I first tried some simple programs and they seem to work; however, I ran into problems with the C abort function. If I build the following program on Linux #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { printf("bla bla bla\n"); abort(); } and later run it, I simply get the output bla bla bla Aborted However, on Windows the output is bla bla bla This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information. A message window also appears with the message a.exe has stopped working -- A problem caused the program to stop working correctly. Windows will close the program and notify you if a solution is available. Is this the way it is supposed to be? Anyway, I much prefer the Linux version. A: abort is the same as raise(SIGABRT). If you don't catch the SIGABRT signal, the default OS handler is invoked, on Linux this is dumping core, causing the shell to write Aborted on standard error. On Windows, it terminates and the message you saw is displayed, on standard error if console subsystem is used or in a standard message box if gui. This can be suppressed by the non-standard _set_abort_behavior. If you want a uniform action across systems, you need to register a SIGABRT handler and do something yourself: #include <stdlib.h> #include <signal.h> #include <stdio.h> void handle_abort(int sig) { // do something (e.g write to log) // don't let this handler return if you want to suppress defaut handler } int main(void) { signal(SIGABRT, handle_abort); abort(); }
{ "pile_set_name": "StackExchange" }
Q: Is there an in-game catalog? Previous entries into the Animal Crossing series offered an in-game catalog at Nook's shop where I could review all of the items I've obtained in the game. In New Leaf, the shops have changed dramatically and I'm not sure if this feature is still in the game. Is there a catalog in New Leaf? And if so, where can I find it? A: The catalog in New Leaf doesn't unlock until you upgrade the Nookling Junction to T&T Mart. This will unlock the catalog machine, which functions in the same way as previous entries in the series did, letting you order (most) items that you've previously collected/sold. In order to upgrade Nookling Junction to T&T Mart, you must meet the following requirements: Complete the 10,000 Bell house down payment Spend 12,000 bells at Nookling Junction Either 7 or 10 days need to have passed since town creation. The Animal Crossing Wikia states 7, but Nookipedia states 10. Other sources I can find also state 10, but it'll be difficult to verify whether or not this has changed from the Japanese version until sufficient time has passed from the release date.
{ "pile_set_name": "StackExchange" }
Q: Where is my Mortarboard Badge? According to https://stackoverflow.com/users/3987441/lea-tano?tab=reputation I earned 220 reputation points yesterday and yet I'm not seeing the Mortarboard Badge? Something else I'm wondering too... if 200 is the daily rep limit how is it that I got 220? A: The association bonus does not count towards the daily reputation badges. So you only earned 120 qualifying reputation that day.
{ "pile_set_name": "StackExchange" }
Q: iOS: IBAction/Private methods -- why declare in .m under @interface? What's the purpose for declaring IBActions or private methods in .m file under @interface? Xcode seems to compile fine if I put the methods anywhere in .m file without the declaration. A: More recent versions of Clang parse a little more. The compiler no longer needs to see the method declaration before use within an @implementation in this case because it knows the @implementation will close in the same translation (using @end). So it's just there for your convenience, but it's still quite recent and a lot of code was written before it was introduced. Thus, the declaration is no longer necessary. It's of course still valid, so you can add it if you must support older toolchains or if you prefer to have its declaration in the @interface ().
{ "pile_set_name": "StackExchange" }
Q: Copy location in local space I have rigged train wheels, and it works, except when you rotate the train. The piston's "Copy Location" is using world space instead of local space, which causes it to go all wonky. I tried every combination of "Local Space" and "World Space" on the "Copy Location" constraint, but nothing works. blend file: https://drive.google.com/open?id=0B9fajYcxL7pvUWF4T0tRZHdLcFU A: I tried changing "piston" constraint settings a bit, setting world <==> world adding X as contraint axis then I animated the train rotation, to check and it seems to work now, see the attached file. (btw, next time please use the same service I used, here http://blend-exchange.giantcowfilms.com/, it helps preserving example files for others in future). edit: as you say in commenmts, there were other issues on different train's movements. I tried and probably you just need to add also Z axis to the piston contraint, and then ALSO add a location contraint for piston on Z, limiting max Z to its "deafult" Z location in local space, like this: and it seems to behave well (hopefully) on all desired train movements...
{ "pile_set_name": "StackExchange" }
Q: Call function from different directory C I was wondering if there is a way to call a C function in directory /home/dec/file1.C int add( int a, int b){ c=a+b; return c; } , from a C file in the directory /home/work/file2.C #include "file1.h" sum = add(1,2); So when I call add, it doesn't recognise that there is a function add in the other directory, but when I put them in the same directory, the program works. I looked around but I only see how to call when the file is in the same directory, using an #include. Thanks in Advance A: I think I got it. Thank you all who helped. But I had to link each and every file individually. So I used gcc file1.o file2.o. And it worked. If anyone else stumbles on to this question, this might be helpful. I am posting this as an answer because it worked for me. But if someone has some explanation on this topic or some links, please feel free to share.
{ "pile_set_name": "StackExchange" }
Q: What are expressions in mathematics? Like algebraic expressions are logarithmic, Experimental, trigonometric, differential, etc., expressions also there? I am not referring to functions, but just expressions or equations. Are their definitions similar to how we define their corresponding function? I know Functions are more frequently and widely used than any expression, why? A: An expression is essentially a string of symbols (e.g., $$\frac{-b\pm\sqrt{b^2-4ac}}{2a}$$ or $x^2$) with some technical requirements; an equation is a relationship between expressions that is given by an equality (e.g., $c=2\pi r$). I doubt that functions are more frequently/widely used than expressions. In mathematical literature, a typical author talks about the LHS or the RHS of the definition of a function (and the derivations thereof) far more often than the function itself. For every equation, there is at least two expressions.
{ "pile_set_name": "StackExchange" }
Q: What do graphical icons and symbols in Android Studio mean? This one is not covered on the IntelliJ IDEA's symbols help page. It can be guessed that the 'o' in the circle is related to Override methods but what about the upward arrow? And more generally where can I find any reference about meaning of these symbols that are specific to Android Studio? A: The arrow upwards means the current method overrides another method. This icon is part of four such icons, as listed below: This function overrides another. This function is overridden elsewhere. This function implements an interface. This interface has one or more implementations elsewhere. Combinations of these icons van occur, an overriding function can be overridden, and an implemented interface could be overridden too. As far as I am aware, no other combinations are possible.
{ "pile_set_name": "StackExchange" }
Q: React native: Why does stylesheet.create return object with numbers and not styles? I created styles, but sometimes I cannot use them because they return numbers: const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#FFFFFF' }, moodSliderContainer: { justifyContent: 'center', alignItems: 'center', width: '100%' }, postListContainer: { width: '100%', height: '100%', paddingBottom: 120 } }); console.log(styles); A: From React Native documentation - StyleSheet: Performance: Making a stylesheet from a style object makes it possible to refer to it by ID instead of creating a new style object every time. It also allows to send the style only once through the bridge. All subsequent uses are going to refer an id (not implemented yet). If you want to retrieve the actual style object, you can use StyleSheet.flatten(styles.container).
{ "pile_set_name": "StackExchange" }